Skip to content

Merge upstream main - #74

Merged
plotarmordev merged 91 commits into
mainfrom
feat/95-merge-upstream-main
Nov 19, 2026
Merged

plotarmordev merged 91 commits into
mainfrom
feat/95-merge-upstream-main

Conversation

@plotarmordev

@plotarmordev plotarmordev commented Nov 19, 2026 •

Copy link
Copy Markdown
Owner

I merged upstream main (ashhart/TensorFold) into this branch, so it now holds every upstream commit as a normal merge. The two files that conflicted keep what both sides meant, and nothing else changed.

  • docs/kernel-contract.md: kept both new paragraphs — upstream's Nemotron 3.5 Transcribe CUDA audio-encoder checks and this branch's MiniMax-H3-Image Metal checks.
  • zig/src/server/device/profile.zig: took upstream's JSON-value reader. Both sides keep the device-profile parse out of compiler-rt's quad floats; upstream's reader also reads the exponent and fractional integer forms its new profile_test.zig case pins.
  • origin/main had moved past this branch's base, so I merged it in as well (no conflicts).
  • zig build test test-golden passes (928/928 steps), and swarm scan . origin/main..HEAD is clean.

jschmied and others added 30 commits November 18, 2026 15:35
…t WINDOW 0 and RING 0 (ashhart#2251)

Every line of core/prompt_attention_nax.metal that names WINDOW or RING must be one of its four guarded forms, the
mask line among them, and Llama's loader must define both as 0 over the shared text, so a later edit can't unfold it.
A control checks that an unguarded window term or a missing mask line fails. It runs in test-kernel-symbols-host.
…ers per row and dispatch class

Six synthetic layers of the release's widths (one of each attention kind, few experts) are timed at
1-16 rows of one slot and at 4 slots x 1 row, each dispatch alone and the layer on the serving
encoder, and split into FP8 rows, experts, attention and glue, with a 40-layer round weighted by
kind. timing_real's report takes a launch (context and spans) so both harnesses share it.
…x tile, bit-equal to the row kernel

Launches of 6 to 16 rows run the dense FP8 projections on fp8_tile.metal: 8 or 16 columns a
threadgroup, K split over up to 16 simdgroups in aligned power-of-two runs of groups, each 32-wide
group summed from zero in four 8-wide MMA steps in k order (the prompt tile's group root), the
groups' roots and the slices' roots in the same zero-padded pair tree the row kernel uses. Every
row's bits are the row kernel's one row a launch; 1-5 rows keep the row kernel (chosen by row
count only), since below 6 rows it reads the weights faster.

Contract: six registrations (f32, bf16, a forced 16-column form, one simdgroup, the row kernel one
row a launch as replaced baseline, the release wkv fixture), four planted controls, gate-5 records
with M1/M2 limits, and an equality probe over every model FP8 shape at 1-16 rows, every form, the
16/17 seam and a batch with NaN and Inf planted. Device tests: the layer's kernel by row count, and
four slots of two rows each in one launch against each alone.
…ates

With stream: true, an engine that reports its steps sends image_generation.progress
after each denoising step and image_generation.completed with the PNG, then [DONE];
preview_interval adds image_generation.partial_image, a separate PNG of at most 128
pixels a side and 80 KiB, every N steps. The engine's observer is null unless the
request streams, so a whole reply does no extra work and its bytes are unchanged; the
final PNG is the same with or without progress and previews. A client that leaves or
a failed write cancels at the next step. With n above 1 each picture streams its own
steps in order on one stream.

Fixes ashhart#3224
… pair launch, the same bytes

prompt_lean gains a SwiGLU pair form: a 128 x 256 tile stages gate's two 64-column blocks and up's at the same
features, each warp holds a feature's gate and up sums in one lane, and the epilogue rounds both to bf16 and takes
tf_q35_mlp_act's steps. The two existing instances keep their SASS on sm_80/86/89/120/121 (renamed: int out kind,
four trailing arguments). Qwen3.5 dense layers with NVFP4 gate and up take it for prompt rows past 16.
…ir; inline four single-use imports in the CUDA test dispatcher

The dispatcher sat at 600 lines on main, so the two new commands pushed it to 604 once applied there.
…shhart#840)

native/cuda_kept.zig holds what Flash Next's kept_disk held: the image's words,
the copies, the probe. A family declares a view of its layout. Flash Next moves
onto it with its probe bytes and seed unchanged; its key gains the prompt files.

Gemma 4 keeps its states on disk with --learn-conversations and --spill-gib.
Keys bind the tokenizer's and template's bytes, a drafter's checkpoint and the
KV form. A state over an image stays off disk: RAM alone tells which image.
A stale key opens another namespace, a cold pass.
Their views over native/cuda_kept.zig: full caches as block rows, ring tails in
the state's own file, the loop count, ring, row and paging in the key.
…ough core's bound (ashhart#2388)

A Gemma 4 31B state at 9.3k tokens is 1.5 GiB, past the 1 GiB default: every save
was skipped as StagingFull. Kept passes the served window as rows.Options.longest,
so core prices one whole state within the RAM store's budget. Families without a
window (Flash Next) keep the default permit.
…m) from its bf16 weights, audio rows spliced after the embeds

