Skip to content

Nemotron Super video input: tubelet tower path, sampling, labels and EVS - #317

Merged
Gajesh2007 merged 168 commits into
mainfrom
feat/nemotron-super-video
Oct 21, 2026
Merged

Gajesh2007 merged 168 commits into
mainfrom
feat/nemotron-super-video

Conversation

@jonathan308

@jonathan308 jonathan308 commented Oct 21, 2026 •

Copy link
Copy Markdown

Summary

Video input for Nemotron 3.5 Super VL in the SDK, stacked on #315. Ports NVIDIA's video path (modeling_nemotron_h_omni.py, image_processing_nemotron_h_omni.py, processing_nemotron_h_omni.py, vLLM's opencv loader and evs.py) token- and feature-exactly:

  • NemotronSuperVideoPreprocessing: 2 fps / 256-frame sampling (vLLM linspace truncation), truncated-millisecond timestamps ("%.2f" of index × ⌊1000/fps⌋ / 1000), per-tubelet labels (Frame 1 sampled at 0.00 seconds and frame 2 sampled at 0.49 seconds: , odd last group alone), and the 1024-patch even-snapped frame grid (252 tokens per tubelet at 16:9, 256 square).
  • NemotronSuperEVS: weight-free pruning after the projector (keep max(N, ⌊T·N·(1−q)⌋), first tubelet always kept, stable descending order); dissimilarity is pairwise so hosts can score overlapping windows.
  • RADIO tubelet path: frames paired as [T, 2·C, H, W] with the [t, c, y, x] patch order, the checkpoint's separate patch_generator.video_embedder (BF16 1280×1536, no bias; previously skipped), then the shared CPE/encoder/prefix drop/final norm/pixel shuffle/mlp1. NemotronSuperImageComposition.videoFeatures(normalizedFrames:) returns [T, N, 4096]; image behaviour is unchanged.
  • Installation: the video embedder is now loaded and charged (+3,932,160 payload bytes; installation payload 73,217,162,760).

Before

flowchart LR
  V1["video_url part"] --> R1["no SDK path<br/>video_embedder skipped at load"]
Loading

After

flowchart LR
  F["sampled RGB frames<br/>(2 fps, ≤256)"] --> G["frameGrid · normalizeRGB"]
  G --> P["pair frames → [T, 6, H, W]"]
  P --> E["video_embedder (1536→1280)"]
  E --> T["RADIO encoder · drop 10 prefix · final norm"]
  T --> S["pixel shuffle v2 · mlp1"] --> X["[T, N, 4096]"]
  X --> EVS["NemotronSuperEVS.keptPositions"]
  L["tubeletLabels · timestamps"] --> PR["provider prompt layout"]
Loading

