Skip to content

CUDA: an int4 W4A16 kernel for GPTQ group-128 routed experts and the LM head - #4183

Open
BadAd84 wants to merge 10 commits into
ashhart:mainfrom
BadAd84:cuda-int4-kernel-m
Open

BadAd84 wants to merge 10 commits into
ashhart:mainfrom
BadAd84:cuda-int4-kernel-m

Conversation

@BadAd84

@BadAd84 BadAd84 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Terms used below: "the base" is upstream main at 7d4a77aa5bfa14deffaa18a7ce31bd8a0dffaca8, which carries the GPTQ reader of pull request #3611 (merged as 51a108030, fe3622b72, 08540d797 and da8e4444b), and "the branch" is that base merged with the three commits this pull request adds, whose head is named below.

What this changes

Before, TensorFold on CUDA could read AutoGPTQ weights with the base's reader (zig/src/core/quant/gptq.zig,
merged as #3611) and multiplied none of them as stored: git grep -l fn_int4 7d4a77aa5bfa14deffaa18a7ce31bd8a0dffaca8 -- zig lists no file. After, zig/kernels/cuda/fn_int4.cu multiplies them as stored and zig/src/cuda/int4.zig packs and launches it. No family loads the module yet, so every checkpoint served today takes the path it took before; the caller is step 5 of the same order, and the kernel's contract suite is the only thing that runs it here.

  • Issue: Refs Flash Next on CUDA: serve a GPTQ int4 checkpoint as stored (top-5 routing, block-FP8 mixers) #3368, step 4 of the six steps agreed there ("the int4 kernel"). This completes none of them.
  • Stacked on: upstream main at 7d4a77aa5bfa14deffaa18a7ce31bd8a0dffaca8 (changelog: each line once under Unreleased). The branch is this change's two commits on 32c4e3d8fe7b696de738839a0cf1d8cc596c80fe, the two
    signed merges of main: fa7d93d9a for d796b267e6f535a4819cf049c1aa034288611209 and 73a3d618b for
    7d4a77aa5bfa14deffaa18a7ce31bd8a0dffaca8, and one commit after them, 582994e22 (fn_int4.cu: the mma, the non-allocating load and the cp.async copies come from common/). The GPTQ reader this kernel packs is merged
    (core/quant: a GPTQ reader for AutoGPTQ v1 group 128 symmetric weights #3611, 51a108030, fe3622b72, 08540d797, da8e4444b), so the branch is cut from main itself and needs no
    parent pull request: the reader owns the layout constants this kernel packs (zig/src/core/quant/gptq.zig's
    group = 128 and zero_nibble = 7), and nothing else is needed to apply the branch. The second merge conflicted
    in exactly one file, zig/kernels/cuda/contract_controls_set.cu, where both sides appended an include to the same
    image list (main's contract_embed_controls.cuh, this change's contract_int4_controls.cuh); it was resolved by
    keeping both, main's line first. The gates below are at the head named above; the device run is at 73a3d618b,
    whose compiled kernel is byte-identical to this head's (see below).
  • The last commit exists because of a check the parent head failed. tools/zig/cuda_common_check.py, the "Shared
    CUDA primitive copies" step that opens the zig job, rejects local copies of the cp.async instructions,
    ld.global.nc and mma.sync outside zig/kernels/cuda/common: at 73a3d618b it read cuda common: 60 local copies, 5 violations and named five lines of fn_int4.cu (cp.async.cg at 281, commit_group at 283,
    wait_group at 285, ld.global.nc.L1 at 48 and mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 at 40).
    The kernel now calls tf_common::cp16z, tf_common::cp_commit, tf_common::cp_wait, tf_common::ld_nc and
    qmm_frag::mma, whose instruction text is the one the file carried, and the check reads cuda common: 55 local copies, 0 violations, the count the base tree reads too (the allowlist carries no fn_int4 line either way).
    fn_int4.cu is the commit's only compiled source: the same nvcc 13.3 -fatbin command on the old and the new
    file produces one file, 4,154,648 bytes with sha256
    1e2b5ee6c0bce3b297168e000449b61cb1047d826d3b5375195945c3085901c0, byte-identical to the image the device run
    measured, and the dependency files show the new build read common/cp_async.cuh and common/qmm_frag.cuh where
    the old read no common/ path, so the shared forms are what the compiler consumed and the device results stand.
  • atc overlap --json: run in this branch's worktree at the head named above with up/main at
    57c792ae5eb6795451e93e15056325983f6aea04 (upstream main as fetched on 2026-11-20), on 2026-11-20:
    complete: false with its own four limits (otherPullRequestsLimit, pullFilesUnavailable,
    pullRequestsLimit, timeLimit), 20 changed files and 22 overlaps, all of them working-tree overlaps against 22
    open pull requests (atc's own states: 7 clean, 3 conflicts, 12 unknown because it could not fetch their
    files). No entry is sourced from our own pull requests: myPullRequests is empty, our glm cuda: decode windows' EXL3 experts run on the 16-pair item plan #2044 having merged. Each
    of the 22 was then merged three ways read-only (git merge-tree with main alone and with this head): 7 merge
    cleanly with this head; 8 conflict in exactly the files they conflict with main alone, 7 of them with the same
    number of conflict blocks in every file and ricursive: serve Ripple-65B on two GB10s with up to 1M tokens of context #2522 with one block fewer in zig/tests/cuda/main.zig; 2 conflict in
    fewer files than they do with main alone, MiMo-V2.6-Flash on CUDA (2x GB10) with DFlash as the drafter #728 not in zig/exl3_prompt_host.zig and qwen3_5: TF_QWEN_KV_HOST - pinned-host KV pages (capacity mode for long windows) #2637 not in
    zig/src/families/qwen3_5/cuda_native.zig, files main changed after the base and this head does not touch; and
    5 conflict in at least one file that main alone merges, each of those files with one conflict block: lfm3: serve LFM3-1.7B on CUDA: NVFP4 and FP8 weight-only, MLX 4-bit (stacked on #1513, #1492 and #1503) #1508 and
    idol: the octree and Gaussian decoders on CUDA (stacked on #1773, #1767; not yet run on a GPU) #1858 in zig/tests/cuda/contract_limits.zig, MoE route tap: optional TF_ROUTE_TAP trace of global top-k #1886 and glm cuda: TF_GLM_GRAPHS=1 replays verify windows as CUDA graphs (#1490) #2279 in zig/tests/fixtures/gradient-serving.tsv, and
    Ling-3.1-flash on CUDA, on one or two GB10s #2340 in zig/src/core/contract/measurements/pending_133.zig. Every one of those is a shared registration table
    or a pin row this change also touches: a registration list resolves by keeping both sides' lines, and a pin row
    by writing the merged tree's own bytes.
  • Merge with upstream main: this head's CI ran at 582994e22 against the base this description names,
    7d4a77aa5, and the branch conflicts with main's newest tip, 57c792ae5eb6795451e93e15056325983f6aea04:
    git merge-tree --write-tree --name-only of this head and that tip exits 1 with one conflict block in each of
    two files, zig/kernels/cuda/contract_controls_set.cu, where main appends contract_hcn_controls.cuh to the
    include list this change also appends to (542deb953), and zig/tests/fixtures/gradient-serving.tsv, where both
    sides re-pin the zig/src/cuda/kernels.zig row. Both are shared registries this change extends, and each takes
    the resolution the registries take: the image list keeps both sides' includes, main's first, and the row is
    re-pinned from the merged blob. Against 3661a4281, the main of the previous round, and against 7d4a77aa5,
    the same command exits 0.

How the stored form is read, and why its bits are stable:

  • A code is exact in the MMAs. A stored code q (0..15) enters the bf16 tensor cores as the bf16 values 128 + q, and the product against 136 (128 + the zero point 8) is subtracted in bf16, which leaves q - 8 exactly: every value 0..15 and 128..143 is a bf16 exactly, and the subtraction of two bf16 values this close is exact. No nibble is widened through an f32 round and no product is formed in a narrower type than its inputs.
  • A group's products run in one fp32 MMA chain. For each output column, the group of 128 inputs is four k32 blocks in order, each block's two k16 steps in order, with the k permutation fixed by the packed word; then the group's sum multiplies its fp16 scale with one fma and adds to the accumulator, group by group. So a row's bits depend on its own inputs and weights alone: never on the other rows of the call, the row count, the plan's item layout, the n8 tiles a warp takes or the grid. The contract's repeat gate and its skipped-slot check are this claim's proof.
  • The prompt forms are the same arithmetic in a different place. int4_prompt_kernel stages the same packed words and the item's rows in shared memory with cp.async; the contract compares both prompt launches byte for byte with the plain ones.

What the module keeps, and what it drops:

  • Three epilogues of int4_kernel (gate/up with SwiGLU, down to fp32, down to bf16) at 1, 2 and 4 n8 tiles a warp and 1 or 2 row tiles a pass: 18 launches. Two int4_prompt_kernel launches for the routed down (fp32 and bf16 out) and one for the routed gate/up. The head and the down share the bf16-down instantiation, because the epilogue is the whole difference.
  • Groups of 64 are not built. They exist for a two-rank serve, whose half of the 640-input width cuts a group of 128; --tp 2 is refused by name at admission (step 5), so the instantiations would be dead weight and 12 more records.
  • The three settings the kernel's port read are dropped with the caller: TF_FLASHNEXT_INT4_TILE, TF_FLASHNEXT_INT4_PROMPT_GATE_UP and TF_FLASHNEXT_HEAD_ROW_TILES, plus a prompt-down switch. Each would be a direct getenv today, none is measured, and no caller exists to honour one. The module offers the paths as calls (gateUp, down, downPrompt, gateUpPrompt, dense); the caller that wants a plan tile of 64 pairs says so. The PR that turns one on brings its platform/environment.zig row and its measurement.
  • No entry in cuda.experts.Format. The format's kernels belong to the backend, as fp8.zig and nvfp4.zig are host-only in core/quant, and the family's layer view (step 5) is where a format is declared.

Why not affine4, which already serves 4-bit weights on CUDA: its lane reads a bf16 scale and a bf16 bias for every 64 inputs (zig/src/cuda/qlinear.zig Affine4.layout sizes both tables at k / 64, and zig/src/cuda/affine4_kernels.zig packs MLX's (n, k/64) scales and biases into the tiles), while these weights carry one fp16 scale for every 128 inputs and no bias. Rounding that fp16 scale to bf16 is lossy, measurably so on this checkpoint's own scales (our reply on #3368), and the format has a zero point (8, from qzeros) rather than a bias. Serving these weights on the affine lane would trade a stored format for a re-encoded one, which the engine does not do.

Provenance and licence: fn_int4.cu is MiaAI-Lab's file from their two-rank recipe at
04f2b53826dca9a52893f2bce9d49bb3d1828e88 (patches/0002-kernels.patch creates it, 489 lines), Apache-2.0,
Copyright 2026 MiaAI-Lab. Three changes are TensorFold's, the first two marked TF: in the file and all three
stated in THIRD_PARTY_NOTICES.md with the recipe's NOTICE line: the head's dense items hold 16 MT rows rather
than 16, one more int4_prompt_kernel instantiation builds for the routed gate/up, and the local copies of the
mma, the non-allocating load and the cp.async copies are replaced by the shared ones in
zig/kernels/cuda/common/, whose instruction text is the same. The file's header states the three.
zig/src/cuda/int4.zig and its tests are this branch's own.

What the branch does not do: it adds no setting (so docs/environment.md is unchanged), no lossy conversion (the only widenings are the exact ones above), and no mode that changes output tokens. Nothing calls it, so there is no default path to compare and no token hash to take; the receipt below is the device gates and the limits audit, measured on a GB10.

Checks on this head

  • Head commit: 582994e2291711e861068d3d123be8b8a6979c1e, signed (%G? = G in this checkout), tree
    63a931abee646ec50f605a3fcad993f538855e85: the two commits on 32c4e3d8fe7b696de738839a0cf1d8cc596c80fe
    (7fe47dbe0, the kernel, 18 files, +1,864/-4, and 619d5e95b, the contract fix, 7 files, +192/-31), the two
    signed merges of main named above, and one commit after them (582994e22, the shared primitives, 2 files,
    +23/-30); against the base the branch is 20 changed files, 8 of them new, +2,018/-4. The contract fix is the
    skipped-slot check by row, the second control registered at gate 3, the gate/up allowance derived from the
    epilogue at zig/tests/cuda/int4_ref.zig, the stress rows' magnitudes, and the 21 nvcc 13.3 receipts. The last
    commit is the shared-primitive change described above, and its only compiled output is byte-identical to the
    image the device run measured. The two rows the pin fixture re-pins are the bytes of the two serving sources this
    change edits, zig/src/cuda/kernels.zig and zig/src/cuda/root.zig. No CHANGELOG.md line is in the branch:
    the maintainer adds a merged pull request's bullet in a follow-up commit, as they did for the reader's own merge.
  • The merges and the last commit kept the change identical where it matters. Ten of the files this change owns are
    byte-identical by blob at the GPU-measured head 619d5e95b and at this head: zig/src/cuda/int4.zig
    61625c9eae, zig/src/cuda/int4_test.zig 5155a3b5b6, zig/src/cuda/root.zig 0e3ac57219,
    zig/build/cuda_int4_host.zig 8275134ba4, zig/kernels/cuda/contract_int4_controls.cuh e8a41d963f,
    zig/src/core/contract/int4_records.zig 0a43335817, zig/tests/cuda/contract_int4.zig b83fcd81bd,
    zig/tests/cuda/int4_ref.zig 4102656d42, zig/src/core/contract/measurements/pending_133.zig dccc116f6c
    (the 21 added lines, every one a fn_int4 receipt, none lost) and zig/tests/cuda/contract_after.zig
    80d73fc337. zig/kernels/cuda/fn_int4.cu is the one that moved: 6d0b5de16e at 619d5e95b, 0c5e5ca3a1 at
    this head, from the shared-primitive change. zig/kernels/cuda/contract_controls_set.cu is 81410ea1bb at this
    head: main's contract_embed_controls.cuh include and this change's contract_int4_controls.cuh include are
    both there, main's first, and the rest of the file is main's. Three shared files moved only because main added to
    them, this change's line unchanged in each: zig/src/cuda/kernels.zig (the fatbin_fn_int4 line, between main's
    drama3_codec and drama3_staged_gemv), zig/build/cuda_kernels.zig (its fn_int4 entry at the end of the
    image list) and zig/tests/cuda/contract_limits.zig ("fn_int4" added to the image names main lists). The rest
    are shared text and pins: docs/kernel-contract.md and THIRD_PARTY_NOTICES.md carry this change's added lines,
    zig/build/cuda.zig and zig/src/core/contract/registry_joins.zig add one line each, and
    zig/tests/fixtures/gradient-serving.tsv differs from main in exactly its two pinned rows, the bytes of the two
    serving sources this change edits; its other rows are main's.
  • Trees: both are git archive outputs verified blob by blob against git ls-tree -r of their commit before any
    step ran: on the x86_64 machine head 12,557 entries and base 12,549, 0 mismatches, 0 extra files; on the device
    box the head, 12,557 entries, 0 mismatches, 0 extra files.
  • Lean checker, the head's tools/zig/lean_check.py put in the base worktree as CI puts it and run from each root:
    this head 6,962 files, 168 problems (rc 1), the base 6,954 files, 168 problems (rc 1), the two file counts
    differing by this change's 8 new files, so lean_new.py reads lean: 168 problems, 168 on the base, 0 new (rc 0).
  • python3 tools/pr_check.py --base 7d4a77aa5bfa14deffaa18a7ce31bd8a0dffaca8 --pr 4183 (upstream main at the
    sha the branch merges), rc 0: merge base 7d4a77aa5bfa14deffaa18a7ce31bd8a0dffaca8; 20 changed files; lean 168 vs 168, 0 new and 0 error(s), 1 warning(s); warnings are advisory. The warning is WARN: Zig changed: no Unreleased bullet naming this PR: the branch changes Zig files and the CHANGELOG carries no Unreleased bullet
    naming this pull request, which the tool treats as advisory, the maintainer adding a merged pull request's bullet
    in a follow-up commit. The check needs a git checkout, so it runs here on the branch's own worktree. The two rows
    this change re-pins in zig/tests/fixtures/gradient-serving.tsv are read by test-gradient-serving, the step
    that runs against this head's own tree: 11/11 steps succeeded; 6/6 tests passed over the file's 169 rows.
  • Gates on the head tree, on the x86_64 Linux machine with 16 CPUs (Zig 0.17.0, no GPU), each tree extracted fresh
    and verified as above, zig fmt --check build.zig zig rc 0 on the head and rc 0 on the base: on the head,
    zig build -Dfixed-cpu test-int4-host rc 0 in 32 s, 6/6 steps succeeded; 33/33 tests passed; zig build -Dfixed-cpu test-kernel-contract rc 0 in 404 s, 36/36 steps succeeded; 260/260 tests passed; zig build test-environment-host rc 0 in 3 s, 3/3 steps succeeded; 26/26 tests passed; zig build -Dfixed-cpu test-gradient-serving test-qwen-serving-host test-glm-pdl-scan rc 0 in 4 s, 11/11 steps succeeded; 6/6 tests passed. The run stopped after those four steps because the request budget ended and a queued gate run was
    waiting for the machine's build lock, so these are not this head's own local runs: compile-cuda-tests and
    compile-config-server cross-compiled for aarch64-linux-gnu
    (10/10 and 8/8 steps at fa7d93d9a), test-cuda-host, test-host-a, test-host-b, test-golden,
    test-server-security test-pull-security, fuzz-cortheon and check-release-paths. CI ran every one of those
    steps on this head (below). The head's contract run is 260 tests against the base's 258, the difference being
    int4_records.zig's two test "int4: blocks, which are in this diff; the base tree's run, on the same machine
    in the previous round, read 36/36 steps succeeded; 258/258 tests passed in 295 s.
  • The zig job's python steps, run here at this head with the workflow's own commands, all rc 0: python3 tools/zig/cuda_common_check.py, cuda common: 55 local copies, 0 violations; python3 tools/zig/cuda_fragment_check.py, cuda fragments: 2 fragments, 15 includes, 0 misses; python3 -m unittest discover -s tools/zig -p cuda_common_check_test.py -v, Ran 9 tests in 0.012s, OK; python3 tools/test_pdl_early_loads.py -v, Ran 17 tests in 0.010s, OK; the lean check above; python3 -m unittest discover -s tools/zig -p zig_cache_restat_test.py -v, Ran 2 tests in 226.634s, OK, with its own line
    zig_cache_restat: 12 manifests, 2 rewritten, 2 records updated, 2 changed, 0 unreadable, 4 pruned with 3 output folders; python3 -m unittest discover -s tools/zig -p host_tests_test.py -v, Ran 13 tests in 17.345s, OK;
    python3 -m unittest discover -s tools/zig -p flashnext_batch_serve_test.py, Ran 8 tests, OK; python3 tools/zig/nfkd_tables.py --check --zig with Zig 0.17.0 as the argument, no output; cd tools/zig && python3 -m unittest test_nfkd_tables, Ran 5 tests in 0.887s, OK; python3 -m unittest discover -s tools/zig -p build_options_test.py, Ran 5 tests in 144.414s, OK. The first attempt of the first command read rc 127, the
    host's timeout wrapper failing to exec python3 once; the three commands of that step were re-run unchanged
    seconds later, and those reruns are the record above. The workflow's "Let a restored cache fit this checkout"
    step only warns and was not run, and its "Save the build cache" step runs on main pushes only.
  • The pytest job at this head: python3 -m pytest -q -p no:cacheprovider from the root, rc 0, 645 passed, 95 skipped, 670 subtests passed in 522.22s (0:08:42), on python 3.14.4.
    The benchmark-clients job's two steps ran at this head on both legs: the ubuntu leg Ran 201 tests in 169.558s,
    OK for the benchmark clients and Ran 32 tests in 0.902s, OK for the evidence index, and the windows leg
    Ran 201 tests in 213.401s, OK and Ran 32 tests in 32.702s, OK.
  • The host tests, and what they cover: zig build -Dfixed-cpu test-int4-host runs the cuda module's host tests, this
    change's int4: blocks among them (the step's filters field narrows nothing in this Zig: std.Build never emits
    --test-filter, so a filtered step runs its module's whole test file set and the count is the module's): the
    word shuffle, packWords against every stored code of a slice, a whole 640 x 2,560 matrix's scale layout and its own column groups, every slice refusal by name, the stored codes and fp16 scales against hand-computed binary64 weights, the 21 mangled symbols, the two prompt launches' shared-memory sizes and the gate/up launch's alignment guards. They pass 33/33 at this head (6/6 steps succeeded; 33/33 tests passed), 12 of those tests being this change's (11 int4: blocks plus the import test that pulls them in). The file had never been compiled before the module's test list named it, so five of its expectations were wrong and are fixed here: the shuffle mapping is not an involution, a k32 block index read (kin % 32) / 32 (always 0) instead of (kin % checkpoint_group) / 32, a source whose k_full disagrees with its buffers is error.BadLength not error.BadSlice, the fp16 constant for -2.0 was written 0xBC00 (-1.0) instead of 0xC000, and a 2,560 x 640 matrix carries 12,800 scales, not 5,120.
  • Mutant scores, from the run at 3a33f80ab, whose zig/src/cuda/int4.zig is this head's blob (61625c9eae): each
    mutant is the inverse of one check the module makes, applied to its own fresh extraction of the tree and run
    through test-int4-host, and a mutant is killed only when it fails a
    named int4: test that the unmutated control passes. The anchors all resolve (ANCHORS 23 mutants, 0 not exactly once), the control reads rc 0, 6/6 steps succeeded; 33/33 tests passed, 0 failing int4 test(s), and the
    scoring reads SCORED 23 mutants, 23 killed, 0 no kill. scale-widen's replacement keeps only bf16's seven
    mantissa bits, so its kill is a test failure and not a build error. The table is in the branch's gate record, not
    in this diff.
  • test-host in full was not run at this head: the machine's run stopped after the four steps above. At the parent
    head 73a3d618b the same machine's zig build -Dfixed-cpu test-cuda-host (the CUDA side's host unit tests
    alone, which the test-host-a shard runs) reads rc 0, 440/440 steps succeeded; 7618/7658 tests passed (40 skipped) in 844 s. CI ran test-host-a in the zig job and test-host-b in the zig-b job on this head, and
    both passed.
  • zig fmt --check build.zig zig: rc 0 on the head and rc 0 on the base; git diff --check
    7d4a77aa5bfa14deffaa18a7ce31bd8a0dffaca8..582994e2291711e861068d3d123be8b8a6979c1e prints no output and exits
    0, and git diff --check over the two commits, over the second merge and over the last commit does the same.
  • CI at this head: every check passes on 582994e22. gh pr checks 4183 reads pass for fmt, zig, zig-b,
    zig-windows, pytest, benchmark-clients (ubuntu-latest), benchmark-clients (windows-latest),
    release-paths (ubuntu-24.04) and zig-macos-dev-tools, and skip for host-nightly-linux and
    host-nightly-macos, whose jobs are if: github.event_name == 'schedule'. That puts on this head the steps the
    machine above did not run: zig runs test-host-a, test-kernel-contract, test-golden,
    test-gradient-serving test-qwen-serving-host test-glm-pdl-scan, test-server-security test-pull-security and
    fuzz-cortheon; zig-b runs test-host-b; zig-windows runs zig build test, test-golden, fuzz-cortheon
    and test-pull-security; release-paths runs check-release-paths; and zig-macos-dev-tools runs dev-tools.
    The step that failed at the parent head is the first of zig, and it passes here with cuda common: 55 local copies, 0 violations.
  • Not run, and why: the device gates on sm_80, sm_86, sm_89 and sm_120, for want of those GPUs (their limits come
    from the compiled cubins in the five-SM audit). Metal and HIP are not reached by a .cu file. Two ranks are not
    reached: the groups-of-64 form is not built. The device run was taken at 73a3d618b on 2026-11-20, and this
    head's fn_int4.cu compiles to the same fn_int4.fatbin byte for byte, so the limits name table
    zig/tests/cuda/contract_limits.zig, which main extended beside this change's line, is described by that run
    rather than by an earlier head's.

Receipt

  • Main against branch: n/a, because this change cannot reach inference. No family imports the module, no recipe sets a setting, and no served source is edited, so every checkpoint takes the path it took before. grep -rln 'fn_int4\|cuda\.int4\|cuda/int4' zig lists fourteen files: the kernel, the host module and its test, the reference the contract derives its allowance from, the two image registrations (zig/build/cuda_kernels.zig, zig/src/cuda/kernels.zig), zig/src/cuda/root.zig's export and its test list, the controls header, the contract suite, the launch records and the 13.3 receipts that carry them, the image name in zig/tests/cuda/contract_limits.zig, the build step that runs the host tests (zig/build/cuda_int4_host.zig) and the pin row in zig/tests/fixtures/gradient-serving.tsv, and no family, server or recipe file.
  • Boxes it reaches: none that serve, for the reason above. The only execution path is the contract suite.
  • New switch? n/a: no setting is added, zig/src/platform/environment.zig is untouched and so is docs/environment.md. The settings the kernel's port read are removed rather than routed (see above).
  • Environment, with the TensorFold commit, Zig and backend toolchain, machine and GPU, checkpoint and revision: base
    7d4a77aa5bfa14deffaa18a7ce31bd8a0dffaca8, head 582994e2291711e861068d3d123be8b8a6979c1e (the device suite and the limits audit below ran at 73a3d618b, whose compiled kernel is byte-identical to this head's), Zig 0.17.0,
    nvcc 13.3.73 for the device suite and the limits audit, an aarch64 Linux machine with an NVIDIA GB10 (Ubuntu 24.04.5
    LTS, 20 CPUs, 123 GiB RAM, driver 580.178.04, compute capability 12.1), an x86_64 Linux machine with 16 CPUs and no
    GPU (the host gates below, and the aarch64 cross-compiles at fa7d93d9a), and no checkpoint: the host
    test and the device suite build their own stored matrices. The checkpoint the shapes come from is
    azampatti/Qwen3.8-Flash-Next-125B-A5B-INT4-AutoRound at revision 8b145d7f6505f71521a73646c268e51f6af532e4:
    hidden 2,560, 512 experts of width 640, group 128, 4-bit symmetric GPTQ weights with zero point 8.
  • Paths and platforms the change reaches, which I ran and which I could not: the host path (the packer and the launch guards) run on x86_64 Linux, the same tree cross-compiled for aarch64-linux-gnu at fa7d93d9a and not re-run at this head, the device path on sm_121 (a GB10), where the int4 suite passes every gate and both planted controls read red as planted (see the kernel contract section); no SM is claimed qualified. sm_80, sm_86, sm_89 and sm_120 were not run.
  • Exactness, from tools/bench_concurrent.py --alone --serial or token_sha against "draft": false: n/a, no served path. The exactness this change does own is the stored weight: the host test checks (code - 8) * scale in binary64 against hand-computed values for a zero point, a negative scale, an infinite scale, fp16's least subnormal and a scale of 0.1 whose fp16 bits are not decimal 0.1.
  • Main against this branch, same machine and checkpoint, posted before asking for a run on our machines: n/a, no checkpoint and no serve.
  • Decode speed before and after, from tools/bench_openai.py: n/a, no served path.
  • Prompt speed before and after: n/a, no served path.
  • Licence of any new weights or drafter: n/a, no weights are added. The kernel is MiaAI-Lab's Apache-2.0 file with three changes, two of them marked in the file, recorded in THIRD_PARTY_NOTICES.md.

The device lines are the run at 73a3d618b, the head this one adds its commit to, taken on 2026-11-20 from that
head's git archive, verified blob by blob against git ls-tree -r on the box before the build. This head's
fn_int4.cu compiles to that run's own fn_int4.fatbin byte for byte, so every line describes this head's kernel.
Two runners did the work: that head's own runner for kernel-contract fn_int4 and the limits audit, and the same
tree plus one dispatch line naming the int4 suite's own verb (which main does not carry) for int4-contract. The
full kernel-contract run was not taken: the same box took 3,930 s over it at an earlier head, over the one-hour
cap this window works to, so that run has no full-run aggregate and none is quoted below. The planted head without
the nibble shuffle is a control at gate 3 (Fixture.kernel() maps .unshuffled_nibbles to .shapes), not an
eighth kernel, so its failure is CONTROL ... red at shapes, as planted and not a gate failure. The gate/up
registrations compute their allowance from zig/tests/cuda/int4_ref.zig (both fp32 sums through silu's slope over
the rounding's interval, then bf(g), bf(u), bf(silu) and the store at their own values, and expf's fp32 overflow),
state gate 4's bf16 proof at 60 with its arithmetic in why, and gate 4's stress rows carry 8 to 2,040 with the
eight nudged inputs at 4 to 16. Production was down from 2026-11-20T02:19:01+00:00 to
2026-11-20T02:21:08+00:00, and the box read /health 200 afterwards. Two hashes carry the run: fn_int4.fatbin
is 4,154,648 bytes with sha256
1e2b5ee6c0bce3b297168e000449b61cb1047d826d3b5375195945c3085901c0, the same bytes as the earlier head's, and
contract_controls.fatbin reads eff8853391d641d43fa50edb12508610d8e110a4385f3a119c34ace7db245e9f where the
earlier head read b15f6bff69ab92bcda1d3adbaab14c5c2273933322b663657bfdec20d8947d54, because the merged tree adds
main's contract_embed_controls.cuh include to the planted-controls image. The int4 suite's log is byte-identical
to the earlier head's, sha256 3673fb00ebaa2179b78409b230dd88b2f39beb5c1d960aa0f6c81a7674a90d93.

Each declaration, and what derives it:

  • accum = .f32, depth = k/16 + k/128 + 36: one mma k16 step an input's 16 products accumulate in (k/16 of them, in order), one fmaf(group sum, scale, acc) a group of 128 inputs (k/128), and the 36 roundings one bf16 mma k16 step carries at worst (core/attention_range.mma_step, the count the other CUDA experts state).
  • ops = 5: expf's 2 ulps, the 1 + e, the quotient and the product.
  • mids = 3: bf(g), bf(u) and bf(silu), the three bf16 roundings experts.cuh's SwiGLU makes before the product (fn_int4.cu's swiglu, float gv = bf(g), uv = bf(u); ... bf(gv / (1.f + expf(-gv))) * uv).
  • out = .bf16: the store's __floats2bfloat162_rn in both kernels.
  • the allowance itself: int4_ref.zig's gateUp, the sums through |silu'| on the rounding's interval (its turning points are +-2.3993572805, so the interval's largest slope is exact), then bf(g), bf(u) and bf(silu) at their own values, the store, expf's fp32 overflow above 88.72, and the five fp32 ops; rows is the same two lines for a down or the head.
  • gate 4's .bf16 = 60: the largest miss a low-precision sum can make on a mirrored row is want itself (the halves order cancels it exactly), and the roundings already allow 4.1368 u of it (computed from the harness's boundExact: (5 * 2^-24 + 3 u) (1 + u) + u, where the undivided generic form is 4.0118 u and its ceiling 63.812x, the number the device printed), so 1 / (4.1368 u) = 61.9x is the ceiling and 60 is stated below it.
