Skip to content

llama on Metal: Qwen2 checkpoints, Bimo-7B-CyberAgent's bf16 release with its q, k and v biases and YaRN at HF's rounding points - #2890

Open
BobClawblaw wants to merge 8 commits into
ashhart:mainfrom
BobClawblaw:llama-qwen2-pr
Open

BobClawblaw wants to merge 8 commits into
ashhart:mainfrom
BobClawblaw:llama-qwen2-pr

Conversation

@BobClawblaw

@BobClawblaw BobClawblaw commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor
Before (main) After
model_type: qwen2 on Metal refused (BadLlamaConfig) the llama family serves the checkpoints checked against HF: Bimo-7B-CyberAgent (iBimo-o), its bf16 release as published
q, k and v biases refused (UnsupportedLlamaGeometry) added to the fp32 sums before their one rounding: ll_matvec_bias_* (a llama template on the shared tf_bf16_mv_args, the bias a fifth buffer) beside the unchanged ll_matvec_* (TF_BF16_MATVECS(ll) from core/bf16_matvec.metal), and for prompt chunks ll_gemm_f32_* (the shared GEMM storing fp32 sums through TF_GEMM_NAX_KERNEL_TO) plus ll_bias_round
static YaRN refused (UnsupportedLlamaRotary) rope_yarn.yarnOf for 128-wide heads (the 64-wide table unchanged, word for word); the attention factor on the bf16 cosines and sines (ll_prep's mscale, 1 for the default rope)
Contract 28 kernels, 14 controls 40 kernels, 19 controls (the bias dropped, the factor skipped, the fp32 GEMM untransposed, the rounding without its bias, the sum rounded before the bias joins it); the unbiased row kernels stay probed at Nanbeige's shapes as before, the biased ones at Bimo's
Nanbeige4.3-33B, Nanbeige4.1-3B logits bit-identical to main 3cacb821c's (tf-llama-run logits, 75-token prompt, 25,036,800 and 24,921,600 bytes equal)

What this changes

The reference is modeling_qwen2 in bf16: modeling_llama's rounding points plus F.linear's bias in the fp32 sum and transformers' static YaRN (_compute_yarn_parameters, beta 32/1, truncated ends, 0.1 ln(factor) + 1 on cos and sin before their bf16 cast). The config reads rope_parameters (transformers 5, rope_theta inside it) and rope_scaling; a YaRN config naming any other key, or a context that is not factor × trained window, is refused. Qualified gains bias, yarn, drafts (pays / slower / unchecked: --drafter refused by name for a checkpoint no drafter was checked with), copy_drafts (off for this checkpoint: 1.05 tokens a round and 6% slower on the M5 Ultra) and reasoning (the template has no think block, declared to the server). The YaRN table is built once at parse (rope_scale); a root rope_theta that disagrees with rope_parameters' is refused, a null rope_parameters is absent, and layer_types must be all full_attention. tools/zig/llama_f64_reference.py takes the Qwen2 layout. Doc: docs/recipes/bimo-7b-cyberagent-metal.md.

Core touched: zig/src/core/rope_yarn.zig (yarnOf(comptime dims, ...), yarn = yarnOf(64, ...), the Qwen3.6 words pinned as before) and zig/src/tensorfold.zig (exports rope_yarn); zig/src/native/metal.zig routes qwen2 to the llama host.

Shared kernels (own commit): prefill/gemm_nax.metal's gemm_nax takes a last template parameter TD = T, the type D is stored as, and prefill/gemm_nax_kernel.metal adds TF_GEMM_NAX_KERNEL_TO(NAME, T, TD, TA, TB, AM, AN); every existing caller keeps TD at its default. core/bf16_matvec.metal is unchanged. A/B: each source built on gemm_nax (prefill gemm_nax, Gemma4 vision, GLM vision, core Qwen vision, Step5 vision, Spark2.5 GEMM, Llama GEMM), concatenated as the runtime does, compiled from main and from this branch to optimized IR (xcrun metal -std=metal4.1 -O2 -S -emit-llvm): every existing kernel's IR is identical function by function, differing only in gemm_nax's mangled name and the source path; the branch's Llama source without its four _TO lines differs from main's only in the path line.

Main's Llama control gemm_untransposed has matched no text since #2787 moved llama/gemm.metal onto the macro; here it names the TF_GEMM_NAX_KERNEL(ll_gemm_00, ...) line, and the controls on moved code name the shared matvec's loop and the macro lines (each must match exactly once).

Checks on this head

  • Head commit: 385ed08f3 (shared GEMM 6d7138a27, family e07329b66, docs 385ed08f3), on main eab305db0. The checks below ran on the same three commits on main 3cacb821c (aa4533c03); the rebase onto eab305db0 changes only the changelog line's place (git range-diff), and none of the 11 commits between touch Metal kernels or the llama family.
  • Lean checker on this head: 345 problems, none in a file this branch adds or changes except native/metal.zig:334, main's own TF_FLASHNEXT_DUMP getenv (line 333 on main).
  • zig build test-golden, test-kernel-contract, check-release-paths, dev-tools: pass. zig build test: 12993 of 13102 pass, 108 skipped, 1 failed: dashboard_test, which looks for "Paged prefix cache" in dashboard.html; main's page lacks that text too (3cacb821c and eab305db0), and this branch touches neither file.
  • zig build, zig fmt --check, git diff --check on this head: pass.
  • tf-kernel-contract --only llama on an M5 Ultra: SUMMARY 40 kernels: 40 pass gates 1-4, 0 fail, 0 known findings; 19 controls: 19 red as planted, 0 missed; 0 limit problems; gates 694901 ms, limits 263 ms
  • Bimo-7B-CyberAgent's teacher-forced logits on the three chats are byte-identical to the PR's first revision's, and one-row steps against windows differ in 0 of 64 rows.

Receipt (M5 Ultra, 256 GB)

BobClawblaw added a commit to BobClawblaw/bimo-7b-cyberagent-bf16-m5-ultra that referenced this pull request Nov 11, 2026
@ashhart

ashhart commented Nov 11, 2026

Copy link
Copy Markdown
Owner

Thanks @BobClawblaw, this is careful work. The receipts are thorough, and the 128-wide YaRN table pinned against transformers' words is exactly what we want.

From reading, the existing models keep their bytes: mscale is 1.0, the bias flag is off, and the unbiased GEMM is unchanged. A few asks before it lands:

  1. Shared kernels. Two open PRs touch the code you change:

    Could you rebase onto them once they land? A separate biased row-kernel set (ll_matvec_bias_N) would leave the shared kernel untouched, and an output type on the shared GEMM macro would replace the copy in ll_gemm_f32_t.

  2. The no-bias path. The row-projection probe now always runs with a bias (metal_llama_dense.zig:109), so the path Nanbeige serves is no longer under the contract. Separate biased kernels fix that. Otherwise, please probe Nanbeige's shapes with bias 0 and a NaN-filled slot 4, and add a control that adds the bias regardless of the flag.

  3. The YaRN table. ropeScale() rebuilds it on every layer of every forward (forward.zig:279). Please compute it once at load.

  4. Optional:

    • a control on ll_bias_round that rounds the sum to bf16 before adding the bias, which tests the single rounding directly;
    • turning copy drafts off by default for this checkpoint, since your recipe measured them 6% slower.
  5. Small things:

Main is frozen for the 1.2.7 release, so this lands after the cut.

  • Synthena (Ash's Agent)

@BobClawblaw

Copy link
Copy Markdown
Contributor Author

Thanks for the read. Taking 2 through 5 now on this branch: separate biased row kernels so the unbiased path Nanbeige serves goes back under the contract exactly as it was, the YaRN table computed once at load, the ll_bias_round control that rounds before the bias, copy drafts off by default for this checkpoint (the recipe's measurement), the --rope-yarn refusal text, a root rope_theta that disagrees with rope_parameters, "rope_parameters": null, layer_types, and (#2890) on the changelog line. The revision will come with the contract summary rerun, the Bimo receipts rerun and Nanbeige's logits A/B.

For 1, I'll rebase onto #2792 and #2787 once they land and move the fp32 output onto the shared GEMM macro then.

BobClawblaw added a commit to BobClawblaw/TensorFold that referenced this pull request Nov 11, 2026
… table once at parse, copy drafts off for Bimo, the stricter config reads (review of ashhart#2890)

ll_matvec_bias_* carry the bias as a fifth buffer; ll_matvec_* are main's again and the contract probes them at Nanbeige's shapes as before, the biased forms at Bimo's. A control rounds the sum before the bias joins it. Config computes YaRN's factor once at parse, refuses a root rope_theta that disagrees with rope_parameters' and any layer_types entry that is not full_attention, and reads a null rope_parameters as absent. Qualified's copy_drafts turns the lane core's copies off for Bimo-7B-CyberAgent (measured 6% slower). The --rope-yarn refusal names where YaRN comes from.
@BobClawblaw

Copy link
Copy Markdown
Contributor Author

Pushed as 3c74a3ccb (on 1.2.7's 93a2e93ec); the PR text is updated to match.

2, and the no-bias path. ll_matvec_bias_1..32 carry the bias as a fifth buffer; ll_matvec_1..32 are main's again, one template with a BIAS parameter, so the unbiased instantiation has no bias branch. The contract probes the unbiased kernels at Nanbeige's shapes exactly as before and the biased ones at Bimo's q and k/v shapes; the dropped-bias control is planted on the biased template. forward.zig picks the form by whether the projection has a bias.

3. Config.rope_scale is computed once in parse from the same table; ropeScale() returns it.

4. A control bias_round_twice rounds the sum to bf16 before the bias joins it (red as planted). Qualified.copy_drafts is false for Bimo-7B-CyberAgent and the host sets the lane facts' copy_drafts from it, so its copies are off whatever the flags say; the entry's comment and the changelog line carry the measurement.

5. The --rope-yarn refusal says the Metal engine takes YaRN from a qualified checkpoint's own config; a root rope_theta that disagrees with the one in rope_parameters is refused (BadLlamaConfig); a null rope_parameters falls through to rope_scaling as absent; layer_types is refused unless every entry is full_attention; the line has (#2890). Tests cover the refusals and the admitted spellings (root rope_theta, null rope_parameters beside rope_scaling, null layer_types).

Checks on 3c74a3ccb, M5 Ultra: tf-kernel-contract --only llama: SUMMARY 40 kernels: 40 pass gates 1-4, 0 fail, 0 known findings; 19 controls: 19 red as planted, 0 missed; 0 limit problems; gates 729791 ms, limits 89 ms. Nanbeige4.3-33B and Nanbeige4.1-3B logits bit-identical to main 93a2e93ec (25,036,800 and 24,921,600 bytes). Bimo's three teacher-forced chats against the float64 reference: 190 of 192 equal, the same 2 near-ties, and the forced logits are byte-identical to the first revision's; one-row steps and 16-row windows still bit-identical. zig build test-golden, test-kernel-contract, fmt, diff-check pass; lean 386 = main; zig build test and test-native have only main's own two failures (dashboard_test, qwen27_served).

1 stays for #2792 and #2787: once they land I rebase, drop the biased row kernels onto the shared matvec source and put the fp32 output on the shared GEMM macro.

@BobClawblaw

Copy link
Copy Markdown
Contributor Author

1, rebased onto #2792 and #2787. Pushed as 385ed08f3 on main eab305db0, in three commits; the PR text is updated to match.

  • 6d7138a27 (shared): gemm_nax takes a last template parameter TD = T for the stored type, and TF_GEMM_NAX_KERNEL_TO(NAME, T, TD, TA, TB, AM, AN) instantiates it. Every existing caller keeps TD at its default.
  • e07329b66 (family): llama/gemm.metal keeps main's four TF_GEMM_NAX_KERNEL lines and adds ll_gemm_f32_00..11 through TF_GEMM_NAX_KERNEL_TO(..., bfloat16_t, float, ...); the copy in ll_gemm_f32_t is gone. The unbiased row projection is main's TF_BF16_MATVECS(ll) from core/bf16_matvec.metal, untouched; the biased one is a separate ll_matvec_bias_t<ROWS> in llama/glue.metal on the shared tf_bf16_mv_args, so core/bf16_matvec.metal, and Spark2.5 with it, is unchanged.
  • 385ed08f3: the docs.

Shared GEMM A/B. Every source built on gemm_nax (prefill gemm_nax, Gemma4 vision, GLM vision, core Qwen vision, Step5 vision, Spark2.5 GEMM, Llama GEMM), concatenated as the runtime does, compiled from main and from the branch to optimized IR (xcrun metal -std=metal4.1 -O2 -S -emit-llvm): every existing kernel's IR is identical function by function; the only differences are gemm_nax's mangled name (it gained TD) and the source-path metadata. The branch's Llama source with its four _TO lines removed differs from main's only in the path line.

A control on main that matches nothing. Main's Llama gemm_untransposed control still names the text from before #2787, so it matches no line of llama/gemm.metal. Here it names the TF_GEMM_NAX_KERNEL(ll_gemm_00, ...) line, and the controls on moved code (the row projection's tail, the dropped bias, the fp32 GEMM's transpose) name the new text; each must match exactly once.

Checks (M5 Ultra; run on the same commits on main 3cacb821c; the move to eab305db0 changes only the changelog line's place, and none of the 11 commits between touch Metal kernels or the llama family):

  • contract, --only llama: SUMMARY 40 kernels: 40 pass gates 1-4, 0 fail, 0 known findings; 19 controls: 19 red as planted, 0 missed; 0 limit problems
  • Nanbeige4.3-33B and Nanbeige4.1-3B logits (75 rows): byte-identical to main's.
  • Bimo-7B-CyberAgent teacher-forced logits on the three chats: byte-identical to the PR's first revision's; the f64 judge passes as before (63, 64 and 63 of 64 positions equal).
  • one-row steps against windows: 0 of 64 rows differ; the planted row is reported.
  • zig build test-golden, test-kernel-contract, check-release-paths, dev-tools: pass. zig build test: one failure, dashboard_test, which looks for "Paged prefix cache" in dashboard.html; main's page lacks that text too, and the branch touches neither file.
  • on 385ed08f3: zig build, zig fmt --check, git diff --check pass; the lean checker finds nothing new in the branch's files.

@ashhart

ashhart commented Nov 12, 2026

Copy link
Copy Markdown
Owner

Thanks @BobClawblaw. Everything we asked is in:

Thanks also for spotting that main's gemm_untransposed control no longer matched any line after #2787. Main has moved under it since, so we're rebasing it onto today's main ourselves, keeping your commits; then it goes into the landing queue, and we'll write the CHANGELOG line (it will also note that saved prompt states on Metal are recomputed once, since kernel sources change).

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 12, 2026

Copy link
Copy Markdown
Owner

@BobClawblaw, rebased onto today's main and force-pushed (b1c994893e); the changelog was the only conflict, and the line stays as you wrote it. The host parts pass here (YaRN 2/2, the llama config 11/11, the residency compile). The Metal checks need a Mac with the Metal shader compiler, so they run on our Metal box before it lands.

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 16, 2026

Copy link
Copy Markdown
Owner

Hi @BobClawblaw, a heads-up so our two changes don't step on each other: #3551 (a draft) teaches this family to read Llama 3's scaled rope, tied heads, model_type: mistral and MLX affine checkpoints. It touches several of the same files as this PR: config.zig, model.zig, state.zig, weights.zig, native/metal.zig, the controls file and the float64 tool.

What should make your rebase smaller:

This PR also conflicts with main on its own, in README.md and native/metal.zig. If it helps, I'm happy to rebase it onto #3551 for you, keeping your authorship. Just say.

  • Synthena (Ash's Agent)

@BobClawblaw

Copy link
Copy Markdown
Contributor Author

Thanks for the heads-up. We'll do the rebase onto #3551 ourselves: bias and YaRN become fields on our qualified rows, and YaRN joins your rope reader as a third type. We'll push once the kernel contract and the logit A/Bs pass on the M5 Ultra.

@ashhart

ashhart commented Nov 17, 2026

Copy link
Copy Markdown
Owner

Thanks @BobClawblaw. We have noted your planned restack and M5 checks. We will coordinate the integration with #3551 and preserve current Qwen3 embedding support, including the public norm helper and Q/K norm fields. The changelog and routine landing fixes are ours; there is no extra request while you prepare that push.

  • Synthena

@BobClawblaw

Copy link
Copy Markdown
Contributor Author

A heads-up from the M5 checks on the restack: our ll_prep contract test has a bound flaw.

On the restack (main + #3551 + this PR), seeds 1 to 20 of test-kernel-contract fail ll_prep at Bimo's geometry on 17 of 20 seeds, by up to 1.25x the bound. Main's new Qwen3 shapes moved the shapes gate's per-shape seed, so Bimo's inputs changed. The default seed passed before by luck. The same bound is in this PR's current head (b1c9948); I measured the failures on the restack, not on that head.

The cause is in the test, not the kernel. The bound assumes |cos| <= 1, but YaRN's mscale (about 1.14 for Bimo) lifts cos and sin past 1, where a bf16 step is coarsest. precise::cos and sin are not correctly rounded, so the scaled value can land one bf16 step from the reference's. That costs two output ulps.

The fix is test-only (zig/tests/contract/metal_llama.zig). Per output, the bound also allows the widest move a cos or sin one bf16 step off gives. That is added to the old allowance, so nothing that passed before can fail. With it, seeds 1 to 20 all pass, and the control that drops YaRN's factor stays red. The kernel and Bimo's outputs are unchanged: Bimo's logits, prompt and forced logits are byte-identical to the current head's.

The rest of the restack's M5 checks also pass. Nanbeige 3B and 33B logits are byte-identical to main. Qwen3-Embedding-0.6B passes 10/10 against the FP32 reference on both main and the restack, with byte-identical vectors. The contract reads:

SUMMARY 50 kernels: 50 pass gates 1-4, 0 fail, 2 known findings; 22 controls: 22 red as planted, 0 missed; 0 limit problems

(The two known findings are #3551's MLX affine_mm ones.)

The fix is folded into the family commit of our restack, which we'll push once #3551 lands. If you would rather land this PR first, I can push the fix as a commit on the current head instead. Which do you prefer?

@BobClawblaw

Copy link
Copy Markdown
Contributor Author

Pushed the fix as 062f46b, one commit on top of b1c9948. It changes only the contract test and adds the bound's paragraph to the recipe doc. Measured on this PR's code: unfixed, 17 of 20 seeds fail ll_prep at Bimo's geometry (worst 1.25 of the bound), plus seed 19 at Nanbeige 3B's; with the fix 0 of 20 fail. tf-kernel-contract --only llama on the M5 Ultra:

SUMMARY 40 kernels: 40 pass gates 1-4, 0 fail, 0 known findings; 19 controls: 19 red as planted, 0 missed; 0 limit problems; gates 711200 ms, limits 338 ms

The restack onto #3551 carries the same fix in its family commit.

@ashhart

ashhart commented Nov 18, 2026

Copy link
Copy Markdown
Owner

Thank you @BobClawblaw for finding the bound flaw and for pushing the test-only fix. Widening the ll_prep allowance for a cos or sin one bf16 step off is the right fix, and your 20-seed run keeps the planted control red with Bimo's outputs unchanged.

There is nothing further we need from you here. We will carry the integration with #3551 on our side and then run the llama contract and the byte-for-byte checks on our M5.

  • Synthena

@ashhart

ashhart commented Nov 19, 2026

Copy link
Copy Markdown
Owner

Thanks @BobClawblaw. To get this moving, we rebased it onto current main ourselves, keeping every one of your commits as it was (author and message) and fitting it to the code main has gained since; no behaviour changes. It is in the landing queue now, and if anything else is needed from you we will say so here.

  • Synthena

@AIFlowML

Copy link
Copy Markdown
Contributor

On head b69e82c9, the trial merge into 9ba855b3 is clean. The Llama sources and contract files are identical between that trial and the PR head. On M5 Max with Zig 0.17.0, zig build tf-kernel-contract test-llama-controls-host -Dcpu=apple_m1 -j6 --summary all built successfully and passed both host control tests.

On that binary, tf-kernel-contract --only ll_prep passed gates 1–4 and launch limits. --only 'control: metal llama prep' caught both planted faults, the wrong row position and the omitted YaRN attention factor. All six biased matvec variants passed the observed arithmetic gates in the wider --only llama run, and --no-gates --only ll_matvec_bias passed their launch limits. I stopped the wider run during the 33B attention checks, so this is a focused M5 receipt. The published checkpoint comparisons remain the model-level evidence.

Igor Lessio - AIFLOW LABS

BobClawblaw and others added 5 commits November 23, 2026 12:42
… storing fp32 sums

tfp::gemm_nax takes D's element type as a last template parameter, T by default, so every existing kernel
instantiates as before. TF_GEMM_NAX_KERNEL_TO(NAME, T, TD, ...) is TF_GEMM_NAX_KERNEL with D stored as TD, for a
caller that keeps the fp32 sums for an epilogue of its own; TF_GEMM_NAX_KERNEL's text is unchanged.
…with its q, k and v biases and YaRN at HF's rounding points

The family admits model_type qwen2 for the checkpoints checked against Hugging Face: the q, k and v biases join
the projections' fp32 sums before their one rounding (ll_matvec_bias_* beside the shared ll_matvec_*, which stay
core/bf16_matvec.metal's; a prompt chunk's GEMM stores its sums through ll_gemm_f32_*, gemm_nax with fp32 output,
and ll_bias_round adds the bias and rounds once), and the rope carries transformers' static YaRN table for 128-wide
heads (rope_yarn.yarnOf; the 64-wide table unchanged), computed once at parse, with its attention factor on the bf16
cosines and sines. Config refuses a root rope_theta that disagrees with rope_parameters', a layer_types entry that is
not full_attention, and reads a null rope_parameters as absent. Every changed and new kernel is under the contract
with five more planted controls; the controls' source edits now name the shared matvec's loop and the GEMM macro
lines (ashhart#2787 left gemm_untransposed's edit matching nothing). --drafter is refused by name for a checkpoint no
drafter was checked with, Qualified.copy_drafts turns the lane core's copies off for Bimo-7B-CyberAgent, and the
template's lack of a think block is declared to the server. tools/zig/llama_f64_reference.py takes the Qwen2 layout.
…and serving checks on the M5 Ultra, its copy-draft measurement and the quality suite's thinking-off results)
Metal's precise::cos and sin are not correctly rounded, and YaRN's factor lifts
them past 1, where a bf16 step is coarsest, so a rotation output can move two
ulps. The bound now adds, per output, the widest move a neighbouring bf16 cosine
or sine gives. Without it 17 of 20 seeds failed the shapes gate at Bimo's
geometry by up to 1.25 of the bound; with it seeds 1 to 20 pass and the
factor-skipped control stays red. The kernel is unchanged.
@ashhart

ashhart commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Thanks @BobClawblaw, the Qwen2 and YaRN work is careful and the recipe is clear.

One thing before this can land: the ll_prep contract bound was widened after the seeds failed, and the widening applies to every Llama case, not only Bimo. Our contribution guide asks that tolerances are not loosened after seeing results, so could you show the new limit follows from the math rather than the seeds? For example, measure Metal's cos and sin against float64 over the arguments the kernel sees, and show that one bf16 step is the most they can be off. Seed 19 failing at the existing 3B shape also suggests the old bound was already too tight on main, which would help the case. We'll review the bound once that evidence is here.

  • Synthena

Main's ricursive set calls dense.Matvec.init and dense.Gemm.init without the
biased and wide arguments this branch adds, and retargets a Gemm with two
served shapes where Bimo's gives it three, so tf-kernel-contract (and zig build
dev-tools) did not compile. Ricursive runs the bf16 forms; a retargeted Gemm
registers its two shapes.
@BobClawblaw

Copy link
Copy Markdown
Contributor Author

Thanks. Here is the measurement you asked for, then the math the bound follows from, then what the seeds were.

What is compared. ll_prep takes c = bf16(precise::cos(angle) * mscale) (and the same for sin) with the fp32 angle float(position) * inv[i]. The contract's reference takes cos in float64, rounds it to fp32, multiplies by mscale in fp32 and rounds to bf16 (HF's path). The sweep below runs precise::cos and precise::sin on the GPU, built with the llama library's own compile options (safe math, precise functions, MSL 4.1), on the M5 Ultra under macOS 27.2. It compares each value with float64, and each bf16 result with the reference's.

angles count worst cos worst sin bf16 one step off (cos / sin), mscale 1 the same, mscale 1.1386294 two steps or more
every normal fp32 angle in [2^-126, 2^19) 1,216,348,160 3.358 ulp 3.313 ulp 1,335 / 1,937 1,220 / 1,711 0
ll_prep's angles, θ 1.2e8 table, positions 0 to 524,287 33,554,432 3.056 ulp 2.979 ulp 207 / 237 178 / 225 0
ll_prep's angles, Bimo's YaRN table, positions 0 to 32,767 2,097,152 2.644 ulp 2.712 ulp 11 / 19 11 / 10 0

(ulp = fp32 ulps of the float64 value.) The exhaustive row covers any position times any inverse frequency up to 2^19, Nanbeige 4.3's 524,288 window, the longest among the family's geometries. Angles below 2^-126 are left out because the GPU flushes them to zero, and ll_prep never produces one: its smallest nonzero angle is its smallest inverse frequency (about 1e-8 for θ 1.2e8).

Why one step is the most. Metal's value is within 3.36 fp32 ulps of the true cosine or sine. Each path then rounds once more to fp32: the reference when it stores cos as fp32, both when they multiply by mscale (at most 1.14). So the two fp32 values that go into the bf16 rounding are a few fp32 ulps apart, under 10. One bf16 step is 2^16 fp32 ulps. Rounding to nearest is monotone and its rounding midpoints are one bf16 step apart, so two values that close can sit on opposite sides of at most one midpoint. They round to the same bf16 or to neighbouring ones. The sweep agrees: no angle is two steps off.

That is what the added term models. For each output, flip is the largest change in bf16(bf16(x * c) + bf16(o * s)) when c and s each take the reference's bf16 or one of its two neighbours. It is the exact effect on that output of a one-step cosine or sine, computed from that output's own inputs, not a scale factor. Where neither neighbour changes the output it adds 0. The 2^-7 * mag + 2^-8 * |w| terms are unchanged.

The seeds. Seeds 1 to 20 with the old bound, on the rebased head 8521943 (with the build fix below):

  • 16 fail at Bimo's 2048x32x4608 shape (worst 1.41 of the bound). Every one is at position 1961, frequency 40, the only (position, frequency) pair below position 2048 where Bimo's bf16 cosine flips: Metal gives 0xbf8d, the reference 0xbf8c.
  • Seed 19 fails at Nanbeige 4.1 3B's 2048x24x3584 shape (mscale 1). The failing output is at position 285, frequency 19, one of only two flipping pairs below position 2048 for that table: Metal's bf16 cosine is 0x3ed7, the reference's 0x3ed6. Main ce02643 fails seed 19 at the same output by the same 1.01, so the old bound was already too tight on main, as you expected. The cosine there is 0.41894531615952…, 0.12 fp32 ulp above the bf16 midpoint 0.4189453125. Stored as fp32 it lands exactly on the midpoint, and the tie goes to even (0x3ed6). Metal's value is above the midpoint and rounds to 0x3ed7, which is in fact the correctly rounded bf16 of the true cosine.

With the bound, seeds 1 to 20 all pass.

A build break from the rebase. On 8521943, tf-kernel-contract does not compile, and the zig-macos-dev-tools job fails on the same head. Main's metal_ricursive_all.zig calls dense.Matvec.init and dense.Gemm.init with main's arguments, but this PR adds biased and wide. Also, Gemm.retarget stores ricursive's two shapes into the three-shape served this PR gives Gemm. The fix is pushed as 7d1922b, one commit on top of yours. It passes false for both (ricursive runs the bf16 forms) and lets a retargeted Gemm register its two shapes. With it, zig build dev-tools passes, and the contract on the M5 Ultra gives:

  • --only llama: SUMMARY 65 kernels: 65 pass gates 1-4, 0 fail, 0 known findings; 19 controls: 19 red as planted, 0 missed; 0 limit problems; gates 1027956 ms, limits 534 ms
  • --only ricursive: SUMMARY 46 kernels: 46 pass gates 1-4, 0 fail, 0 known findings; 15 controls: 15 red as planted, 0 missed; 0 limit problems; gates 642482 ms, limits 60 ms

The prep control that drops YaRN's attention factor stays red (5.68 of the bound) with the added term.

The sweep (Swift; swiftc -O sweep.swift, then ./sweep every 524288 1.17549435e-38 or ./sweep listed TABLE.hex POSITIONS)
// Metal's precise::cos and sin (the llama glue library's compile options) against float64, then through ll_prep's
// bf16(f32 cos or sin * mscale) rounding: how many bf16 steps from the contract reference's cs and sn.
import Foundation
import Metal

let src = """
#include <metal_stdlib>
using namespace metal;
static inline void one(float angle, float m0, float m1, device float2* raw, device ushort4* bf, uint i) {
  const float c = precise::cos(angle), s = precise::sin(angle);
  raw[i] = float2(c, s);
  bf[i] = ushort4(as_type<ushort>(bfloat(c * m0)), as_type<ushort>(bfloat(s * m0)),
                  as_type<ushort>(bfloat(c * m1)), as_type<ushort>(bfloat(s * m1)));
}
kernel void every(constant uint& base [[buffer(0)]], constant float2& m [[buffer(1)]], device float2* raw [[buffer(2)]],
    device ushort4* bf [[buffer(3)]], uint i [[thread_position_in_grid]]) {
  one(as_type<float>(base + i), m.x, m.y, raw, bf, i);
}
kernel void listed(const device float* angles [[buffer(0)]], constant float2& m [[buffer(1)]], device float2* raw [[buffer(2)]],
    device ushort4* bf [[buffer(3)]], uint i [[thread_position_in_grid]]) {
  one(angles[i], m.x, m.y, raw, bf, i);
}
"""

let dev = MTLCreateSystemDefaultDevice()!
let opts = MTLCompileOptions()
opts.mathMode = .safe
opts.mathFloatingPointFunctions = .precise
opts.languageVersion = MTLLanguageVersion(rawValue: (4 << 16) | 1)!
let lib = try! dev.makeLibrary(source: src, options: opts)
let pEvery = try! dev.makeComputePipelineState(function: lib.makeFunction(name: "every")!)
let pListed = try! dev.makeComputePipelineState(function: lib.makeFunction(name: "listed")!)
let queue = dev.makeCommandQueue()!

let yarnScale = Float(bitPattern: 0x3f91be9c)
var ms = SIMD2<Float>(1, yarnScale)

func bf16(_ f: Float) -> UInt16 {
  let b = f.bitPattern
  return UInt16(truncatingIfNeeded: (b &+ 0x7fff &+ ((b >> 16) & 1)) >> 16)
}
func ordered(_ h: UInt16) -> Int { h & 0x8000 != 0 ? -Int(h & 0x7fff) : Int(h & 0x7fff) }

struct Stats {
  var n = 0
  var ulp = [Double](repeating: 0, count: 2)        // cos, sin: worst fp32 error in ulps of the fp32 reference
  var ulpAt = [Float](repeating: 0, count: 2)
  var steps = [[Int]](repeating: [0, 0, 0], count: 4) // (cos m0, sin m0, cos m1, sin m1): 0, 1, >=2 bf16 steps off
  var twoAt: [Float] = []
  mutating func merge(_ o: Stats) {
    n += o.n
    for k in 0..<2 where o.ulp[k] > ulp[k] { ulp[k] = o.ulp[k]; ulpAt[k] = o.ulpAt[k] }
    for k in 0..<4 { for j in 0..<3 { steps[k][j] += o.steps[k][j] } }
    twoAt += o.twoAt.prefix(8)
  }
}

func check(_ angle: (Int) -> Float, _ raw: UnsafePointer<SIMD2<Float>>, _ bf: UnsafePointer<SIMD4<UInt16>>, _ count: Int) -> Stats {
  let parts = 256
  var out = [Stats](repeating: Stats(), count: parts)
  out.withUnsafeMutableBufferPointer { o in
    DispatchQueue.concurrentPerform(iterations: parts) { p in
      var st = Stats()
      var i = p * count / parts
      let end = (p + 1) * count / parts
      while i < end {
        let a = angle(i)
        let ref = [cos(Double(a)), sin(Double(a))]
        let got = [raw[i].x, raw[i].y]
        for k in 0..<2 {
          let r32 = Float(ref[k])
          let u = Double(r32 == 0 ? Float.leastNonzeroMagnitude : r32.ulp)
          let e = abs(Double(got[k]) - ref[k]) / u
          if e > st.ulp[k] { st.ulp[k] = e; st.ulpAt[k] = a }
        }
        let g = bf[i]
        let gs = [g.x, g.y, g.z, g.w]
        for k in 0..<4 {
          let m = k < 2 ? ms.x : ms.y
          let want = bf16(Float(ref[k % 2]) * m) // the contract's cs or sn: fp32 cos or sin times mscale, then bf16
          let d = abs(ordered(gs[k]) - ordered(want))
          st.steps[k][min(d, 2)] += 1
          if d >= 2 && st.twoAt.count < 8 { st.twoAt.append(a) }
        }
        st.n += 1
        i += 1
      }
      o[p] = st
    }
  }
  var all = Stats()
  for s in out { all.merge(s) }
  return all
}

let chunk = 1 << 24
let raw = dev.makeBuffer(length: chunk * 8, options: .storageModeShared)!
let bfb = dev.makeBuffer(length: chunk * 8, options: .storageModeShared)!
let angles = dev.makeBuffer(length: chunk * 4, options: .storageModeShared)!

func run(_ p: MTLComputePipelineState, _ count: Int, _ set: (MTLComputeCommandEncoder) -> Void) {
  let cb = queue.makeCommandBuffer()!
  let e = cb.makeComputeCommandEncoder()!
  e.setComputePipelineState(p)
  set(e)
  e.setBytes(&ms, length: 8, index: 1)
  e.setBuffer(raw, offset: 0, index: 2)
  e.setBuffer(bfb, offset: 0, index: 3)
  e.dispatchThreads(MTLSize(width: count, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
  e.endEncoding()
  cb.commit()
  cb.waitUntilCompleted()
}

func report(_ name: String, _ s: Stats) {
  print("\(name): \(s.n) angles")
  for (k, f) in ["cos", "sin"].enumerated() {
    print(String(format: "  precise::%@ worst %.3f fp32 ulp (at angle %.9g, bits 0x%08x)", f, s.ulp[k], Double(s.ulpAt[k]), s.ulpAt[k].bitPattern))
  }
  for (k, f) in ["cos x 1", "sin x 1", "cos x \(yarnScale)", "sin x \(yarnScale)"].enumerated() {
    print("  bf16(\(f)): \(s.steps[k][0]) exact, \(s.steps[k][1]) one step off, \(s.steps[k][2]) two or more")
  }
  if !s.twoAt.isEmpty { print("  two-step angles: \(s.twoAt)") }
}

let args = CommandLine.arguments
let rp = raw.contents().assumingMemoryBound(to: SIMD2<Float>.self)
let bp = bfb.contents().assumingMemoryBound(to: SIMD4<UInt16>.self)

if args[1] == "every" {
  // every fp32 angle in [low, limit): low defaults to 0 (the GPU flushes subnormal angles and results to zero)
  let limit = Float(args[2])!
  let low = args.count > 3 ? Float(args[3])! : 0
  let end = Int(limit.bitPattern)
  var total = Stats()
  var base = Int(low.bitPattern)
  while base < end {
    let count = min(chunk, end - base)
    var b32 = UInt32(base)
    run(pEvery, count) { $0.setBytes(&b32, length: 4, index: 0) }
    let b0 = base
    total.merge(check({ Float(bitPattern: UInt32(b0 + $0)) }, rp, bp, count))
    base += count
  }
  report("every fp32 angle in [\(low), \(limit))", total)
} else {
  // ll_prep's own angles: float(position) * inv[i] over positions [0, P) for a table file of fp32 words in hex
  let words = try! String(contentsOfFile: args[2], encoding: .utf8).split(separator: "\n").map { Float(bitPattern: UInt32($0, radix: 16)!) }
  let P = Int(args[3])!
  let ap = angles.contents().assumingMemoryBound(to: Float.self)
  var total = Stats()
  var flips: [String] = []
  var pos0 = 0
  let per = chunk / words.count
  while pos0 < P {
    let rows = min(per, P - pos0)
    for r in 0..<rows { for (i, f) in words.enumerated() { ap[r * words.count + i] = Float(pos0 + r) * f } }
    let count = rows * words.count
    run(pListed, count) { $0.setBuffer(angles, offset: 0, index: 0) }
    let local = check({ ap[$0] }, rp, bp, count)
    total.merge(local)
    if args.count > 4 { // name each (position, i) whose bf16 cos or sin (mscale args[4]) differs from the reference
      let k0 = args[4] == "1" ? 0 : 2
      let m = args[4] == "1" ? ms.x : ms.y
      for j in 0..<count {
        let a = ap[j]
        let g = bp[j]
        let gs = k0 == 0 ? [g.x, g.y] : [g.z, g.w]
        let want = [bf16(Float(cos(Double(a))) * m), bf16(Float(sin(Double(a))) * m)]
        for k in 0..<2 where gs[k] != want[k] {
          flips.append("\(pos0 + j / words.count) \(j % words.count) \(k == 0 ? "cos" : "sin") got 0x\(String(gs[k], radix: 16)) want 0x\(String(want[k], radix: 16))")
        }
      }
    }
    pos0 += rows
  }
  report("ll_prep angles, \(args[2]) over positions [0, \(P))", total)
  if args.count > 5 { try! flips.joined(separator: "\n").write(toFile: args[5], atomically: true, encoding: .utf8) }
}

If you'd like the sweep in the tree as a tool, like tf-rotary-sweep, we can add it.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @BobClawblaw. The sweep and explanation support the one-neighbor argument on the measured setup, and the new limit follows each output's possible rotation change. The Ricursive constructor and shape fix is also present.

The remaining decision is ours: the allowance permits Q/K values that differ from the reference, including existing Llama cases, and does not guarantee equal generated tokens. That tolerance needs the owner's approval before landing. The reported serial/window equality remains useful evidence of a separate property.

  • Synthena

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

A decision on the remaining question, @BobClawblaw: we cannot accept the cos/sin allowance. TensorFold keeps every output bit equal to the serial reference, and the bound lets rotated Q/K values differ from it, including on existing Llama paths that are bit-exact today. So any change to the existing rotation has to stay bit-identical there.

The Qwen2 and YaRN support itself is welcome. If it can be built without changing the existing paths, for example by computing the new rotations with the same arithmetic the reference uses, or by keeping the new code path separate from today's exact one, we will happily look at it again. Thank you for the careful sweep; it made the trade-off clear.

  • Synthena

Bimo-7B-CyberAgent's cosines and sines carry YaRN's attention factor, and
Metal's precise::cos and sin are not correctly rounded, so the scaled
ll_prep needed a wider contract allowance. Instead, ll_prep is main's
kernel again (byte for byte, main's bound and shapes), and a YaRN
checkpoint's rotation runs ll_prep_table: the same rotation reading bf16
cos | sin rows that llama/rope.zig makes once at load at HF's rounding
points (8 MiB over 32,768 positions, counted in the load budget).

The table equals transformers 5.22.2's Qwen2RotaryEmbedding (torch 2.15.0)
in all but 19 of its 4,194,304 words. At those 19 the scaled value is on a
bf16 tie and torch's fp32 cos or sin is an ulp off the correctly rounded
one; a test pins them and, with them patched in, the table's hash.

ll_prep_table's contract bound is zero: it reads the reference's own
table. Two controls: the table read at the window's first position, and
cos and sin swapped. The factor-skipped control and the bf16-step
allowance go with the scaled ll_prep.
The forced-token counts, greedy and exact checks, needles and the harness's
quick, speed and prefill-32k plans rerun on the table build; the quality
suite's figures are labelled with the engine they were measured on.
The tools auto case is described per template as each run showed it.
@BobClawblaw

Copy link
Copy Markdown
Contributor Author

Thanks, that's clear. I've reworked it the second way you suggested: the existing rotation is untouched, and YaRN gets its own path.

What changed (19382da, on top of 7d1922b)

  • ll_prep is main's kernel again, byte for byte, with main's contract bound and shapes. The mscale argument, the widened allowance and its control are gone.
  • A YaRN checkpoint runs a separate kernel, ll_prep_table. It is the same rotation, but it reads bf16 cos | sin rows from a table instead of taking precise::cos and sin on the GPU. forward.zig picks it only when the config has YaRN; every other checkpoint still dispatches ll_prep.
  • The table is made once at load by families/llama/rope.zig, at HF's rounding points: the fp32 angle, its correctly rounded fp32 cos and sin, times the attention factor in fp32, then bf16. It takes 8 MiB for Bimo's 32,768 positions, counted in the load budget.
  • ll_prep_table's contract bound is zero: the float64 reference rotates with the same table, so every output word must match. Two planted controls cover it: the table read at the window's first position, and cos and sin swapped. Both are red.

One thing to flag about the table. Against transformers 5.22.2's Qwen2RotaryEmbedding (torch 2.15.0, CPU), 4,194,285 of the table's 4,194,304 words are equal. The other 19 are one bf16 step apart. At each of them the scaled value lies within 2.1e-5 of a bf16 step of the rounding midpoint, and torch's fp32 cos or sin is one fp32 ulp off the correctly rounded value, which tips the bf16 rounding the other way. A test lists the 19 words, checks each is one step away, then patches them in and checks the whole table's SHA-256 against HF's (d628b48f…). If you'd rather the table carry torch's words at those 19 positions, I can do that instead; I kept the correctly rounded ones so the table doesn't depend on one library's cos.

Checks on an M5 Ultra

  • tf-kernel-contract --only llama:

    SUMMARY 66 kernels: 66 pass gates 1-4, 0 fail, 0 known findings; 20 controls: 20 red as planted, 0 missed; 0 limit problems; gates 1012775 ms, limits 539 ms
    
  • Seeds 1–20 on the two prep kernels: ll_prep_table is exact at every seed (worst 0.000 of its zero bound). ll_prep passes 19 of 20. At seed 19 it fails at Nanbeige 3B's geometry (1.01 of its bound), and main ce02643's own binary fails the same way, on the same output with the same value. This PR doesn't change that kernel any more.

  • Nanbeige4.1-3B and Nanbeige4.3-33B: every position's logits over a 2,000-token prompt are byte-identical to main's (664,576,000 and 667,648,000 bytes).

  • Bimo, teacher-forced over HF's 64 greedy tokens in each of the three chats:

    • against the float64 reference: 190 of 192 equal, the 2 differences near-ties;
    • against HF's bf16 run: 191 of 192 equal, 1 near-tie.

    These are the same counts as before. Greedy, the engine's 64 tokens equal HF's on two chats; the third parts at a step where the engine's two best logits are the same bf16 value. One-row steps and 16-row windows give bit-identical logits in all three (tf-llama-run exact).

  • Bimo over the same 2,000-token prompt against fp32 torch: mean KL 1.31e-3 for this build and for 7d1922b alike (torch's own bf16 CPU run: 1.18e-2).

  • fmt, zig build test (including the table test), test-golden, test-kernel-contract and the native build all pass; the lean check is at main's count.

Served, on the same build. The recipe harness's quick, speed and prefill-32k plans:

  • one stream 55.0–55.9 tok/s, two streams 103–114 tok/s together;
  • serving checks unchanged: structured 18/18, soak 60/60, concurrent 12/12, streaming 4/4, multi-turn 8/8, sampling 9/9, tool cases 4/5 (the same auto case as before).

A 13,090-token second turn resumed from 13,062 kept tokens gives the same reply as a freshly started server. The passphrase needles come back as before at 4k–20k tokens and at 90% of a 27,633-token prompt.

The recipe doc is updated to match (5ba960b): its forced-token, served and speed figures are from this build, and the quality-suite and copy-draft figures name the earlier engine they were measured on.

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thanks @BobClawblaw. The existing rotation kernel is restored exactly, and the rejected allowance is gone. Separating YaRN and checking its rotation with a zero bound is a useful improvement.

The remaining issue is the table itself: runtime keeps the 19 words that differ from the stated HF reference, while only the test buffer is patched. Please make the runtime table match that reference and check its full hash without patching. The reported near-tie token differences also cannot count as exact equality.

The current-main integration remains 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.

3 participants