Repository navigation
Add GLM-5.3-Flash (glm5next) on the CPU and CUDA - #242
kotselidis wants to merge 42 commits into
Conversation
b065460 to
149341f
Compare
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
149341f to
5f0e1e2
Compare
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
50f7472 to
0ceb531
Compare
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
Add Kimi-Linear-48B-A3B (kimi-linear)
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
|
@orionpapadakis This is ready for review |
orionpapadakis
left a comment
There was a problem hiding this comment.
Review: #242 Add GLM-5.3-Flash (glm5next) on the CPU and CUDA
Changes requested. Please handle the scope items (A–C) before the code findings, because they change what the PR contains.
A. Move the Kimi-Linear work to its own PR
This PR includes all of Kimi-Linear through the merge of #275 (78de5bea): KimiLinear*, KimiTokenizer, KimiChatFormat, KimiLinearModelLoader, KimiLinearProvider, docs/architecture/kimi-linear.md, and their entries in the service files. Kimi-Linear is a separate model family and should be reviewed on its own.
- Open a separate PR with the Kimi-Linear commits (
2403783f,ed9e28a7,94fbc57b,081e25bf,dd74da13,fc7ac807). - GLM also uses the shared KDA classes (
KdaForward,KdaKernels,KdaBatchKernels,KdaWeights,KdaHostState,KdaDeviceArrays,KdaBatchArrays). These came fromce978388and770036e0. Put those two commits in whichever PR lands first, and rebase the other PR onto it, so they aren't reviewed twice. - Once the split is done, this PR should contain only
glm5nextand the shared changes GLM needs.
B. Remove the GGUF files in src/test/resources/goldens/glm5next-tiny/
There are 8 GGUF files, about 29.9 MB in total: goldens.gguf, model-F32, model-Q8_0, model-Q8_0-layer0, model-Q8_0-layer3, model-Q8_0-experts-Q4_0, model-medium-Q8_0 and model-medium-Q8_0-experts-Q4_0. The whole goldens/ folder on main is 1.0 MB, so this PR makes it about 30 times bigger. Git keeps those binaries in history permanently, even if they are deleted later.
The repo's convention is to commit only recorded outputs (final-row.f32le, row-hashes.txt, token-ids.txt, metadata.json), produced by scripts/regenerate-goldens.sh. Model files stay outside the repo, and the tests skip with assumeTrue when a file is missing.
Please:
- Host the small models outside the repo, for example in a Hugging Face repository or as a release asset.
- Load them from
~/LLMModels/glm5next-tiny/, and skip withassumeTrue("environment absent: fixture ...")when they are missing, as the existing fixtures do. - Note that
Glm5NextForwardTestis a plain unit test, so it runs in everymvn test. After this change it is skipped unless the models are on disk. Say in the test javadoc how to get them.
C. Remove scripts/glm5next/
The folder holds three scripts (convert.py, gguf_io.py, reference.py), 1,539 lines in total, and nothing uses them when the tests run.
convert.py:docs/architecture/glm5next.mdsays llama.cpp'sconvert_hf_to_gguf.pywrites the same tensors. The only thingconvert.pyadds is converting a slice of the layers. That is a development tool; it doesn't belong in jitllm.reference.pyandgguf_io.py: these are needed only to rebuild the goldens. Keep them next to the small models, outside the repo.- If you keep the scripts anywhere, please fix these first:
- No recipe for rebuilding the files. The exact commands for each of the 8 files are not written down anywhere:
--config tiny|medium,--layers 0/3,--type F32|Q8_0,--expert-type Q4_0. The torch and numpy versions are missing too, and thehf/checkpoint thatconvert.pyreads isn't committed. Nobody can rebuild the goldens exactly. - Indexer ties are only caught with
--check-transformers(reference.py:633). A normal run writes goldens even when indexer pool scores are tied. The script breaks ties toward the lower pool, while the official code leaves the order totorch.topk. With random weights, many scores are exactly 0, so ties are likely, and the goldens end up testing that tie rule rather than the model. Refuse ties on every run. - The medium models have no reference goldens. They are only compared device against host. The test javadoc should say so.
- No recipe for rebuilding the files. The exact commands for each of the 8 files are not written down anywhere:
Coverage gaps. These files never reach the code paths behind findings 1, 2, 4 and 7 below:
convert.py:404writes the sameswiglu_clamp_expfor every layer ([limit] * blocks).convert.py:394writesexpert_feed_forward_lengthas one number, not an array.- The tiny config sets
index_kpool_always_select_tail: True. - 16 experts in stacks of 6 never give a device more than two stacks.
- The tensor-split tests put both ranks on one device (
"0:0,0:0").
D. Resolve the merge conflicts
The PR is CONFLICTING against main. These files conflict:
README.mdsrc/main/java/org/beehive/jitllm/backend/tornado/plan/PrefillDecodeForwardPlan.javasrc/main/java/org/beehive/jitllm/model/ModelType.javasrc/main/java/org/beehive/jitllm/tokenizer/Qwen3Tokenizer.javasrc/main/resources/META-INF/services/org.beehive.jitllm.backend.cpu.CpuForwardProvidersrc/main/resources/META-INF/services/org.beehive.jitllm.backend.tornado.plan.TornadoPlanProvidersrc/main/resources/META-INF/services/org.beehive.jitllm.model.provider.ModelProvidersrc/test/java/org/beehive/jitllm/arch/Allowlists.javasrc/test/java/org/beehive/jitllm/backend/tornado/plan/TornadoPlanRegistryTest.java
Do the Kimi split (A) first. Several of these conflicts are Kimi registrations, so they will change.
E. Code findings
Important
Glm5NextModelLoader.java:150: one SwiGLU clamp limit for every layer.swigluLimittakes the largest value of a per-layerswiglu_clamp_exparray, and the configuration keeps a single float. If a file stores 0 (no clamp) for the dense first layers, those layers get clamped anyway. Keep the limits per layer, or refuse files whose values differ by layer. Please check what llama.cpp's converter writes for the dense layers.Glm5NextModelLoader.java:141:perLayer(expert_feed_forward_length)[0]reads layer 0, which is dense. If a file stores the width per layer with 0 for the dense layers,expertHiddenDimis 0 and every MoE layer gives wrong output. Read the value atdenseLead, the first MoE layer.Qwen35MoeBatchKernels.java:379: unwritten rows can put NaN into the residual. An assignment to an expert held on another device gets sorted row 0 with weight 0. If no row was written in that chunk, row 0 holds old device memory, and0 * NaN = NaNreaches the residual. Skip slots with weight 0 incombine.Glm5NextTensorShards.java:200: a device can cover more than two expert stacks. For example, 256 experts in stacks of 43 split across 2 devices gives rank 0 three stacks.Glm5NextLayersthen throwsUnsupportedOperationExceptionwhen the plan is built. Re-cut each device's experts into stacks, or reject the configuration inconfiguration()with a clear error.DeviceSplit.java:220: the last pipeline stage can get less than one group of layers. The byte-balancedlayerBoundsallows a cut just before the last layer. Withlayers=10,alignment=4and 2 stages it can return[0, 8, 10], which breaks the code's own rule ("every stage keeping one group of layers or more") and differs fromalign(). This is shared code, so it affects every family.TornadoVMMasterPlanPipeline.java:101: the new default layer split also changes existing families. The default split now countsgetTokenEmbeddingTable()bytes as load on stage 0, even when the embedding stays on the host.LayerWeightBytes.ofsees only public fields that are arrays or lists indexed by layer. A Llama Q8_0 model split across 2 GPUs without--tensor-splitcan run out of memory on the last device, where the old equal split fit. Count only tensors that are really uploaded to the device, and compare the result with the old split on the existing families.Glm5NextForward.java:492: empty indexer selection. Withkpool_select_tail=false, until the first pool ofkpoolpositions is complete the indexer selects nothing, and attention outputs zeros.reference.pydoes the same, so the goldens can't catch this. Check what the official implementation does.
Minor
MappedFileRegions.java:41:REGIONSis a static map that is never cleared. A server that loads and unloads models keeps every entry and the oldFileChannel. Entries are matched by address alone, so a reused address can map the wrong region. Store the regions with the model, or remove them when the model is released.jitllm:216:--split-mode tensorwithout--devicesis silently ignored.DeviceSplit.fromSystemPropertiesreturns empty before it reads the mode. Report an error instead.
Adds GLM-5.3-Flash (
zai-org/GLM-5.3-Flash) as theglm5nextfamily: its text backbone on the CPU and on CUDA, loaded from llama.cpp'sglm5-nextGGUF files.What it adds
convert_hf_to_gguf.pywrites for this model (general.architecture = glm5-next). Each layer's expert tensor is loaded as stacks under 2³¹ bytes (two stacks of 144 in Q8_0). GGUF keys may now hold a-, as llama.cpp's architecture prefixes do.scripts/glm5next/convert.pywrites the same format from the official FP8 checkpoint and can convert a slice of the layers from only the shards that hold them. Apart from one-ulp rounding inssm_a, it writes the same tensors as llama.cpp's converter.convert.py --expert-type Q4_0keeps the routed experts in Q4_0 and everything else in Q8_0, which brings the full model to 172.6 GiB. The GPU keeps them in Q4_0: decode reads them with DP4A dot products, and the batched prefill unpacks them into the same int8 tiles its grouped GEMMs already use.--devicessplits the layers across GPUs, one pipeline stage each, carrying the four residual streams between stages.--split-mode tensorsplits every layer across the GPUs instead of giving each GPU whole layers, with an NCCL all-reduce after each sublayer. KDA and sparse attention are split by head, the dense FFN by hidden unit, and the routed experts by expert, 72 of the 288 on each of four GPUs; the router, the latent compression, the indexer and the mHC streams run whole on every GPU, the shared expert on the first. Decode and batched prefill both run split this way. The batched prefill all-reduces its chunk outputs in FP16, half the bytes of FP32 (-Djitllm.tensorSplit.fp32AllReduce=truekeeps FP32). Each GPU's share of a projection or an expert stack is mapped from the model file where it is contiguous rather than copied, so the full model loads without a host copy of its experts. Llama-architecture Q8_0 models decode split the same way.--tensor-split, the layers of any family are now split so that the GPU holding the most weight bytes holds as few as possible, counting the embedding table on the first GPU and the output projection on the last. An equal number of layers per GPU put twelve of GLM-5.3-Flash's expert layers (47.5 GiB) on one 48 GB GPU, because its first three layers are small and dense; the new default gives 13, 11, 11 and 10 layers.DeepSeek2Kernels.rmsNormQuantize) now spreads over one workgroup per 256 values, with the same results bit for bit; GLM-4.7-Flash decodes 12% faster. Both softmaxes skip the exponentials that round to zero, with the same results bit for bit; sampling at temperature 0.1 costs about a third of what it did on GLM-4.7-Flash.docs/architecture/glm5next.mddescribes the model, how it maps onto jitllm, the GPU kernels, the GGUF layout and the checks.Usage
python -I scripts/glm5next/convert.py --hf-repo zai-org/GLM-5.3-Flash --download-dir ~/glm53 --layers 3-10 --type Q8_0 --out glm53-l3-10-Q8_0.ggufThe full model on four GPUs:
Split by tensor (NCCL):
The GPU path needs Q8_0 projections (K-quants and Q4_0 projections other than the routed experts are converted to Q8_0 at load) and an FP32 latent cache (
--fp32-kv-cache).Performance
The full model on four GPUs
4× NVIDIA RTX A6000 48 GB (no NVLink), the full GLM-5.3-Flash with Q8_0 weights and Q4_0 routed experts (172.6 GiB), the same GGUF for both engines, layers split across the four GPUs. jitllm with
--cuda-graphs --fp32-kv-cache --split-transport hostand 13/11/11/10 layers per GPU; llama.cpp (build a9d43ecc3) with-ngl 99 -sm layer -ts 13.5/11/11/11.5and an FP16 KV cache. Three repetitions, tokens per second:Split by tensor instead, on the same machine and file; jitllm with
--split-mode tensorand NCCL, llama.cpp (built with NCCL) with-sm tensor. The batched prefill split by tensor and the layer split's prefill ran alongside another user's CPU-only job; the rest had the machine to themselves. Tokens per second:Fed the same 64 tokens, the tensor split and the layer split agree on the top token at 62 positions and share the top five at most; their logits differ by about 3% of the largest one, the int8 activations rounding apart where the GPUs sum their partial results in another order.
Slices of the model on one GPU
NVIDIA A100 80GB, Q8_0, the same GGUF for both engines; jitllm with
--cuda-graphs, llama.cpp with-fa on -ngl 99. Tokens per second.Layers 3–10 of the real weights (8 MoE layers: 6 KDA, 2 sparse attention; 60 GiB):
Layers 0–3 (3 dense layers and 1 MoE layer; 9.5 GiB):
Tests
Glm5NextForwardTest: the CPU pass against goldens from a PyTorch reference (scripts/glm5next/reference.py) of a tiny model with every layer kind, layer by layer.Glm5NextKernelsAccelTest: the decode kernels against host evaluations.Glm5NextDecodeParityAccelTest: the whole GPU plan against the host pass, token by token and after a batched prefill, on the tiny model, its single-layer slices and a medium model whose widths fill whole GEMM tiles; with Q4_0 routed experts; and split across two GPUs.Glm5NextDecodeParityAccelTestandTensorParallelLlamaAccelTestsplit by tensor: on one device exactly the plan without a split; on two, as close to the host (GLM) or to FP32 activations (Llama) as one device.TensorSplitAgainstLayerSplitAccelTestcompares a model's logits split by tensor and by layer on the same tokens.TensorSlicesTest,MappedTensorSlicesTestandTensorShardTestcover the cuts.DeviceSplitTestandLayerWeightBytesAccelTest: the byte-balanced default split, and that each layer's measured device bytes match its tensors in the file.On an A100, all unit tests pass. In the GPU suite, all glm5next tests pass; the 17 failures (qwen35 plan topology, parity and lifecycle tests) fail identically on main.
Not supported yet
The full model does not fit one 80 GB GPU (about 340 GB in Q8_0; 172.6 GiB with Q4_0 routed experts), so it runs split across GPUs. The MTP layer, the vision encoder, the FP16 latent cache and
--with-native-librariesare not supported on the GPU.Follow-up
#275 (Kimi-Linear-48B-A3B,
kimi-linear) is stacked on this branch: it reuses this PR's KDA, routed-expert and int8 GEMM pieces, and moves the shared ones into family-neutral classes. Merge this PR first.