Kernel contract, only when a GPU kernel is new or changed
  • Kernels registered with the contract, and the kernel each one replaces: fn_int4.cu's int4_kernel (three epilogues) and int4_prompt_kernel (the routed down and the routed gate/up) are registered in zig/tests/cuda/contract_int4.zig as seven kernel entries at the checkpoint's shapes, with the two planted controls as the last two rows of the same entries array: gate/up and down at 1, 3, 16 and 64 token rows and at 64 and 200 pair rows for the prompt forms, the head at 1, 16 and 32 rows including its full 248,320 columns at one row, and each entry's edges. The two prompt entries replace the plain form they must equal, byte for byte, and say so. It replaces no kernel on any served path; nothing loads it yet.
  • A planted control for each new kernel, and each one fails as planted: on a GB10 (sm_121), the runner built at 73a3d618b with nvcc 13.3.73, CONTROL control: int4 routed down with each group's sum rounded to bf16: red at sums, as planted (FAIL sums control: ... 1103940812.8x over its exact-sum bound at k 640: not fp32 sums (fp16 would miss 96087692x, bf16 640330411x)) and CONTROL control: int4 lm head with each word's nibbles unshuffled: red at shapes, as planted (FAIL shapes control: ... at 1x2560x2560 output 0 is 4.650000e1 where float64 gives 2.521465e0: 1301.67 of its bound). Both are entered as controls, so neither counts as a gate failure: 2 controls: 2 red as planted, 0 missed.
  • Each backend's SUMMARY line and exit status: CUDA on a GB10 (sm_121), runners built from 73a3d618b's tree with
    nvcc 13.3.73. The int4 suite, tf-cuda-test int4-contract, exits 0 after 28 s with 29 PASS lines, the 2 planted
    controls' FAIL ... control lines and their CONTROL ... red at lines, PASS int4 skipped slot: 16 of 96 pair rows left at 0xff, the others byte-equal to the all-live run, and SUMMARY int4: 7 kernels, 7 pass gates 1-4, 0 fail, 0 known findings; 2 controls: 2 red as planted, 0 missed. 73a3d618b's own runner,
    tf-cuda-test kernel-contract fn_int4, exits 0 in 1 s with 23 PASS lines, no FAIL, and
    (filtered) SUMMARY 0 kernels: 0 pass gates 1-4, 0 fail, 0 known findings; 0 controls: 0 red as planted, 0 missed; 0 limit problems; gates 32 ms, limits 2 ms. The limits audit over the 21 committed records and the five-SM images reads
    LIMITS head exit 1 51s lines 10024 int4 RECORD lines 21: 850 problems, 850 (record stale) lines, and 105 PASS; fn_int4 verdicts with (record current) on every one, no int4 entry among the stale lines. The full run, tf-cuda-test kernel-contract, was not taken at 73a3d618b: it took 3,930 s on the same box at an earlier head,
    past the one-hour cap this window works to, and this head runs main's new suites after the main body as well.
  • Chips I could not run: sm_80, sm_86, sm_89 and sm_120, whose limits come from the compiled cubins only; nvcc 13.0 and 13.2, so the 13.0 records stay pending. Metal and HIP: n/a, the kernel is CUDA only.

