Skip to content

Commit fb985b8

Browse files
taussoeashhart
authored andcommitted
glm5_next: long contexts on a latent MLA cache (256k on two Sparks)
Past its 2,051-token dense window, GLM-5.3-Flash on 0.3.5.1 answered "!!!!..." on two DGX Sparks (--context 36864, a 32k prompt), and the per-head cache admitted at most ~40k tokens. This keeps the DSA layers' 512-wide latent instead of per-head keys and values and makes the sparse path fast: - latent.py: the cache holds c (1 KB a token and layer, both ranks); queries absorb kv_b's key blocks (read as stored, 4-bit), outputs expand through its value blocks; dense and sparse attention over latents, 32-head tiles in prompt chunks, 16 in decode windows (same bits). - sparse.py: token selection for all rows of a chunk over the visible pools, bucketed to powers of two; the top 512 pools by one radix-select kernel (the same set as a stable sort). - graphs.py: CUDA graphs past the dense limit, one per pool bucket. - kda: prompt chunks run the chain as three kernels (same bits). - geometry.mla_geometry(latent=True): admission sizes the latent cache, so --context 0 allocates 487,495 tokens on two Sparks. - engine: prompts of several conversations kept (rows saved when another conversation takes the caches) within TF_GLM_CACHE_GIB (default 3). - TF_GLM_PROFILE: prefill time and memory by block. Two DGX Sparks, MLX 4-bit checkpoint, MTP drafts, cold synthetic codebase with one hidden fact: 32k prompt 1,155 tok/s (28 s to the first token), 128k 1,110 tok/s (118 s), 256k 1,033 tok/s (254 s), fact found each time; decode 42.7 / 45.1 / 40.1 tok/s at those depths; short prompts 49.8 / 42.3 / 60.9 / 48.0 tok/s; drafted == serial 9/9. tests/cuda: 336 passed, 7 skipped on a GB10 (tests/cuda/test_glm_latent.py and test_glm_long_context.py added).
1 parent 34bae79 commit fb985b8

37 files changed

Lines changed: 2170 additions & 133 deletions

‎README.md‎

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ for installation and a first request.
2020
| Qwen3.8-27B | `Vontra/Qwen3.8-27B-MLX-4bit` | MLX, CUDA | `z-lab/Qwen3.8-27B-DFlash2` and context copies; DFlash2 is optional on MLX |
2121
| Qwen3.8 Flash Next | `Vontra/Qwen3.8-Flash-Next-MLX-4bit-MTP` | MLX, CUDA | Included MTP head and context copies |
2222
| GLM-5.3-Flash | `Vontra/GLM-5.3-Flash-MLX-4bit-MTP` | MLX on a 256 GB Mac, CUDA with two ranks | MTP; optional DFlash2 on CUDA |
23-
| Gemma 4 26B-A4B | `mlx-community/gemma-4-26b-a4b-it-4bit` | MLX | Context copies |
23+
| Gemma 4 26B-A4B | `mlx-community/gemma-4-26b-a4b-it-4bit` | MLX | Context copies; `z-lab/gemma-4-26B-A4B-it-DFlash` is optional |
2424
| Qwen3.8-27B (EXL3, experimental) | `turboderp/Qwen3.8-27B-exl3` (branches `3.00bpw`, `4.00bpw`; any codebook, 1 to 8 bits per weight) | CUDA | `z-lab/Qwen3.8-27B-DFlash2` and context copies |
2525
| Qwen3.8 Flash Next (EXL3, experimental) | `turboderp/Qwen3.8-Flash-Next-exl3` (branch `3.05bpw_h5_ng5`; any codebook, a width per tensor) | CUDA | Included MTP head and context copies |
2626

