Skip to content

glm: sampled decoding on Metal — temperature, top_k, top_p and min_p behind the lane core - #524

Closed
heitke wants to merge 7 commits into
ashhart:mainfrom
heitke:glm-metal-sampling
Closed

heitke wants to merge 7 commits into
ashhart:mainfrom
heitke:glm-metal-sampling

Conversation

@heitke

@heitke heitke commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

glm: sampled decoding on Metal — temperature, top_k, top_p and min_p behind the lane core

What this changes

The native GLM-5.3-Flash engine refused every request with a positive temperature. This PR wires the lane core's Sampling through the GLM backend so temperature, top_k, top_p, min_p and seed work on one Mac, with the head drawing through the shared sampler — the same tf_sample_full kernel (zig/kernels/metal/nemotron_sample.metal) and the same lanes.gpu_rule.rule rule arithmetic every family uses. Temperature zero keeps the untouched glm_argmax greedy path.

The shared sampler (this update)

The branch previously launched its own glm_sample shader. That copy is deleted. families/glm/draw_dispatch.zig is now a binding adapter: it derives the shared kernel's per-row arrays (seeds, positions, cfg, top_k caps) from the payload's rules through lanes.gpu_rule.rule, so 1/T, top_p, the near window, ln(min_p) and top_k are the lane core's arithmetic, not the family's. A payload's rows split into maximal runs of one mode — sampled rows launch the shared tf_sample_full, greedy-marker rows launch the family's glm_argmax (the shared kernel has no greedy marker; a marker position would key a real race). The GLM-5.3 head registers the shared library's tf_sample_full entry point; glm_sample.metal, its kernels registration and its duplicated selection/nucleus/race arithmetic are removed.

Semantics preserved

  • Temperature 0 (or no sampling) decodes exactly as before — the same glm_argmax launch; explicit temperature zero parses and arms nothing.
  • Per-stream seeds and absolute token positions: prompt first-token keyed at the prompt length, queued rounds at slot.s.pos + 1, verify-window rows at their own positions, standalone rounds re-armed through rulesFor each round.
  • Mixed sampled/greedy rows ride one head call (run-split dispatch); the MTP draft head still draws greedily, with target verification deciding acceptance.
  • The two-Mac (TP2/EP) pair still refuses positive-temperature requests with SampledPeerUnsupported before any state moves or the peer hears of it; greedy peer execution is unchanged.

