GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
A chat's pictures keep their size past the 8th: the picture budget is MAX_IMAGES x IMAGE_TOKENS
Ahmed Badawe36df86e82892
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e1f99b1..7a63d30 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,20 @@ Every change to this recipe, newest first. Each release names the image it serve## Unreleased+- **A chat's pictures keep their size past the 8th, so it still resumes from its kept prompt state**+ (`TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS`, by [abadawe-dev](https://github.com/abadawe-dev)): TensorFold caps a picture+ at min(`IMAGE_TOKENS`, the request's picture budget / its pictures), and its own budget of 16,384 holds 8 pictures at+ 2,048. From the 9th on, every new picture shrank all the earlier ones: their rows and content keys changed, the+ kept state matched only up to the chat's first picture, and the rest was read again on every turn that brought a+ picture. An agent session reading screenshots at ~420k tokens waited 150-167 s (187-191k tokens) after each one.+ `scripts/config.sh` now sets the budget to `MAX_IMAGES` x `IMAGE_TOKENS` (50 x 2,048 = 102,400, at most 262,144),+ so the cap is the same for any number of pictures a request can carry, and reserves the feature rows that adds in+ the tower's workspace (`TENSORFOLD_VISION_WORKSPACE_MIB` 768 -> 1,440 MiB: rank 0's startup estimate 88.09 ->+ 88.74 GiB, the pool 2,582,528 -> 2,537,472 tokens on two Sparks at `PARALLEL=4`). `tools/picture_turns.py`, a+ 48k-token chat, pictures 9 to 11: 16.4-16.6k tokens read and 13.0-13.3 s a turn before, 2.1k and 2.5-2.8 s now; a+ cold request of 50 full-size pictures (102,118 tokens) answers and resumes. Pictures past the 8th are no longer+ downscaled, so they cost up to 2,048 tokens each. `TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS=16384` restores the shared+ budget. No patch and no image change. CPU check: `tools/picture_budget_check.py`.- **A prompt that fills beside other replies, ~10-14% sooner** (`FILL_ROWS`, by [BadAd84](https://github.com/BadAd84)):while other requests decode, a new prompt filled in 1,024-row chunks (TensorFold's `TF_GLM_FILL_ROWS` default),half the 2,048-row prompt chunk whose buffers the engine keeps anyway. `scripts/config.sh` now sets 2,048 (atdiff --git a/README.md b/README.mdindex 083746a..316bd7c 100644--- a/README.md+++ b/README.md@@ -192,7 +192,7 @@ If `start.sh` stops at a check:## Images and video-GLM's own vision tower runs on the head (rank 0: 1.05 GiB of bf16 weights and 0.75 GiB of workspace). Send images and+GLM's own vision tower runs on the head (rank 0: 1.05 GiB of bf16 weights and 1.41 GiB of workspace). Send images andvideos as OpenAI-style content parts in a user message:```bash@@ -216,7 +216,7 @@ pictures are the same.| --- | --- | --- || Formats | JPEG, PNG, WebP | MP4, WebM, MOV, MKV (anything FFmpeg decodes) || 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 |+| Tokens | at most 2,048 a picture (`TENSORFOLD_GLM_IMAGE_TOKENS`; a 1080p picture takes 2,040); every picture of a chat keeps that cap however many it has (a request's pictures share `TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS`, here 50 x 2,048 = 102,400), so a new picture never resizes the earlier ones and the chat still resumes from its kept prompt state | 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.@@ -552,7 +552,8 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `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) |+| `TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS` / `_REQUEST_VIDEO_TOKENS` | `102400` / `32768` | tokens a request's pictures and clips share (each still within its own cap). Pictures: `scripts/config.sh` sets `MAX_IMAGES` x `IMAGE_TOKENS` (at most 262,144; TensorFold's own default is 16,384), so a picture's cap does not depend on how many pictures the chat has. With 16,384, the 9th picture and every one after it shrank all the earlier ones, and the chat's kept prompt state then matched only up to its first picture: an agent session at ~420k tokens waited 150-167 s after each screenshot; `tools/picture_turns.py` on two Sparks, a 48k-token chat, pictures 9 to 11: 16.4-16.6k tokens read and 13.0-13.3 s a turn, now 2.1k and 2.5-2.8 s. 50 full-size pictures are then a 102k-token prompt, not 16k. `16384`: the shared budget, as before |+| `TENSORFOLD_VISION_WORKSPACE_MIB` | `1440` | what rank 0 sets aside for the tower's encode and a request's feature rows (8 KiB a row, kept through its prefill). TensorFold's 768 MiB plus the rows the picture budget adds past 16,384, so a cold request of 50 full-size pictures fits (rank 0's startup estimate 88.09 -> 88.74 GiB, the pool 2,582,528 -> 2,537,472 tokens on two Sparks at `PARALLEL=4`). Set it to size it yourself (`768` if your requests never carry many pictures) || `TENSORFOLD_GLM_PICTURE_CACHE` / `_PICTURE_CACHE_MB` / `_PICTURE_CANVASES` | `1` / `384` / `8` | the vision frontend reads a request's pictures once, not on every turn of the chat (patch `0079`): what reading each source cost is kept by the source's bytes (host memory only, LRU under `_MB`, that many fitted canvases); `0`: the path before the patch, bit for bit (by ThomasWadeZ, #63) || `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 |@@ -739,6 +740,8 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform| `tools/test_queued_cancellation.py --source-root DIR` | patch 0073's checks on the CPU, against TensorFold's source with the patches applied (no GPU, no server): requests that wait while every slot is busy and whose client leaves are dropped at once, in queue order; `--expect-stock` before 0073 shows the old wait || `tools/end_of_turn.py [label] [max_cut]` | 8 short French coding prompts, thinking off: counts the replies that run to `max_tokens` (48 requests) and measures P(end of turn) right after each reply's closing code fence; exit 1 above `max_cut` cut replies (default 4) || `tools/prompt_reuse.py [size]` | a ~33k-token conversation takes three more turns, each after a request of another conversation with the same system prompt (an agent and its sub-agents); exit 1 when a turn resumes less than 90% of its prompt. Needs `PARALLEL` above 1 |+| `tools/picture_turns.py [pictures] [size]` | a chat of ~`size` tokens (default 40000) gets one new 1920x1080 picture a turn (default 12), with a text turn after each; exit 1 when a turn re-reads more than the new picture, which is what a picture cap that moves with the picture count does from the 9th picture on |+| `tools/picture_budget_check.py <checkout>` | the picture budget's checks, run in the image (`docker run ... --entrypoint python3`, see the file; CPU): `scripts/config.sh` and `start.sh` send every rank a budget under which a picture's cap is the same for 1 to `MAX_IMAGES` pictures, the environment's values win, and the workspace covers the budget's rows |## Repository layoutdiff --git a/scripts/config.sh b/scripts/config.shindex b8d3036..b995fac 100644--- a/scripts/config.sh+++ b/scripts/config.sh@@ -96,11 +96,41 @@ DRAFTER="${DRAFTER:-dflash2}" # dflash2: incoai/GLM-5.3-Flash-DFlash2 dra# The checkpoint's MTP head beside DFlash2 (TensorFold's TF_GLM_MTP): auto (default) leaves it out while DFlash2# drafts every request; TensorFold v0.6.0's own default, 1, would load it (1.77 GiB a Spark) with PARALLEL=1.export TF_GLM_MTP="${TF_GLM_MTP:-auto}"-# Image and video input (rank 0 runs GLM's vision tower: 1.05 GiB of bf16 weights and 0.75 GiB of workspace). A picture+# Image and video input (rank 0 runs GLM's vision tower: 1.05 GiB of bf16 weights and 1.41 GiB of workspace). A picture# takes at most TENSORFOLD_GLM_IMAGE_TOKENS tokens (2048), a clip TENSORFOLD_GLM_VIDEO_TOKENS (16384) over at most# TENSORFOLD_GLM_VIDEO_FRAMES frames (128, 2 a second). VISION_URLS=1 also accepts public https URLs (default: data URLs).VISION="${VISION:-1}"VISION_URLS="${VISION_URLS:-0}"+# A picture keeps its size for a whole chat. TensorFold gives each picture of a request min(IMAGE_TOKENS,+# TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS / pictures) tokens, with a budget of 16,384 of its own: 8 pictures keep 2,048+# each, and from the 9th on every new picture shrinks all the earlier ones. Their rows and content keys change, so the+# conversation's kept prompt state only matches up to its first picture and the rest is read again on every turn that+# brings a picture: in an agent session at ~420k tokens, 187-191k tokens and 150-167 s before the first token after+# each screenshot (two Sparks, v1.10, PARALLEL=4). The default here is MAX_IMAGES x IMAGE_TOKENS (50 x 2,048 =+# 102,400; at most 262,144, TensorFold's ceiling, and never under its 16,384), which no request can exceed, so the cap+# never moves. tools/picture_turns.py, a 48k-token chat, pictures 9 to 11: 16.4-16.6k tokens read and 13.0-13.3 s a+# turn with 16,384, 2.1k tokens and 2.5-2.8 s with the default (as pictures 1 to 8 either way). Pictures past the 8th+# also keep their detail, at up to 2,048 tokens each instead of a share: 50 full-size pictures are a 102k-token prompt.+# TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS=16384 restores the shared budget.+# The tower's workspace (TENSORFOLD_VISION_WORKSPACE_MIB, TensorFold's default 768 MiB at up to 4,096 tokens a+# picture) holds a request's feature rows through its prefill, 8 KiB a row: 128 MiB of it at 16,384 rows. The rows the+# budget adds are reserved beside it (102,400: 768 + 672 = 1,440 MiB), so a cold request of 50 full-size pictures+# still fits what startup set aside. Two Sparks, PARALLEL=4: rank 0's startup estimate 88.09 -> 88.74 GiB, the pool+# 2,582,528 -> 2,537,472 tokens (-1.7%). Set it yourself to size it otherwise (768: TensorFold's own).+_img_tokens="${TENSORFOLD_GLM_IMAGE_TOKENS:-2048}"+_img_max="${TENSORFOLD_GLM_MAX_IMAGES:-50}"+if [[ "$_img_tokens" =~ ^[0-9]{1,6}$ && "$_img_max" =~ ^[0-9]{1,4}$ ]]; then # (anything else: TensorFold refuses it)+ _img_budget=$(( 10#$_img_tokens * 10#$_img_max ))+ (( _img_budget <= 262144 )) || _img_budget=262144+ (( _img_budget >= 16384 )) || _img_budget=16384+ export TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS="${TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS:-$_img_budget}"+ if [[ -z "${TENSORFOLD_VISION_WORKSPACE_MIB:-}" && "$TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS" =~ ^[0-9]{1,7}$ ]]; then+ _img_rows=$(( 10#$TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS > 16384 ? 10#$TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS - 16384 : 0 ))+ _img_base=$(( 768 * (10#$_img_tokens > 4096 ? 10#$_img_tokens : 4096) / 4096 ))+ (( _img_rows == 0 )) || export TENSORFOLD_VISION_WORKSPACE_MIB=$(( _img_base + (_img_rows * 8 + 1023) / 1024 ))+ fi+fi+unset _img_tokens _img_max _img_budget _img_rows _img_base# Concurrent requests (patches 0026-0030, 0035, 0040, 0041: one shared pool of per-token caches, one batched verify window# a round): 1 to 8 (patch 0069), with DRAFTER=dflash2 only (mtp: 1). Default 4 on two Sparks, 8 on three (v1.5).# sparkDash aggregate decode at 4 / 8 requests at once: two Sparks prose 103.2 / 130.8 tok/s, code 126.7 / 167.0; threediff --git a/start.sh b/start.shindex 70a1875..2135a9c 100755--- a/start.sh+++ b/start.sh@@ -39,7 +39,8 @@# TF_GLM_MULTI_WINDOW (32)# ranks every TENSORFOLD_*, TF_GLM_* and TF_ROCE_* variable goes to every rank (TP>2: TF_ROCE_HCA per node, found),# e.g.-# TENSORFOLD_GLM_IMAGE_TOKENS, TENSORFOLD_MEMORY_RESERVE_GIB, TF_GLM_KEEP_REASONING=0+# TENSORFOLD_GLM_IMAGE_TOKENS, TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS (scripts/config.sh: MAX_IMAGES x+# IMAGE_TOKENS), TENSORFOLD_MEMORY_RESERVE_GIB, TF_GLM_KEEP_REASONING=0set -euo pipefailcd "$(dirname "$(readlink -f "$0")")"source ./scripts/config.shdiff --git a/tools/picture_budget_check.py b/tools/picture_budget_check.pynew file mode 100755index 0000000..6b61da8--- /dev/null+++ b/tools/picture_budget_check.py@@ -0,0 +1,105 @@+#!/usr/bin/env python3+"""tools/picture_budget_check.py <recipe checkout>: the picture budget, CPU only, in the image (TensorFold's limits+are read and called, nothing runs on a GPU):++ docker run --rm --network none -e CUDA_VISIBLE_DEVICES= -v "$PWD:/recipe:ro" --entrypoint python3 \+ tensorfold-glm53:v0.6.0 /recipe/tools/picture_budget_check.py /recipe++1. Every rank gets it: scripts/config.sh exports TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS = MAX_IMAGES x IMAGE_TOKENS (at+ most 262,144, TensorFold's ceiling), following TENSORFOLD_GLM_MAX_IMAGES and TENSORFOLD_GLM_IMAGE_TOKENS; a value+ from the environment wins; start.sh's own env_args puts it in ENV_ARGS, which every rank's docker run gets.+2. A picture's cap does not move: under what the ranks get, GlmVisionLimits.from_env().picture_tokens(n) is the same+ for every n from 1 to max_images, so a chat's earlier pictures keep their canvases (their rows and content keys,+ which prompt reuse matches) when another picture arrives. Under TensorFold's own 16,384 it drops at the 9th.+3. The workspace covers the rows: TENSORFOLD_VISION_WORKSPACE_MIB is TensorFold's own reserve plus 8 KiB for every+ row the budget adds past 16,384, the engine's vision_workspace() reads it, and a value from the environment wins.+Prints PASS / FAIL lines and ALL PASS; exit 1 on any FAIL."""+import os+import pathlib+import re+import shutil+import subprocess+import sys+import tempfile++recipe = pathlib.Path(sys.argv[1]).resolve()+fails = 0+# the repository's defaults, not this setup's: scripts/config.sh is read from a copy without scripts/local.sh and .env+defaults = pathlib.Path(tempfile.mkdtemp())+(defaults / "scripts").mkdir()+shutil.copy(recipe / "scripts" / "config.sh", defaults / "scripts" / "config.sh")+BUDGET, WORKSPACE = "TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS", "TENSORFOLD_VISION_WORKSPACE_MIB"+++def check(name, ok):+ global fails+ print(("PASS " if ok else "FAIL ") + name, flush=True)+ fails += not ok+++start = (recipe / "start.sh").read_text()+m = re.search(r"^env_args\(\) \{\n.*?^\}\n", start, re.S | re.M)+check("start.sh defines env_args", m is not None)+check("every rank's docker run takes ENV_ARGS (the workers' and rank 0's)", start.count('"${ENV_ARGS[@]}"') >= 2)+++def forwarded(env, tp="2"):+ """The TENSORFOLD_* variables start.sh's env_args passes to the ranks, after scripts/config.sh, in a clean env."""+ script = (f"cd {defaults} && source scripts/config.sh >/dev/null 2>&1; TP={tp}\n"+ + (m.group(0) if m else "env_args() { ENV_ARGS=(); }\n")+ + 'env_args\nfor a in "${ENV_ARGS[@]}"; do [[ "$a" == TENSORFOLD_* ]] && echo "$a"; done\n')+ base = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": "/nonexistent"}+ out = subprocess.run(["bash", "-c", script], env={**base, **env}, capture_output=True, text=True, timeout=60)+ return dict(line.split("=", 1) for line in out.stdout.split())+++def caps(env):+ """picture_tokens(n) for n = 1..max_images as a rank with ``env`` computes it, and the engine's workspace."""+ code = ("from tensorfold.vision.glm import GlmVisionLimits as L\n"+ "from tensorfold.families.glm5_next.cuda.engine import vision_workspace\n"+ "l = L.from_env()\n"+ "print(l.max_images, vision_workspace(), *[l.picture_tokens(n) for n in range(1, l.max_images + 1)])\n")+ base = {k: v for k, v in os.environ.items() if not k.startswith(("TENSORFOLD_", "TF_GLM_"))}+ out = subprocess.run([sys.executable, "-c", code], env={**base, **env}, capture_output=True, text=True, timeout=300)+ if out.returncode:+ return 0, 0, []+ n, workspace, *each = (int(x) for x in out.stdout.split())+ return n, workspace, each+++# TensorFold alone: the cap this recipe's default removes+n, workspace, each = caps({})+check(f"TensorFold's own budget: {n} pictures a request, 8 keep the cap and the 9th lowers it ({each[7:9]})",+ n == 50 and each[:8] == [2048] * 8 and each[8] < 2048)+own_workspace = workspace++for env, budget, what in (({}, 102400, "by default"),+ ({"TENSORFOLD_GLM_MAX_IMAGES": "100"}, 204800, "TENSORFOLD_GLM_MAX_IMAGES=100"),+ ({"TENSORFOLD_GLM_IMAGE_TOKENS": "1024"}, 51200, "TENSORFOLD_GLM_IMAGE_TOKENS=1024"),+ ({"TENSORFOLD_GLM_IMAGE_TOKENS": "4096"}, 204800, "TENSORFOLD_GLM_IMAGE_TOKENS=4096"),+ ({"TENSORFOLD_GLM_MAX_IMAGES": "4"}, 16384, "TENSORFOLD_GLM_MAX_IMAGES=4 (never below 16,384)")):+ got = forwarded(env)+ check(f"{what}: every rank gets {BUDGET}={budget} (got {got.get(BUDGET)})", got.get(BUDGET) == str(budget))+ n, workspace, each = caps(got)+ check(f"{what}: one cap for 1 to {n} pictures ({sorted(set(each))})", n > 0 and len(set(each)) == 1)+ rows = max(0, budget - 16384)+ want = own_workspace * max(4096, int(env.get("TENSORFOLD_GLM_IMAGE_TOKENS", 2048))) // 4096 + rows * 8192+ check(f"{what}: the workspace is TensorFold's plus 8 KiB a row past 16,384 ({workspace >> 20} MiB)",+ 0 <= workspace - want < 2 ** 20)+check("three Sparks too (TP=3)", forwarded({}, tp="3").get(BUDGET) == "102400")++got = forwarded({"TENSORFOLD_GLM_MAX_IMAGES": "256"})+n, _, each = caps(got)+check(f"TENSORFOLD_GLM_MAX_IMAGES=256: the budget stops at TensorFold's ceiling, 262,144 (got {got.get(BUDGET)}), "+ f"which holds 128 pictures at the cap", got.get(BUDGET) == "262144" and each[127] == 2048 and each[128] < 2048)++got = forwarded({BUDGET: "16384"})+check(f"{BUDGET}=16384 from the environment wins, and the workspace is left to TensorFold",+ got.get(BUDGET) == "16384" and WORKSPACE not in got)+got = forwarded({WORKSPACE: "768"})+check(f"{WORKSPACE}=768 from the environment wins", got.get(WORKSPACE) == "768" and got.get(BUDGET) == "102400")+got = forwarded({"TENSORFOLD_GLM_IMAGE_TOKENS": "many"})+check("a value that is not a number is left for TensorFold to refuse", BUDGET not in got and WORKSPACE not in got)++print("ALL PASS" if not fails else f"{fails} FAILED")+sys.exit(1 if fails else 0)diff --git a/tools/picture_turns.py b/tools/picture_turns.pynew file mode 100755index 0000000..136c811--- /dev/null+++ b/tools/picture_turns.py@@ -0,0 +1,96 @@+#!/usr/bin/env python3+"""A chat that gets one new picture a turn (an agent reading screenshots) must only read the new picture each time: its+earlier pictures keep their size, so the prompt still resumes from its kept state.++Usage: tools/picture_turns.py [pictures] [size] (API_URL / PORT as in client.py). ``pictures`` 1920x1080 PNGs+(default 12: past the 8 that TensorFold's own 16,384-token picture budget holds at full size), one a turn, each+followed by a text turn, after ~0.82 x ``size`` tokens of text (default 40000). Exit code 1 when a turn after the+first (the text, read cold) reads more than what it added, or when an earlier picture changes size.++With a picture cap that depends on the number of pictures (TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS=16384) the 9th+picture's turn reads the whole chat again and every later one reads it from the first picture on.+"""+import base64+import json+import os+import random+import struct+import sys+import time+import urllib.request+import zlib++sys.dont_write_bytecode = True # no tools/__pycache__ from importing client+from client import URL, open_url, prose # noqa: E402++MODEL = os.environ.get("MODEL", "GLM-5.3-Flash-EXL3")+WIDTH, HEIGHT, BLOCK = 1920, 1080, 40+SLACK = 512 # a turn's own text and reply, and the 64-token grid kept states sit on+++def picture(rng: random.Random) -> str:+ """A 1920x1080 PNG of random colour blocks (2,040 tokens at the default cap), as a data URL."""++ rows = []+ for _ in range(HEIGHT // BLOCK):+ line = b"".join(bytes(rng.randrange(256) for _ in range(3)) * BLOCK for _ in range(WIDTH // BLOCK))+ rows.append((b"\0" + line) * BLOCK)++ def chunk(kind: bytes, data: bytes) -> bytes:+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))++ png = (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", WIDTH, HEIGHT, 8, 2, 0, 0, 0))+ + chunk(b"IDAT", zlib.compress(b"".join(rows), 6)) + chunk(b"IEND", b""))+ return "data:image/png;base64," + base64.b64encode(png).decode()+++def chat(messages: list) -> tuple[int, int, float]:+ body = {"model": MODEL, "messages": messages, "max_tokens": 16, "temperature": 0,+ "chat_template_kwargs": {"enable_thinking": False}}+ req = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})+ t0 = time.time()+ reply = json.load(open_url(req, 1800))+ usage = reply["usage"]+ cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens") or 0+ messages.append({"role": "assistant", "content": reply["choices"][0]["message"].get("content") or "ok"})+ return usage["prompt_tokens"], cached, time.time() - t0+++def main() -> None:+ pictures = int(sys.argv[1]) if len(sys.argv) > 1 else 12+ size = int(sys.argv[2]) if len(sys.argv) > 2 else 40000+ rng = random.Random(time.time_ns()) # new pictures and text every run: nothing resumes from an earlier run+ messages = [{"role": "system", "content": "You are terse. " + prose(64, rng.randrange(1 << 30))},+ {"role": "user", "content": "Notes for later, reply ok.\n" + prose(size, rng.randrange(1 << 30))}]+ bad, first = [], 0+ print("turn prompt cached new seconds")+ before, cached, secs = chat(messages)+ print(f" text {before:7d} {cached:7d} {before - cached:7d} {secs:7.1f} (cold)", flush=True)+ for n in range(1, pictures + 1):+ messages.append({"role": "user", "content": [+ {"type": "text", "text": f"Screenshot {n}. One word for it."},+ {"type": "image_url", "image_url": {"url": picture(rng)}}]})+ prompt, cached, secs = chat(messages)+ grew = prompt - before+ first = first or grew+ note = ""+ if prompt - cached > max(grew, 0) + SLACK:+ note = " <- re-read its history"+ bad.append(f"picture {n}'s turn read {prompt - cached} tokens for a picture of {grew}")+ if grew < 0.75 * first: # the earlier pictures shrank: the prompt grew by less than one picture+ note = note or " <- earlier pictures resized"+ bad.append(f"picture {n} added {grew} tokens to the prompt, the first one {first}")+ print(f"picture {n:2d} {prompt:7d} {cached:7d} {prompt - cached:7d} {secs:7.1f}{note}", flush=True)+ messages.append({"role": "user", "content": "One more word."})+ prompt, cached, secs = chat(messages)+ if prompt - cached > SLACK:+ bad.append(f"the text turn after picture {n} read {prompt - cached} tokens")+ print(f" text {n:2d} {prompt:7d} {cached:7d} {prompt - cached:7d} {secs:7.1f}", flush=True)+ before = prompt+ if bad:+ sys.exit("FAIL: " + "; ".join(bad))+ print(f"OK: {pictures} pictures, every turn read only what it added")+++if __name__ == "__main__":+ main()