Checklist

  • The title and description match the head commit, including the stack, and no receipt number is invented: every device line is quoted from the run whose logs are cited, and the run that exits 1, the limits audit over other families' records, is decomposed rather than rounded off.
  • New tests fail before the change, pass after it, and skip cleanly without their dependency: the host tests need no device and pass (33/33 at this head, 6/6 steps succeeded), the two new blocks being int4_ref.zig's derivation and its tightness check. That check requires the generic formula to be short on some of 4,000 epilogue draws, so reverting the allowance to the generic formula fails test-int4-host. The contract suite, reached only by the contract runner that requires -Dnvcc, is the run this commit exists to make pass, and it passes every gate on the device (SUMMARY int4: 7 kernels, 7 pass gates 1-4, 0 fail, 0 known findings).
  • Comments and docstrings are one line within 120 columns, and carry no measurements or history; the provenance header is a licence notice, as Apache-2.0 section 4 asks.
  • No personal data, machine names, internal hosts or local paths in the diff or its commits, and no AI attribution lines.
  • Every token still goes through the lane rounds: not applicable, the receipt is n/a and no served path changes.
  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo: not applicable as above.
  • No precision traded for speed: not applicable. Nothing is re-encoded: a code becomes the bf16 pair 128 + q and the subtraction of 136 is exact, an fp16 scale widens exactly, and no sum is re-ordered by the launch.
  • Decode and prompt processing are no slower than main: not applicable, no served path changes; the family's caller (step 5) brings that measurement with it.

