Skip to content

GLM-5.3-Flash image input on CUDA (two ranks), and both ranks stop a reply when its caller leaves - #194

Closed
pulseandthread wants to merge 7 commits into
ashhart:mainfrom
pulseandthread:glm-cuda-vision
Closed

pulseandthread wants to merge 7 commits into
ashhart:mainfrom
pulseandthread:glm-cuda-vision

Conversation

@pulseandthread

@pulseandthread pulseandthread commented Oct 1, 2026 •

Copy link
Copy Markdown

GLM-5.3-Flash image input on CUDA (two ranks)

--vision was refused for GLM-5.3-Flash on CUDA ("currently MLX-only"). This adds it to the two-rank CUDA engine,
following the Qwen CUDA design in docs/vision.md: rank 0 encodes, rank 1 receives the features, image prompts start
with fresh caches and keep no prompt state.

How it works

  • No positions to send. GLM-5.3-Flash's DSA layers are NoPE (qk_rope_head_dim: 0) and the rest are KDA, so an
    image prompt only replaces the placeholder rows of the input embeddings. Rank 1 finds those rows in the prompt it
    already holds; only the features cross the link (the engine's existing NCCL all-gather).
  • Tower: vision/glm_cuda.py checks the GLM5-Next tower from safetensors headers alone (every tensor, shapes from
    vision_config, floating-point, PyTorch or channels-last convolutions), counts its bytes and a workspace in rank 0's
    startup estimate, and loads it into transformers' Glm5NextVisionModel (meta-device build, filled from the
    checkpoint bytes, each tensor in its stored dtype, SDPA), as QwenCudaVision does for Qwen.
  • Prefill: decode.prefill writes the features over each chunk's placeholder rows in every hyper-connection
    stream, and over the MTP head's next-token rows (the CUDA counterpart of the MLX runtime's _vision_next).
    Decode is unchanged.
  • Preprocessing off MLX: GLMImageProcessor falls back to the checkpoint tokenizer plus transformers'
    Glm5NextImageProcessorPil, the torch-free backend MLX-VLM's processor copies. On five synthetic images
    (40x40 to 2000x1000, budgets 256-4096) both give identical grids and pixel values within 4.8e-7.
    transformers 5.17 is the first release with glm5_next, so the vision extra asks for it off macOS.
  • Fix found on the way: ThinkingOffTemplate.render dropped allow_images, so any image request on GLM's CUDA
    server failed to render (separate commit).
  • The server extends a gate's continuation with the frontend's own continued() when it has one (GLM has no
    positions to recompute).
  • Shared vision options (0.6.4). --vision-image-tokens N reaches GLM through the shared CUDA app: a request's
    images share up to N visual tokens (each image keeps at most 4,096, as on Qwen), and the tower encodes runs of
    whole images of at most 16,384 patches, so a request inside one run is still one call. --vision-offload keeps the
    tower in host RAM and moves it to the GPU only while an image is encoded (rank 0 reserves the tower plus 2 GiB for a
    visit instead of the 4 GiB workspace on top of the resident tower; the 2 GiB is a conservative guess, GLM's peak
    has not been measured). Video stays Flash Next's: GLM's frontend has no video support, so a video_url part is
    refused with content parts must be text or image_url; audio and video are unsupported.

Precision