@@ -32,10 +32,11 @@ tensorfold pull Vontra/Qwen3.8-27B-MLX-4bit z-lab/Qwen3.8-27B-DFlash2
3232
tensorfold serve Vontra/Qwen3.8-27B-MLX-4bit
3333
```
3434

35-
Qwen3.8-27B's M5 tensor-unit path reads MLX affine 2-, 3-, 4-, 5-, 6- and 8-bit projections in groups of 64.
36-
On M1 through M4, `row_forward` uses the row-exact `simd_qmm` decoder, with 4-bit/group-64 weights and
37-
windows of up to 16 rows. Serial and drafted calls use the same decoder. On CUDA, pull DFlash2 before
38-
serving; without it, explicitly choose `--no-drafts` for the serial reference.
35+
Qwen3.8-27B reads MLX affine 2-, 3-, 4-, 5-, 6- and 8-bit checkpoints, including mixed layer formats.
36+
This branch adds packed row readers for groups of 32, 64 and 128 on Apple Silicon and CUDA, with hardware
37+
qualification still pending for the new paths. M5 keeps its native tensor-unit kernels for compatible formats,
38+
and other formats use the row decoder. See [quantized checkpoints](docs/quantization.md) for the exact scope.
39+
On CUDA, pull DFlash2 before serving; without it, explicitly choose `--no-drafts` for the serial reference.
3940

4041
Nemotron uses TensorFold projections and routed-expert kernels. Its load-time row check controls drafting;
4142
keep the installed MLX version within the package requirements. The named checkpoint includes
@@ -49,7 +50,8 @@ MLX 4-bit/group-64 weights and the experimental `Mia-AiLab/GLM-5.3-Flash-EXL3-TR
4950
`incoai/GLM-5.3-Flash-DFlash2` checkpoint has non-commercial license
5051
terms, described in [third-party notices](THIRD_PARTY_NOTICES.md).
5152

52-
Gemma 4 has no draft head and drafts copies of its context. Its kernels read 4-bit weights in groups of 32 or 64
53+
Gemma 4 has no draft head. It drafts copies of its context, and chains from z-lab's DFlash model when served with
54+
`--drafter z-lab/gemma-4-26B-A4B-it-DFlash` (pulled once). Its kernels read 4-bit weights in groups of 32 or 64
5355
with an 8-bit router, as the mlx-community conversion stores them; `serve` refuses other Gemma 4 layouts
5456
before downloading.
5557

@@ -90,8 +92,12 @@ between MLX and CUDA, different quantizations, or different tensor-parallel rank
9092
| `--no-drafts` | Decode serially | Both |
9193
| `--drafter auto`, `none`, or model ID | Select an optional draft model where the family supports it | Both |
9294
| `--mtp-drafts N` | Family-specific cap on MTP drafts | Both |
95+
| `--kv-dtype bf16`, `int8`, `int4` | Flash Next: `int8` or `int4` stores keys and values with one fp16 scale per 32 values. Other families and the MLX path refuse it | CUDA |
96+
| `--mtp-confidence P` | Flash Next: stop a draft chain before a later draft under this probability, 0 to 1 (default 0.30) | CUDA |
9397
| `--tp 2 --rank R --master HOST` | Two-rank CUDA execution | CUDA |
9498
| `--prompt-cache-gib N` | Retained conversation-prefix budget; zero disables retention | MLX |
99+
| `--checkpoint-slots N` | Retained conversation prefixes (default 3 per lane, at least 8); long conversations hit this before the byte budget | MLX |
100+
| `--spill-gib N` | Write evicted conversation prefixes to disk (up to N GiB) and read them back instead of prefilling again; zero disables | MLX |
95101
| `--mlx-cache-gib N` | Reusable freed-buffer cache, default 8 GiB | MLX |
96102
| `--snapshot-dir DIR` | Persistent prefix snapshots; `none` disables them | MLX |
97103
| `--no-update-check` | Disable the startup release check | Both |
@@ -109,17 +115,27 @@ that cannot fit one request is refused at startup. `--context 0` removes the met
109115
capacity and memory admission still apply. Use the reported context when configuring client compaction.
110116