The checkpoint's llm.* tensors load as published: NeMo's layer names, fp32 A_log/D/dt_bias, the stacked [E, in, out]
experts on the bf16 grouped format with the shared expert as experts E and E + 1, TE's empty _extra_state skipped.
The audio encoder and CTC aligner tensors are left for the audio path. A prompt pass's audio rows replace the
<|audio|> positions' embeddings, as image rows do.
The Bolt load-recovery tests build an Engine by hand and null each optional kernel set; bf16x was left
undefined, so deinit unloaded a garbage module (seven tests crashed on Linux and Windows CI).
The perception encoder as a family of its own (zig/src/families/nemo_audio): WAV decoding, log-mel features and
their per-feature normalisation, the ASR and streaming speaker transformers window by window (speaker cache and queue
with AOSC compression, arXiv 2507.18446), the sinusoidal speaker fusion and the projection to the language model's
width. Weights read as stored (bf16), perception.* only.

nemotron/cuda_audio.zig holds the encoder, prepares clips (samples, rows, hash) and encodes each span at a prompt
pass, up to an hour of audio. tf-cuda-test audio-check writes every stage under the reference dumps' names;
audio-contract runs nemo_audio.cu's kernels through gates 1-4, each with a control built from nemo_audio.cuh.
…ore_threshold as the release does, with brief-speaker tests

A speaker's frame score is log max(p, pred_score_threshold) plus the other speakers' log(1 - p); frames under 0.5
never score. A score above log 0.5 is positive, and a speaker with floor(share x min_pos_scores_rate) positive scores
keeps only those (share = (188 - 8 x silence rows) / 8, rounded down: 22 shipped, so 11). The latest boost and the
strong and weak boost counts follow, from the same share. When fewer than 188 frames can score, the rest of the
cache is silence rows, after the scored rows.

Fitted to black-box NeMo dumps at several values of both keys and of spkcache_sil_frames_per_spk; the tests use
window 0 of a brief-speaker clip and of a clip with 37 s of silence, against the release's own caches.
… engines

The two hand-built engines in cuda_subset_batch_test.zig start from undefined; they now null the
Transcribe fields as cuda_load_gpu.zig's do, so no test reads or unloads a garbage pointer.
… main

Engine.record and its body move to cuda_seq_graphs.zig, Forward's lesson adapter call to
cuda_lesson_trace.zig, and tf-cuda-test imports chunk_costs and nemotron_draw_tests where they run,
as window-profile and tree-accept do. No behaviour changes.
ashhart and others added 28 commits November 18, 2026 17:06
…t once

A grammar request compiled under the server-wide grammar lock with no time
bound. xgrammar's compile time grows faster than the square of an object's
optional properties, so one such schema held every other grammar request,
cached ones included, for as long as it took. A 207 KB schema takes minutes.

tf_grammar.cc now hands each compile to tfc::Cache in tf_compile.h. A hit
among the last 8 grammars that finished in time is served under its lock.
A miss runs on its own thread, with the 8 MiB stack the request threads
have, against the same long-lived xgrammar compiler, options and caches as
before. Identical pending requests share one compile. At most 4 compiles
run at once, and a request that finds all 4 busy waits for one. A request
waits at most 2,000 ms in all, then gets the 400 naming the limit.

xgrammar has no point at which a compile can be stopped. An abandoned
compile runs to the end in the background and keeps its slot until it
returns. The grammar it finishes goes into xgrammar's cache but never into
the in-time cache, so the same request sent after that is served. The Zig
caller drops its compile mutex. The C ABI is unchanged apart from
tfg_compiling, a slot count for tests, and an older library still compiles
without the time limit.

A grammar that compiles within the limit is the one main compiles, from the
same compiler object, calls and options. Masks over 14 grammars in all six
formats hash equal to main's library's at every step, and two invalid
inputs give the same errors.

Tests: tf_compile_test.cc drives the runner with fake compiles through the
deadline, late results kept out of the cache, a small compile passing a
running large one, shared jobs, slot waits, ownership past close, failures
and stack depth. It runs in zig build test and test-grammar-compile-host. A
lanes test shows one caller's slow compile no longer holds another's. A
server test checks the 400 for every format. Through a real libtfgrammar,
the 8,000-property schema is refused at 2 s while a small schema compiles,
a retry joins the running compile, and once that returns the grammar comes
from the cache.