@AIFlowML

Copy link
Copy Markdown
Contributor

@BadAd84 @ashhart I reproduced the documented host check on 582994e22 with Zig 0.17.0. zig build test-int4-host test-environment-host --summary all passed all 59 tests on macOS arm64 (-Dcpu=apple_m1) and Linux x86-64 (-Dfixed-cpu). The CUDA common checker also reported zero violations.

I confirmed both conflicts against 1ece6e6db. In a disposable merge I kept contract_hcn_controls.cuh and contract_int4_controls.cuh in the control image and regenerated the raw zig/src/cuda/kernels.zig pin from the merged bytes. zig build test-gradient-serving test-int4-host -Dcpu=apple_m1 --summary all then passed all 34 tests. The pin on that exact merge is 8ea09fb6461988737b91bbcbc9a533e32205d44f5b1dce3a8f4e769177541ad9.

That is a tested host-side route through the two conflicts. The merged CUDA control image still needs its nvcc build and device run.

Igor Lessio - AIFLOW LABS

@ashhart

ashhart commented Nov 21, 2026

Copy link
Copy Markdown
Owner

The kernel arithmetic looks sound, and this leaves every current serving path unchanged. It still needs changes before landing.

Please rebase onto current main and resolve the control-image, CUDA-root, limits-image and generated-pin conflicts, preserving the newer registrations and regenerating pins from the actual merged bytes. Also add gates 1–4 and byte-replacement coverage for the compiled prompt-down BF16 form, and either add the missing dense-FP32 contract case or narrow that public wrapper to BF16 (zig/src/cuda/int4.zig:162-164,325-349,378-383; zig/tests/cuda/contract_int4.zig:92-102,315-323,469-478).

