Skip to content

GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold

Python

Up to 50 images and 4 videos a request (patch 0053); pin the image by digest; CHANGELOG

MiaAI-Labf50c8f177c08
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..0a3316f
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,48 @@
+# Changelog
+
+Every change to this recipe, newest first. Each release names the image it serves: `scripts/prepare.sh` pulls
+`ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold` by the digest pinned in `scripts/config.sh`.
+
+## v1.1 (2026-10-01): up to 50 images and 4 videos a request
+
+Image `v0.5.0-cb7c56f7f921` (`sha256:6ee3c6e0430040b69ddcb0c96c7fbbcb94a5bed47d48a8ba092626369ae533b9`), 53 patches.
+
+### Added
+- Patch `0053-glm-many-media`: up to **50 images** and **4 videos** a request (was 4 and 2).
+ - A request's images share 16,384 tokens: up to 8 keep the full 2,048 each, more get an equal share (327 with 50).
+ Its videos share 32,768: 1 or 2 keep 16,384 each, 3 or 4 get 10,922 or 8,192.
+ - Request bodies up to 96 MiB (was 32 MiB), so data URLs can carry about 70 MB of images and videos; images up to
+ 64 MB in all (was 20 MB).
+ - Each image is resized as it is decoded, so only one full-size image is in memory at a time, and the vision
+ tower's output is no longer copied once more at the end: lower peak memory for every image or video request.
+ - New settings: `TENSORFOLD_GLM_MAX_IMAGES` (50), `TENSORFOLD_GLM_MAX_VIDEOS` (4),
+ `TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS` (16,384), `TENSORFOLD_GLM_REQUEST_VIDEO_TOKENS` (32,768).
+- `CHANGELOG.md`.
+
+### Changed
+- The published image is pinned by digest (`IMAGE_TAG` / `IMAGE_DIGEST` in `scripts/config.sh`): `prepare.sh` pulls
+ exactly that image while the patches are this release's. `scripts/publish-image.sh` prints the values to pin after
+ a push; `start.sh` shows the patches hash it serves.
+
+### Unchanged
+- Replies to text requests, and to requests with up to 4 images and 2 videos, are byte-identical to v1.0 (drafted
+ and serial); the KV pool (2,684,928 tokens) and speed are the same.
+- Measured: 50 images in one request answered in 12.5 s (16,239 prompt tokens), lowest free memory on the head
+ 6.75 GiB; 4 videos 6.90 GiB.
+
+## v1.0 (2026-10-01): first release
+
+Image `v0.5.0-cefe8bf45d07` (`sha256:7bcbb617b1f40f1ce12d37e5ba5e42caf1b1c53b444be9951915e966314c3e1d`), 52 patches.
+
+- GLM-5.3-Flash (EXL3 4-bit routed experts, checkpoint `Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw`) on two DGX Sparks
+ with TensorFold v0.5.0 and 52 patches, as an OpenAI-compatible API on port 8888 (model id `GLM-5.3-Flash-EXL3`).
+- 1,048,576-token context, up to 4 requests at once over one shared FP8 KV pool of ~2.7M tokens, prompts that
+ arrive together filled in one forward.
+- DFlash2 and copy drafts (drafted replies equal serial ones), 4-bit dense weights, the RoCE all-gather between the
+ Sparks, prompt and shared-system-prompt reuse.
+- Image and video input (up to 4 images and 2 videos a request), tool calling, structured outputs, `/tokenize`,
+ `/metrics`, `context_length_exceeded` refusals.
+- `start.sh` sets everything up on first run (image, pinned checkpoint and drafter, copy to the worker) and starts
+ both ranks; `stop.sh` stops them.
+- Measured with sparkDash: one request 60.4 tok/s prose, 114.7 structured; 4 at once 108.8 / 227.9 tok/s in all;
+ prefill ~1,950 tok/s up to 64k tokens.
diff --git a/README.md b/README.md
index 528e4b1..6ca1c8e 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@
Serve **GLM-5.3-Flash** from two NVIDIA DGX Sparks (GB10, 128 GB each, linked by their ConnectX-7 ports) through an
OpenAI-compatible API, with **4 concurrent requests**, the model's full **1,048,576-token context** and **image and
video input**. It runs [TensorFold](https://github.com/ashhart/TensorFold) v0.5.0 on both Sparks (one rank on each)
-in NVIDIA's PyTorch container, plus 52 patches: DFlash2 and copy drafts, 4-bit dense weights, an FP8 KV cache,
+in NVIDIA's PyTorch container, plus 53 patches: DFlash2 and copy drafts, 4-bit dense weights, an FP8 KV cache,
faster prompt kernels, a one-shot RoCE all-gather between the Sparks, several requests over one shared cache pool,
vision, tool calling, `/tokenize` and `/metrics`.
@@ -160,9 +160,10 @@ A video is a `video_url` part (`{"type": "video_url", "video_url": {"url": "data
| | Images | Videos |
| --- | --- | --- |
| Formats | JPEG, PNG, WebP | MP4, WebM, MOV, MKV (anything FFmpeg decodes) |
-| Per request | up to 4, 10 MB each, 20 MB in all | up to 2, 64 MB each, 96 MB in all, up to an hour of footage |
-| Tokens | at most 2,048 a picture (`TENSORFOLD_GLM_IMAGE_TOKENS`; a 1080p picture takes 2,040) | 2 frames a second, at most 128 frames spread over the whole clip (`TENSORFOLD_GLM_VIDEO_FRAMES`), at most 16,384 tokens a clip (`TENSORFOLD_GLM_VIDEO_TOKENS`) |
+| Per request | up to 50 (`TENSORFOLD_GLM_MAX_IMAGES`), 10 MB each, 64 MB in all | up to 4 (`TENSORFOLD_GLM_MAX_VIDEOS`), 64 MB each, 96 MB in all, up to an hour of footage each |
+| Tokens | at most 2,048 a picture (`TENSORFOLD_GLM_IMAGE_TOKENS`; a 1080p picture takes 2,040); a request's pictures share 16,384 (`TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS`), so past 8 each gets an equal share (327 with 50) | 2 frames a second, at most 128 frames spread over the whole clip (`TENSORFOLD_GLM_VIDEO_FRAMES`), at most 16,384 tokens a clip (`TENSORFOLD_GLM_VIDEO_TOKENS`); a request's clips share 32,768 (`TENSORFOLD_GLM_REQUEST_VIDEO_TOKENS`), so 3 or 4 clips get 10,922 or 8,192 each |
+A request body can be up to 96 MiB, so data URLs carry about 70 MB of pictures and clips in all.
By default only data URLs are accepted; `VISION_URLS=1` also lets the server fetch public `https://` URLs.
`VISION=0` serves text only and leaves the tower's ~1.8 GiB on rank 0 to the cache.
@@ -191,8 +192,10 @@ the progress lines, the window retry or the smoke test; when either rank ends, i
1. Preflight on both Sparks: Docker, the GPU, `rsync`, key-based ssh, the RoCE link, disk space.
2. The image `tensorfold-glm53:v0.5.0` on the head: TensorFold v0.5.0 with every `patches/*.patch` applied, plus PyAV
(video decoding) and xgrammar (structured outputs), on NVIDIA's `nvcr.io/nvidia/pytorch:26.07-py3`. It first
- pulls `ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold:v0.5.0-<image hash>` (the hash covers the
- patches and those pip packages); without that tag (e.g. after you change `patches/`), or with `PULL=0`, it builds.
+ pulls the published image `ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold:v0.5.0-<image hash>`,
+ by the digest pinned in `scripts/config.sh` (`IMAGE_TAG` / `IMAGE_DIGEST`) while the patches are this release's
+ (the hash covers the patches and those pip packages); after you change `patches/`, it pulls that hash's tag if
+ one is published, else (or with `PULL=0`) it builds.
3. The same image on the worker: pulled, else streamed from the head (`docker save | docker load`), checked identical.
4. The checkpoint, and DFlash2 with `DRAFTER=dflash2`, downloaded into `~/.cache/huggingface` on the head at their
pinned revisions (the checkpoint checked with `tensorfold info`), then copied to the worker with `rsync` over ssh
@@ -273,6 +276,8 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `MULTI_PREFILL` | `1` | prompts that arrive together are filled in one forward (each with the bits it gets alone); `0`: one after another |
| `SERVED_NAME` / `PORT` / `HOST` | `GLM-5.3-Flash-EXL3` / `8888` / `0.0.0.0` | the model id in `/v1/models` and replies; where the API listens |
| `TENSORFOLD_GLM_IMAGE_TOKENS` / `_VIDEO_TOKENS` / `_VIDEO_FRAMES` | `2048` / `16384` / `128` | a picture's and a clip's token caps, and a clip's frames |
+| `TENSORFOLD_GLM_MAX_IMAGES` / `_MAX_VIDEOS` | `50` / `4` | pictures and clips a request |
+| `TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS` / `_REQUEST_VIDEO_TOKENS` | `16384` / `32768` | tokens a request's pictures and clips share (each still within its own cap) |
| `PREPARE` / `PULL` | `auto` / `1` | `start.sh` runs `scripts/prepare.sh` when needed (`1` always, `0` never); `prepare.sh` tries the prebuilt image first (`0`: always build locally) |
| `WAIT_TIMEOUT` / `STOP_TIMEOUT` | `1800` / `30` | seconds `start.sh` waits for the server, and `stop.sh` gives it to shut down |
@@ -344,7 +349,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Drafts, tooling | `0011-glm-draft-sim` | records of DFlash2's drafts for an offline simulator of stop rules (`TF_GLM_DRAFT_DUMP`, off) | how the stop rules were tuned |
| Concurrent requests | `0028-glm-multi-kda`, `0029-glm-multi-dflash2`, `0032-glm-multi-dsa`, `0033-glm-multi-stream-engine`, `0038-glm-multi-rounds`, `0043-glm-parallel-deadlocks`, `0044-glm-parallel-ring-base`, `0051-glm-timing-tokens`, `0052-glm-multi-prefill` | several streams over one shared pool of per-token caches, one batched verify window a round, both ranks kept in step; prompts that arrive together filled in one forward (`MULTI_PREFILL`: 4 prose requests at once 103.4 -> 108.8 tok/s, first token 590 -> 340 ms); a request alone on the one-stream graphs (`TF_GLM_MULTI_LONE`: +0.6-0.9%); the startup timings of verify windows on distinct tokens | 4 requests at once ([Performance](#performance)) |
| Sampling | `0037-cuda-nucleus-union` | a top_p draw from both ranks' candidates together, the same draw with fewer whole-shard reads (`TENSORFOLD_NUCLEUS_UNION=1`, off by default) | opt-in |
-| Server | `0003-glm-vision`, `0039-glm-tool-calls`, `0040-cuda-tokenize`, `0024-server-effort-max`, `0025-cuda-memory-reserve`, `0047-cuda-context-errors`, `0048-cuda-metrics` | GLM's image and video processors and vision tower; GLM tool calls for agent clients; `/tokenize` and `/detokenize`; `reasoning_effort: "max"`; a settable host reserve; context-window refusals with code `context_length_exceeded` and Prometheus `/metrics` (both ported from TensorFold v0.6.0) | the API features above |
+| Server | `0003-glm-vision`, `0053-glm-many-media`, `0039-glm-tool-calls`, `0040-cuda-tokenize`, `0024-server-effort-max`, `0025-cuda-memory-reserve`, `0047-cuda-context-errors`, `0048-cuda-metrics` | GLM's image and video processors and vision tower; up to 50 pictures and 4 clips a request in 96 MiB bodies; GLM tool calls for agent clients; `/tokenize` and `/detokenize`; `reasoning_effort: "max"`; a settable host reserve; context-window refusals with code `context_length_exceeded` and Prometheus `/metrics` (both ported from TensorFold v0.6.0) | the API features above |
## Checks
@@ -375,6 +380,7 @@ scripts/ config.sh (all settings), local.sh.example (this setup's WORKER),
banner.sh (start.sh's banner)
patches/ patches baked into the image
tools/ benchmark and checks
+CHANGELOG.md what changed in each release
CREDITS.md who and what this builds on
LICENSE Apache License 2.0
NOTICE third-party notices (TensorFold's MIT and Apache-2.0 notices, b12x, glm53-tensorfold-spark, ShapleyMcg)
diff --git a/patches/0053-glm-many-media.patch b/patches/0053-glm-many-media.patch
new file mode 100644
index 0000000..a4ac28d
--- /dev/null
+++ b/patches/0053-glm-many-media.patch
@@ -0,0 +1,274 @@
+diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
+index 589b56b..81c9b0f 100644
+--- tensorfold/cuda/http.py
++++ tensorfold/cuda/http.py
+@@ -91,9 +91,9 @@ def make_handler(app: App):
+ return self._json(404, {"error": "not found"})
+ try:
+ length = int(self.headers.get("Content-Length", 0))
+- if not 0 <= length <= 32 * 1024**2:
++ if not 0 <= length <= 96 * 1024**2: # up to 50 pictures or 4 clips as data URLs
+ self.close_connection = True # the unread body must not reach the next request
+- return self._json(400, {"error": {"message": "request body exceeds the 32 MiB limit",
++ return self._json(400, {"error": {"message": "request body exceeds the 96 MiB limit",
+ "type": "invalid_request_error"}})
+ body = json.loads(self.rfile.read(length) or b"{}")
+ except (json.JSONDecodeError, UnicodeDecodeError):
+diff --git tensorfold/server/prompts.py tensorfold/server/prompts.py
+index 3b3a23b..ac3fdc7 100644
+--- tensorfold/server/prompts.py
++++ tensorfold/server/prompts.py
+@@ -40,21 +40,28 @@ def image_slot():
+
+
+ def prepare_images(frontend, messages, render, *, context_limit=None):
+- from tensorfold.vision.images import ImageInputError, load_images, split_images
++ from tensorfold.vision.images import DEFAULT_LIMITS, ImageInputError, load_images, split_images
+
+ if frontend is None:
+ raise RequestError('image input requires a supported vision checkpoint served with --vision')
+ allow_urls = bool(getattr(frontend, 'allow_urls', False))
+ videos = bool(getattr(frontend, 'videos', False)) # a frontend that encodes video frames too
++ # a frontend's own limits (GLM: up to 50 pictures and 4 clips a request); the shared ones otherwise
++ limits = getattr(frontend, 'image_limits', None) or DEFAULT_LIMITS
+ try:
+- template, sources = split_images(messages, allow_urls=allow_urls, allow_videos=videos)
++ template, sources = split_images(messages, limits=limits, allow_urls=allow_urls, allow_videos=videos,
++ max_videos=getattr(frontend, 'max_videos', None))
+ except (ImageInputError, ValueError) as exc:
+ raise RequestError(str(exc)) from exc
+ slot = image_slot()
+ try:
+ from tensorfold.vision.images import ImageSource
+
+- images = load_images([s for s in sources if isinstance(s, ImageSource)], allow_urls=allow_urls)
++ pictures = [s for s in sources if isinstance(s, ImageSource)]
++ if hasattr(frontend, 'load_images'): # a frontend that fits each picture as it decodes it
++ images = frontend.load_images(pictures)
++ else:
++ images = load_images(pictures, limits=limits, allow_urls=allow_urls)
+ clips = [s for s in sources if not isinstance(s, ImageSource)]
+ if clips:
+ if hasattr(frontend, 'load_videos'): # a frontend with its own frame sampling
+diff --git tensorfold/vision/glm.py tensorfold/vision/glm.py
+index 0cda666..08b7bac 100644
+--- tensorfold/vision/glm.py
++++ tensorfold/vision/glm.py
+@@ -16,7 +16,7 @@ import json
+ import math
+ import os
+ import time
+-from dataclasses import dataclass, field
++from dataclasses import dataclass, field, replace
+ from pathlib import Path
+ from typing import Any
+
+@@ -47,20 +47,44 @@ def _env_int(name: str, default: int, low: int, high: int) -> int:
+ @dataclass(frozen=True, slots=True)
+ class GlmVisionLimits:
+ """Token caps: the checkpoint allows 8,000 tokens a picture and 240,000 a clip; these keep a request's
+- encode within the tower's reserved workspace and the prompt within a sensible share of the window."""
++ encode within the tower's reserved workspace and the prompt within a sensible share of the window.
++
++ A request takes up to ``max_images`` pictures and ``max_videos`` clips. Its pictures share
++ ``request_image_tokens`` and its clips ``request_video_tokens`` in equal parts, each still within its own cap:
++ up to 8 pictures and 2 clips (the defaults) keep their full caps, so their canvases and bits are as before."""
+
+ image_tokens: int = 2048 # a picture's tokens at most (a 1080p frame is 2,040 at 2,048)
+ video_tokens: int = 16384 # a clip's tokens at most, over all its frame pairs
+ video_frames: int = 128 # frames sampled from a clip at most (2 a second, spread wider past this)
+ fps: float = 2.0 # the processor's rate
+ min_tokens: int = 16
++ max_images: int = 50 # pictures a request
++ max_videos: int = 4 # clips a request
++ request_image_tokens: int = 16384 # a request's pictures' tokens, shared
++ request_video_tokens: int = 32768 # a request's clips' tokens, shared
+
+ @classmethod
+ def from_env(cls) -> "GlmVisionLimits":
+ d = cls() # a slots class keeps its defaults on instances, not the class
+ return cls(image_tokens=_env_int("TENSORFOLD_GLM_IMAGE_TOKENS", d.image_tokens, 16, 8000),
+ video_tokens=_env_int("TENSORFOLD_GLM_VIDEO_TOKENS", d.video_tokens, 64, 240000),
+- video_frames=_env_int("TENSORFOLD_GLM_VIDEO_FRAMES", d.video_frames, 2, 2048))
++ video_frames=_env_int("TENSORFOLD_GLM_VIDEO_FRAMES", d.video_frames, 2, 2048),
++ max_images=_env_int("TENSORFOLD_GLM_MAX_IMAGES", d.max_images, 1, 256),
++ max_videos=_env_int("TENSORFOLD_GLM_MAX_VIDEOS", d.max_videos, 1, 16),
++ request_image_tokens=_env_int("TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS", d.request_image_tokens,
++ 16, 262144),
++ request_video_tokens=_env_int("TENSORFOLD_GLM_REQUEST_VIDEO_TOKENS", d.request_video_tokens,
++ 64, 1048576))
++
++ def picture_tokens(self, pictures: int) -> int:
++ """Each picture's token cap in a request with ``pictures`` of them."""
++
++ return max(self.min_tokens, min(self.image_tokens, self.request_image_tokens // max(1, pictures)))
++
++ def clip_tokens(self, clips: int) -> int:
++ """Each clip's token cap in a request with ``clips`` of them."""
++
++ return max(64, min(self.video_tokens, self.request_video_tokens // max(1, clips)))
+
+
+ # -- the processors' geometry ---------------------------------------------------------------------------------
+@@ -364,7 +388,10 @@ class GlmVisionTower:
+
+ import torch
+
+- out = []
++ # each pass writes its rows into the request's output at once: the rows are held once, not twice over a cat
++ rows = sum(GlmVision._rows(kind, frames) for kind, frames in items)
++ out = torch.empty((rows, self.out), dtype=torch.bfloat16, device=self.device)
++ at = 0
+ for _, frames in items:
+ frames = frames if frames.dim() == 4 else frames.unsqueeze(0).expand(2, -1, -1, -1)
+ T, _, H, W = frames.shape
+@@ -372,8 +399,11 @@ class GlmVisionTower:
+ per = max(1, PASS_PATCHES // (gh * gw)) # frame pairs a pass
+ for start in range(0, T // 2, per):
+ pairs = frames[2 * start:2 * min(T // 2, start + per)].to(self.device, non_blocking=True)
+- out.append(self.encode(self.patches(pairs), pairs.shape[0] // 2, gh, gw))
+- return torch.cat(out) if out else torch.empty((0, self.out), dtype=torch.bfloat16, device=self.device)
++ x = self.encode(self.patches(pairs), pairs.shape[0] // 2, gh, gw)
++ out[at:at + x.shape[0]].copy_(x)
++ at += x.shape[0]
++ del x
++ return out
+
+
+ # -- the frontend ------------------------------------------------------------------------------------------------
+@@ -397,13 +427,64 @@ class GlmVision:
+ self.tower = GlmVisionTower(model_dir, device)
+ self.weight_bytes = self.tower.weight_bytes
+
++ @property
++ def image_limits(self):
++ """The shared image limits with this frontend's picture count; bytes and pixels scale with it (each picture
++ is fitted to its canvas as it is decoded, so one full-size picture is in host memory at a time)."""
++
++ from .images import DEFAULT_LIMITS as D
++
++ n = self.limits.max_images
++ if n <= D.max_images:
++ return replace(D, max_images=n)
++ return replace(D, max_images=n, max_total_encoded_bytes=64 * 1024 * 1024,
++ max_total_pixels=max(D.max_total_pixels, n * 8 * 1024 * 1024),
++ total_timeout_seconds=max(D.total_timeout_seconds, 2.0 * n))
++
++ @property
++ def max_videos(self) -> int:
++ return self.limits.max_videos
++
++ def load_images(self, sources) -> list:
++ """The request's pictures, each decoded and fitted to its canvas (uint8 [3, H, W]) in turn."""
++
++ from .images import _check_source, _data_bytes, _decode
++ from .images_http import fetch_image
++
++ L = self.image_limits
++ if len(sources) > L.max_images:
++ raise ImageInputError(f"a request supports at most {L.max_images} images")
++ tokens = self.limits.picture_tokens(len(sources))
++ total_bytes, total_pixels, out = 0, 0, []
++ deadline = time.monotonic() + L.total_timeout_seconds
++ for source in sources:
++ _check_source(source, L, self.allow_urls)
++ remaining = min(L.max_encoded_bytes, L.max_total_encoded_bytes - total_bytes)
++ if remaining <= 0 or time.monotonic() >= deadline:
++ raise ImageInputError("image request exceeds the total byte or time limit")
++ if source.url.startswith("data:"):
++ data = _data_bytes(source.url, remaining)
++ else:
++ data, _ = fetch_image(source.url, max_bytes=remaining,
++ deadline=min(deadline, time.monotonic() + L.timeout_seconds),
++ max_redirects=L.max_redirects, max_url_chars=L.max_url_chars)
++ total_bytes += len(data)
++ decoded = _decode(data, source.detail, L, L.max_total_pixels - total_pixels)
++ total_pixels += decoded.width * decoded.height
++ out.append(self._picture(decoded, tokens))
++ del decoded
++ if time.monotonic() >= deadline:
++ raise ImageInputError("image request exceeds the total time limit")
++ return out
++
+ def load_videos(self, sources) -> list[GlmClip]:
+ from .videos import DEFAULT_VIDEO_LIMITS as L, VIDEO_MEDIA_TYPES
+ from .images import _data_bytes
+ from .images_http import fetch_image
+
+- if len(sources) > L.max_videos:
+- raise ImageInputError(f"a request supports at most {L.max_videos} videos")
++ if len(sources) > self.limits.max_videos:
++ raise ImageInputError(f"a request supports at most {self.limits.max_videos} videos")
++ limits = replace(self.limits, video_tokens=self.limits.clip_tokens(len(sources)))
+ total, out = 0, []
+ deadline = time.monotonic() + L.total_timeout_seconds
+ for source in sources:
+@@ -420,16 +501,16 @@ class GlmVision:
+ else:
+ raise ImageInputError("video URLs are off on this server")
+ total += len(data)
+- out.append(decode_clip(data, self.limits, deadline, max_dimension=L.max_dimension,
++ out.append(decode_clip(data, limits, deadline, max_dimension=L.max_dimension,
+ max_seconds=L.max_seconds))
+ return out
+
+- def _picture(self, image):
++ def _picture(self, image, tokens: int):
+ import torch
+
+ rgb = torch.frombuffer(bytearray(image.pixels), dtype=torch.uint8).view(image.height, image.width, 3)
+ rgb = rgb.permute(2, 0, 1)
+- canvas = smart_resize(2, image.height, image.width, self.limits.image_tokens, self.limits.min_tokens)
++ canvas = smart_resize(2, image.height, image.width, tokens, self.limits.min_tokens)
+ return fit(rgb, canvas, content_size(2, image.height, image.width, canvas, self.limits.min_tokens))
+
+ def prepare(self, text: str, images, *, videos=(), max_prompt_tokens: int | None = None) -> GlmPrepared:
+@@ -440,6 +521,7 @@ class GlmVision:
+ text.count(VIDEO) != len(videos) or text.count(VIDEO_SPAN) != len(videos):
+ raise ImageInputError("the prompt's image and video markers do not match its images and videos "
+ "(is <|image|> or <|video|> in the text?)")
++ tokens = self.limits.picture_tokens(len(images))
+ items: list[tuple[str, Any]] = []
+ pieces: list[str] = []
+ image_iter, video_iter = iter(images), iter(videos)
+@@ -450,7 +532,8 @@ class GlmVision:
+ pieces.append(rest)
+ break
+ if v < 0 or 0 <= i < v:
+- picture = self._picture(next(image_iter))
++ picture = next(image_iter) # load_images fits pictures as it decodes them
++ picture = picture if hasattr(picture, "dim") else self._picture(picture, tokens)
+ n = picture.shape[1] // 28 * (picture.shape[2] // 28)
+ pieces.append(rest[:i] + "<|begin_of_image|>" + IMAGE * n + "<|end_of_image|>")
+ items.append(("image", picture))
+diff --git tensorfold/vision/images.py tensorfold/vision/images.py
+index e68c516..c90a79b 100644
+--- tensorfold/vision/images.py
++++ tensorfold/vision/images.py
+@@ -114,9 +114,11 @@ def _check_source(source: ImageSource, limits: ImageLimits, allow_urls: bool = F
+
+
+ def split_images(messages: list[dict[str, Any]], *, limits: ImageLimits = DEFAULT_LIMITS, allow_urls: bool = False,
+- allow_videos: bool = False) -> tuple[list[dict[str, Any]], list[ImageSource]]:
++ allow_videos: bool = False, max_videos: int | None = None
++ ) -> tuple[list[dict[str, Any]], list[ImageSource]]:
+ """Preserve ordered parts, replacing user image URLs with processor image markers; ``allow_videos``: also
+- ``video_url`` parts (``VideoSource`` among the sources, a video marker in the template)."""
++ ``video_url`` parts (``VideoSource`` among the sources, a video marker in the template), at most ``max_videos``
++ (default: the shared video limits')."""
+ if not isinstance(messages, list) or not messages:
+ raise ImageInputError("messages must be a non-empty list")
+ output, sources = [], []
+@@ -150,9 +152,10 @@ def split_images(messages: list[dict[str, Any]], *, limits: ImageLimits = DEFAUL
+ raise ImageInputError("video_url parts are supported only in user messages")
+ if any(part.get(key) for key in _MEDIA - {"video_url"}):
+ raise ImageInputError("video_url parts cannot contain other media")
++ most = max_videos or DEFAULT_VIDEO_LIMITS.max_videos
+ videos = sum(type(s).__name__ == "VideoSource" for s in sources)
+- if videos >= DEFAULT_VIDEO_LIMITS.max_videos:
+- raise ImageInputError(f"a request supports at most {DEFAULT_VIDEO_LIMITS.max_videos} videos")
++ if videos >= most:
++ raise ImageInputError(f"a request supports at most {most} videos")
+ sources.append(video_source(part.get("video_url"), DEFAULT_VIDEO_LIMITS, allow_urls))
+ parts.append({"type": "video"})
+ elif kind == "image_url":
diff --git a/scripts/config.sh b/scripts/config.sh
index 441c40e..2f0b1cc 100644
--- a/scripts/config.sh
+++ b/scripts/config.sh
@@ -47,6 +47,16 @@ IMAGE="${IMAGE:-tensorfold-glm53:${TF_VERSION}}"
IMAGE_EXTRAS="av==18.1.0 xgrammar>=0.2.8,<0.3"
image_hash() { (cat patches/*.patch 2>/dev/null; echo "$IMAGE_EXTRAS") | sha256sum | cut -c1-12; }
GHCR_IMAGE="${GHCR_IMAGE:-ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold}"
+# The published image of this release's patches, pinned: prepare.sh pulls it by digest (a tag can be moved, a digest
+# cannot) while patches/*.patch and IMAGE_EXTRAS still hash to IMAGE_TAG's hash. Other patches pull
+# $GHCR_IMAGE:<TF_VERSION>-<hash> when one is published, else build locally. scripts/publish-image.sh prints both.
+IMAGE_TAG="${IMAGE_TAG:-v0.5.0-cb7c56f7f921}"
+IMAGE_DIGEST="${IMAGE_DIGEST:-sha256:6ee3c6e0430040b69ddcb0c96c7fbbcb94a5bed47d48a8ba092626369ae533b9}"
+# the registry reference prepare.sh pulls for these patches: the pinned digest, or the hash's tag
+prebuilt_image() {
+ local tag="${TF_VERSION}-$(image_hash)"
+ if [[ "$tag" == "$IMAGE_TAG" && -n "$IMAGE_DIGEST" ]]; then echo "$GHCR_IMAGE@$IMAGE_DIGEST"; else echo "$GHCR_IMAGE:$tag"; fi
+}
CONTAINER_NAME="${CONTAINER_NAME:-glm53-flash-tf}" # the same name on both Sparks
SERVED_NAME="${SERVED_NAME:-GLM-5.3-Flash-EXL3}"
diff --git a/scripts/prepare.sh b/scripts/prepare.sh
index eece0cb..3f399bf 100755
--- a/scripts/prepare.sh
+++ b/scripts/prepare.sh
@@ -70,7 +70,7 @@ log "Disk: $(free_gb "$HF_CACHE") GB free under $HF_CACHE here, $(worker_free_gb
# ---------------------------------------------------------------- 2. image (head)
# Local fixes in ./patches (unified diffs against site-packages, applied with patch -p0) are baked into the image.
# The image is rebuilt when they (or IMAGE_EXTRAS) change; the TensorFold install layer stays cached, so that takes seconds.
-prebuilt="$GHCR_IMAGE:${TF_VERSION}-${PATCHES_HASH}"
+prebuilt=$(prebuilt_image) # the pinned digest (config.sh's IMAGE_TAG / IMAGE_DIGEST), else the hash's tag
if [[ $REBUILD -eq 0 && "${PULL:-1}" == 1 && "$built_hash" != "$PATCHES_HASH" ]]; then
log "Pulling the prebuilt image $prebuilt (PULL=0 builds instead)"
if docker pull "$prebuilt" &&
diff --git a/scripts/publish-image.sh b/scripts/publish-image.sh
index 0e0723b..8e9d649 100755
--- a/scripts/publish-image.sh
+++ b/scripts/publish-image.sh
@@ -37,4 +37,7 @@ trap 'rm -rf -- "$login_dir"' EXIT
echo "$token" | DOCKER_CONFIG="$login_dir" docker login ghcr.io -u "$user" --password-stdin >/dev/null
DOCKER_CONFIG="$login_dir" docker push "$GHCR_IMAGE:$tag"
DOCKER_CONFIG="$login_dir" docker push "$GHCR_IMAGE:latest"
+digest=$(docker image inspect -f '{{range .RepoDigests}}{{println .}}{{end}}' "$GHCR_IMAGE:$tag" | grep -m1 "^$GHCR_IMAGE@" |
+ cut -d@ -f2)
log "Done: docker pull $GHCR_IMAGE:$tag"
+log "Pin it in scripts/config.sh: IMAGE_TAG=$tag IMAGE_DIGEST=$digest"
diff --git a/start.sh b/start.sh
index 881114f..ef3a11a 100755
--- a/start.sh
+++ b/start.sh
@@ -22,7 +22,8 @@
# nodes WORKER, FABRIC_PEER, MASTER_PORT, NCCL_RAILS (1: one CX7 port), NCCL_CHANNELS, NCCL_DEBUG
# files MODEL_ID, MODEL_REVISION, DFLASH2_ID, DFLASH2_REVISION, HF_CACHE (default: HF_HOME), KERNEL_CACHE,
# STATE_DIR, HF_HUB_OFFLINE=0 (let TensorFold reach the Hub; default serves from the local cache only)
-# image IMAGE, TF_VERSION, TF_REPO, BASE_IMAGE, GHCR_IMAGE, CONTAINER_NAME
+# image IMAGE, TF_VERSION, TF_REPO, BASE_IMAGE, GHCR_IMAGE, IMAGE_TAG / IMAGE_DIGEST (the pinned published
+# image), CONTAINER_NAME
# setup PREPARE (auto | 1 | 0), PULL, MIN_FREE_GB, IMAGE_FREE_GB, RSYNC_OPTS, HF_TOKEN (prepare.sh's downloads);
# FOREGROUND=1 (stay attached to rank 0's log, exit with its code); WAIT_TIMEOUT (seconds, default 1800);
# STOP_TIMEOUT (stop.sh)
@@ -123,7 +124,7 @@ if [[ "${PREPARE:-auto}" == 1 || ( "${PREPARE:-auto}" != 0 && "$(prepared_state
log "Not ready yet: running scripts/prepare.sh (the first time this pulls the image, downloads ~166 GiB and copies both to the worker)"
./scripts/prepare.sh
else
- log "Ready: $IMAGE and $MODEL_ID on both Sparks${PREPARE:+ (PREPARE=$PREPARE)}"
+ log "Ready: $IMAGE (patches $(image_hash)) and $MODEL_ID on both Sparks${PREPARE:+ (PREPARE=$PREPARE)}"
fi
why="scripts/prepare.sh did not"; [[ "${PREPARE:-auto}" == 0 ]] && why="PREPARE=0 skipped scripts/prepare.sh, which would"
docker image inspect "$IMAGE" >/dev/null 2>&1 || die "image $IMAGE missing: $why build it"