Review asked that the tower keep the checkpoint's own dtypes instead of casting F16 and F32 tensors to BF16. It does.

  • Kept: every tower tensor is loaded to the device in its stored dtype (BF16, F16 or F32; the test checkpoint mixes
    all three). The memory estimate counts the stored bytes (F32 = 4, it counted 2 before). Pixels are made in the patch
    convolution's own dtype. Rotary frequencies stay F32, as transformers builds them.
  • Why a few activation casts are needed: transformers' tower assumes one dtype, so a mixed-dtype tower would fail
    (an F32 RMSNorm weight makes its output F32, and the next BF16 linear refuses it). Three places, none touching a
    weight (keep_stored_dtypes, glm_cuda.py): (1) a forward pre-hook turns the activation entering a Linear,
    Conv or LayerNorm into that module's weight dtype; (2) attention's q, k, v are widened to their common dtype
    before SDPA (lossless; a norm weight in F32 makes q and k F32 while v keeps its linear's dtype); (3) a module whose
    bias is stored in another dtype than its weight adds the bias to the output unfused, in the wider dtype.
    When all tensors are BF16, as in the GLM-5.3-Flash checkpoints tested here, all three do nothing and the output is
    bit-identical to the previous loader's (the existing equality test still passes).
  • The one required cast: the final features become BF16 as they enter the engine. The engine's prompt rows
    (b.x) are BF16 and every embedding path (4-bit table or BF16 table) writes BF16 rows, so an image feature must be
    the model's own activation dtype there, as a token's embedding is.
  • Side by side: tools/glm_vision_dtypes.py MODEL_DIR IMAGE encodes the image through the stored-dtype tower and
    an all-BF16 copy of it and prints the dtype of every tensor kind and the max/mean absolute difference of the
    features; with --server URL [--server-b URL] it sends the same image prompt twice (to one server for a run-to-run
    baseline, or to the stored-dtype and the BF16-cast builds) and prints both replies' token ids and where they first
    differ. --synthetic runs it on a tiny mixed-dtype tower without a checkpoint.
  • Tests (tests/test_vision_glm_dtypes.py, CPU): the loaded parameters equal the stored tensors bit for bit and
    keep their dtypes; on a synthetic tower with F32 norms, an F16 linear and BF16 elsewhere, the features are closer to
    the F32 computation of the same stored values than the all-BF16 cast path is (0.92x of its mean error; 0.76x with
    an F32 bias beside a BF16 weight; 0.48x when every linear is F16); the byte count uses stored sizes.

Tested

The measurements below were taken on the 0.6.0 tree this branch started from; the rebase onto 0.6.4 (communicator
interface, shared vision options) was checked on CPU only, and the GPU tests are to be rerun on the Sparks.

Two DGX Sparks (GB10), EXL3 checkpoint (4-bit routed experts, BF16 elsewhere including the tower), --tp 2,
--drafter none (MTP drafts), --context 65536, temperature 0, thinking off:

request prompt tokens first token decode
text, 0.6.0 (no --vision) 17 / 425 2.15 s / 2.64 s 24.2 / 30.3 tok/s
text, this branch with --vision 17 / 425 0.92 s / 1.18 s 26.6 / 30.2 tok/s
one 512x512 image 384 1.17 s (warm; 4.26 s the first image after start) 30.0 tok/s
two images 716 2.78 s 35.3 tok/s
four images 1,402 4.22 s 40.0 tok/s
  • The text rows are each server's first requests after a start, so their first-token times include warm-up and
    are not a speed comparison.
  • Text replies are byte-identical to unmodified 0.6.0 for both prompts, and for six prompts of 13 to 3,332
    tokens, thinking on and off.
  • Long prompts (synthetic text, one 512x512 image at the end or in the middle, streaming and not, thinking on and
    off): 3,766, 7,103-7,111 and 10,463-10,469 tokens, all described correctly; the same long text prefix first sent
    as a text turn (kept state) and then with an image; a field-shaped request (system notes, eight history turns
    with reasoning_content, three tools, temperature 1, 10,931 tokens); and a camera-sized 4000x3000 JPEG
    (4,096 image rows, 12,164 tokens in all) whose rows straddle prefill chunks and the 2,051-token dense limit.
    Image prompts prefill at about 320 tok/s here, so a 12k-token one takes about 40 s to its first token.
  • A synthetic image (red circle top left, blue square bottom right, the word SEVEN) is described with every shape,
    colour, position and the word. Two images, and four distinct images, are each described correctly and in order.
  • A fifth image is refused: 400 a request supports at most 4 images.
  • Drafted replies equal serial ones (draft: false) for an image prompt, greedy and seeded sampling.
  • A text prompt sent after image requests still resumes from its kept state with the same reply.
  • GPU memory per process (nvidia-smi --query-compute-apps, sampled every 0.5 s during requests): rank 0
    91.5 GiB on 0.6.0 after text, 92.7 GiB on this branch after text (the 1.05 GiB tower and its startup reserve)
    and 93.1 GiB at the peak of the image requests; rank 1 91.5 GiB on 0.6.0, 91.6-91.7 GiB on this branch.

Unit tests: tests/test_vision_glm_cuda.py (a 12,164-token prompt's 4,096 image rows written once per chunk, main
and MTP rows, on both ranks; headers, startup estimate, rows into every stream, transport,
continuation, the meta-built and the checkpoint-loaded tower equal to a normal build, the template fix);
tests/cuda/test_glm_vision.py on the synthetic GLM checkpoint: image rows whose features are the replaced tokens'
own embeddings leave the text prompt's state, MTP cache and reply bit for bit (greedy and sampled), keep no prompt
state, and a server without the tower refuses images; a 2,400-token image prompt whose rows cross a chunk and the
dense limit replies as its text twin. These and the GLM engine and long-context tests pass on both GB10s (55 with the
precision tests); the CPU suite shows no new failures.

Not covered

  • --vision-offload and a --vision-image-tokens above 4,096 on GLM are new in the rebase and untested on GPU; the
    offload reserve (tower + 2 GiB) is unmeasured.

  • The two-rank stop-on-disconnect fix that was in this PR (both ranks stop a reply when its caller asks) is now its
    own PR, the GLM twin of fix(flash next cuda): both ranks stop a reply when its caller asks #231, so this one is only the image input.

  • Not run with the DFlash2 drafter (--drafter none throughout). The drafter reads the target's taps, which carry
    the image rows, so no change was needed, but it is untested here.

  • Not run on the MLX-format GLM checkpoint on CUDA (its tower is BF16 too; the loader accepts both layouts).

crescit added a commit to crescit/TensorFold that referenced this pull request Oct 2, 2026
Adapt PR ashhart#194 image input and cancellation for TP=1 and materialize the full EXL3 vision tower with strict checkpoint validation. Preserve native image markers in text-only templates and qualify image drafting, four-image requests, and mesh coexistence.

Co-authored-by: PulseAndThread <[email protected]>
@plotarmordev

Copy link
Copy Markdown
Contributor

Ran the stop vote together with #218 on two DGX Sparks, as discussed there: GLM-5.3-Flash EXL3 4 bpw, --tp 2 --context 16384, this PR at f61ad1d (on v0.6.1) alone and merged with #218 (no conflicts). Same test as on #218: idle keep-alive connections to push the request's socket past 1023, a non-streaming ignore_eos request of 4,000 tokens, client closes after 3 s.

socket below 1024 socket past 1023
v0.6.1 pair busy 157 s (76 tokens counted) busy 157 s (4,000)
+ #218 busy 157 s (73) busy 157 s (77)
+ #194 free in 0.25 s (71) busy 157 s (4,000)
+ #194 + #218 free in 0.25 s (76) free in 0.25 s (77)

So, as you said, the two don't overlap and a pair needs both. After each run a follow-up greedy request was answered in about 2 s with the same reply, so rank 1 was free. Neither rank logged errors.

Flash Next on two ranks has the same problem, and the stop vote here is GLM's only. Same test on v0.6.1 with Flash Next (Vontra MLX 4-bit, --tp 2 --context 16384):

Flash Next, two ranks socket below 1024 socket past 1023
v0.6.1 pair busy 46 s (235 tokens counted) busy 46 s (4,000)
+ #218 busy 46 s (240) busy 46 s (246)

@pulseandthread happy to port the stop vote to Flash Next's two-rank engine if you want, or leave it to you, your call.

Not covered: I only tested the stop vote. The image input in this PR I didn't run.

@pulseandthread

Copy link
Copy Markdown
Author

Thanks for the full matrix, that settles it. Please go ahead with the Flash Next port, I'll stay on the GLM side (the image input, and a follow-up so an image turn can resume a kept text prefix). If it helps, the stop vote is self-contained in StopVote in engine.py: rank 0's caller decides, both ranks gather one int per round and stop together.

@ashhart

ashhart commented Oct 3, 2026

Copy link
Copy Markdown
Owner

Thank you, @pulseandthread. We would like a re-roll rather than a close. The part we cannot take is the precision change while loading the vision tower: F16 and F32 tensors are cast to BF16, which changes the numbers the rest of the model sees, so replies drift from a run that keeps the checkpoint's own dtypes. Could you rework the loader so each tensor keeps its stored dtype? If one operation truly needs another dtype, show it with the same prompt run both ways, side by side. The stop-on-disconnect part overlaps #231, which is under test for the next release. This stays open while you re-roll.

@pulseandthread

Copy link
Copy Markdown
Author

Thanks for the look. Reworked: the tower now loads every tensor in its stored dtype, with no cast on any weight; a mixed-dtype tower needs three activation casts at module boundaries (documented in the loader and the PR text), and the one remaining conversion is the features entering the engine's BF16 prompt rows, same as a token embedding. Measured on the real checkpoint: all 347 tower tensors are BF16 in both the EXL3 export and zai-org's release, so the features are bit-identical before and after (tools/glm_vision_dtypes.py prints the side-by-side; max |diff| 0). Tests cover a synthetic tower mixing F32, F16 and BF16.

The stop vote is now its own PR (#320), the GLM twin of #231, so this one is only the image input. Both are rebased onto 0.6.4, and the tower honours --vision-offload and --vision-image-tokens there.

qwen_cuda.float_headers returns a tower's tensor headers once each is a floating-point tensor whose bytes lie
inside its file; checkpoint_vision reads it as before, and GLM's CUDA tower reuses it.

(cherry picked from commit b9a1e99)
Off MLX, GLMImageProcessor takes the checkpoint's tokenizer and transformers' Glm5NextImageProcessorPil, the
torch-free backend MLX-VLM's processor copies: on five synthetic images (40x40 to 2000x1000, budgets 256-4096)
both give the same grids and pixel values within 4.8e-7. transformers 5.17 is the first release with it, so the
vision extra asks for it off macOS.

continued() extends a prepared prompt by text only (a gate's continuation); GLM has no image positions to extend.

(cherry picked from commit 48bed57)
…heckpoint template

ThinkingOffTemplate.render took no allow_images, so an image request on GLM's CUDA server failed to render.

(cherry picked from commit d900641)
GLM-5.3-Flash took images on MLX only. On CUDA:

- vision/glm_cuda.py: header-only checks of the GLM5-Next tower (every tensor, shapes from vision_config,
  floating-point, PyTorch or channels-last convolutions), its bytes and a workspace in rank 0's startup estimate,
  the tower in transformers' Glm5NextVisionModel built on the meta device and filled from the checkpoint bytes
  as BF16, and encode() checking the rows against every placeholder before rank 1 is woken
- Its DSA layers are NoPE and the rest KDA, so an image prompt needs no positions: rank 1 finds the image rows in
  the prompt it already holds and receives only the features through the engine's all-gather
- decode.prefill writes the features over the placeholder rows of each chunk, in every hyper-connection stream,
  and over the MTP head's next-token rows, as the MLX runtime's _vision_next does
- An image request never resumes and keeps no prompt state (fresh caches, as Qwen on CUDA); the live rows mark
  image positions so no kept text prompt can match them
- --vision on both ranks (the settings check names it); the gate in serve_options goes
- The server extends a gate's continuation with the frontend's own continued() when it has one

Two DGX Sparks, EXL3 checkpoint, --drafter none, temperature 0: text replies equal 0.6.0's; a 512x512 image of a
red circle, a blue square and the word SEVEN is described with its colours, positions and the word; two and four
images in one request are each described in order; a fifth is refused. 1.17 s to first token for a 384-token
image prompt, 1.18 s for a 425-token text prompt; the tower holds 1.05 GiB on rank 0.

Tests: tests/test_vision_glm_cuda.py (headers, estimate, rows into every stream, transport, continuation, the
meta-built and checkpoint-loaded tower equal to a normal build); tests/cuda/test_glm_vision.py (image rows whose
features are the replaced tokens' embeddings leave the text prompt's state, MTP cache and reply bit for bit,
greedy and sampled; no state kept; a server without the tower refuses).

(cherry picked from commit 8eae15d)
- a 12,164-token prompt whose 4,096 image rows straddle 2,048-row chunks and the 2,051-token dense limit: every
  image row is written exactly once, main and MTP next-token rows, with the features both ranks receive
- on the synthetic checkpoint, a 2,400-token image prompt whose rows cross a 256-row chunk and the dense limit
  replies as its text twin, greedy and sampled

On two DGX Sparks, image prompts of 3,766 to 12,164 tokens (image at the end or in the middle, streaming or not,
thinking on or off, after a kept long text prefix, a 4000x3000 JPEG) were all described correctly.

(cherry picked from commit 2a3acc1)
…d CUDA app

The option reaches GlmApp through App's keyword and the same ImageLimits that split_images and load_images read, so a
raised count lets a GLM request carry more than four images.

(cherry picked from commit a34d8dc)
The loader cast every F16 and F32 vision tensor to bf16, changing the numbers the
model sees. Tensors now load in their stored dtype. A mixed-dtype tower needs three
activation casts and no weight casts: the input of each Linear, Conv and LayerNorm
takes the module's weight dtype; attention's q, k and v are widened to a common
dtype; a bias stored in another dtype than its weight is added unfused. The one
required cast stays, the final features into the engine's bf16 prompt rows. The
startup estimate counts stored bytes (F32 = 4). tools/glm_vision_dtypes.py shows
the stored-dtype and an all-bf16 tower side by side.

(cherry picked from commit b6d92449d61053cf030463ba8af01b4a689f47d5)
@ashhart

ashhart commented Oct 6, 2026

Copy link
Copy Markdown
Owner

Thank you, @pulseandthread. Reworking the tower so every tensor keeps its stored dtype, as the review asked, settled the main concern, and the side-by-side tool makes it easy to check.

The Python engine is frozen (#286) and new work goes into the Zig engine, so this won't merge. The Zig engine has no GLM-5.3-Flash family yet, its server takes text only so far, and Zig CUDA runs only Nemotron. When GLM-5.3-Flash and image input reach it, your design carries over with your credit: rank 0 encodes and sends only the features, the features overwrite the placeholder rows with no positions to move, and image rows built from a token's own embedding must leave the reply unchanged bit for bit.

@ashhart ashhart closed this Oct 6, 2026
grearjake-star added a commit to grearjake-star/TensorFold that referenced this pull request Oct 8, 2026
The GLM serial, MTP and DFlash2 decode loops (and auto_decode) called on_tokens but never read its
result, and rank 1 followed with a callback that could not stop. So when a client left, a stop string
matched or a grammar cut the reply, both ranks decoded on to max_tokens and every later request
waited behind it (a 343 s busy pair in the report). A sticky stop vote (stop.StopVote) now rides one
extra word on the round's existing sample all-gather, so both ranks end after the same round with no
added exchange. Replies up to the stop are unchanged.

Upstream: ashhart#301 (the same bug as ashhart#320 and ashhart#194, found on the GLM-5.3-Flash DGX Spark
recipe), closed unmerged with the Python engine frozen. Host tests in tests/test_glm_serial_stop.py;
the CUDA test needs a GLM checkpoint on two ranks, which this fork's gate does not run.

Co-authored-by: MiaAI-Lab <[email protected]>
grearjake-star added a commit to grearjake-star/TensorFold that referenced this pull request Oct 8, 2026
On two ranks Flash Next threw away on_tokens' True ("both ranks decode to the end") and rank 1 followed
with no callback, so when a client left, a stop string matched or a gate cut the reply, both ranks
decoded on to max_tokens (a 28-token reply took 38.7 s on two Sparks). A StopVote all-gathers rank
0's sticky stop, one int a round, and both ranks end after the same round; rank 1's follower passes a
vote that never asks. One GPU is unchanged: the vote is only built when tp == 2.

Upstream: ashhart#231 (GLM's stop vote from ashhart#194 ported to Flash Next), closed unmerged with
the Python engine frozen. Host tests only here; the fork's gate runs one GPU, so two-rank serving is
not exercised by it.

Co-authored-by: plotarmordev <[email protected]>
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.

3 participants