Fixes ashhart#3209
 item 3)

qwen3_5/draw_topk.zig moves unchanged to core/lanes/sampling_row_topk.zig (lanes imports become
sampling.zig/grammar.zig, the Qwen error names become NonfiniteLogits/NoAllowedToken, the parameter
`sampling` is `settings`). sampling_row.draw tries it first for a sampled top_k of 1..128, as
qwen3_5/draw.zig did, so qwen3_5/draw.zig is core's draw with the errors mapped back to the Qwen names.
The three selection tests move with the code; a core test pins the heap-free path through sampling_row.draw.
…ests

The planned decode walk's score kernels (tf_plan_score*, the long-span
and the short-span ones, q fp32 and in the cache's kind) take a path
for head size 256, the Qwen3.6-35B-A3B and Qwen3.8-27B attention:

- every lane takes its eight elements without the `lane + 32 i < d`
  test, so a key's products form one plain chain;
- a wave's keys are scored in one basic block (no branch per key on
  `visible`), so their chains and folds interleave;
- lane 0 writes a head's scores of the wave in one 16-byte (long) or
  8-byte (short) store when the rows are aligned and the span is a
  multiple of the wave's keys, else one at a time;
- keys are read through global, not flat, pointers, so LDS waits do
  not also wait on the cache loads;
- a long-span block walks eight steps of its warps' keys and loads the
  next step's keys while the step before is summed; launches/plan.zig
  divides the score grid by the steps.

Stats, apply and the partial sums are unchanged, and other head sizes
keep the current path.

Why the bits hold: each score is the same sum in the same order. Lane
l adds its eight products in element order from 0.f, then the folds
run at xor 16, 8, 4, 2, 1 with each lane's own value as the first
operand, as before. Keys past the row's position are not loaded (their
registers hold zeros) and their scores are still -inf. A fused
v_add_f32_dpp fold (partner + x) was tried and dropped: on gfx1151 it
keeps the other operand's payload when both are NaN.

kernel_tests/plan_pin.zig pins every byte the walk writes (scores,
stats, partials, output) on keys and queries poisoned with NaNs of
distinct payloads and signs and with infinities, long and short spans,
q fp32 and bf16, by a digest recorded on the kernels this replaces.
The eight score records take the registers ROCm 10.1's hipcc reports
for each served chip, updated in place.

Refs ashhart#3429
…el contract

The contract's walk fixed d = 128, so it never entered the score's
d == 256 path. It now registers that path for both Qwen head groups
(16 query heads over 2 KV heads and 24 over 4), on short spans (two
keys a wave) and long ones (four keys, eight steps a block), with q
fp32 and in the cache's kind: eight kernels through gates 1-4.

- Rows end at causal cuts: inside a wave's keys, on a wave's, a step's
  and a block's edge, at the span's end, one key and all but the last;
  the float64 reference sums each row over the keys it sees.
- Spans past the 8- and 16-byte score stores (1023, 4093, 16386,
  16387, 16511, 16513) take the scalar tail, and served[0] of the
  24-head cases is one, so gate 2's guard bytes cover that tail.
- Gate 4's rows see every key, so its weights stay 1 / keys.
- A control launches the walk with the long-span score grid counted
  for 16 steps a block where the kernel walks 8; gate 3 must go red.

Refs ashhart#3429
The d == 256 branch inside plan_score_body shared the register
allocation of tf_plan_score_*, so Nemotron's d = 128 walk ran at 107
VGPRs where main runs 48. The branch moves into its own entry points,
and every existing score kernel is main's source again.

- plan.hip: tf_plan_score256_{f16,bf16,act_f16,act_bf16} run
  plan_score256_body, which holds plan_score_d256's walk verbatim
  (eight steps of four keys a warp a block, keys loaded a step early,
  no element tests). plan_score_body and the eight tf_plan_score*
  kernels equal main's byte for byte; the file only adds lines.
- launches/plan.zig dispatches d == 256 on long spans to the new
  kernels and divides their grid by score_steps; other head sizes and
  short spans launch main's kernels, as on main.
- Records: hip_records.zig is main's again (in place, 600 lines); the
  four new kernels get records in hip_records_score.zig.
- Contract: the planted grid fault now targets tf_plan_score256_*,
  with a control for q fp32 and one for q in the cache's kind.
- plan_pin.zig pins Nemotron's shape too (32 heads over 2, d 128, a
  long span), with its own digest beside the d = 256 one.