The receipt's filtered command ran zero kernels, while the useful standalone verb was an uncommitted local edit. Please commit a real int4-contract dispatch and usage entry, or make the int4 filter execute the suite, then rerun on the rebased tree with the added BF16 coverage and post the complete summary and planted-control results.

  • Synthena

@AIFlowML

Copy link
Copy Markdown
Contributor

The refreshed 5aced6d3e head applied cleanly to main 1eed88bb0. On M5 Max with Zig 0.17.0, the int4 host target passed all 33 tests, the serving pin passed, and the Linux x86-64 CUDA test runner compiled.

zig build test-int4-host test-gradient-serving test-environment-host \
  -Dcpu=apple_m1 -j3 --summary all
zig build compile-cuda-tests -Dtarget=x86_64-linux -j3 --summary all

The environment target reports the same failure on the trial and on main alone: the inventory expects 24 Flash Next switches and finds 25. 45534cef1 added the fused-split switch. Updating that expectation in a local main checkout passes all 32 environment tests.

For the remaining contract work, contract_int4.zig still drives prompt-down with f32_out=true at both the new and reference launch. That identifies where to add the BF16 comparison. The dense wrapper still exposes FP32 output. The runner build above checks compilation. Gates 1–4 and byte replacement for those forms need CUDA device runs.

Igor Lessio - AIFLOW LABS

BadAd84 and others added 4 commits November 23, 2026 17:51
…LM head

fn_int4.cu multiplies AutoGPTQ v1 weights as stored: a code enters the bf16 MMAs as itself, a
group's products run in one fp32 MMA chain and the groups add with fmaf in group order, so a
row's bits depend on its own inputs and weights alone.

cuda/int4.zig packs the qweight words and fp16 scales for it and launches its three epilogues
(gate/up with SwiGLU, down to fp32 and bf16), the head's dense rows and the two prompt forms.
A host test pins the packer against the stored codes and the binary64 reference, and the
kernel-contract suite runs every form at the checkpoint's shapes with two planted controls and
a plan whose shared expert's slot is skipped.

The kernel is MiaAI-Lab's dual-Spark recipe at 04f2b53826, patches/0002-kernels.patch,
Apache-2.0; TensorFold's two changes are marked TF and recorded in THIRD_PARTY_NOTICES.md. The
settings the recipe read are dropped with the family's caller, and the groups-of-64
instantiations a two-rank serve would need are not built. No family loads it yet, so every
checkpoint served today takes the path it took before.

The device run and the compiled-limit receipts are pending a GPU window.
…te 4's provable margins

The int4 suite failed three gates and two checks of its own on the device. Each
cause was in the test, none in the kernel:

- The skipped-slot check judged bytes: an all-live row whose correct bf16 value
  holds a 0xff byte read as a row the skip run had written. It judges rows now:
  the skip run leaves all of a skipped pair's bytes at 0xff, and the all-live run
  wrote the row.
- The unshuffled head was registered as an eighth kernel, so gate 3's expected
  failure counted as a gate failure. It is a control at gate 3, which the pull
  request's body and docs/kernel-contract.md already said it was.
- Gate 3: the declared bound counts fn_int4.cu's three bf16 roundings at the
  output's size, but the kernel rounds the gate sum, the up sum and silu each at
  its own size, and a rounded gate sum reaches the output through silu's slope
  times the up value. At 64x640x128 that came to 1.04 of the bound.
  zig/tests/cuda/int4_ref.zig derives every output's allowance from its own
  terms: both fp32 sums through silu's slope over the rounding's interval, the
  three bf16 roundings and the store at their own values, and expf's fp32
  overflow, where the kernel's silu is 0 and float64 keeps a denormal-sized
  value. Checked against the kernel's own arithmetic on 40,000 outputs at k 128,
  256 and 2,560, the derived allowance holds at 0.74 to 0.87 of itself where the
  generic formula is short by up to 75x; its test holds 4,000 epilogue draws
  inside it and requires the generic bound to be short on some of them.