111117
On CUDA, Qwen defaults to the affordable native capacity. GLM targets a dense 2,051-token window,
112-
and Nemotron targets 16,384 tokens; the capacity estimate can lower these defaults. Explicit `--context 0` targets the affordable native capacity for every CUDA family.
118+
and Nemotron targets 16,384 tokens; the capacity estimate can lower these defaults. Flash Next's `--kv-dtype int8` or `int4` counts
119+
its smaller cache, so the same memory admits a longer window. Explicit `--context 0` targets the affordable native capacity for every CUDA family.
113120
A positive CUDA value must fit both the native window and the capacity estimate on every rank;
114121
otherwise startup refuses it with fitting guidance. Increasing GLM beyond its dense window enables
115122
its sparse-attention path. The startup report distinguishes native and allocated capacity.
116123

117-
MLX uses a process budget capped by 70% of RAM and the GPU's recommended working set. A family can state a
118-
larger share: GLM-5.3-Flash takes 85% on a Mac with 256 GB or less, with nothing else loaded. It reserves 3 GiB
119-
for the rest of the process before setting the MLX allocator limit. Admission accounts for weights,
120-
cache growth, reply tokens and prefill workspace. `TENSORFOLD_MEMORY_LIMIT_GB` can lower the budget in
121-
GiB. Retained prefixes and reusable MLX buffers have separate limits. Admission can evict retained
122-
prefixes or queue another stream; fitting weights alone does not establish a usable context size.
124+
MLX defaults to a process budget of 70% of RAM. A family can state a larger share: GLM-5.3-Flash takes 85%
125+
on a Mac with 256 GB or less, with nothing else loaded. `TENSORFOLD_MEMORY_LIMIT_GB` replaces that default in
126+
GiB, raising or lowering it; physical RAM and the GPU's recommended working set still cap the result.
127+
The server reserves 3 GiB for the rest of the process before setting the MLX allocator limit, so a
128+
110 GiB process budget allows 107 GiB of MLX buffers. Concurrent admission honors the raised budget
129+
while accounting for memory held elsewhere on the machine. Admission accounts for weights, cache
130+
growth, reply tokens and prefill workspace. Retained prefixes and reusable MLX buffers have separate
131+
limits. Admission can evict retained prefixes or queue another stream; fitting weights alone does not
132+
establish a usable context size. A larger budget leaves less RAM for other applications and cached file pages.
133+
The startup line says how far the variable can raise the budget on this Mac, and a startup refusal says how far it
134+
must go. On a 32 GB Mac, Qwen3.8-27B needs more than the default 22.4 GiB, with or without its draft model.
135+
136+
Flash Next's startup weight check excludes n-gram tensors when the loader keeps them in host file
137+
mappings. The startup report shows resident and file-backed bytes separately. Cached file pages still
138+
consume RAM and can be reclaimed by the OS; see [Flash Next memory](docs/recipes/qwen3.8-flash-next.md#mlx-execution).
123139

124140
An explicit reply limit is reserved before prefill. A request that exceeds context or memory is refused
125141
with fitting guidance; an omitted reply limit is capped by the remaining context. MLX reports a
@@ -128,11 +144,13 @@ CUDA checks context before opening a stream.
128144

129145
The memory-class table below keeps the model combinations under qualification. Its GiB budget ceilings
130146
emulate the listed RAM classes before the 3 GiB process reserve. The actual default budget uses
131-
OS-reported physical memory; a smaller GPU working set or an explicit memory limit lowers it. Context and peak-memory results remain TBD until a public
147+
OS-reported physical memory and the GPU working set; an explicit memory budget can lower or raise it.
148+
Context and peak-memory results remain TBD until a public
132149
prompt fixture, checkpoint revision, runtime, command and measurement output accompany each result.
133150

134151
| Nominal RAM class | Budget ceiling | Qwen3.8-27B + DFlash2 | Qwen3.8-27B, `--drafter none` | Nemotron 3.5 Lightning | Qwen3.8 Flash Next |
135152
| --- | --- | --- | --- | --- | --- |
153+
| 32 GB | 22.4 GiB | TBD | TBD | TBD | TBD |
136154
| 36 GB | 25.2 GiB | TBD | TBD | TBD | TBD |
137155
| 48 GB | 33.6 GiB | TBD | TBD | TBD | TBD |
138156
| 64 GB | 44.8 GiB | TBD | TBD | TBD | TBD |

‎RUNBOOK.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,16 @@ and 16,384 for Nemotron; the capacity estimate can lower these defaults. On CUDA
9999
removes the metadata cap while memory admission still applies. A positive context that cannot fit
100100
is refused at startup.
101101

102+
On MLX, `TENSORFOLD_MEMORY_LIMIT_GB` sets the process budget in GiB in place of the default 70% of RAM.
103+
It can raise or lower the budget, within physical RAM and the GPU's recommended working set:
104+
105+
```bash
106+
TENSORFOLD_MEMORY_LIMIT_GB=110 tensorfold serve Vontra/Qwen3.8-Flash-Next-MLX-4bit-MTP
107+
```
108+
109+
On a 128 GiB M4 Max this gives 110 GiB to the process and 107 GiB to MLX after the 3 GiB reserve.
110+
The same budget reaches concurrent admission; context and request memory checks still apply.
111+
102112
Requested replies need cache space too. Reduce context, reply length, retained prefixes on MLX, or
103113
checkpoint size after a memory refusal. The MLX process budget reserves 3 GiB outside the allocator.
104114
Release-qualified memory and speed results are TBD [release-0.3.5]; see the

‎THIRD_PARTY_NOTICES.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ Next's packs also carry ExLlamaV3's n-gram row codec, read as its `ngram_dequant
7474
MIT License, Copyright © 2025 Turboderp. TensorFold's decoders and kernels are separate implementations,
7575
checked bit for bit against ExLlamaV3's dequantization.
7676

77+
Flash Next's optional int8 and int4 KV caches (`families/qwen4_exp/cuda/kvcache.py`) follow the cache quantization scheme of [ExLlamaV3](https://github.com/turboderp-org/exllamav3) `-cq 8` and `-cq 4` (MIT License, Copyright (c) 2025 Turboderp, text below): groups of 32, one fp16 absmax scale per group, the group rotated by a 32-point Hadamard, midpoint-grid codes, `compand_a == 0`. 8-bit stores each code as a signed int8 (`q - 128`). 4-bit stores two unsigned codes per byte, low nibble first (the same bits as ExLlamaV3's little-endian packing, a uint8 tensor rather than their uint32 words). Their dequantizer folds another `1/sqrt(32)` into the scale and applies the unnormalized butterfly on the way out; this cache applies the normalized H32 to the query and to the merged output instead, and leaves the stored codes rotated. Scales match their quantizer bit for bit. Reconstructed values agree within fp16/bf16 rounding (under 0.01 on random groups), not bit for bit. The quantizer and the attention dequant are written for TensorFold and checked against an independent reference of that arithmetic.
78+
7779
## Vendored code and weights
7880

7981
`src/tensorfold/drafters/vendor/z_lab_dflash/model_mlx.py` is the unmodified `dflash/model_mlx.py` from

‎docs/api.md‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ Image, audio and video input or output requests receive HTTP 400.
1919
| --- | --- | --- |
2020
| `messages` | Text messages, including system, developer, assistant tool calls and tool results | Both |
2121
| `tools` | OpenAI function tools | Both |
22-
| `tool_choice` | `none` hides tools from the template | MLX |
22+
| `tool_choice` | `none` hides tools from the template; `required` or a named function makes the reply call a tool | Both |
2323
| `parallel_tool_calls` | False returns at most one completed call | Both |
2424
| `max_tokens`, `max_completion_tokens` | Explicit reply limit; rejected if prompt plus reply exceeds the window | Both |
2525
| `temperature`, `top_p`, `top_k` | Sampling overrides; zero temperature is greedy | Both |
@@ -42,7 +42,13 @@ MLX rejects malformed numeric controls and out-of-vocabulary raw prompt IDs with
4242
On MLX, `--parallel auto` is the default: requests share rounds within the configured concurrency and memory
4343
budget. Background work waits behind foreground requests. An active background request yields when a
4444
foreground request needs its lane or memory, then restarts with already-delivered tokens suppressed.
45-
Session-title requests are also treated as background work. CUDA serializes generation through its server lock.
45+
Session-title requests are also treated as background work.
46+
47+
On CUDA, `--parallel auto` serves one request at a time. An explicit `--parallel N` above one shares rounds
48+
for Qwen3.8-27B on one or two ranks and for Flash Next on one rank; GLM, Nemotron and Qwen3.6 stay serialized.
49+
When a client disconnects, its CUDA request stops at the next round, and a request still waiting behind
50+
another in one-at-a-time serving does not start; two-rank Flash Next, Nemotron and GLM requests finish on
51+
both ranks.
4652

4753
## Messages and tools
4854

@@ -65,14 +71,28 @@ With `parallel_tool_calls: false`, the server buffers tool deltas until it can r
6571
completed call. Prose and reasoning can still stream. Usage counts the entire decoded reply, including
6672
additional calls omitted from the response.
6773

74+
With `tool_choice: "required"`, or a function named in `tool_choice`, the reply's answer (after any think block
75+
or thought channel) opens a call to an offered tool. The server replaces the first answer token that isn't
76+
whitespace with the tool-call opener (`<tool_call>`, or Gemma 4's `<|tool_call>`) and the template's text before a
77+
tool name, then holds the name to the offered tools: a token that leaves them is replaced by the rest of the first
78+
offered name its written part starts. The template's own rendered call gives that text. A named function is the
79+
only tool the template offers. Each fix depends only on the tokens before it, so drafted, serial and concurrent
80+
decoding write the same call. The MLX engine fixes tokens inside its rounds; CUDA stops the engine at a fix and
81+
decodes on from the reply. The model writes the arguments; a malformed call returns as content.
82+
6883
## Reasoning
6984

7085
On MLX, `reasoning_effort: none` disables thinking; other effort values enable it and reach the chat template.
86+
MLX also reads it from `chat_template_kwargs.reasoning_effort`, where vLLM's clients send it; the top-level field wins.
7187
`high` maps to `xhigh`, and `minimal` maps to `low`. An explicit
7288
`chat_template_kwargs.enable_thinking` takes precedence. Effort support depends on the checkpoint's
7389
template, and effort does not set a token budget. The GLM CUDA handler closes the template's open
7490
think block when thinking is disabled.
7591

92+
A tool call written before the think block closes is the reply's tool call when the reply ends inside the block,
93+
on both backends; the reasoning stops where the call starts, and streamed reasoning never carries the call's markup.
94+
A call only mentioned while thinking, with the block closed after it, stays reasoning.
95+
7696
`thinking_budget` on MLX forces a newline and the closing think marker at the budget, then continues the
7797
answer. The cut depends on token count, so serial and drafted decoding use the same cut. A model that
7898
closes the block earlier is left alone.

‎docs/quantization.md‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Quantized checkpoints
2+
3+
TensorFold reads the precision stored in a checkpoint, including its per-layer settings.
4+
Serve a local or Hugging Face checkpoint through the usual CLI:
5+
6+
```bash
7+
tensorfold info ./model-8bit
8+
tensorfold serve ./model-8bit
9+
```
10+
11+
The `quants` branch extends the Qwen3.5/3.8 dense family to MLX affine weights at 2, 3, 4, 5, 6 and 8 bits, with group sizes 32, 64 and 128.
12+
It keeps packed words, scales and biases at their stored precision, including mixed layer formats.
13+
It does not convert a checkpoint during loading.
14+
Choose an 8-bit checkpoint made from the original model when you want its 8-bit quality.
15+
16+
## Backend paths
17+
18+
| Path | Formats |
19+
| --- | --- |
20+
| Qwen dense, M5 native lane kernels | Affine 2/3/4/5/6/8-bit, group 64; affine 4-bit also group 32 |
21+
| Qwen dense, packed row kernels on Apple Silicon | Affine 2/3/4/5/6/8-bit, groups 32/64/128 |
22+
| Qwen dense, CUDA | Affine 2/3/4/5/6/8-bit, groups 32/64/128 |
23+
| Nemotron | Existing affine 4-bit recipe; broader expert formats are not enabled here |
24+
| Flash Next | Existing uniform affine 4-bit/group-32 recipe |
25+
| GLM and EXL3 | Existing family recipes and separate EXL3 integration |
26+
27+
With `--lane-kernels auto`, M5 uses its native kernels when they support the checkpoint's formats and otherwise uses the packed row decoder.
28+
M1 through M4 use the packed row decoder.
29+
`--lane-kernels on` requires an M5-generation GPU and formats supported by its native kernels; an incompatible format is refused with guidance.
30+
The language path retains BF16 activation requirements.
31+
The new Metal affine projection reader accepts BF16, FP16 or FP32 affine scales and biases with matching metadata dtypes.
32+
33+
All paths still verify draft rows through the lane engine.
34+
The existing specialized 4-bit routes remain available; the general readers make different formats executable without expanding the entire model into dense weights.
35+
Their performance can differ substantially from the specialized routes.
36+
37+
## Mixed precision
38+
39+
The loader reads `quantization` before the legacy `quantization_config`, matching the current MLX loader.
40+
A nonempty per-module mapping uses that mapping's own defaults, so `{"bits": 8}` means affine 8-bit with group 64 even when the global group is 128.
41+
Boolean `true` inherits global settings; `false` and an empty mapping disable quantization for that module where the family supports its resulting unquantized projection.
42+
Conflicting aliases and packed shapes that disagree with the declared bit width or group size are refused.
43+
44+
Fused stacks combine projections only when bit width, group size, input width and metadata dtypes agree.
45+
Otherwise the model computes those projections separately with their declared formats.
46+
CUDA tensor-parallel splits retain complete groups and packed-word boundaries, and memory admission counts the actual packed precision.
47+
Changing a checkpoint, precision or kernel implementation also changes the conditions under which cached states remain valid.
48+
49+
## Scope and qualification
50+
51+
These additions cover MLX affine safetensors checkpoints for the dense Qwen family.
52+
GGUF, AWQ, GPTQ, NVFP, MXFP and arbitrary 8-bit MoE expert formats require their own readers and kernels.
53+
Unsupported formats remain explicit errors.
54+
55+
The new paths are experimental until their hardware qualification is complete.
56+
Each backend must pass packed-value checks, one-row versus batched output equality, full-model drafted versus serial equality, prefix resume, concurrent-stream equality and memory admission before a release claim.
57+
The Metal kernel has a dedicated hardware test in `tests/test_affine_rows_metal.py`; model and GPU tests must run under the machine's existing resource controls.
58+
No speed or quality improvement is implied by a higher bit width.

‎docs/recipes/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Each family page describes its supported checkpoint, kernels and operating limit
99
| Qwen3.8 Flash Next | [MLX prefill and CUDA](qwen3.8-flash-next.md) |
1010
| GLM-5.3-Flash | [MLX on a 256 GB Mac, two-rank CUDA](glm-5.3-flash.md) |
1111
| Gemma 4 26B-A4B | [MLX, fused one-row decode](gemma-4.md) |
12+
| Qwen3.6-35B-A3B | [One-GPU CUDA](qwen3.6-moe.md) |
1213

1314
Contributor guides cover [adding an MLX family](adding-a-family.md),
1415
[adding a CUDA family](adding-a-cuda-family.md) and [CUDA implementation rules](cuda.md).

0 commit comments

Comments
 (0)