Refs ashhart#3429
… their arrival order (ashhart#3775)

Flash Next's chat template renders each tool result as an anonymous <tool_response> block, so the model reads them
by position. When an assistant made several calls and the results arrived out of call order, each answer was read
as the wrong call's: two read_file calls answered production-first gave the defaults file's port as production's.

After normalizing, renderStarts now reorders, for flashnext-zig only, a contiguous run of tool results that follows
an assistant with two or more tool_calls: only when the run holds exactly one result for each call's id, with no
blank or repeated id. Any other run keeps arrival order. Every other request and backend renders as before.

The regression test renders AB, BA, BA with the ids swapped, and a repeated id through a template that emits
anonymous result blocks; it fails on main without the fix (BA renders 9137 first) and passes with it.

Reported, fixed and tested by @srh3877, ported to main.

Co-authored-by: srh3877 <84433664+srh3877@users.noreply.github.com>
…shhart#2833)

Every host save and disk-recall blank pinned new memory (cuMemHostAlloc) and
every drop unpinned it. A dropped copy's buffer now goes to a list of at most
two spares on the target, once no copy into or out of it can be queued: the
save synchronized, and no restore still reads it (a stuck one still goes to
the copy-source quarantine). The next save or blank of exactly that size takes
it instead of pinning. The prompt cache counts the spares inside its budget
(snap_spare), frees them when it needs the room (snap_trim, now wired through
cuda_snaps.zig) and keeps a state in a spare without evicting more
(snap_reuses); the dense and MoE entries both declare the hooks. The spares
are freed with the engine, after the host closes the prompt cache.

The bytes copied are the same; only their buffer changes. Host tests on a
mock driver that moves real bytes: reuse after a drain, none before, another
size pins, the cap, trim and teardown, byte-equal saves and restores in every
layout, a recall blank, and the store reusing an evicted state's buffer.
… stage

Main's stage geometry reads first and whole; a geometry built field by field from undefined left them unset,
so deltas() read past the layer table and every kept-spares test crashed on today's main.
…o spares

saveCache takes the spare list now; the checker's three saves passed five arguments, so the Linux checker
(compile-qwen35-rounds-host, and tf-qwen35-cuda on a device) no longer compiled.
…imported inline, so cuda_native.zig stays under 600 lines
POST /v1/responses with background: true answers at once with the response, status "queued", and runs the turn on
its own thread after the POST returns; leaving the connection does not cancel it. GET /v1/responses/{id} polls it:
queued, in_progress (no output yet), then the finished response as the same request sent normally returns it. The
job runs its own copy of the translated chat body through the same turn and chat path, on a connection that is gone
only when cancelled, so the same body and seed give the same tokens. Its end is an ordinary stored response, kept
before the job leaves the running list so a poll always finds one of the two. The store itself is unchanged.

POST /v1/responses/{id}/cancel goes through the request cancel route's registry: a running reply ends "cancelled"
with the text it had, as POST /v1/requests/{id}/cancel ends it, and either route takes the resp_ id; before the turn
registers, the gone hook stops it with nothing run. The route waits up to 2 s for the end and answers with it. A
second cancel answers the cancelled response again; any other ended background response, or one not created with
background, answers 400; an unknown id 404. DELETE of a running one stops it and keeps nothing.

Limits: 64 queued or running per server, 16 per API key, 256 MiB of copied requests; past them a create answers 429
background_limit_exceeded before any thread starts. A job takes the route's gate counts and lease (Held.take) and
releases them once its end is stored, so --max-inflight, idle unload and a stop's drain see it as a request in
progress; Server.deinit cancels and waits for any left. Refused with 400 by name: stream: true or store: false with
background, a non-boolean true value, background over a Responses socket, GET ?stream=true of a background
response, and a previous_response_id that names one still running. With keys only a full or [admin] key reaches
stored responses, as before; without keys the 128-bit id is the right to read, cancel or delete one, as for GET
and DELETE.

The golden refuse-background case now sends stream: true with background, which is still refused, so the frozen
answers stay deterministic; its expected body is the new refusal.

Fixes ashhart#3187
kernel-contract.md: keep upstream's Nemotron 3.5 Transcribe CUDA audio encoder
paragraph beside this branch's MiniMax-H3-Image Metal paragraph.

device/profile.zig: take upstream's JSON-value reader, which reads exponent
and fractional integer forms (12e1, 18446744073709551615.0) that this branch's
field-by-field reader rejected, and whose new test requires them. Both sides
keep the parse out of compiler-rt's quad floats.
@plotarmordev
plotarmordev merged commit c43045b into main Nov 19, 2026
@plotarmordev
plotarmordev deleted the feat/95-merge-upstream-main branch November 19, 2026 00:04
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.

7 participants