Skip to content

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

Python

Patch 0099: no stall at a long request's start - the server tokenizes with Python's GIL released

BadAd8495b31719e581
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54a3f69..5894100 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,20 @@
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`.
+## Unreleased
+
+- **No stall at a long request's start** (patch `0099-glm-tokenize-nogil`, by [BadAd84](https://github.com/BadAd84)):
+ the server tokenized each prompt with the tokenizer's `encode`, which holds Python's GIL for the whole text (~1.2
+ us a token), so while a long prompt was being tokenized the engine loop, and every other stream with it, stopped:
+ ~270 ms at 226k tokens and 725-768 ms at a ~619k-token agent turn (a second stream's longest gap, three Sparks).
+ Every tokenizer call in the server now goes through one helper that uses `encode_batch_fast` on the one text:
+ the same ids (`tools/tokenize_check.py`: real code and prose files, filler, every added token, random Unicode,
+ edge cases, both `add_special_tokens` values, and no `encode` call left in `server.py`), the GIL released (a
+ counting thread keeps 93-99% of its rate, against ~1% under `encode`) and ~30% faster (689k tokens: 799-825 ms
+ -> 559-593 ms). Requests with pictures or clips (`GlmVision.prepare`) tokenize the same way: the same ids, picture
+ positions and content hash (`tools/vision_tokenize_check.py`), and a counting thread's longest gap at ~784k tokens
+ 749 -> 8 ms.
+
## v1.10 (2026-10-08): the effort line at the tail (opt-in), a kept-state share, and a checked second rail
Image: `v0.6.0-a1897d591f70` (`sha256:bc34d7d63f978cf601f42863b284bc95a567c50c10e9adb0866a635be568bf5f`), 96 patches (v1.9.1's plus `0096`, `0097`). Tested live on two
diff --git a/CREDITS.md b/CREDITS.md
index 521996e..904d374 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -134,6 +134,7 @@ checkpoint's ShapleyMcg attribution and the drafter's license).
[BadAd84](https://github.com/BadAd84).
- `0086-glm-prompt-scores-loop` (the prompt scoring, one row and many pool blocks a program): by
[BadAd84](https://github.com/BadAd84).
+- `0099-glm-tokenize-nogil` (prompts tokenized with Python's GIL released): by [BadAd84](https://github.com/BadAd84).
- `0087-glm-display-kv-dispram` (`DISPLAY_KV_BACKEND=dispram`: `0072`'s display reservation on kindling spark-os): by
[BadAd84](https://github.com/BadAd84). It maps the span through `dispram`, the display-carveout lender of
[kindling spark-os](https://github.com/kindlingai/kindling-spark-os) by Matt Mastracci (Kindling AI). Nothing of
diff --git a/README.md b/README.md
index 2bace9c..826049f 100644
--- a/README.md
+++ b/README.md
@@ -653,6 +653,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Capacity status | `0081-tfcap-capacity-status` | every capacity refusal renders the same way: 429 with `Retry-After: 5` (was a bare 503 at two sites, a 400 on the generate path) (by johnwhited, #48) | a refused request's client can back off instead of stacking |
| Admission control | `0082-tfcap-admission-cap` | `TF_GLM_MAX_QUEUED` (unset: queue, as before; a number: past the lanes plus that many queued foreground requests, refuse) turns saturation into a refusal instead of an invisible queue (by johnwhited, #48) | with `TF_GLM_MAX_QUEUED=0`, the fifth request on four lanes: 429 at once with `Retry-After: 5`; unset, it queues as before |
| Delivery abort | `0083-tfcap-delivery-abort` | a stream whose delivery callback raises (broken pipe, reset, timeout) ends at once and frees its lane, instead of the exception escaping and the lane leaking until generation ends (by johnwhited, #48) | a client that dies mid-reply no longer holds a lane |
+| Tokenizing | `0099-glm-tokenize-nogil` | the server, and the vision path for prompts with pictures or clips (`GlmVision.prepare`), turn a prompt into ids with the tokenizer's batch call, which releases Python's GIL (`encode` held it for the whole prompt, ~1.2 us a token, so a long request's start stopped the engine loop and every other stream: 725-768 ms at a ~619k-token turn) and skips the character offsets nothing reads (by [BadAd84](https://github.com/BadAd84)) | the same ids (and picture positions); other streams keep decoding while a long prompt is tokenized |
| Anthropic Messages | `0084-anthropic-messages` | Anthropic's `/v1/messages` (also `/messages`, with `/count_tokens` suffixes), translated to the same chat completion the OpenAI route serves — text and image blocks, `tool_use` / `tool_result`, thinking, `stop_sequences`, `output_config` effort/JSON schema — with Anthropic SSE streaming and bodies capped at 32 MiB (upstream v0.6.3, by [evilpsycho42](https://github.com/evilpsycho42) and [ashhart](https://github.com/ashhart), request bodies by [Jordi Posthumus](https://github.com/JordiPosthumus); backported by [Eduardo Florencio](https://github.com/eduffd)) | Claude Code and the Anthropic SDKs work against the server directly, without a translating proxy |
| Checked draft candidates | `0092-glm-draft-candidates-checked` | the drafter checks each block pass's candidate ids against the vocabulary; on an id outside it (issue #80: a float's bits read as an id) it logs the value, copies the rows again once the device is idle, and fails only if they are still bad | a rare drafter `IndexError` is retried (and its cause logged) instead of killing a rank |
| Spill tier | `0088-glm-spill-tier` | kept prompt states written to local disk on every Spark when they leave the pool (early, in the background, past `SPILL_HIGHWATER`) and read back beside decoding streams, also after a clean restart (`SPILL_GIB`, off by default; authored by Robert Wojciechowski, [wojo](https://github.com/wojo), #78) | [Spill tier](#spill-tier-optional) |
@@ -710,6 +711,7 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform
| --- | --- |
| `tools/needle.py [label] [size]` | hides a passphrase in a ~195k-token prompt (the prompt comes out at ~0.8 x `size` tokens) and checks the model returns it |
| `tools/toolcheck.py` | makes a tool call with an array parameter and checks it comes back as a JSON array |
+| `tools/tokenize_check.py <tokenizer.json> [dir...]` / `tools/vision_tokenize_check.py <tokenizer.json>` | patch 0099's checks on the CPU, run in the image (`docker run ... --entrypoint python3`, see each file): the server's and the vision path's ids equal `encode`'s, no `encode` call left in either file, and a counting thread kept ticking during a long tokenization |
| `tools/display_kv_check.py [--gpu]` | patch 0072's checks, run in the image (`docker run ... --entrypoint python`, see the file): the setting, the span's mapping and unwinding through a fake driver, the carved planes and the pool's copies; with `--gpu`, the real span on a Spark whose display reservation is free |
| `tools/pool_pressure.py [size]` | on a fresh server with nothing else sending requests: two conversations of ~`size` tokens (default 30000) take a turn each, others fill the pool, then each takes another turn; exit 1 when a turn resumes less than 90% of its previous prompt, 2 when the kept-prompt cap stops the fill first (a smaller pool runs it faster: `CONTEXT=131072 KV_POOL_GIB=0.5`) |
| `tools/pool_room_check.py` | patch 0074's checks, run in the image (`docker run ... --entrypoint python`, see the file): the pool's room-making on a CPU arena, what it evicts and moves, and rank 1 replaying the same ops |
diff --git a/patches/0099-glm-tokenize-nogil.patch b/patches/0099-glm-tokenize-nogil.patch
new file mode 100644
index 0000000..d802dad
--- /dev/null
+++ b/patches/0099-glm-tokenize-nogil.patch
@@ -0,0 +1,86 @@
+# The server tokenizes with Python's GIL released: every tokenizer call in the server (the chat and prompt routes,
+# /tokenize, the forced think close and the tool-call gate's encode) goes through App._encode_ids, which calls HF
+# tokenizers' encode_batch_fast on the one text: the same ids as encode, without the character offsets nothing here
+# reads; and GlmVision.prepare (every request with pictures or clips) does the same. encode held the GIL for the whole
+# text, ~1.2 us a token, so a long request's start stopped the engine loop and every other stream (~0.75 s at ~600k
+# tokens). tools/tokenize_check.py, tools/vision_tokenize_check.py.
+
+diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py
+--- tensorfold/cuda/server.py
++++ tensorfold/cuda/server.py
+@@ -236,14 +236,14 @@ class App:
+ vision=rendered.vision, grammar=compiled, think_budget=budget)
+ else:
+ text = render(body["messages"])
+- prompt = self.tok.encode(text, add_special_tokens=False).ids
++ prompt = self._encode_ids(text, False)
+ elif isinstance(body.get("prompt"), list): # token ids (vLLM's and OpenAI's form): served as given
+ prompt = self.token_ids(body["prompt"])
+ else:
+ text = body.get("prompt")
+ if not isinstance(text, str):
+ raise RequestError("prompt must be a string or a list of token ids")
+- prompt = self.tok.encode(text, add_special_tokens=_flag(body, "add_special_tokens", False)).ids
++ prompt = self._encode_ids(text, _flag(body, "add_special_tokens", False))
+ if not prompt:
+ raise RequestError("rendered prompt is empty")
+ # sampling is resolved here, so a malformed control is refused before a stream opens
+@@ -264,6 +264,14 @@ class App:
+ raise RequestError(f"{field} token ids must be in the vocabulary's range 0{top}")
+ return list(value)
+
++ def _encode_ids(self, text: str, special: bool) -> list[int]:
++ """``self.tok.encode(text, add_special_tokens=special).ids``, the same ids, through the batch call: it tokenizes
++ with Python's GIL released (``encode`` holds it, ~1.2 us a token: a 600k-token prompt stopped the engine loop,
++ and every other stream, for ~0.8 s at each request's start) and skips the character offsets nothing here reads
++ (~30% faster)."""
++
++ return self.tok.encode_batch_fast([text], add_special_tokens=special)[0].ids
++
+ def tokenize(self, body: dict[str, Any]) -> dict[str, Any]:
+ """vLLM's ``/tokenize``: a prompt's ids (``add_special_tokens`` as vLLM, default true), or ``messages``' as the
+ chat route renders them (``add_generation_prompt``, default true)."""
+@@ -284,7 +292,7 @@ class App:
+ text = body.get("prompt")
+ if not isinstance(text, str):
+ raise RequestError("prompt must be a string (or send messages)")
+- ids = self.tok.encode(text, add_special_tokens=_flag(body, "add_special_tokens", True)).ids
++ ids = self._encode_ids(text, _flag(body, "add_special_tokens", True))
+ limit = self._context_limit()
+ return {"count": len(ids), "max_model_len": limit if limit is not None else self.native_context_window,
+ "tokens": [int(t) for t in ids]}
+@@ -662,9 +670,9 @@ class App:
+
+ if think_end is None:
+ return []
+- close = [*self.tok.encode("\n", add_special_tokens=False).ids, think_end]
++ close = [*self._encode_ids("\n", False), think_end]
+ if prepared.grammar is None:
+- close += self.tok.encode("\n\n", add_special_tokens=False).ids
++ close += self._encode_ids("\n\n", False)
+ return close
+
+ def _glm_calls(self) -> bool:
+@@ -703,7 +711,7 @@ class App:
+ names = [str((t.get("function") or t).get("name") or "") for t in tools] if lead is not None else []
+ return CallGate.after_prompt(prompt, self.tok.token_to_id(opener), blank, think_open=think[0],
+ think_end=think[1], text=text, lead=lead or "", names=names, tail=tail or "",
+- encode=lambda t: list(self.tok.encode(t, add_special_tokens=False).ids))
++ encode=lambda t: list(self._encode_ids(t, False)))
+
+
+ def _flag(body: dict[str, Any], name: str, default: bool) -> bool:
+diff --git tensorfold/vision/glm.py tensorfold/vision/glm.py
+--- tensorfold/vision/glm.py
++++ tensorfold/vision/glm.py
+@@ -727,7 +727,9 @@
+ pieces.append(_as_text(rest[:v]) + "<|begin_of_video|>" + frames + "<|end_of_video|>")
+ items.append(("video", clip.frames))
+ rest = rest[v + len(VIDEO_SPAN):]
+- ids = self.tok.encode("".join(pieces), add_special_tokens=False).ids
++ # patch 0099: the batch call tokenizes with Python's GIL released (encode holds it, ~1.2 us a token: a long
++ # prompt with a picture stopped the engine loop and every other stream), the same ids (as App._encode_ids)
++ ids = self.tok.encode_batch_fast(["".join(pieces)], add_special_tokens=False)[0].ids
+ if max_prompt_tokens and len(ids) >= max_prompt_tokens:
+ # v0.6.0's context refusal wording (68c6e35, Apache-2.0): served as context_length_exceeded
+ raise ValueError(f"{CONTEXT_LIMIT} {max_prompt_tokens} tokens: the prompt with its images is {len(ids):,} "
diff --git a/tools/tokenize_check.py b/tools/tokenize_check.py
new file mode 100644
index 0000000..c44dcc9
--- /dev/null
+++ b/tools/tokenize_check.py
@@ -0,0 +1,123 @@
+#!/usr/bin/env python3
+"""tools/tokenize_check.py <tokenizer.json> [text dir...]: patch 0099, run in the image (CPU only, the server
+stopped or not).
+
+1. Every call site: the installed server.py (parsed, not run) calls the tokenizer's `encode` nowhere and the helper
+ `App._encode_ids` at every site that used to (the chat and prompt routes, /tokenize, the two forced think-close
+ encodes, the tool-call gate's encode: 6 calls).
+2. The same ids: the server's own `App._encode_ids` (called on a stand-in holding the real GLM tokenizer) must give
+ exactly `tok.encode(text, add_special_tokens=flag).ids` for both flags over every .py file of the installed
+ tensorfold package and every .md / .py / .sh file under the given dirs (the recipe checkout, say), all of them as
+ one string, a long numbered filler, every added/special token's text interleaved with words, random Unicode (CJK,
+ emoji, combining marks, controls) and edge cases; and, on a small template tokenizer whose special tokens the flag
+ adds, that the flag passes through.
+3. The GIL released: a counting thread keeps at least half its idle rate during a ~780k-token encode (`encode` holds
+ the GIL and leaves it near 1%).
+Prints PASS / FAIL lines and ALL PASS; exit 1 on any FAIL.
+
+ docker run --rm --network none -e CUDA_VISIBLE_DEVICES= --entrypoint python3 \
+ -v "$PWD/tools/tokenize_check.py:/c.py:ro" \
+ -v "$HF/models--Mia-AiLab--GLM-5.3-Flash-EXL3-4bpw-TensorFold/snapshots/<rev>/tokenizer.json:/tok.json:ro" \
+ -v "$PWD:/recipe:ro" tensorfold-glm53:v0.6.0 /c.py /tok.json /recipe
+"""
+import ast
+import pathlib
+import random
+import sys
+import threading
+import time
+
+import tensorfold
+import tensorfold.cuda.server as server
+from tokenizers import Tokenizer, models, pre_tokenizers, processors
+
+fails = 0
+
+
+def check(name, ok):
+ global fails
+ print(("PASS " if ok else "FAIL ") + name, flush=True)
+ fails += not ok
+
+
+# 1. every call site
+tree = ast.parse(pathlib.Path(server.__file__).read_text())
+calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)]
+held = [n.lineno for n in calls if n.func.attr == "encode" and isinstance(n.func.value, ast.Attribute)
+ and n.func.value.attr == "tok"]
+helper = [n.lineno for n in calls if n.func.attr == "_encode_ids"]
+check(f"server.py calls the tokenizer's encode nowhere (lines {held})", not held)
+check(f"server.py tokenizes through App._encode_ids at 6 sites (found {len(helper)})", len(helper) == 6)
+encode_ids = getattr(server.App, "_encode_ids", None)
+check("App._encode_ids exists", encode_ids is not None)
+if encode_ids is None:
+ print(f"{fails} FAIL", flush=True)
+ sys.exit(1)
+
+# 2. the same ids
+tok = Tokenizer.from_file(sys.argv[1])
+stand_in = type("S", (), {"tok": tok})()
+
+
+def same(text):
+ return all(encode_ids(stand_in, text, f) == tok.encode(text, add_special_tokens=f).ids for f in (False, True))
+
+
+files = sorted(pathlib.Path(tensorfold.__file__).parent.rglob("*.py"))
+for d in sys.argv[2:]:
+ files += sorted(p for p in pathlib.Path(d).rglob("*") if p.suffix in (".md", ".py", ".sh") and p.is_file())
+bad = [str(f) for f in files if not same(f.read_text(errors="replace"))]
+check(f"{len(files)} real code and prose files, both flags", not bad and len(files) > 50)
+corpus = "".join(f.read_text(errors="replace") for f in files)
+check(f"all of them as one string ({len(corpus) / 1e6:.1f} MB), both flags", same(corpus))
+words = ("lattice probe ferrule datum spindle gauge trellis offset stylus kinematic fixture wafer cosine baseline "
+ "granite bearing encoder servo axis spline tolerance flatness runout").split()
+rnd = random.Random(591)
+filler = "\n".join(f"{i:06d} " + " ".join(rnd.choice(words) for _ in range(11)) for i in range(20000))
+check("a numbered filler, both flags", same(filler))
+special = [t.content for t in tok.get_added_tokens_decoder().values()]
+mixed = [" ".join(rnd.choice(special + words + ["\n", " ", "\t"]) for _ in range(400)) for _ in range(50)]
+check(f"{len(special)} added/special tokens' texts interleaved with words (50 strings), both flags",
+ all(same(t) for t in mixed) and len(special) > 0)
+ranges = [(0x4E00, 0x9FFF), (0x1F300, 0x1FAFF), (0x0300, 0x036F), (0x0000, 0x001F), (0x0400, 0x04FF), (0x0600, 0x06FF)]
+uni = ["".join(chr(rnd.randint(*rnd.choice(ranges))) for _ in range(rnd.randint(1, 3000))) for _ in range(200)]
+check("200 random Unicode strings (CJK, emoji, combining marks, controls, Cyrillic, Arabic), both flags",
+ all(same(t) for t in uni))
+edge = ["", " ", "\n", "\n\n", "\t" * 50, " " * 1000, "a", "\u00a0\u2003", "<|user|>", "</think>\n"]
+check("edge cases (empty, whitespace runs, single tokens), both flags", all(same(t) for t in edge))
+# GLM's post-processor adds nothing (ByteLevel only), so add_special_tokens cannot change its ids: a tokenizer whose
+# template does add tokens makes the flag's pass-through observable
+t2 = Tokenizer(models.WordLevel({"[UNK]": 0, "[BOS]": 1, "[EOS]": 2, "hello": 3, "world": 4}, unk_token="[UNK]"))
+t2.pre_tokenizer = pre_tokenizers.Whitespace()
+t2.post_processor = processors.TemplateProcessing(single="[BOS] $A [EOS]", special_tokens=[("[BOS]", 1), ("[EOS]", 2)])
+s2 = type("S2", (), {"tok": t2})()
+differs = t2.encode("hello world", add_special_tokens=True).ids != t2.encode("hello world", add_special_tokens=False).ids
+check("add_special_tokens passes through (a template tokenizer: the flag changes its ids)",
+ differs and all(encode_ids(s2, "hello world", f) == t2.encode("hello world", add_special_tokens=f).ids
+ for f in (False, True)))
+
+# 3. the GIL released
+big = filler * 2 # ~780k tokens
+count, stop = [0], [False]
+
+
+def spin():
+ while not stop[0]:
+ count[0] += 1
+
+
+th = threading.Thread(target=spin, daemon=True)
+th.start()
+time.sleep(0.3)
+c0, t0 = count[0], time.perf_counter()
+time.sleep(0.5)
+idle = (count[0] - c0) / (time.perf_counter() - t0)
+c0, t0 = count[0], time.perf_counter()
+n = len(encode_ids(stand_in, big, False))
+s = time.perf_counter() - t0
+rate = (count[0] - c0) / s / idle
+stop[0] = True
+check(f"tokenizes with the GIL released ({n} tokens in {1000 * s:.0f} ms, the other thread at {rate:.0%} of idle)",
+ rate >= 0.5)
+print("ALL PASS" if not fails else f"{fails} FAIL", flush=True)
+sys.exit(1 if fails else 0)
diff --git a/tools/vision_tokenize_check.py b/tools/vision_tokenize_check.py
new file mode 100644
index 0000000..1a7072b
--- /dev/null
+++ b/tools/vision_tokenize_check.py
@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+"""tools/vision_tokenize_check.py <tokenizer.json>: patch 0099, run in the image (CPU only, no server, no weights).
+
+1. The call site: the installed vision/glm.py (parsed, not run) calls `self.tok.encode` nowhere and
+ `encode_batch_fast` in GlmVision.prepare.
+2. The same prompt: GlmVision.prepare, run on a stand-in holding the real GLM tokenizer, gives exactly the ids,
+ picture positions and digest it gives with a tokenizer whose batch call is `encode` (the code before the patch),
+ for prompts with 1-3 pictures (other sizes), a quoted marker, text in several scripts and every added token's text,
+ and for a ~800k-token prompt with a picture; and, on a small tokenizer whose post-processor adds a special token,
+ that prepare adds none (add_special_tokens stays False).
+3. The GIL released: a counting thread keeps ticking during prepare on the ~800k-token prompt (its longest gap under
+ 50 ms; with `encode` it stops for the whole tokenization, ~1 s).
+Prints PASS / FAIL lines and ALL PASS; exit 1 on any FAIL.
+
+ docker run --rm --network none -e CUDA_VISIBLE_DEVICES= --entrypoint python3 \
+ -v "$PWD/tools/vision_tokenize_check.py:/c.py:ro" \
+ -v "$HF/models--Mia-AiLab--GLM-5.3-Flash-EXL3-4bpw-TensorFold/snapshots/<rev>/tokenizer.json:/tok.json:ro" \
+ tensorfold-glm53:v0.6.0 /c.py /tok.json
+"""
+import ast
+import inspect
+import sys
+import threading
+import time
+from types import SimpleNamespace
+
+import torch
+from tokenizers import Tokenizer, models, pre_tokenizers, processors
+
+import tensorfold.vision.glm as glm
+
+fails = 0
+
+
+def check(name, ok):
+ global fails
+ print(("PASS " if ok else "FAIL ") + name, flush=True)
+ fails += not ok
+
+
+tok = Tokenizer.from_file(sys.argv[1])
+
+# 1. the call site
+tree = ast.parse(inspect.getsource(glm))
+calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)]
+encodes = [n.lineno for n in calls if n.func.attr == "encode" and ast.unparse(n.func.value) == "self.tok"]
+prep = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "prepare")
+batch = [n for n in ast.walk(prep) if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
+ and n.func.attr == "encode_batch_fast"]
+check(f"vision/glm.py calls self.tok.encode nowhere (lines {encodes}) and encode_batch_fast in prepare ({len(batch)})",
+ not encodes and len(batch) == 1)
+if fails:
+ print("1 FAIL", flush=True)
+ sys.exit(1)
+
+
+class OldTok:
+ """The tokenizer as the code before the patch used it: `encode` (the GIL held), behind the batch call's name."""
+ def __init__(self, t):
+ self.t = t
+
+ def encode_batch_fast(self, texts, add_special_tokens=True):
+ return [self.t.encode(x, add_special_tokens=add_special_tokens) for x in texts]
+
+
+def vision(t):
+ v = object.__new__(glm.GlmVision)
+ v.tok, v.image_token = t, 154854
+ v.limits = SimpleNamespace(picture_tokens=lambda n: 4096)
+ return v
+
+
+def picture(h, w, seed):
+ g = torch.Generator().manual_seed(seed)
+ return torch.rand((3, 28 * h, 28 * w), generator=g)
+
+
+def same(a, b):
+ return (a.token_ids == b.token_ids and a.positions == b.positions and a.content_hash == b.content_hash
+ and a.item_rows == b.item_rows and a.item_keys == b.item_keys)
+
+
+SPAN = glm.IMAGE_SPAN
+added = "".join(f" {t.content} word" for t in tok.get_added_tokens_decoder().values())
+cases = {
+ "one picture": (f"<|user|>look {SPAN} what is it?<|assistant|>", [picture(16, 16, 1)]),
+ "three pictures, other sizes": (f"a {SPAN} b {SPAN} c {SPAN} d", [picture(8, 20, 2), picture(30, 4, 3),
+ picture(1, 1, 4)]),
+ "a quoted marker beside a picture": (f"the log said <|image|> then {SPAN} done", [picture(12, 12, 5)]),
+ "scripts and added tokens": (f"中文 العربية 😀 e\u0301 {SPAN}{added}", [picture(6, 9, 6)]),
+}
+long = "".join(f"Line {i}: the quick brown fox, def f(x): return x * {i}\n" for i in range(18000))
+cases["~800k tokens with a picture"] = (long + SPAN + long, [picture(16, 16, 7)])
+new, old = vision(tok), vision(OldTok(tok))
+for name, (text, pics) in cases.items():
+ try:
+ a = new.prepare(text, pics)
+ b = old.prepare(text, pics)
+ check(f"{name}: {len(a.token_ids):,} ids, positions, hash, rows and keys equal the encode path's", same(a, b))
+ except Exception as e:
+ check(f"{name}: raised {type(e).__name__}: {str(e)[:150]}", False)
+
+# a tokenizer whose post-processor adds special tokens: prepare must not add them (add_special_tokens=False, as before)
+small = Tokenizer(models.WordLevel({"[UNK]": 0, "[CLS]": 1, "a": 2, "b": 3, "<|begin_of_image|>": 4, "<|image|>": 5,
+ "<|end_of_image|>": 6}, unk_token="[UNK]"))
+small.pre_tokenizer = pre_tokenizers.Whitespace()
+small.add_special_tokens(["<|begin_of_image|>", "<|image|>", "<|end_of_image|>"])
+small.post_processor = processors.TemplateProcessing(single="[CLS] $A", special_tokens=[("[CLS]", 1)])
+sv, so = vision(small), vision(OldTok(small))
+sv.image_token = so.image_token = 5
+a, b = sv.prepare(f"a {SPAN} b", [picture(2, 2, 8)]), so.prepare(f"a {SPAN} b", [picture(2, 2, 8)])
+check(f"a tokenizer that adds [CLS]: no special token added, as with encode ({a.token_ids[:3]})",
+ same(a, b) and 1 not in a.token_ids)
+
+# 3. the GIL released
+text, pics = cases["~800k tokens with a picture"]
+gaps, stop = [], threading.Event()
+
+
+def tick():
+ last = time.perf_counter()
+ while not stop.is_set():
+ time.sleep(0.001)
+ now = time.perf_counter()
+ gaps.append(now - last)
+ last = now
+
+
+for label, v, want in (("encode_batch_fast", new, lambda g: g < 0.05), ("encode (before)", old, lambda g: g > 0.3)):
+ gaps.clear()
+ stop.clear()
+ th = threading.Thread(target=tick, daemon=True)
+ th.start()
+ time.sleep(0.05)
+ gaps.clear()
+ v.prepare(text, pics)
+ stop.set()
+ th.join()
+ check(f"prepare on ~800k tokens through {label}: the longest gap of a counting thread {max(gaps) * 1e3:.0f} ms",
+ want(max(gaps)))
+
+print("ALL PASS" if fails == 0 else f"{fails} FAIL", flush=True)
+sys.exit(1 if fails else 0)