Validation

  • swift test --filter "NemotronSuper|NemotronRadio" (SDK harness, M3 Ultra): 206 tests in 58 suites pass, including the new sampling/timestamp/label/grid/EVS unit tests, tubelet ordering, embedder load/charge, and the per-tubelet activation bound.
  • Full-checkpoint golden (NemotronSuperVideoReferenceTests, gated on NEMOTRON_SUPER_REFERENCE_DIR + NEMOTRON_SUPER_VIDEO_GOLDEN_DIR): BF16 videoFeatures on the pinned checkpoint vs NVIDIA's own modeling code in float32 on the first two tubelets of a 256×256 clip — per-token cosine mean 0.99986, min 0.9865 (NVIDIA's code in BF16 measured mean 0.99988 against the same golden).
  • Sampling and EVS logic cross-checked against Python on 200k random inputs and vLLM evs.py cases (no mismatch).
  • Through the provider (Serve Nemotron Super video input (mp4/QuickTime) on the managed slot d-inference#1528): prompt token counts equal NVIDIA's processor exactly on three clips at q = 0 and q = 0.5; the full model names colors/words in order and motion direction correctly.

Refactor Pass

Independent review: no change needed (exactness of sampling, timestamps, labels, grid, packing, EVS and installation byte deltas confirmed against upstream). Applied its nit: dissimilarity documents that scores are pairwise.

Merge-readiness fixes (2026-10-21)

#312 and #315 were squash-merged to main (025d65a4, f2f5e4fd); every review fix for their code lands here, so this PR also changes shared CBv2/EngineV2 code used by every model. Independent reviews covered all three SDK PRs; each fix has a regression test that fails without it.

Before / After (paged prefix bank publication, shared engine)

flowchart LR
  subgraph Before
    A1["donor retires"] --> B1["gatherRange(prompt KV) + asyncEval<br/>(outside withError, uncharged)"] --> C1["bank decides:<br/>refresh / refuse / accept"]
    C1 -->|"refresh or refuse"| D1["copy discarded<br/>(up to 2 GiB at 262K tokens)"]
  end
  subgraph After
    A2["donor retires"] --> B2["bank decides from row geometry<br/>(gatheredByteCount)"]
    B2 -->|"refresh or refuse"| D2["no gather"]
    B2 -->|"accept or compact"| C2["build + schedule gather inside withError;<br/>failure refuses publication, drops fence edges"]
  end
Loading

Before / After (ModelOpt load path)

flowchart LR
  subgraph Before
    L1["RouteTables / calibrated-linear init"] --> E1["eval / .item outside withError<br/>(MLX error = process exit)"]
  end
  subgraph After
    L2["init builds constants from validated host Floats"] --> E2["first forward materializes them;<br/>update reads scalars inside withError and throws"]
  end
Loading

What changed

  • Engine (shared): the paged bank decides before gathering and builds/schedules the gather inside withError (HybridPrefixCache.publish(backingBytes:kv:), PagedSequenceKV.gatheredByteCount); MTP owner round bounds cover every planned decode width with drafting capped by the speculative batch (CBv2MTPBoundedAdmission); the Super assistant's owner-bound guard compares against the deepest reachable round (CBv2MTPAllocationLimits.maximumRoundDepth, roundDepth(_:requests:)), so a depth table such as 1,2 no longer refuses every request; non-finite-logit flags are computed before any sampler sees the logits (a host sampler masking in place can no longer flag healthy rows). Contiguous banks and every model without a depth table behave as before.
  • ModelOpt (Super-only types): no MLX evaluation at construction; update throws invalid calibration instead of silently disabling the graph path; non-object safetensors header entries are rejected instead of raising an Objective-C exception; expert banks above 1,024 use MLX's product instead of trapping in the grouped GEMM; the grouped-GEMM tile scheduler is bounded by capacity (uint32 ids clamp unsigned).
  • Super model/installation: an already-faulted construction scope is refused before anything is reserved (it leaked the whole LOAD charge); the adapter's LMInput prepare refuses media instead of dropping it; NemotronSuperDecodeCommandBuffers.limits is a constant; NemotronSuperImagePreprocessing.validateWorkspace is public so the provider refuses oversize images before decoding.
  • Video: public planning helpers no longer trap on degenerate input (dissimilarity returns an empty score set, overflow-checked EVS shapes, retainedCount returns Int?, keptPositions(features:) is internal); timestamps guard absurd rates; tests pin the [t, c, y, x] tubelet order with three channels and a four-tubelet activation peak.
  • Docs: docs/nemotron-super.md and fork.yaml now match the code (2,048-token chunks under a 24 GiB ceiling; tiled prefill not bitwise; weight reads per eight-row dispatch; long-context charging; paged bank; video section).
  • Reverted during review: a checkpoint file stamp with inode and status-change time (00b93cb9, reverted in 024f0824): status-change time moves on metadata-only changes and refused the provider's managed-slot loads.
  • Pins: mlx-swift 81f58d79 (merged GPU: thread-scoped command-buffer commit limits mlx-swift#57, mlx 71271f08 = merged [Metal] thread-scoped command-buffer commit limits mlx#36); main through c17693f5 (Stage provider checkpoint imports without the MLX eval lock #316).

Validation (M3 Ultra, Xcode 27.1, metallib from mlx 71271f08)

  • swift test --filter 'ModelOpt|Nemotron|NVFP4|CBv2NonFinite|CBv2MTP|CBv2Hybrid|CBv2Paged': 760 Swift Testing tests in 140 suites + XCTest pass; \.UnitTests/: 277 + 67 pass; broad CBv2: 730 + 767 XCTest pass (refactor/fix agents' runs).
  • Provider (Layr-Labs/d-inference #1528 with this SDK): 279 Super, SSD, ToolChoice, factory, liveness and capacity tests pass.
  • scripts/check-unit-test-files.sh, swift-format no-op on changed files.

Merge Danger

Door: two-way. Blast radius: CBv2/EngineV2 for every model (bank publication ordering, MTP round bounds, non-finite flag ordering), all verified behavior-preserving except where a fix intends a change; ModelOpt and Super types (Super-only).

jonathan308 and others added 30 commits October 15, 2026 14:17
The Lint workflow formats every Swift file this branch changes and fails
on any difference. Output matches the diff CI produced on 3fc3a10 byte
for byte, and a second pass is a no-op. Formatting only; no behavior
change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
check_forkdiff.py failed because 30 new paths matched no section: the
ModelOpt NVFP4/FP8 and Nemotron Super quantization files, the Super MTP
files in MLXLLM, Tests/MLXLMTests/Integration/Nemotron and
docs/nemotron-super.md. Add a Nemotron 3.5 Super VL section next to the
Nemotron-H 3.5 one and name Kernel/Quantization in the kernel tests
section. Locally the gate now describes all 1,611 changed files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
NemotronSuperImageConfiguration refused any config.json over 4 MiB. The
pinned checkpoint's config.json is 8,668,620 bytes, about 7 MB of it the
ModelOpt per-layer quantization_config, so the real checkpoint could not
load; the synthetic fixtures were all small. Raise the bound to 16 MiB,
the same cap ModelOptTensorFile uses for safetensors headers, and test
both a config of the pinned size and an oversized one.

Found on the first full-checkpoint load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FileHandle.read returns autoreleased buffers, and checkpoint opening
and staging run synchronously, so nothing drained them: opening the 88
real shards (SHA256 in 1 MiB chunks) left the process at 76 GB physical
footprint before any weight was loaded, and staging leaked a second
copy of every payload read. The full checkpoint load then died under
memory pressure without an error.

Hash inside a pool per chunk, and return a Swift-owned copy from
read(_:bytes:) made inside a pool, so each buffer is freed as soon as
the caller's MLXArray copy exists. Fixture suites: 112 Swift Testing
tests in 32 suites pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
NemotronSuperImageConfiguration refused any config.json over 4 MiB. The
pinned checkpoint's config.json is 8,668,620 bytes, about 7 MB of it the
ModelOpt per-layer quantization_config, so the real checkpoint could not
load; the synthetic fixtures were all small. Raise the bound to 16 MiB,
the same cap ModelOptTensorFile uses for safetensors headers, and test
both a config of the pinned size and an oversized one.

Found on the first full-checkpoint load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FileHandle.read returns autoreleased buffers, and checkpoint opening
and staging run synchronously, so nothing drained them: opening the 88
real shards (SHA256 in 1 MiB chunks) left the process at 76 GB physical
footprint before any weight was loaded, and staging leaked a second
copy of every payload read. The full checkpoint load then died under
memory pressure without an error.

Hash inside a pool per chunk, and return a Swift-owned copy from
read(_:bytes:) made inside a pool, so each buffer is freed as soon as
the caller's MLXArray copy exists. Fixture suites: 112 Swift Testing
tests in 32 suites pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The real checkpoint stores all 40 Mamba A_log tensors as BF16, but
NemotronHModel keeps A_log in float32 (castPredicate), so installation
rejected layer 0 as a shape/dtype mismatch. The reference computes
A_log.float(), and BF16 to float32 is exact, so accept exactly that
widening for parameters the model keeps in float32. Any other dtype
mismatch still fails; a test covers both.

Found on the first full-checkpoint load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The real checkpoint stores all 40 Mamba A_log tensors as BF16, but
NemotronHModel keeps A_log in float32 (castPredicate), so installation
rejected layer 0 as a shape/dtype mismatch. The reference computes
A_log.float(), and BF16 to float32 is exact, so accept exactly that
widening for parameters the model keeps in float32. Any other dtype
mismatch still fails; a test covers both.

Found on the first full-checkpoint load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ModelOptNVFP4SwitchLinear now runs a graph route by default. One Metal
kernel reproduces MLX's NVFP4 activation fake quantization bit for bit with
each row's expert input scale, applies the eager NaN/overflow/invalid-ID
masks, and emits clamped IDs and row weight scales. A single gathered packed
NVFP4 product (no global scale, float32 sums) and one weight-scale rounding
follow, so rowwise accumulation is bit-identical to checkedForward. Invalid
IDs give NaN rows plus a validity flag for the owner's fence; the eager path
stays selectable as the reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ModelOptCalibratedLinear validates its registered scalar calibration on the
host at init and after every parameter update, keeps it as device constants,
and runs graphForward by default: no per-call item, no per-tile eval.
NVFP4 rowwise output is bit-identical to checkedForward. FP8 uses MXFP8
kernels with shared unit E8M0 planes on the unmodified E4M3 bytes and scales
the float32 sums once (fp8Product .packed); .exactReference reproduces the
eager tiles and per-weight rounding bit for bit. Invalid calibration still
updates, as before, and the graph path then refuses every call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… chunks

NemotronHModel can switch every installed ModelOpt module between graph and
eager execution and choose the FP8 product and prefill accumulation. With
the graph path selected, calibratedPrefillTokenLimit admits up to 2048 tokens
inside an explicit 2 GiB ModelOpt workspace (per-token bytes of the heaviest
layer); the eager baseline keeps its 64 MiB, 32-token bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Kernel tests compare graph and eager NVFP4 experts and projections bit for
bit across fast and general kernel widths and dtypes, including overflow,
NaN and invalid-ID rows, exhaustively check the FP8 activation kernel over
every bfloat16, bound the packed FP8 product by weight-dtype rounding,
cover invalid calibration updates and NaN-code weights. A tiny latent-MoE
trunk runs plain and CBv2 prefill/decode bitwise, and mixed FP8 within the
stated rounding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Request-owned E4M3 attention history for the embedded prediction head.
Rows are encoded once; an exact decoded mirror keeps returned K/V
bit-identical to NemotronSuperFP8KVCache without re-decoding history.
Storage grows in whole blocks to a fixed capacity, rewind moves only the
offset, restore stages into new buffers, and explicit append/resident
allowances bound admission.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…sistant

graphForward runs the embedded head without host synchronization: routed
experts use ModelOptNVFP4SwitchLinear.lazyDecode, shared experts a local
lazy NVFP4 projection that issues the eager path's exact
quantizedQuantizedMM and overflow rule from registered tensors, attention the
FP8 history, and drafts the shared FP8 output head through lazyFP8Forward.
GraphQuote names every simultaneously live allowance; refusals precede the
first KV append. The loader gains a header-derived LOAD quote and an
exclusive-epoch load for an exact target.

NemotronSuperMTPAssistant is a request-stateful drafter bound to the exact
loaded language model. It queues trusted shifted target history, primes the
prompt in canonical chunks, rewinds every chained draft row and replays
accepted inputs with verifier hidden. It requires greedy serial target
verification, B=1, depth one by default (two or three behind
allowsDeepDrafts), checks calibration validity at the committed fence and
declares a bounded per-request admission (history, backlog, every draft
step's dense FP8 output head, one history chunk, backend scratch).
NemotronSuperMTPTextTarget opts into MTP; the ordinary adapter stays
fail-closed and media requests are refused at submit.

Synthetic fixtures: the graph head and lazy output head equal the eager
reference bitwise; EngineV2 greedy output equals the ordinary adapter token
for token across heads, prompts, lengths and depths; a hand-driven serial
round test checks bitwise target state after natural and forced rejections;
cancellation retires every owner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t wrappers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rappers

The draft graph now uses the same device-resident wrappers as the target:
ModelOptNVFP4SwitchLinear.graphForward (gathered NVFP4, exact activation
quantization) for routed experts and ModelOptCalibratedLinear.graphForward for
shared experts and the shared FP8 output head, with the target's fp8Product.
The local lazy NVFP4 projection and the dense lazy FP8 head are removed, so
the per-request draft quote no longer carries a dense output-head decode.

A projection that refuses graph construction (invalid registered
calibration) is probed before any history write; the assistant returns a
well-formed proposal and ends the request at the committed fence instead of
trapping the engine thread. Invalid device routing ends it the same way.
Synthetic fixtures: graph head equals the eager reference head bitwise, the
exactReference FP8 head equals the eager head bitwise, and the packed FP8
head differs by at most 9.5e-7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Graph FP8 projections now default to .exactReference: the E4M3 storage is
decoded on the device with the eager per-weight rounding and output-row
tiles, bit-identical to checkedForward and without host synchronization.
Single-vector calls merge adjacent eager tiles that MLX's gemv reduces
identically (same K split), so decode issues a few products instead of
hundreds. MXFP8 unit-scale .packed stays opt-in; its shared plane is
allocated when selected, never inside a forward. graphCalibrationValid
exposes the host validation result; workspace quotes include the decoded
slice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
calibratedPrefillTokenLimit bisects for the largest chunk, up to 2048
tokens, whose heaviest layer's ModelOpt workspace (per-call slices plus
per-token activations, sums, outputs and routed copies) fits the explicit
2 GiB budget. modelOptGraphPrefillWorkspaceBytes(tokens:) quotes it for the
owner's admission; FP8 product selection is exposed on the model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Bit-exact graph FP8 against the eager reference at every Super FP8 shape
(including q_proj's mixed K split and the 131072-row head), packed FP8
within its rounding bound, deterministic trunk fixtures, the admitted
prefill limit in the installation test (eager bound still 32), and an
opt-in real-dimension benchmark of one MoE, Mamba and attention layer and
the FP8 head (MODELOPT_GRAPH_BENCH_CONFIG). fork.yaml describes the graph
path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The antialiased bicubic derived kernel centres from a Double scale while
CPU PyTorch uses a float32 scale, so at large output indices the centre
landed one float ulp (2.4e-4) away. Next to a sharp edge that moved the
normalized output by up to 1.05e-3 (2560 -> 2464 columns); upscales
differed by up to 2.2e-5. Reproduce PyTorch 2.12 float32 rounding
instead: float32 scale and centre, a tap argument rounded once from
double, and the fused multiply-adds its arm64 build uses in the Keys
filter and in accumulation, with each sum starting from its first
product. Outputs are now bitwise equal on the existing oracle vectors
and on 50 provider PNG fixtures, including a downscale.

The passes are also vectorized without changing any per-element
operation order: RGB taps as SIMD4 lanes into planar rows, and the
vertical pass as SIMD8 fused multiply-adds across each row. At the
largest admitted 5751x5751 input the CPU resize drops from 403 ms to
87 ms (M3 Ultra, optimized build). Workspace accounting is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…branch

Brings the graph-only MTP head, the serial-verified text assistant, the
rewindable FP8 KV history and, through its merge of claude/super-fastpath
at 63e8f6d, the device-resident ModelOpt wrappers. The three coordinator
fixes it carries as cherry-picks (f61033f, ce2db2b, fd2b9b1) are
byte-identical to 4be1047, 9c063ae and 7175211 already on this branch,
so the merge resolved them as identical changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Takes the fastpath track's latest committed head: the bit-exact device FP8
product as the graph default, prefill chunks admitted by layer workspace and
the Super-shape FP8 tests and benchmark. Uncommitted work in that track's
worktree is not included.

Conflict: fork.yaml, where both sides extended the "Nemotron 3.5 Super VL"
description and the Kernel/Quantization test summary. Resolved by keeping
both: the fastpath graph-path paragraph followed by the MTP assistant
paragraph, and one test summary naming the graph parity tests, the FP8 KV
history and the opt-in benchmark.

The installation test already asserts the new admitted prefill limit
(the token cap, with its workspace under the admitted limit) and keeps the
eager 32-token bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A Metal copy of MLX's single-vector product decodes each E4M3 weight with
the eager rounding as it reads it (1 byte per weight), so .exactReference
decode is as fast as .packed and still bit-identical to checkedForward:
per-output reductions depend only on MLX's K split, taken from the eager
tile that held each row, so each run of same-split tiles is one dispatch.
Prefill rows beyond the eager bound, where no reference tiling exists,
use 32 Mi-element slices instead of 2 Mi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ming

The opt-in benchmark now splits one decode step of a Super MoE and Mamba
layer into router, latent projections, routed experts, shared expert and
FP8 projections, and separates host graph construction from evaluation
for chained layers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fastpath track's final committed head for this round: the fused
bit-exact FP8 vector product behind the exactReference default and the
per-component decode breakdown benchmark. No conflicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ionValid

The assistant's output-head check and the MTP graph's shared-expert check
built one-row probe graphs only to learn whether the fastpath projection
would refuse its registered calibration. The projection now exposes that
host validation result, so read it and throw the same invalidMetadata
error without constructing a graph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	fork.yaml
Hosts reserve media memory before decoding, but nothing quoted the MLX
working set of the RADIO tower and projector. Add a shape-derived upper
bound per image: the embeddings phase (dtype cast, patch rearrangement,
FP32 position interpolation), one transformer block (14 token-width and
3 MLP-width tensors, plus the score matrix and softmax when MLX's fused
attention kernel does not support the head dimension), and the
projector (FP32 norm, pixel shuffle and the 20480-wide hidden layer).
The phase bounds are summed, so the result does not depend on MLX
releasing one phase before the next. `pinnedActivationBytes` evaluates
it for the pinned composition: 2,095,272,960 bytes at 13312 patches.

Measured MLX peak growth at 104x128 patches stays within the bound on
both attention paths: 753 MB vs 1503 MB (head dim 2, unfused, float32)
and 226 MB vs 298 MB (head dim 80, fused, bfloat16).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007 and others added 10 commits October 21, 2026 01:31
NemotronSuperRecurrentAdapter.prepare(_:cache:windowSize:) forwarded to
the language model's default LLMModel prepare, which reads only the
tokens. An LMInput with an image or video was prepared as plain text,
and the media was dropped silently.

The adapter now throws NemotronHModel.SuperMTPTextError.media for an
input with images or video, the refusal NemotronSuperMTPTextTarget
already applies. Media is served through the CBv2 engine.
NemotronSuperRecurrentAdapterTests checks both refusals and that text
alone still prepares to its tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…stant

NemotronSuperDecodeCommandBuffers.limits was a nonisolated(unsafe)
static var, read on every plain decode step. Nothing in the SDK, its
tests or the provider assigns it. It is now a static let (non-optional,
same 100-operation limits), so the decode path reads no unsynchronized
global.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment-only.

- The fused prefill SSD is bit-identical to ssmAttn since cda62e9
  (NemotronSuperSSDTests assert it), but setModelOptFusedSSD still said
  its float32 rounding differs. The 32-token threshold in NemotronH
  also implied that longer prompts are inexact because of the SSD; only
  the tiled matrix products differ there.
- Row-exact batches read each weight once per dispatch of up to eight
  rows (ModelOptRowExact.rowsPerDispatch), for FP8 projections, the BF16
  latent projections and the router. NVFP4 projections and experts run
  one single-vector product per row. The adapter's DecodeProducts.rowExact
  doc put BF16 and router products with NVFP4. Several docs claimed a
  single read for all 16 rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The paged resident bank gathered every retiring donor's prompt KV and
scheduled the copy before `publish` decided anything. A refreshed donor
(the common repeat turn, since Super checkpoints only on its prefill
chunk grid) or an ineligible one then dropped that copy: 8 KiB per token
for Super (512 MiB at 65K tokens), charged neither to the KV grant nor
to the bank. An allocation failure in that asyncEval ran mlx-swift's
default error handler, which exits.

`publish` now decides first, from bytes the engine derives from row
geometry (`PagedSequenceKV.gatheredByteCount`), and asks for the rows
only when it keeps KV: accepted, or left to compaction. The engine then
gathers exactly as before, so kept entries hold the same bytes, and
schedules the copy inside `withError`. A failed or mis-sized copy
refuses the publication: the bank returns its reservation and counts a
capacity refusal, and the engine drains the stream and drops the copy's
write-fence edges. Contiguous donors are unchanged.

`NemotronSuperPagedPrefixReuseTests` checks that a refreshed repeat turn
gathers nothing and that a failed gather leaves the engine serving the
cold run bit for bit; `CBv2HybridPublicationDecisionTests` covers the
bank's decision for each outcome.
`roundBounds` and `capturedWindowGenerations` paired each width up to
the speculative batch with that width's depth, but the depth controller
picks the depth from every planned decode row, target-only media rows
included. A plan can therefore be wider than the rows that draft, and a
depth table that grows past the batch under-sized the owner's round:
with a batch of 2, `[1, 1, 3]`, one media and two text rows draft 6
steps over 8 positions with 10 window generations against bounds of 2,
4 and 2.

Both now walk every planned width up to the larger of the batch and the
table length, with at most the batch drafting, as `historyCopies`
already does. One depth, a non-increasing table, a table no longer than
the batch and the adaptive policy give the same bounds as before;
`CBv2MTPRoundBoundsTests` checks those cases against the old rule and
the widening case above.
The assistant's bounded declaration refused limits whose round draft
steps, window positions or history copies did not cover a chain of
`maximumDraftTokens`, the uncapped configured depth. Those bounds follow
the depth table, so an owner whose table never drafts its maximum was
refused outright: a one-request owner of `1,2` gets one draft step, two
positions and two copies against a depth of 2, and EngineV2 then sets
`fixedBytesPerRequest` to Int.max, which refuses every request.

`CBv2MTPAllocationLimits.maximumRoundDepth` carries the deepest chain a
round can run. EngineV2 fills it from `roundDepth`: the largest depth
the policy fixes for a decode width up to the scheduler's concurrent
requests, the most rows one plan holds. The guard compares against it.
It defaults to `maximumDraftTokens` and only this assistant reads it, so
limits built without it, configs without a table and other drafters are
unchanged.

The widths stop at the request count rather than `maxSpeculativeBatch`:
the two are equal on the provider's Super owner, and a one-request owner
left at the default batch of 8 would otherwise still be refused.
`NemotronSuperMTPSequenceChargeTests` serves a one-request `[1, 2]`
owner with the plain greedy tokens.
The non-finite flags were built from the logits array after
`CBv2StepSampler.sample` received it. MLXArray is a class whose
subscript setters rebind it in place, so a host sampler that masks a
token with `logits[..., id] = -inf` changed what the flags read and
failed healthy rows as non-finite.

Every sampled row and verify window now builds its flags from the
model's logits before the sampler call. The built-in samplers never
write their input, so for them this only reorders lazy graph
construction and the tokens and flags are unchanged.
`CBv2NonFiniteLogitsTests` serves a prompt through an in-place masking
sampler on both backends without a failure.
…w-exact comments

The row-exact projection reads FP8 and dense weights once per eight-row dispatch and runs NVFP4 experts one product per row; two comments still said every weight is read once per group.
…lx-swift#57)

mlx-swift moves from the PR branch tip 45c74613 to the squash-merged main commit 81f58d79 (same API, plus its tests), which pins mlx to the merged Layr-Labs/mlx#36 (71271f08).
Gajesh2007 pushed a commit that referenced this pull request Oct 21, 2026
…MTP assistant and batched decode (#312)

Native Nemotron 3.5 Super VL (ModelOpt NVFP4/FP8/BF16) for the SDK: calibrated loaders and a fenced, pin-verified installation; the RADIO tower and projector image path with bounded preprocessing; a graph-only execution path for the ModelOpt layers (device-side expert routing, calibration scalars as device constants, fused FP8 product, no per-call host syncs); the embedded MTP head with an exact stateful speculative assistant (rectangular verification); exact row-wise batched decode; and chunk-grid recurrent prefix checkpoints. Decode, row-exact batches and MTP verify windows are bitwise equal to the eager reference; default prefill uses tiled accumulation and grouped GEMMs within the documented bound. Everything new is Super-specific; other models' paths are unchanged. Includes main through c17693f (#316). Review fixes for this code (load-time eval discipline, safetensors header and file-stamp hardening, grouped GEMM bounds, faulted-scope and media refusals, docs) land with the top of the Super stack (#317).
Gajesh2007 pushed a commit that referenced this pull request Oct 21, 2026
… the speculating owner, saturating activations, paged prefix bank, MTP depth table (#315)

What the provider's managed Nemotron Super slot needs from the SDK, on top of #312: image requests run target-only on the speculating owner (CBv2RecurrentMTPRequestScopedMediaFallback, Super MTP targets only) while text keeps speculating with identical tokens; the Super installation and MTP head quantize activations with deployment (SATFINITE) overflow semantics (ModelOptActivationOverflow.saturating; every other loader keeps the eager-NaN default); public NemotronSuperCheckpointPin; exact prefix checkpoints on the speculating owner and for image turns; fail-closed sampling on non-finite logits (all models, raw logits only); fused SSD prefill windows bit-identical to ssmAttn; native paged KV declared by the Super adapter and an opt-in exact recurrent prefix bank on segmented paged KV (permitsPagedStorage); fused router-select, expert-combine, Mamba-step and residual-norm decode kernels, each bitwise-tested; an optional MTP depth table by decode rows; per-token charging of the MTP assistant's history with round work sized once per owner; the measured prefill lane bound; thread-scoped command-buffer limits for plain Super decode steps. Pins mlx-swift to the merged Layr-Labs/mlx-swift#57 (81f58d79). Review fixes for this code land with #317.
@Gajesh2007
Gajesh2007 changed the base branch from feat/nemotron-super-production to main October 21, 2026 08:42
Gajesh2007 and others added 5 commits October 21, 2026 01:43
…hange time"

This reverts commit 00b93cb. The status change time also moves on metadata-only changes (permissions, extended attributes, hard links), so a checkpoint whose metadata changed after hashing failed every later read with invalidFile: the provider's managed-slot fixtures refuse their loads with it. Device and inode from fstat of the already open descriptor never change, so they added nothing. The size and modification time stamp is restored; an in-place rewrite that restores both still needs local write access to the pinned files.
roundBounds and capturedWindowGenerations each walked plannedWidths and
recomputed the rule 01e90ee introduced: a plan of N decode rows drafts
at most the speculative batch, at the depth the policy fixes for N.
plannedRounds now yields that (drafting, depth) pair per planned width,
so the rule lives in one place and both bounds only read it.

Behavior-preserving: the widths (1 ... max(batch, table count), with
batch = max(1, maxSpeculativeBatch)), the drafting cap and the depth
call are the same expressions, and both bounds keep their arithmetic and
order. Both run once, from EngineV2.init. CBv2MTPRoundBoundsTests, which
pins the old rule and the widening case, passes unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
retire validated a retiring donor's rows and summed the bank's bytes in
a loop that cleared a `valid` flag and broke out, then branched on the
flag. hybridPublicationDonor returns the rows and bytes, or nil, with
early returns, so retire reads as: find the donor, publish from its
bytes with a deferred copy, or discard its checkpoints.

Behavior-preserving: the same conditions (one row per layer kind, every
row present and covering the prompt, known per-row bytes, no overflow)
decide, and the same rows and bytes reach publish. A layer-count
mismatch now returns before the per-row size reads instead of after
them; those reads (byteCount, gatheredByteCount) are pure lookups, so
the outcome is unchanged. NemotronSuperPagedPrefixReuseTests,
CBv2HybridPublicationDecisionTests, CBv2RecurrentStateTests,
HybridMediaLifecycleTests and CBv2QwenMTPIntegrationTests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
f20d2a2 made the shared NVFP4 activation body read `expert_valid` and
a uint `expert` from its selection snippet, besides `source_row`. The
body's doc now names the three declarations a selection must make.
Comment only; the Metal sources are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Building a paged gather allocates its transfer records, so an allocation failure while the graph was built reached MLX's default handler, which exits. The gather graph is now built inside the same withError scope that schedules it, so any failure refuses the publication and drops its write-fence edges. Also corrects the paged-bank section of docs/nemotron-super.md (decide before copying; failed gathers refuse), the video timestamp comment and the row-exact projection comment.
@Gajesh2007
Gajesh2007 merged commit 8df7bb6 into main Oct 21, 2026
6 checks passed
Gajesh2007 added a commit to Layr-Labs/d-inference that referenced this pull request Oct 21, 2026
Brings in master through 927172b (#1394, #1524) and the merged-dependency pins through the parent: mlx 71271f08 (Layr-Labs/mlx#36) and mlx-swift 81f58d79 (Layr-Labs/mlx-swift#57). The libs/mlx-swift-lm conflict resolves to 8df7bb62, the squash-merged Layr-Labs/mlx-swift-lm#317 on main (same tree as the SDK this branch's fixes were tested against, a00f4730).
jonathan308 added a commit that referenced this pull request Oct 21, 2026
Brings in the Nemotron 3.5 Super stack (#312, #315, #317). Conflicts:
- CBv2MTPBoundedAdmission: keeps GLM's per-token MTP buffers and
  Nemotron's owner-wide work and sequence-scaled declarations side by side;
  the resolved charge carries both (ownerBytes, linear slack, per-pool
  per-token limits).
- Engine loop and MTP execution: keeps GLM's step-scratch deferral and
  prefill frontier capture beside main's decode command-buffer limits,
  non-finite logit flags and durable-checkpoint gate.
- Package.swift: mlx-swift c2cbef34 (contains main's 81f58d79).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 22, 2026
…uster SDK

#314 carries the bitwise GLM speedups cherry-picked from #308, with its own
resolutions and qualification fixes: the shared-expert bitwise gate, the MTP
charge per chunk, sampled-frame video decoding, step-scratch deferral, the
MTP charge test bounds and the strict pool-score tolerance. It also carries
main's Nemotron Super stack (#312, #315, #316, #317). Where both sides changed
the same speedup code, this merge takes #314's version and re-applies the
cluster-only pieces on top:
- the tensor-parallel shard and reduce hooks (bf77bf2, 2cb5efc);
- whole-stage MTP verification windows (23db6fa);
- fenced HC inputs (624fd05);
- the text-stage and final-stage MTP APIs;
- the cluster image plans and the paged engine (#307).
The mlx-swift pin stays at the cluster's 536ea22. The library keeps #308's
final DSA state, without the absorbed-query overlap.

Resolutions:
- GLM5NextArtifactLoader: #314 plus loadTextStage and loadMTP(stage:).
- GLM5NextHyperConnectionNormFusion: #314's one-launch HC kernel plus the
  fenced-input wait and fencedInputs: ["output"] (624fd05).
- GLM5NextMTP: #314 plus the stage-owned target reference, primeHistory,
  primeAndPropose and GLM5NextMTPCheckpoint.arrays.
- GLM5NextMoE: #314's runsPlainQuantizedMatmul gate (0ceec3a). A TP rank
  builds its MLP from the local configuration, so the gate uses local widths.
- GLM5NextMoEPrefillKernel: #314. The two sides differed only in formatting.
- GLM5NextTextCache: #314 plus the KDA captured window (23db6fa).
- GLM5NextWeightInventory: #314 plus the tensor-parallel shard slice.
- NemotronH: main's Super changes plus the #307 layer-stage seam.
  cbv2Forward and cbv2Hidden take inputEmbedding, captureMTP and
  appliesFinalNorm, in that order: main's order first, then the seam's flag.
  appliesFinalNorm: false returns the residual before the fused final norm.
- MLXVLM GLM5NextProcessor: #314's sampled-frame video decoding. It calls the
  cluster's shared GLM5NextRGBDecoder.render instead of the removed rgb().
- Package.swift: #314 and main, with the cluster mlx-swift pin 536ea22.
- fork.yaml: #314 and main, plus the cluster's GLM paragraph and its
  final-stage readout section.
- docs/glm5-next/README.md: the cluster's text, which contains all of
  #314's.
- Tests:
  - From the cluster: FusedConstruction (stage entries) and
    HyperConnectionSiteRevision (fenced old source).
  - StageEntry: #314's version (validity suite in KernelTests) plus the
    cluster's stage bitwise test.
  - From #314: MTP, DSADecodeChain, KDALongConvolution, KDAPrefillKernel,
    KDAStepGraph, MoEDecodeKernel, RouterKernel and PrismMTPBinding.
  - PrefillPipelineTests from #314. This drops GLM5NextDSAOverlapTests and
    the bench's overlap A/B, which both set the removed
    overlapsAbsorbedQueries.
  - Unit/Models/GLM5NextKernelConstantsTests is removed, because #314 moved
    that suite to Kernel/Layers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
javiech1 pushed a commit to javiech1/mlx-swift-lm that referenced this pull request Oct 24, 2026
…ayr-Labs#317)

g and beta were inheriting bfloat16 from input tensors rather than matching the float32 SSM state dtype. This caused Metal kernel recompilation between generation turns, triggering a use-after-free validation failure when reusing QuantizedKVCache.
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