- Gate 4: a mirrored row's terms cancel in pairs, so its total is small and a
  low-precision chain loses the whole of it; how far depends on the chain's
  partial sums, which scale with the inputs. At 4 to 508 the f16 chain of the
  down's bf16 output missed by only 85x of a one-unit bound. The cancelling
  inputs now carry 8 to 2,040, and the eight nudged ones stay at 4 to 16, where
  the mirror's nudge 4 is exact in bf16: a chain's partial sums reach 2^19 to
  2^21 while a row's total stays below 2^24, so fp32 sums remain exact in any
  order and the f16 proof grows with the partials' ulp.
- Gate 4's bf16 proof of a bf16 SwiGLU output cannot pass 1 / (4.1 u) = 62x: a
  mirrored row cancels exactly in the halves order, so a low-precision sum's
  largest miss is `want` itself, and the epilogue's three bf16 roundings and the
  store already allow 4.1 u of it. The registration states 60 with that
  arithmetic in its `why`.

nvcc 13.3's usage of the 21 int4 launches joins measurements/pending_133.zig, as
docs/kernel-contract.md keeps each later release's receipts apart from 13.0's; a
13.0 record stays pending.
…come from common/

The shared cuda_common_check rejects local copies of these primitives. The kernel now includes common/cp_async.cuh and
common/qmm_frag.cuh and calls their forms, whose instruction text is the one the file carried: cp.async.cg with the
source-size operand, commit_group, wait_group, ld.global.nc.L1::no_allocate.v4.u32 and mma.sync m16n8k16 bf16.
The header and THIRD_PARTY_NOTICES.md state the change.
@ashhart

ashhart commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Thanks @BadAd84 for the int4 W4A16 kernel and the detailed derivation. One thing before this can land: gate 3 failed on device at 1.04 of its bound, and the next commit adds a per-output allowance and a custom bf16 margin of 60. Our contribution guide asks that tolerances are not loosened after seeing results, so could you show these limits follow from the arithmetic alone, independent of the failing run, with a control that still goes red? We'll review the bound once that evidence is here.

  • Synthena

kernel-contract's WORD filter selects registered kernels, and no int4 kernel
is registered there, so a filtered run over this family gated nothing. The
verb runs contract_int4.run on the built runner, the build step runs the
runner with it, and the usage text and the contract's page name it. Its
summary counts the suite's registrations: each form a kernel, each control at
its own gate.
…ts arithmetic pinned

gateUp added gamma(depth) times a magnitude on top of an epilogue line that
already carries both sums' error inside dg and du. That line was a second
count of the same error: on the fixture's term magnitudes it made the
allowance a median 11 percent looser at the served width (50 percent on some
outputs), 2 percent at k 640 and under 1 percent at k 256 and below. It is
removed, and the up's line is (s + d dg) du, so the cross term of the gate's
and the up's errors is covered by name. The allowance is now the epilogue's
worst case term for term: at the served width it is 1.05 to 1.09 times the
generic bound by median for a gate above 1 (the up sum's error through silu,
which the generic magnitude never had) and smaller for a gate below 0.

Three host tests pin what no device run moves: a stated gate (g -10.53,
u -28.75, exact sums) lands the epilogue at 2.15 times boundExact and at 0.66
of the derived allowance, and the gate's bf16 rounding alone past boundExact;
the exact-sum allowance is 4.039307 u on every stress sum of the form, so
63.38 is the most provable bf16 margin and 100 is past it; and the planted
faults are outside the allowance on seeded draws.

Gate 4's margin text states that exact-sum allowance (4.0393 u, 63.4x) where
it rounded it up to 4.1 u.
…lar model, and the allowances derived

The gate/up form's allowance is derived and gate 4's bf16 margin for the form
is 60, so the form carries controls that must go red under both. The controls
image's tf_ctl_int4_swiglu is the form as one thread an output and a block row
a pair. At fault 0 it is fn_int4.cu's epilogue on fp32 sums, registered as a
kernel: it passes gates 1 to 4, so a control's red is its fault alone. At fault
1 it takes silu of the up sum times the gate sum, and at fault 2 it cuts gate,
up and silu toward zero where the kernel rounds to nearest; both are red at
gate 3. At fault 3 it rounds each group's sums to bf16, red at gate 4. The cut
control is one rounding mode from the kernel: its four errors all shrink the
output, each by up to twice the unit the allowance grants that rounding.

docs/int4-contract-allowances.md derives the allowance term by term from the
kernel's arithmetic, names the generic bound's two gaps with a stated gate,
and derives gate 4's ceiling: a bf16 sum that returns 0 misses by want itself,
which is 1 / (4.0393 u) = 63.38 times the exact-sum allowance, so 100 asks for
a miss larger than the output and 60 is the largest multiple of 10 under it.
Each control's fault is derived there too. The contract's page lists the verb's
suite, the model and the five controls, and links the derivation.
@BadAd84

BadAd84 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the re-cut! I have read the head at d1d763ca0 against the tree, and this note answers the one question in your last review: whether the gate/up allowance and gate 4's margin come from the arithmetic, and whether a control still goes red under them.

