Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Server: chat and legacy completions requests take `deadline_s` (seconds, more than 0 and at most 1,000,000; any other value is refused before the engine): at that time the server cancels the engine itself and the reply ends with `finish_reason: "deadline"`, keeping every token the engine gave and its usage; a reply the engine ended first, or a cancel that came first, keeps its own ending, and without the field nothing changes (#3438). Thanks to @jayleaton.

- Tools: the follow-up gates (`tools/bench_concurrent.py`, `tools/clef_head_gate.py`, the image-cache turns check and the LFM3 serve check) fail by name when what they compare never ran (#3772, follows #3708). Thanks to @jschmied.

- GLM-5.3-Flash on CUDA: the load races the classic and factored expert forms, which give the same bits, at each of its ten timed decode window widths and keeps the faster one at each (classic unless factored is more than 1% faster), instead of one form for every window; a window takes the form of the narrowest timed width that holds it, and `TF_GLM_EXPERT_FORM` names one form for every width (#3249). Thanks to @Bizuayeu.

- CI: a landing train's pull request skips GitHub's hosted checks, which our own runners already run on its tip (a red local run still starts them by hand), and a newer push cancels an older Zig format run, so main's and contributors' checks no longer queue behind trains (#4106).

- Nemotron 3.5 on Metal: a request cancelled during a whole (unstepped) prompt pass keeps the prompt state that pass already landed, so the next request on that conversation resumes from it; the stepped path is unchanged (#3651, for #3618).
Expand Down
1 change: 1 addition & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,7 @@ delete runs gets 503, an id that is not a number 400, and an id the graph does n
| `reasoning_effort` | `none`, `minimal`, `low`, `medium`, `high`, `xhigh` or `max` | Both |
| `thinking_budget` | Token-count limit inside reasoning | Both |
| `priority` | `background` yields to foreground requests | Both |
| `deadline_s` | Seconds, more than 0 and at most 1,000,000, on chat and legacy completions: at that time the server cancels the engine itself and the reply ends with `finish_reason: "deadline"`, keeping every token the engine gave, usage and token ids. A reply that ends first, or a [cancel](#cancel-a-request) that came first, keeps its own ending; without the field nothing changes | Native |
| `return_token_ids` | The reply's token ids in the response's `tensorfold.token_ids`, the tokens its `token_sha256` hashes | Native |

`n` must be 1; multiple choices receive HTTP 400.
Expand Down
2 changes: 1 addition & 1 deletion docs/environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi
| `TF_GLM_DFLASH2_LOG` | Whole unsigned 64-bit count of DFlash2 rounds whose drafts are logged; default 0 |
| `TF_GLM_DRAFT_CONFIDENCE` | Finite number 0 through 1 where a DFlash2 chain's chance product stops it; default 0.7 |
| `TF_GLM_CONTEXT_CEILING` | GLM-5.3-Flash on CUDA: whole token count 1 through 2147483616, the window `--context` may ask for and `--context 0` serves, in place of config.json's 1048576; read at GLM's open. Past that length the model's quality is the operator's to check. Unset keeps config.json's window |
| `TF_GLM_EXPERT_FORM` | `classic` or `factored`: the expert form GLM's CUDA decode windows use (the same bits either way), also at a load that times nothing; unset or blank races the two when a build first loads with drafts and scratch context and keeps the winner, else classic; read on rank 0, which chooses every rank's form |
| `TF_GLM_EXPERT_FORM` | `classic` or `factored`: the expert form GLM's CUDA decode windows use at every width (the same bits either way), also at a load that times nothing; unset or blank races the two at each timed width when a build first loads with drafts and scratch context and keeps each width's winner, else classic; read on rank 0, which chooses every rank's forms |
| `TF_GLM_INDEX_CUDA` | GLM on CUDA: exactly `1` (both DSA indexer kernels), `0` (neither) or `scores` (scores only); unset or blank is `both` |
| `TF_GLM_KV_HOST_GIB` | GLM on CUDA: a finite GiB amount of at least 0 for the DSA layers' pinned host pages; unset or blank uses one full window and 16 rows a page |
| `TF_GLM_RANK` | GLM-5.3-Flash on CUDA: a whole rank index from 0 through 4294967295, set with `TF_GLM_WORLD`; unset with it gives one rank |
Expand Down
22 changes: 14 additions & 8 deletions docs/recipes/glm-5.3-flash-cuda.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,14 +135,20 @@ range (0.25% at least), and inside the rest. Other checkpoints and sampled repli
## Window prices

Decode windows reach 32 rows and MTP chains 15 drafts. With drafts and enough scratch context, rank 0 races
classic NVFP4 experts against the factored form over real text on every rank, keeping the faster form with the same
bits. MTP also times windows of 1, 2, 3, 4, 6, 8, 12, 16, 24 and 32 rows, with straight lines between them, and a
chained draft step. Its startup line reports `glm: windows (timed)` and the expert form. DFlash2 keeps the existing
seed forward and step prices in lone and shared rounds; it times only the target expert-form race and reports
`glm: expert form (timed)`. No unused DFlash2 window or draft-step table is measured or published to the lane core.
`TF_GLM_EXPERT_FORM=classic` or `factored` names the form instead and skips the race, so launches compare at one
form, and a load that times nothing still runs it (`glm: expert form (untimed)`); a named form's startup line puts
`(TF_GLM_EXPERT_FORM)` after the form's word.
classic NVFP4 experts against the factored form, which gives the same bits, over real text on every rank at windows
of 1, 2, 3, 4, 6, 8, 12, 16, 24 and 32 rows. Five untimed sweeps of every width on both forms come first, then each
width's timed windows take the two forms in turn, classic first on even rounds and factored first on odd ones, so
neither form is timed in a load's first seconds, and a drift through the race or a window right after a switch of
form falls on both alike. Each width keeps its faster form, classic unless factored is more than 1% faster, and a
window runs on the form of the narrowest timed width that holds it. `TF_GLM_EXPERT_FORM=classic` or `factored`
names one form for every width instead and skips the race, so launches compare at one form, and a load that times
nothing still runs it (`glm: expert form (untimed)`); a named form's startup line puts `(TF_GLM_EXPERT_FORM)` after
the form's word. MTP prices each width at its kept form's time, with straight lines between them, and a chained
draft step. Its startup line reports `glm: windows (timed)` and the forms: one word when every width shares one,
else the more common form and the widths where the other runs, as in `experts factored, classic at 4 and 6 rows`.
DFlash2 keeps the existing seed forward and step prices in lone and shared rounds; it times only the target
expert-form race and reports `glm: expert form (timed)`. No unused DFlash2 window or draft-step table is measured or
published to the lane core.

The measurements stay in `~/.cache/tensorfold/window-costs`, keyed by the build, GPU/driver, full checkpoint and drafter
identity, drafter precision, rank count, layer limit, L2-prefetch options, loaded NVFP4 decode warps, KDA and matmul
Expand Down
37 changes: 35 additions & 2 deletions tools/bench_concurrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
``--mixed``: request i takes prompt i % 2 and seed seed + i // 2; also reports the steady aggregate, over the time
every stream is live (tokens split by the characters each stream delivered inside that window).
``--alone``: runs every request alone first and checks each concurrent reply's token-id hash (``token_sha256``)
against it; ``--serial`` checks the alone runs against ``"draft": false``. ``--no-seed``: sampled requests carry
against it; ``--serial`` checks the alone runs against ``"draft": false``. Both counts are a report, not a gate:
the cell names them ``vacuous`` when they compared nothing (``alone``: a rep in which no two streams decoded at once,
so the server served them one at a time; ``serial``: the drafted runs accepted no draft, or the plain ones drafted,
or the server reports no draft counters). ``--no-seed``: sampled requests carry
no seed (mlx_lm's server batches only those), for measuring a standard; no hash checks then. Run a standard with its
prompt cache off (mlx_lm: ``--prompt-cache-size 0``): a cached reply can arrive as one text piece. Tokens come from
the reply's usage. A request that fails to connect or errors counts in ``failed``; one whose text came in fewer than
Expand Down Expand Up @@ -182,6 +185,32 @@ def aggregates(runs: list[dict]) -> dict:
"chunk_tpot_estimate_ms", "round_gap_p50_ms", "round_gap_p95_ms", "tokens_per_chunk")


def overlapped(runs: list[dict]) -> bool | None:
"""True when two streams decoded at once (one's first token before another's last); None under two streams."""
spans = sorted((r["first"], r["last"]) for r in runs if r.get("first") is not None and r.get("last") is not None)
return any(b[0] < a[1] for a, b in zip(spans, spans[1:])) if len(spans) > 1 else None


def draft_count(run: dict, key: str) -> int | None:
"""A run's speculative count, None when the server reported none."""
value = (run.get("speculative") or {}).get(key)
return value if type(value) is int and value >= 0 else None


def serial_evidence(alone: dict) -> dict:
"""Drafts the alone runs accepted and the ``"draft": false`` runs drafted; ``vacuous`` says why that proves none."""
accepted = [draft_count(r, "accepted") for r in alone.values()]
plain = [draft_count(r.get("serial_run") or {}, "drafted") for r in alone.values()]
out = {"accepted": sum(v or 0 for v in accepted), "plain_drafted": sum(v or 0 for v in plain)}
if None in accepted or None in plain:
out["vacuous"] = "the server reported no draft counters for some runs"
elif not out["accepted"]:
out["vacuous"] = "the drafted runs accepted no draft"
elif out["plain_drafted"]:
out["vacuous"] = f"the \"draft\": false runs drafted {out['plain_drafted']} tokens"
return out


def median(values) -> float | None:
"""The median of the values that are not None, rounded to 3 places; None when there are none."""
got = [v for v in values if v is not None]
Expand Down Expand Up @@ -306,6 +335,7 @@ def main() -> None:
rep["client_intervals"] = [{"start": r["sent"], "first": r.get("first"),
"last": r.get("last"), "end": r.get("completed"),
**bench_timing.request(r)} for r in runs]
rep["overlapped"] = overlapped(runs)
if alone:
# None: the request or its solo run failed (not an exactness result)
rep["equal_alone"] = [token_equal(alone[(r["prompt"], r["seed"])], r) for r in runs]
Expand Down Expand Up @@ -340,10 +370,13 @@ def main() -> None:
checks = [v for r in reps for v in r["equal_alone"]]
cell["alone"] = {"equal": checks.count(True), "unequal": checks.count(False),
"failed": checks.count(None)}
apart = sum(r["overlapped"] is False for r in reps)
if apart:
cell["alone"]["vacuous"] = f"{apart} of {len(reps)} reps had no two streams decoding at once"
if args.serial:
checks = [v.get("serial_equal") for v in alone.values()]
cell["serial"] = {"equal": checks.count(True), "unequal": checks.count(False),
"failed": checks.count(None)}
"failed": checks.count(None), **serial_evidence(alone)}
errors = sorted({e for r in reps for e in r["errors"]})
if errors:
cell["errors"] = errors[:3]
Expand Down
7 changes: 6 additions & 1 deletion tools/clef_head_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
# clef_head_gate.py native <tf-clef-test|tf-cuda-test> <model> <cases> <out> [--piece N|whole] [--backend hip|cuda]
# clef_head_gate.py compare <cases> <native> <bf16> <fp64> [--report FILE] [--rule strict|margin]
# The strict rule: per question type, native mean and worst error against FP64 no larger than the reference BF16
# head's. The margin rule keeps the worst and lets the mean sit up to 10% above the reference's.
# head's. The margin rule keeps the worst and lets the mean sit up to 10% above the reference's. A question type with
# no option logits fails compare by name: an empty table would pass.
# The records are clef_backbone_rows.py's; their schema text comes again from its seeded generator, so each field's
# instruction and each option's description give the spans, as token ranges of the record by character offsets.
import argparse, importlib.util, json, math, os, subprocess, sys
Expand Down Expand Up @@ -206,6 +207,10 @@ def cmd_compare(a):
f"{row['bf16_mean']:.3e} | {row['bf16_worst']:.3e} | {'yes' if row['strict'] else 'NO'} | "
f"{'yes' if row['margin'] else 'NO'} |")
total = sum(len(p["native"]) for p in pooled.values())
unexercised = [names_of[t] for t, p in pooled.items() if not p["native"]]
if unexercised:
ok = False
print(f"unexercised: no option logits for {', '.join(unexercised)} (the cases' fields parsed to no options)")
print(f"paired: {total} logits, {same} identical to the reference BF16 head's; of the rest native is nearer FP64 in "
f"{nearer}, farther in {farther}, as near in {total - same - nearer - farther}")
if a.report:
Expand Down
23 changes: 22 additions & 1 deletion tools/image_cache_turns.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@

Per request: prompt and cached tokens (computed = prompt - cached), time to first streamed piece, total time, the
server's prefill seconds and token hash. With --fresh-url (the same model served with --prompt-cache-gib 0), every
request is sent there too and its token hash must equal the resumed one. GET /v1/memory is recorded before and after.
request is sent there too and its token hash must equal the resumed one; then each fresh reply must report 0 cached
tokens, and the text, image and repeat scenarios must each resume, on some request after their first, more tokens than
their first request did (repeat: than the image chat's first; a fresh turn may resume the template's first tokens),
or resumed == fresh compared fresh with fresh and fails by name. GET /v1/memory is recorded before and after.
Standard library only; Python 3.11+.

python3 tools/image_cache_turns.py --url http://127.0.0.1:8080 --image a.png --image-b b.png \
Expand Down Expand Up @@ -117,6 +120,19 @@ def chat(first_image: str | None) -> list[list]:
return out


def unexercised(name: str, rows: list[dict], first: int) -> str | None:
"""Why a scenario's resumed == fresh compared nothing: a fresh reply that resumed, or no later request resumed
more than ``first``, the cached tokens of a first turn."""
fresh = [r["turn"] for r in rows if r.get("fresh_cached_tokens") != 0]
if fresh:
return f"the fresh server's replies for turns {fresh} report cached tokens other than 0 (not fresh)"
later = rows if name == "repeat" else rows[1:]
if name != "changed" and later and not any((r.get("cached_tokens") or 0) > first for r in later):
return (f"no request after the first resumed more than a first turn's {first} cached tokens, so resumed == "
"fresh compared fresh with fresh")
return None


def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--url", default="http://127.0.0.1:8080")
Expand Down Expand Up @@ -158,6 +174,11 @@ def main() -> int:
+ (f" ERROR {row['error']}" if row.get("error") else ""))
failures += bool(row.get("error"))
report["scenarios"][name] = rows
first = (report["scenarios"].get("image") if name == "repeat" else rows) or [{}]
problem = unexercised(name, rows, first[0].get("cached_tokens") or 0) if args.fresh_url else None
if problem:
failures += 1
print(f"FAIL {name}: {problem}")
report["memory_after"] = memory(args.url, key)
if args.output:
args.output.write_text(json.dumps(report, indent=1) + "\n")
Expand Down
56 changes: 56 additions & 0 deletions tools/test_clef_head_gate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""tools/clef_head_gate.py compare on planted cases: an empty table or a question type without logits fails by name.

The gate imports numpy, which the CI jobs do not install, so these tests run only where numpy is.
"""
import contextlib
import importlib.util
import io
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch

sys.path.insert(0, str(Path(__file__).resolve().parent))
NUMPY = importlib.util.find_spec("numpy") is not None


def compare(types):
"""compare's exit code and output over one case whose options belong to questions of ``types`` (0, 1, 2)."""
import clef_head_gate
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
for part in ("cases", "native", "bf16", "fp64"):
(root / part).mkdir()
(root / "cases" / "index.json").write_text(json.dumps({"cases": ["c"]}))
case = {"question_types": list(types), "option_question": list(range(len(types)))}
(root / "cases" / "c.json").write_text(json.dumps(case))
for part, logit in (("native", 1.0), ("bf16", 1.5), ("fp64", 1.0)):
(root / part / "c.json").write_text(json.dumps({"logits": [logit] * len(types)}))
argv = ["clef_head_gate.py", "compare", *(str(root / p) for p in ("cases", "native", "bf16", "fp64"))]
out = io.StringIO()
with patch.object(sys, "argv", argv), contextlib.redirect_stdout(out):
code = clef_head_gate.main()
return code, out.getvalue()


@unittest.skipUnless(NUMPY, "clef_head_gate.py imports numpy")
class CompareTests(unittest.TestCase):
def test_every_type_with_logits_passes(self):
code, out = compare([0, 1, 2])
self.assertEqual(code, 0, out)

def test_no_logits_fails(self):
code, out = compare([])
self.assertEqual(code, 1, out)
self.assertIn("unexercised: no option logits for noul, choice, score", out)

def test_a_type_without_logits_fails(self):
code, out = compare([0, 1])
self.assertEqual(code, 1, out)
self.assertIn("unexercised: no option logits for score", out)


if __name__ == "__main__":
unittest.main()
Loading