Receipt

  • Environment: TensorFold 0174809b on the merge of origin/main c7137bb3 (merge commit 87e5ad21), Apple M3 Ultra (256 GiB), macOS 26.6, Zig 0.17.0, checkpoint GLM-5.3-Flash MLX-4bit-MTP (45 layers + MTP, 180.58 GB in buffers).
  • Host gates: zig build test 160/160 steps pass; zig build native builds the server binary; the GLM family module's tests 127/127; zig build test-golden 309/319 equal with 0 unexpected differences (10 known, recorded); zig fmt --check build.zig zig clean; git diff --check clean; python3 tools/zig/lean_check.py 525 problems against current origin/main's 527 — zero added over main, and no finding belongs to a file this branch introduced (engine.zig's and slots.zig's counts sit at or below 600 lines after the ranks.zig split and main's kept.zig split).
  • Real-Metal synthetic gate (checkpoint-free, MTL_DEBUG_LAYER=1 zig build test-glm-sampling -Dcpu=apple_m1): 15/15 PASS over the shared tf_sample_full with the production dispatch path and Metal API validation enabled, zero findings — min-p normalization, arrival order, top_k 1/1024/1025/at/beyond the vocabulary (filtered and unfiltered), large nucleus, tiny/large vocabulary, shuffled ties, hot distribution — each across repeated, reordered, mixed, trailing and solo rows, with offsets and guard sentinels.
  • Python gate-client tests (python3 -m unittest test_check_glm_sampling): 9/9 pass — the served-token-hash client's drafted-telemetry qualification and its false-positive rejection tests.
  • zig build test-native (the engine module's host tests): pass as part of zig build test.

Not run (stated honestly)

  • The two-Mac TP2 refusal on hardware — this machine has no peer Mac; the refusal path is covered by host tests and the lane core's error mapping. The maintainer's offer to run the sampler checks on one Mac at marking ready stands as the remaining qualification for this branch's real-model runs; the real-model receipts in the earlier review round qualified the deleted duplicate, not this shared-sampler replacement, so they do not carry over and are not claimed here.
  • The served native token-hash comparisons (plain/restored/drafted), the drafted runs with telemetry, the concurrent mixed-mode equality, the cancellation-then-fresh sequence, the standalone sampled depth-zero and drafted runs, and the MTP-omitted configuration need the model resident; they will be re-run against this code before marking ready, per the maintainer's one-Mac qualification offer.

@heitke
heitke marked this pull request as draft October 8, 2026 20:13
@ashhart

ashhart commented Oct 10, 2026

Copy link
Copy Markdown
Owner

Thank you, @heitke. Sampled GLM decoding that reuses the lane core's keyed draws bit for bit, with the rule ABI pinned at compile time, is the right way to do it, and the draw tests are thorough.

One housekeeping change before it lands. SAMPLING-PROGRESS.md is a working record with paths from your machine (lines 4 and 257), and the newest commit's message names one too. We keep working notes out of the tree, so when we land this we'll take the three code commits and the docs commit and leave the progress-file commits out. That gives the commits new ids, so the PR will show as closed, with every commit we take under your name. Please don't rework the branch for this; we'll handle it.

When you mark it ready, we'll run the sampler checks on one Mac. Sampled requests stay refused on a two-Mac pair here, and the full model on a single 256 GB Mac depends on #521, which we're deciding separately because of memory pressure at that size.

@ashhart

ashhart commented Oct 10, 2026

Copy link
Copy Markdown
Owner

An update, @heitke: the one-Mac question is settled. Main now loads GLM-5.3-Flash on one 256 GB Mac by default, leaving the MTP head on disk when only the head is over the limit (2a6755b), and GLM_LOAD_LIMIT_GB raises the limit to 70% of the RAM's bytes for the full model (60c4851). Loads past 70% will need an explicit request with the risk printed (#521 and #580 fold into that). So when you mark this ready, we'll run the sampler checks on one Mac with the full model.

@heitke
heitke force-pushed the glm-metal-sampling branch from 1e7fea0 to 086462e Compare October 10, 2026 16:46
Enable single-Mac sampled GLM target draws with per-stream seeds and absolute positions, while retaining greedy MTP proposals and explicitly refusing sampled peer execution. Select complete top-k boundaries independently of bounded storage and normalize the full retained mass before min-p.

Share production rule construction, initialized payloads and buffer bindings with regression gates. Accept explicit temperature zero. Add a checkpoint-free real-Metal gate and a native token-hash restoration/concurrency client. Document host results and required device/model qualification without private paths or unsupported gate claims.
The rebase onto the current base introduced two production paths that decoded greedily through the sampler: Slots.queueRound built its context without draw rules, so a single-stream request sampled its first token but decoded every queued token after it with argmax; and Engine.generate routed a depth-zero sampled reply into plain_rounds.run, whose rounds carry no rules. Both now take the stream's sampling: the queued round arms its row's keyed rule at the position the lane core queued the draw at, and a sampled standalone reply decodes the synchronous round that rebuilds its rules, leaving the pipeline as the greedy optimization.

The served token-hash gate now qualifies a drafted run only when its telemetry proves drafting (speculative.drafted > 0), distinguishes drafting-unavailable from gate failure, mixes draft modes in its concurrent runs, and its tests reject false-positive qualification.

Host gates: zig build test pass, zig fmt --check clean, lean checker 541 against the branch's 542 (zero added; one pre-existing finding left slots.zig), git diff --check clean; the GLM family module's 47 tests pass including the queued-round rule regression.
The maintainer keeps working notes out of the publication tree; the record's
final results move to the pull request's description.
@heitke
heitke force-pushed the glm-metal-sampling branch from c28fb4a to 52493eb Compare October 11, 2026 18:55
# Conflicts:
#	zig/src/families/glm/glm.zig
#	zig/src/native/glm_host.zig
@heitke

heitke commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

I believe this PR is finally ready. Coded with GLM 5.3 Flash Q4 and the work was checked by GPT 6.1 Sol.

@ashhart

ashhart commented Oct 14, 2026

Copy link
Copy Markdown
Owner

Hello @heitke,

Thank you for the keyed GLM sampler, the draw tests, and the served token-hash match on the M3 Ultra.

The shader is a second copy of tf_sample_full. Please draw with the shared sampler and the shared gpu_rule.rule.

The copy has drifted. The id cut starts at bit 24 (glm_sample.metal:152). tf_sample_full starts at bit 16 (nemotron_sample.metal:118). The race writes the winning id with no clamp (glm_sample.metal:256). The shared kernel clamps to V - 1 (nemotron_sample.metal:307). The shader does not read rule.near, so it misses first_block's window. draw_rule.zig defines its own Rule (draw_rule.zig:33) beside gpu_rule.rule.

A push that launches tf_sample_full from that rule, and keeps the device gate comparing to gpu_full.sample, is the update we need.

Thank you again.

…er copy

The review's duplicate is gone: glm_sample.metal (a second tf_sample_full that had
drifted — the id radix select started at bit 24 instead of 16, the winner carried no
V-1 clamp, rule.near was never read, and draw_rule defined its own Rule beside
gpu_rule.rule) is deleted, and the head launches the shared kernel from
nemotron_sample.metal with the rule arithmetic taken through lanes.gpu_rule.rule.
draw_dispatch becomes the binding adapter: a payload's rules become the shared
kernel's per-row seed/position/cfg/top_k arrays, and its rows split into maximal runs
of one mode — sampled rows through tf_sample_full, the greedy marker rows through
glm_argmax, which the shared kernel has no marker for. The checkpoint-free gate
compiles the shared library and drives the same dispatch, and the 15 cases pass with
Metal API validation on the M3 Ultra.

Engine.zig stays at or below 600 lines: the GLM_RANKS diagnostics moved to ranks.zig.
@heitke heitke closed this Oct 15, 2026
ashhart pushed a commit that referenced this pull request Oct 16, 2026
Port the sampling follow-up from #835 (fb3cc20 and 8e8dc68), incorporating the queued-row and shared-sampler repairs from #524 (79e1004, 1e28ee6 and 0174809). Keep the cache lifetime repair separate.

Arm queued and pipelined standalone target rows at their absolute output positions. Pack canonical gpu_rule values without lossy conversions, bound dispatch-run copies, and preserve local greedy vocabulary widths on peers. Include host regressions and a Mac qualification recipe.
BlivionIaG pushed a commit to BlivionIaG/TensorFold that referenced this pull request Oct 20, 2026
Port the sampling follow-up from ashhart#835 (fb3cc20 and 8e8dc68), incorporating the queued-row and shared-sampler repairs from ashhart#524 (79e1004, 1e28ee6 and 0174809). Keep the cache lifetime repair separate.

Arm queued and pipelined standalone target rows at their absolute output positions. Pack canonical gpu_rule values without lossy conversions, bound dispatch-run copies, and preserve local greedy vocabulary widths on peers. Include host regressions and a Mac qualification recipe.
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.

2 participants