The head already carries the kernel and its launches (fn_int4.cu, zig/src/cuda/int4.zig, the 21 records in int4_records.zig), the per-output allowance and the 60 margin (int4_ref.zig, and the registration's why in contract_int4.zig), the skipped-slot check over rows, the unshuffled head as a gate 3 control, the common cp_async and qmm_frag forms (b8a50f26b), and the two serving pins (gradient-serving.tsv: kernels.zig 654168cb..., root.zig 9eee99ac...).

On top of that head I have one branch, three commits, local only. It keeps to the bound question.

The allowance stops counting the sums' error twice. dg and du already carry it, and the extra gamma(depth) magnitude made the line looser without covering an output the terms do not. The up's line is (s + d dg) du, so the cross term of the gate's and the up's errors is named rather than dropped. At exact sums the two lines meet within 0.1 percent; where the sums have error, the branch is tighter.

Gate 4's margin is derived. On the stress sums the exact-sum allowance is 4.039307 u, so a bf16 sum that returns 0 misses by 1 / (4.039307 u) = 63.38 times the allowance. The head's 62 sits under that ceiling and the registration's 60 stays; 100 would ask for a miss of 1.58 times the output. A host test in the branch holds the ratio inside 60 to 64 across the stress sums; I measure 63.377 on every one, with 60 at 0.947 of the output.

The gate/up form now carries controls that must go red under that allowance. tf_ctl_int4_swiglu is the form as one thread an output. Fault 0 is the kernel's epilogue on fp32 sums, registered as a kernel, and it passes gates 1 to 4. Swapped gate and up goes red at gate 3. Gate, up and silu cut toward zero goes red at gate 3, one rounding mode from the kernel. Each group's sum rounded to bf16 goes red at gate 4. With the two existing controls the suite has five.

docs/int4-contract-allowances.md derives the allowance term by term and each control's fault from the kernel's arithmetic. The same branch adds the int4-contract verb, its build step and its usage line from the earlier review, so the suite runs alone.

The prompt-down BF16 gate coverage and the dense wrapper narrowing from the earlier review are not in this head, and this branch keeps to the bound question. I am not claiming them here.

The arithmetic and its host tests are in the branch. The compile, host and device lines are queued with the GPU window, so I am not quoting a summary or a control line yet. I will post the SUMMARY line and each control's line when the window lands.

@BadAd84

BadAd84 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Both limits follow from the kernel's arithmetic, and neither needed the failing run.

The full derivation is on the branch now: docs/int4-contract-allowances.md. This comment is the short form, then the 1.04, the controls and the new receipt.

Head is 3afd83b5558e57bc341eb069c4bf1af041662d48, 3 commits on top of your d1d763ca0. It is on BadAd84/TensorFold as int4-tolerance.

The gate/up allowance

The kernel rounds the gate sum, the up sum and silu to bf16 before the store. An output's allowance is the worst case of that arithmetic, term by term:

  • both fp32 sums' error, gamma(depth) at the registered depth, each counted once;
  • the gate's bf16 rounding, u |g|, carried through silu's slope and multiplied by the up value;
  • silu's rounding and the up's rounding, each at its own size;
  • expf's 2 ulps, 3 more fp32 operations, and the store's rounding.

The constants are 2^-8, 2^-24, 2^-133, the depth, and the accuracy CUDA states for expf. Nothing else is in the formula, and nothing in it changes with a run.

The generic bound is not a bound for this epilogue. It counts the 3 roundings at the output's size, but the gate is rounded at the gate's size, and that rounding reaches the output as u |g| |silu'(g)| |u|. That is u |want| |1 + g (1 - sigmoid(g))|: about |g| - 1 for a negative gate. The generic magnitude also had no term for the up sum's fp32 error carried by silu(g).

With exact sums and no device, at g = -10.53 and u = -28.75, the gate's rounding alone puts the output at 1.76x boundExact, and the whole epilogue at 2.15x it. That is a host test now (int4_ref.zig).

Where the generic bound was sound, the allowance matches it. For a gate above 1 it is 1.05 to 1.09x the generic bound at the served width, all of it the up sum's error. For a negative gate it is smaller, by orders of magnitude at the served width.

1 correction to the allowance commit, in the stricter direction. Its gateUp carried a gamma(depth) times a magnitude line on top of the terms above. That was a second count of the sums' error, which already sits inside dg and du. It is gone. The bound is now tighter by a median 11 percent at the served width, and under 1 percent at k = 256 and below. On the device the kernel's worst output is 0.862 of it.

The 1.04

It is the generic bound meeting 1 output. It is not the kernel.

The first commit's tree, rerun with only the verb's dispatch added, prints the same line:

FAIL shapes cuda int4 routed gate/up SwiGLU (int4_kernel, 64-pair items): at 64x640x128 output 86809 is -1.250000e0 where float64 gives -1.225090e0: 1.04 of its bound

That output has g = -4.1090167 and u = 18.451357. bf(g) is -4.09375: the gate was rounded up by 0.0152667, 98 percent of a half ulp, and silu(bf(g)) u by itself is already 0.579 of the old bound. The other 3 roundings supplied the rest. The old bound gave that output 0.024035 and the error is 0.024910. The derived allowance gives it 0.029703, and the error is 0.839 of that.

With the first commit's bound back in force over the whole suite, that is the only output over it: 1 of 2,296,320 across the 20 shapes of the 2 gate/up kernels. Under the derived allowance none is.

It showed at 64 x 640 x 128 and nowhere else for 2 reasons:

  • At k = 128 the generic bound's absolute term is about 100x smaller than at the served width, so it no longer covers the gap.
  • The gap only shows when the roundings agree in direction. In a host replay of that shape's term distribution, 1 output in a million goes over the old bound. The shape holds 245,760 outputs.

The kernel's bytes are its epilogue. The epilogue evaluated in float64 at float64's own sums gives the kernel's exact bytes on all 245,760 outputs of that shape, and on 499,190 of the 499,200 outputs of the two kernels at k = 128 and 256. At the served width it matches on 98.7 percent. The scalar model, with its sums in another order, departs from the same float64 epilogue on the same 1.3 percent, so that difference is the fp32 sums against float64's, which the gamma term covers.

The epilogue's scalar model, a different summation with the same roundings, passes gate 3 on every shape with a worst of 0.803 of the allowance. It is inside the first commit's bound on every shape as well:

PASS shapes cuda int4 routed gate/up SwiGLU (the epilogue's scalar model, int4_controls): 10 shapes within the float64 bound (worst 0.803 of the bound), 0 edges refused by the kernel

Gate 4's bf16 margin

On the stress rows the exact-sum allowance for this epilogue is 4.039307 u times the output: the 3 roundings, the store and the fp32 operations. A host test checks that on every stress sum of the form.

A bf16 sum that returns 0 misses by the output itself, which is 1 / (4.039307 u) = 63.38 times the allowance. A mirrored row makes the halves order return 0: the 2 halves round alike with opposite signs and cancel, except where a rounding boundary falls between them.

So 63.38 is the most any mirrored input can prove of a bf16 SwiGLU output, and 100 asks for a miss of 1.57x the output. The device prints 63x under this allowance, and printed 63.812 under the first commit's boundExact: the same ceiling either way. 60 is the largest multiple of 10 under it. experts_bf16.cu's relu^2 up registers 30 under its own 85 in the same way.

Controls

All 4 new entries are the gate/up form as 1 scalar kernel in the controls image, tf_ctl_int4_swiglu, selected by a fault argument.

  • Fault 0 is the kernel's epilogue on fp32 sums, registered as a kernel. It passes gates 1 to 4, so a control's red is its fault alone.
  • Gate and up swapped is red at gate 3, at the first output of the first served shape: at 1x640x2560 output 0 is 3.204346e-4 where float64 gives 1.725688e-11: 102507139.43 of its bound
  • Gate, up and silu cut toward zero, where the kernel rounds to nearest, is red at gate 3: at 1x640x2560 output 19 is -1.181398e-26 where float64 gives -7.923346e-27: 1.24 of its bound. This one is a rounding mode away from the kernel. Its errors all shrink the output, each by up to twice what the allowance grants that rounding. It is outside the allowance on 315 outputs at k = 128 and 256, and on 13,103 of 447,744 at the served width.
  • Each group's sums rounded to bf16 is red at gate 4: 26561.5x over its exact-sum bound at k 2560: not fp32 sums (fp16 would miss infx, bf16 63x)

Both gate 3 controls cross the first commit's bound as well. With that bound in force the cut epilogue is outside it on 156 outputs at k = 128 and 256 and 794 at the served width, and the swap on 6,015 and 255,395. So they were red before the allowance was derived, and are red under the tighter one now.

The 2 earlier controls are unchanged: 1103940812.8x over its exact-sum bound at k 640 for the down with bf16 group sums, and 1301.67 of its bound for the unshuffled head.

Receipt

zig build int4-contract -Dnvcc=/usr/local/cuda/bin/nvcc on a GB10 (sm_121), driver 580.178.04, CUDA 13.3, Zig 0.17.0, from a fresh extract of the head checked against its git ls-tree (13,500 files, 0 mismatches), exit 0, Build Summary: 185/185 steps succeeded:

SUMMARY int4: 8 kernels, 8 pass gates 1-4, 0 fail, 0 known findings; 5 controls: 5 red as planted, 0 missed
PASS shapes cuda int4 routed gate/up SwiGLU (int4_kernel, 16-pair items): 10 shapes within the float64 bound (worst 0.827 of the bound), 0 edges refused by the kernel
PASS shapes cuda int4 routed gate/up SwiGLU (int4_kernel, 64-pair items): 10 shapes within the float64 bound (worst 0.862 of the bound), 0 edges refused by the kernel
PASS sums cuda int4 routed gate/up SwiGLU (int4_kernel, 16-pair items): exact sums at k 2560, where fp16 sums would miss by infx and bf16 by 63x
CONTROL control: int4 routed down with each group's sum rounded to bf16: red at sums, as planted
CONTROL control: int4 lm head with each word's nibbles unshuffled: red at shapes, as planted
CONTROL control: int4 routed gate/up with silu of the up sum times the gate sum (gate and up swapped): red at shapes, as planted
CONTROL control: int4 routed gate/up with gate, up and silu cut toward zero to bf16: red at shapes, as planted
CONTROL control: int4 routed gate/up with each group's sums rounded to bf16: red at sums, as planted

int4-contract is a committed verb now, with its build step and usage line (the 4th point of your first review). The host gates on x86_64, 16 threads, Zig 0.17.0, nvcc 13.3.73:

gate result
tree manifests base files 13490 mismatches 0 extras 0, head files 13500 mismatches 0 extras 0
zig fmt --check build.zig zig exit 0
lean, base against head, each tree's own checker lean: 165 problems, 165 on the base, 0 new (base 7697 files, head 7706)
test-int4-host 6/6 steps succeeded. This run served both test runs from the build cache and prints no count; run in full on the same test sources they read 36/36 tests passed
test-kernel-contract -Dfixed-cpu 41/41 steps succeeded; 246/246 tests passed (the tests this run executed; the rest were cache hits)
compile-cuda-tests -Dnvcc 184/184 steps succeeded
compile-cuda-tests -Dnvcc -Dtarget=aarch64-linux-gnu 184/184 steps succeeded
fatbins kernel-contract-fatbins -Dsm=80,86,89,120,121 compile-cuda-tests 365/365 steps succeeded
fn_int4.fatbin 4,154,648 bytes, sha256 1e2b5ee6c0bce3b297168e000449b61cb1047d826d3b5375195945c3085901c0: the image the PR body names, unchanged by these commits

The whole run's verdict is PASS. The limits audit did not run on that machine: the runner refuses its sm_61 card before it audits.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @BadAd84. The negative-gate example explains why the generic bound can reject this epilogue, and the stress arithmetic supports a margin near 63× rather than 100×.

I reviewed d1d763ca0; the three commits at 3afd83b described in your reply are not on this PR yet (its head is still d1d763ca0), so please push them. That tree still counts the sum error twice and has only the two linear controls, so I cannot yet confirm the corrected formula and new SwiGLU controls. Please retain the complete summary and every control result with the updated head.

The earlier BF16 prompt-down byte comparison and dense-FP32 coverage or wrapper narrowing also remain open. The focused entrypoint is absent from the reviewed tree. The kernel preserves the stored codes and scale bits, and no serving caller selects it yet. The disclosed recipe import also needs a provenance decision before landing.

  • Synthena

@joshuaswarren

Copy link
Copy Markdown
Contributor

5060 Ti (sm_120) kernel-contract int4 on head d1d763c — built off-card on aarch64 Spark (nvcc 13.0, zig baseline aarch64). Two findings:

1. The suite is unreachable by filter. tf-cuda-test kernel-contract int4 selects 0 gate kernels: the cuda int4 … specs live in contract_int4.zig, which is only called from contract_after.zig's suites() — and contract_finish.zig runs after-suites only when only.len == 0 (a full unfiltered run). There is no int4-contract command either. Every other recent family row wires its specs into the filtered registry or a named -contract command; as written, per-PR review can only exercise these gates inside a full contract run. If that's intentional it deserves a note in the checks section.

2. Every launch record is a placeholder. int4_records.zig registers all 21 fn_int4 instantiations with registry.none ("each unmeasured until a compiler receipt fills its usage"; the referenced pending_133.zig isn't in the tree). On sm_120 all 21 fail limits with recorded 0,0. The launches themselves are inside driver limits — measured values from the run for whoever fills the records:

  • fn_int4 prompt gate-up SwiGLU: 256 threads (allows 256), 230 regs, 512 + 99840 B shared
  • fn_int4 prompt down bf16/fp32: 256 threads, 128 regs, 512 + 49664 B shared
  • fn_int4 down fp32 nt 2/4 mt 2 and down bf16 nt 2/4 mt 2: 128 threads, at the 255-reg ceiling
  • fn_int4 down bf16 nt 1 mt 1: 126 regs; nt 2 mt 1: 146; nt 4 mt 1: 166; nt 1 mt 2: 189

rc=1 is the limit-problem exit; no gate spec was exercised by this filter.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @BadAd84 for the arithmetic explanation, and @joshuaswarren for the focused check. The PR still has the older head, so the corrected formula, new SwiGLU controls and standalone entrypoint remain unreviewable until those commits are pushed. BF16 prompt-down comparison and dense-FP32 coverage or wrapper narrowing remain open too. Please retain the complete summary and every control result with the updated head.

The filtered command does skip int4 correctness checks. One distinction on the limits result: this tree has all 21 nvcc 13.3 overrides in pending_133.zig; the reported nvcc 13.0 build remains unmeasured. Records must match the compiler used.

The stored GPTQ build is fine as loaded, but error bounds do not replace bit-exact serial arithmetic and byte comparisons. The disclosed recipe import still needs a provenance decision. Integration conflicts are mechanical and remain on our side.

  • Synthena

… reach the filter

Every fn_int4 record now holds the usage nvcc 13.0.88 measured on sm_80, sm_86,
sm_89, sm_120 and sm_121: registers and static shared bytes from ptxas -v, the
launch bound from each cubin's EIATTR_MAX_THREADS. The 12 launches nvcc 13.3.73
compiles differently carry that compiler's values as the 13.3 set, and the
duplicate receipts leave pending_133, so gate 5 has a measurement on every
recorded SM instead of five "no compiled usage recorded" findings a launch.

The int4 gate registrations join kernel-contract's filtered list, so
kernel-contract int4 selects them; the plan's skipped-slot check and the suite
verb move to contract_int4_run.zig, which keeps contract_int4.zig under the
600-line rule. Two coverage entries are new: the bf16 prompt down against the
paired form's bytes, and the LM head to fp32, the two paths the review named.
The split moved the skipped slot's check into contract_int4_run.zig, which
reads grouped, the spec alias and the suite's dims and width; name them
there and publish the two shapes from contract_int4.zig, so the runner
compiles again.
The file split moved the suite verb to contract_int4_run.zig but left two
references on the old names, so the runner did not compile:

  zig/tests/cuda/main.zig:331: error: root source file struct 'contract_int4' has no member named 'run'
  zig/tests/cuda/contract_int4_run.zig:62: error: 'launch' is not marked 'pub'

main.zig's int4-contract dispatch now imports the run file, and Fixture.launch
is pub because the skipped-slot check calls it from that file.
@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @BadAd84. The corrected allowance, derivation, nonlinear controls, BF16 prompt-down comparison and dense FP32 case are now present. The compiler-specific records and filtered registration are present too.

The runner split has two compile blockers: the dispatcher still calls run in contract_int4.zig, while it moved to contract_int4_run.zig; the skipped-slot check also calls the fixture's private launch across files. Please fix those references and retain the full summary and every control result for the updated head. Error bounds still do not replace the required byte comparisons.

One question on provenance: the notice says fn_int4.cu comes from MiaAI-Lab's dual-Spark recipe patch. We take code written for TensorFold, not code derived from another engine's or library's kernels, even with a license. Was that kernel written from scratch for the recipe, or adapted from another project's int4 kernel? The mechanical integration conflicts stay on our side.

  • Synthena

@BadAd84

BadAd84 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

On provenance: fn_int4.cu was written for the recipe, not adapted from another project's kernel. The evidence is in the recipe's own conventions rather than in an absence.

  • MiaAI-Lab's patches/0002-kernels.patch at 04f2b53826 creates the file. Every kernel in that patch that was copied from TensorFold's Python engine says so in its own header and names the source file, and zig/tests/cuda/copies.py keeps that list (fn_gdn*, fn_nvfp4_experts, fn_qmm*, fn_qmmf). fn_int4.cu says the opposite on line 3, Ours (TensorFold Zig engine, no Python counterpart), and no copies.py entry names it. The other kernels that patch writes new say (ours; work/research/R*.md ...) or written anew in CUDA C++.
  • The recipe's CREDITS.md credits no kernel project, and the file carries no upstream attribution line, where every derivative we compared carries one (Marlin's own file, vLLM's marlin.cu and q_gemm.cu).
  • We compared it against the candidates directly. It shares no distinctive identifier, mnemonic, constant or comment line with Marlin, vLLM's marlin or GPTQ paths, or llama.cpp's mmq: its distinctive matmul constants 0x000F000F, 0x43004300 and 0x43084308 appear in none of them, its nibble permutation differs from vLLM's, its structure differs (its int4_kernel with Stage, Words, load_stage and compute_stage against Marlin's Marlin<...> with Vec, FragA, ldsm4 and lop3), and so does the accumulator type, bf16 against Marlin's f16.

So the kernel is MiaAI-Lab's file, as the notice says: Apache-2.0, Copyright 2026 MiaAI-Lab, with three of our changes marked in it and recorded. If that separation is not enough for you, we will rewrite it from TensorFold's own specification with the reference closed: a machine that has never held this tree, an agent given the GPTQ group-128 format, the required shapes and the exactness gates and nothing else, and the result arrives as a new commit for review.

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thanks @BadAd84. Both runner references are fixed, and the corrected allowance, nonlinear controls, BF16 prompt-down and dense FP32 cases remain present. Your explanation also answers the origin question; please keep the attribution.

Before landing, we still need the complete updated-head gate summary and every control result, including the BF16 prompt-down byte comparison. Error bounds do not replace those exact comparisons. The main integration conflicts remain ours.

  • Synthena

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants