Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- CUDA: an int4 W4A16 kernel serves GPTQ group-128 routed experts and the LM head (#4183). Thanks @BadAd84.

- Flash Next on CUDA, TP=2: plain decode stages its inputs before graph capture and before every replay, and frees its decode graph before aborting the NCCL communicator (fixes #2974).

- Internal: thirty more settings read through the environment registry with the same accepted values; the lean count drops from 123 to 93 (#5188).
Expand Down
13 changes: 13 additions & 0 deletions THIRD_PARTY_NOTICES.md
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,19 @@ recipe commit e1f564eb915bb5272474b6c1c527aec3b9ed3de6. It credits TensorFold Co
arithmetic and staging design. Copyright (c) 2026 MiaAI-Lab and Copyright (c) 2026 TensorFold contributors.
The complete original MIT notices and permission text are retained in [Mia-FlashNext-MIT.txt](LICENSES/Mia-FlashNext-MIT.txt).

## MiaAI-Lab Flash Next int4 kernel

`zig/kernels/cuda/fn_int4.cu` is the `fn_int4.cu` that patch 0002 of
[MiaAI-Lab's dual-Spark recipe](https://github.com/MiaAI-Lab/Qwen3.8-Flash-Dual-DGX-Sparks-TensorFold) creates, at
recipe commit `04f2b53826dca9a52893f2bce9d49bb3d1828e88`, under the Apache License 2.0, Copyright 2026 MiaAI-Lab.
That recipe's NOTICE reads "Qwen3.8-Flash-Next on 2x DGX Spark with TensorFold / Copyright 2026 MiaAI-Lab" and asks a
redistributor to keep it and to state what changed, which this section and the file's own header do. The license text
is [Apache-2.0.txt](LICENSES/Apache-2.0.txt). TensorFold's three changes: the head's dense items hold 16 MT rows rather
than 16, one more `int4_prompt_kernel` instantiation builds for the routed gate/up (both marked `TF:` in the file), 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 groups-of-64 instantiations a two-rank serve would
need are not built. The host packer and the launchers in `zig/src/cuda/int4.zig` are TensorFold's.

## Ling-3.0-tiny and Ling-3.1-flash

Ling-3.0-tiny and Ling-3.1-flash are MIT licensed by inclusionAI. The host family package
Expand Down
128 changes: 128 additions & 0 deletions docs/int4-contract-allowances.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# int4 contract allowances

`fn_int4.cu`'s gate/up form rounds its gate sum, its up sum and silu to bf16 before the store, and the kernel contract
compares each output with float64, so those roundings need an allowance. This page derives that allowance, and gate
4's bf16 margin for the same form, from the kernel's arithmetic alone. Every constant below is a format constant, a
property of the reduction, or the accuracy the CUDA library states for `expf`. No number here comes from a device
run, and none changes with one: the device lines in the pull request are receipts of this arithmetic, not inputs to it.

The contract's rule for every allowance is the same: it is the worst case of the arithmetic the kernel performs,
written before any output is compared with it. Where the worst case of a stated form differs from the generic formula
in `contract.zig`, the registration derives its own (`VTable.bounds`), and this page is that derivation.

## What one gate/up output computes

Source: `zig/kernels/cuda/fn_int4.cu`, `pair`, `compute_stage` and `store` with `EPI` 2.

- A stored code `q` (0 to 15) enters a bf16 MMA as `128 + q`, and `136` is subtracted in bf16. Both are exact and
leave `q - 8`. A product `x (q - 8)` has at most 12 significant bits, so fp32 holds it exactly.
- A group of 128 inputs is four k32 blocks in order, each two k16 MMA steps in order, each step `D = A B + D`; then
`acc = fmaf(group sum, scale, acc)` with the fp16 scale widened exactly. The longest chain of roundings a term
passes is `k / 16 + k / 128 + 36`: one MMA step an input's 16 products, one fma a group, and one step's error over
its own products (`attention_range.mma_step`, the count every CUDA expert registers).
- The epilogue, with `u_b = 2^-8` for bf16's unit roundoff: `gv = bf(g)`, `uv = bf(u)`,
`act = gv / (1 + expf(-gv))` in fp32, `s = bf(act)`, `p = s uv` in fp32, `out = bf(p)`.
- The reference is `want = silu(g*) u*` with `silu(x) = x / (1 + exp(-x))` in float64 and `g*`, `u*` its sums.

With `v = 2^-24` and `gamma(n) = n v / (1 - n v)`, the fp32 sums satisfy `|g - g*| <= gamma(depth) A_g` and
`|u - u*| <= gamma(depth) A_u`, where `A_g`, `A_u` are the sums of the terms' magnitudes.

## The allowance, term by term

`zig/tests/cuda/int4_ref.zig` `gateUp`. Each line says which rounding it bounds; `s = |silu(g*)|`.

| term | bounds |
|---|---|
| `dg = u_b \|g*\| + gamma(depth) A_g (1 + u_b)` | `\|bf(g) - g*\|`: the sum's error, then bf16's rounding of the value it landed on |
| `du` | the same for the up sum |
| `d = max \|silu'\|` on `[g* - dg, g* + dg]` | the slope: at the interval's ends and at its turning points, `+-2.3993572805` |
| `span = \|u*\| + du` | the largest up value the rounded silu meets |
| `d dg span` | the gate's fp32 error and its bf16 rounding, through the slope and times the up value |
| `u_b s span` | silu's bf16 rounding, at silu's own size |
| `(s + d dg) du` | the up sum's fp32 error and its bf16 rounding, times silu |
| `(1 + 2 u_b)` on the three lines above | those roundings evaluated at `s + d dg` rather than `s`, and the fp32 operations |
| `+ (s + d dg) span` where `g - dg < -88` | `expf` overflows fp32 above 88.72: the kernel's silu is 0 where float64 keeps a value |
| `5 v \|want\|` | `expf` (2 ulps, the CUDA library's bound), `1 + e`, the quotient, the product |
| `+ u_b (\|want\| + work)` | the store's bf16 rounding of a value already `work` from `want` |
| `+ 2^-133` | bf16's smallest step near zero (`outFloor`) |

Why the epilogue lines cover their roundings: `act` is within `5 v` of `silu(gv)` in relative terms, so `s` is within
`(u_b + 5 v) (s + d dg)` of `silu(g*)` once the gate's own `d dg` is counted, and `(d dg + u_b s) (1 + 2 u_b)` is
larger than `d dg + (u_b + 5 v) (s + d dg)` because `u_b d dg + 2 u_b^2 s` exceeds the `5 v` terms. The product of
two bf16 values is exact in fp32, so the product's rounding is counted and never spent. Each sum's error is counted
once: inside `dg` and `du`, where it enters.

## Why the generic bound is no bound for this epilogue

`contract.zig` `bound` counts the roundings between the sums and the store at the output's size: `mids u_b |want|`.
That is right when the rounded value has the output's size. The gate has not: the kernel rounds `g`, and that
rounding reaches the output as `u_b |g| |silu'(g)| |u|`, which is `u_b |want| |1 + g (1 - sigmoid(g))|`. The factor
is at most 1.1 for a positive gate and about `|g| - 1` for a negative one: 1.86 at `g = -3`, 9.5 at `g = -10.5`. So
for every gate below about `-2.2` the generic bound is short of the epilogue's own worst case by
`(factor - 1) u_b |want|`, before any sum error is considered. It also has no term for the up sum's fp32 error
carried by `silu(g)`, `gamma(depth) A_u |silu(g*)|`.

One stated gate shows the first gap with exact sums and no device (a host test in `int4_ref.zig`): at `g = -10.53`,
`u = -28.75`, `bf(g)` is `-10.5`, and that one rounding moves the output to 1.76 times `boundExact`; the whole
epilogue lands at 2.15 times it, and at 0.66 of the derived allowance.

The generic bound's absolute term, `gamma(depth) A_g (|u| + 1)`, hides the gap at the served width, where it is larger
than everything else. At the least `k` it is about 100 times smaller and the gap is the whole story. The gap needs the
roundings to agree in direction, so the form passes the generic bound on most shapes and fails it on one that holds
enough outputs: a bound that sometimes holds is not a bound.

The derived allowance holds on every output by construction, and it is the generic bound wherever the generic bound
was right. For a gate above 1 it is 1.05 to 1.09 times the generic bound at the served width: the up sum's error
through `silu(g)`, and nothing else. For a gate below 0 it is smaller, down to orders of magnitude smaller for a
strongly negative gate, whose output is tiny while the generic term still grows with `A_g |u|`.

## Gate 4's bf16 margin

Gate 4 replays each stress row's sums in fp16 and bf16 and requires each to miss by at least the registered factor
times the exact-sum allowance, so that a kernel summing in that precision cannot pass. The default factor is 100.

On the stress rows a gate sum and an up sum are 4 times eight codes of 1 to 3: 32 to 96, with `d = 1` and exact sums.
The allowance at `exact` is `((1 + u_b) (3 + 4 u_b) u_b + 5 v) (1 + u_b) + u_b` times `|want|`, which is
`4.039307 u_b |want|`. A low-precision sum that returns 0 misses by `|want|` itself, which is
`1 / (4.039307 u_b) = 63.38` times the allowance. That is the most any input can prove of a bf16 SwiGLU output whose
low-precision sum is 0, and a mirrored row makes it 0: in the halves order the two halves of the row are rounded
alike with opposite signs, so they cancel and the bf16 sum is 0 unless a rounding boundary falls between them, where
it is one bf16 spacing. An output misses by more than `|want|` only when both of its sums keep such a residual.
100 asks for a miss of `1.57 |want|`, which no sum returning 0 makes. fp16 overflows on these rows, where the partial
sums reach `5.6e6`, so its 100 holds.

The registration states 60, the largest multiple of 10 under the 63.38 ceiling, leaving 5 percent for the constants
above. The same registration shape is the relu^2 up of `experts_bf16.cu`, whose three bf16 roundings allow `3 u_b`
and whose stated 30 sits under its own ceiling of 85. The generic `boundExact` gives 63.81 on the same rows, so the
margin did not move with the allowance: it was 100 against a ceiling near 64 before the allowance was derived.

The stress rows themselves are integers from 8 to 2,040 with the eight nudged inputs at 4 to 16. Every partial sum
stays below `2^24`, so fp32 is exact in any order, and the larger the integers the further the fp16 and bf16 chains
land from the small result.

## The controls

The gates must still go red under this allowance, and they do, by arithmetic first:

- `tf_ctl_int4_swiglu` at fault 0 is the epilogue's scalar model: the same group sums in input order and the same
epilogue, registered as a kernel. It passes gates 1 to 4, so the faults below are the only difference between it
and the controls.
- Fault 1 takes silu of the up sum times the gate sum (gate and up swapped). Silu is not symmetric: where the gate
is negative its silu is tiny, and the swapped output is the up sum's silu times a gate of full size.
- Fault 2 cuts gate, up and silu toward zero where the kernel rounds to nearest: one rounding mode away from the
kernel. Its four errors all shrink the output's magnitude, each by up to twice the unit the allowance grants that
rounding, so on a shape of any size some outputs are outside the allowance. The first served shape holds 3,840.
- Fault 3 rounds each group's sums to bf16 before their scales (gate 4): the group sums of a stress row reach
`2.5e5`, where one bf16 rounding is hundreds, against an exact-sum allowance near 65.

Both gate 3 controls are outside the generic bound of the kernel's first commit too, so they were red before the
allowance was derived and stay red after it.

## What pins it on the host

`zig build test-int4-host` runs `int4_ref.zig`'s tests with no device:

- the derived allowance covers 4,000 epilogue draws, and the generic `boundExact` is short on some of them;
- the stated gate above: outside the generic bound twice over, inside the derived allowance;
- gate 4's ceiling on every stress sum of the form: between 60 and 64, and under 64 with the generic `boundExact` too;
- the planted faults outside the allowance on 4,000 seeded draws: the cut epilogue on some, the swap on most.
33 changes: 26 additions & 7 deletions docs/kernel-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,10 @@ and gate 5. `zig build tf-kernel-contract` builds the program alone; `--only TEX
TEXT, `--offline DIR` adds the M1/M2 compiles, and `--repro` prints the smallest input behind each known finding.

On a CUDA machine, build with `-Dnvcc` (the controls are compiled only then), and run `zig build kernel-contract
-Dnvcc=/usr/local/cuda/bin/nvcc`. For the limits of every SM, `zig build fatbins kernel-contract-fatbins -Dnvcc=...
-Dnvcc=/usr/local/cuda/bin/nvcc`. A family's suite alone runs as `zig build int4-contract -Dnvcc=...` (the GPTQ int4
experts and head, its `SUMMARY` line and each control) or as `tf-cuda-test int4-contract` on a built runner; its gate
registrations are in the filtered list too, so `tf-cuda-test kernel-contract int4` selects them without the suite's
skipped-slot check. For the limits of every SM, `zig build fatbins kernel-contract-fatbins -Dnvcc=...
-Dsm=80,86,89,120,121`, then `tf-cuda-test kernel-contract-limits zig-out/fatbin`. Its `RECORD` lines are the values
`registry.zig` holds for that build's nvcc (see [CUDA records per nvcc release](#cuda-records-per-nvcc-release)).

Expand Down Expand Up @@ -617,6 +620,21 @@ CUDA also checks the affine-3 experts' split decode pair, bit-equal to the pair
one dropping a last round of K groups short of the warps, one chaining the groups in reverse).
CUDA also checks Flash Next's NVFP4 experts on prompt tiles with the decode form's sums (SwiGLU gate-up and fp32
down, each bit-equal to the decode instance it replaces; the scaled-code prompt tile is the planted control).
CUDA also checks Flash Next's GPTQ int4 experts and head (`fn_int4.cu`, `zig/tests/cuda/contract_int4.zig`) at the
checkpoint's widths: gate/up with SwiGLU, down to fp32 and bf16, the head's dense rows and the two prompt forms
bit-equal to the plain ones, each output against float64 at the weights `qweight` and the fp16 scales store. A gate/up
output's allowance is its epilogue's own worst case (`int4_ref.zig`; the arithmetic is in
[int4 contract allowances](int4-contract-allowances.md)): the two fp32 sums through silu's slope and the up value,
then bf(g), bf(u), bf(silu) and the store, each at its own value's size, and the silu 0 that expf's fp32 overflow
leaves where float64 keeps a denormal-sized value. Gate 4's bf16 proof of that epilogue stops at 1 / (4.0393 u) =
63.4x, because the halves of a mirrored row cancel and a bf16 sum misses by want itself, so the registration states
60. The epilogue's scalar model (`tf_ctl_int4_swiglu` at fault 0) passes the same gates. Five controls: a group sum
rounded to bf16 before its scale (gate 4, the down), each group's sums rounded to bf16 (gate 4, the gate/up), a head
whose words are packed unshuffled (gate 3), and on the gate/up silu of the up sum times the gate sum (gate 3) and
gate, up and silu cut toward zero (gate 3).
A plan whose shared expert's slot is skipped must leave those rows untouched. The 21 launches' usage is in
`int4_records.zig`: nvcc 13.0's from each SM's cubin, the release fatbins' compiler, and nvcc 13.3's where it differs
(the `cuda_133` set).
CUDA also checks the bf16 experts (`experts_bf16.cu`, a checkpoint's own bf16 weights: Nemotron 3.5 Transcribe's routed
and shared experts): relu^2 up, fp32 down and bf16 down, in the decode and prompt forms, against float64 (two controls:
the fp32 down launched one 32-input group short, and a down summing in bf16). nvcc 13.2's prompt forms and 13.3's
Expand Down Expand Up @@ -720,12 +738,13 @@ and FP32-output paths, FP8G's 32-row cluster tile with FP32 output, the common E
decode-sized latent top-k and NVFP4 up experts, the Mamba scan and Super's NVFP4 prompt down kernels, three of
GLM-5.3-Flash's packed matmuls and three of its DFlash2 launches, and the training launches it compiles differently,
and nvcc 13.3 keeps 13.2's and changes four of GLM-5.3-Flash's KV page launches, its two prompt-indexer launches,
its wide decode select and the span scan `tf_glm_dsel_scan`. `kernel-contract` and
`kernel-contract-limits` read the release from each image's `.note.nv.tkinfo`, check the image against the newest set
at or below that release (13.0's when an image names none), and print which set they used. A release with no set of
its own is checked against the one below it, so its differences show as stale records: re-derive them with
`kernel-contract-limits` and add a set for that release rather than loosening the audit. Launch dimensions, dynamic
shared memory, the device's limits and the planted controls are checked the same way under every release.
its wide decode select, the span scan `tf_glm_dsel_scan` and 12 of the GPTQ int4 launches' 21 instantiations.
`kernel-contract` and `kernel-contract-limits` read the release from each image's `.note.nv.tkinfo`, check the image
against the newest set at or below that release (13.0's when an image names none), and print which set they used.
A release with no set of its own is checked against the one below it, so its differences show as stale records:
re-derive them with `kernel-contract-limits` and add a set for that release rather than loosening the audit.
Launch dimensions, dynamic shared memory, the device's limits and the planted controls are checked the same way under
every release.

`-Dnative-fp-decode` (off by default; nvcc 13.2 or later) builds prompt16, qmmf and fp8_experts for `sm_<n>a` from
sm_120 on and decodes their FP4/FP8 weight pairs with PTX ISA 9.2's `cvt.rn.bf16x2.e2m1x2`/`.e4m3x2` (qmmf: FP4 only).
Expand Down
1 change: 1 addition & 0 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st
shard_tests.addImport("living", mods.living);
b.step("test-living-shards-host", "Quantized save and reopen through actual shard writer").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = shard_tests })).step);
@import("cuda_contract_host.zig").steps(b, host, cuda, mods, step);
@import("cuda_int4_host.zig").steps(b, host, cuda, mods.core);
const bolt = b.step("test-bolt-host", "Nemotron Bolt and shared lane host contracts");
const cuda_target = b.resolveTargetQuery(.{ .cpu_arch = host.result.cpu.arch, .os_tag = .linux, .abi = .gnu });
const check_cuda = runtime(b, cuda_target, .debug, &.{});
Expand Down
21 changes: 21 additions & 0 deletions zig/build/cuda_int4_host.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//! The GPTQ int4 host tests: the packer, the stored codes, the binary64 reference and the epilogue's allowance.
const std = @import("std");

/// `test-int4-host` over the cuda module's `int4:` tests and the contract's derived allowance, and `test-cuda-host`.
pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Module, core: *std.Build.Module) void {
const step = b.step("test-int4-host", "The GPTQ int4 packer, its stored codes and the binary64 reference (cuda/int4.zig)");
const run = b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"int4:"} }));
step.dependOn(&run.step);
const allow = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{
.root_source_file = b.path("zig/tests/cuda/int4_ref.zig"),
.target = host,
.optimize = .debug,
.link_libc = true,
.imports = &.{.{ .name = "core", .module = core }},
}) }));
step.dependOn(&allow.step);
if (b.top_level_steps.get("test-cuda-host")) |all| {
all.step.dependOn(&run.step);
all.step.dependOn(&allow.step);
}
}
1 change: 1 addition & 0 deletions zig/build/cuda_kernels.zig
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ pub const kernels = [_]Kernel{
.{ .name = "zonos3_codec", .flags = glue }, // ours: ZONOS3's codec decoder in fp32
.{ .name = "zonos3_encoder", .flags = glue }, // ours: ZONOS3's codec encoder front end in fp32
.{ .name = "zonos3_teacher", .flags = glue }, // ours: ZONOS3's SSL teacher's attention and convolution in fp32
.{ .name = "fn_int4", .flags = &.{"-O3"} }, // GPTQ int4 g128 routed experts and lm_head (fn_int4.cu)
};

/// torch.utils.cpp_extension's own nvcc flags (torch 2.13): C++20 and which half/bf16 operators the headers define.
Expand Down
Loading
Loading