Skip to content

feat(mesh): encode the prompts of listed models with fastokens - #3596

Merged
zhuyuhua-v merged 7 commits into
mainfrom
zwan/mesh-fastokens-encode
Nov 23, 2026
Merged

zhuyuhua-v merged 7 commits into
mainfrom
zwan/mesh-fastokens-encode

Conversation

@wanzhenchn

@wanzhenchn wanzhenchn commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

The first of two PRs, both against main: #3597 builds on this one, and targets its branch until it merges.

Since the last review: its five items are in 11ca1b8 (reply), and 6849317 checks token parity against ATOM in CI: the job has ATOM tokenize the requests, with this commit's code, in place of the recorded fixture, which is gone with the test's own download. 9d88181 turns fastokens' segment cache on by default, 1 GiB per tokenizer: fastokens encodes a chat's text between special tokens one segment after another, so without the cache every turn of an agent encodes its history again, and with it a turn at 2 MiB of history encodes in 1.6 ms instead of 6.4 ms. Why, below, has new timings across prompt sizes, concurrent requests and an agent's session. cfc168a loads fastokens from tokenizer.json alone, as HuggingFace tokenizers does, so the tokens only tokenizer_config.json declares encode as text with both, as on main. Their checks, decode path and tests are gone, and fast_tokenizer.rs goes from 944 to 664 lines.

Why

For prefix_hash, and cache_aware with --kv-events, the router tokenizes requests in its preparation pool with the model's HuggingFace tokenizer: a chat's prompt, which it renders with the model's chat template, a completion's prompt, and a /v1/tokenize batch. HuggingFace tokenizers, through llm-tokenizer 1.4.2, takes 1.2 s of a preparation thread to encode a 2 MiB agentic prompt of DeepSeek-V4.1-Flash, and --prepare-max-tokenize-bytes refuses prompts over 1 MiB by default. fastokens encodes the same tokens in 10 ms.

llm-tokenizer 1.11 and later also encode these prompts in milliseconds, with the same tokens, but on most of the host's cores. On a 64-vCPU host, with a new agentic text each encode, 2.0.0 leads fastokens only from 2 MiB, by 1.3x to 1.8x on about 25 cores of CPU to fastokens' 2.3, and trails it below, by 1.1x at 1 MiB to 6.5x at 64 KiB. Weighted by the prompt sizes of an agentic trace (median 262K tokens), a request takes 3.6 ms with either, for 95 ms of CPU with 2.0.0 and 8 ms with fastokens. With 32 requests at once fastokens encodes 2x to 10x the bytes a second, and the p99 of a 256 KiB prompt is 3.4 ms to 2.0.0's 187 ms. An agent's session of 127 turns to 2 MiB encodes in 172 ms with fastokens and its segment cache, 243 ms with 2.0.0 and its L1 cache, and 72 s with 1.4.2. The earlier timings, where 2.0.0 was 1.6x as fast, re-encoded one 2 MiB prompt, a size where it leads. From 1.11 on they also pick a built-in DeepSeek-V4.1 chat encoder from config.json, which main refuses to route by (501 token_routing_unsupported), and which, allowed, renders the V4.1 chats that turn thinking off otherwise than ATOM. This PR leaves llm-tokenizer as it is and lets a deployment opt models into fastokens; the token parity test it adds is the check an upgrade would have to pass.

Change

  • --fastokens-models names the models whose prompts the router encodes with fastokens 0.3.6, by the name or source their tokenizer registers under, or * for every model. FastTokenizer (routers/prepare/fast_tokenizer.rs) encodes with fastokens, and leaves decoding, chat templates and vocabulary lookups to the HuggingFace tokenizer. fastokens is built without hf-hub: it loads the tokenizer.json the factory loaded, from a file, a directory or a HuggingFace download.
  • Exact or not at all. A model encodes with fastokens only once fastokens encodes a set of probe texts exactly as its HuggingFace tokenizer does, with special tokens and without: added tokens, digits, whitespace, several scripts, a chat, a 1 MiB text, and a 256 KiB one with no newline, for fastokens' parallel search for added tokens, since it splits a text across its threads only at newlines. The chat renders without a system message for a template that has no system role; a template that renders neither is logged. The IDs the HuggingFace post-processor puts around a text are added to fastokens' own, so a tokenizer_config.json that adds a BOS its tokenizer.json does not still gets it. A model that fails the probe keeps HuggingFace, with a warning, or under --fastokens-strict its tokenizer fails to register, with no retries. A tokenizer.json that fastokens cannot find or download fails no probe: the model keeps HuggingFace, with a warning that says so, or under --fastokens-strict its registration fails and is retried. mesh_fastokens_tokenizers_total{outcome} counts tokenizers as loaded, fallback or refused.
  • Tokens only tokenizer_config.json declares encode as text, as HuggingFace tokenizers encodes them on main, where transformers, and so the engine, encodes them as tokens: fastokens loads tokenizer.json alone, not with its from_file, which adds them. Of 54 local checkpoints, only Qwen3.5 declares such tokens (7 audio and TTS tokens). With gRPC workers the router sends the ids it encodes as the prompt, so the model runs on fastokens' ids, not only routes by them.
  • Limits and cache. These models tokenize up to --fastokens-max-tokenize-bytes, /v1/tokenize batches included: by default the larger of 64 MiB and the other models' limit (--prepare-max-tokenize-bytes, or with ext-proc --ext-proc-max-tokenize-bytes), so a prompt over 1 MiB encodes. The limits resolve once, as the app context is built. --fastokens-segment-cache-mb sizes fastokens' cache of the ids of the text between special tokens, per tokenizer: 1024 MiB by default, which it grows into as it fills, and 0 turns it off. An agent re-sends its history with every request, and with the cache a turn encodes little more than its newest segments; every hit is checked against the segment's text. It takes the place of --tokenizer-cache-* for these models.
  • Token parity test. test_requests_tokenize_as_on_atom (tests/routing/token_parity.rs) tokenizes a set of DeepSeek-V4.1-Flash requests for routing with each backend, and checks their tokens against the ones ATOM runs them with, which ATOM gives in the same CI job, with the same commit's code. The 19 requests are chats with reasoning controls, tools and tool history, multi-turn chats, scripts and special-token text, a completion, and an agentic history and a completion over 2 MiB, which the test builds from the lines the script records and checks by token count and BLAKE2b digest. The test is #[ignore]d, and the mesh workflow (atomesh-mocker-benchmark.yaml) runs it in a step of its own after the unit tests, with their build: the step installs ATOM and a CPU torch in a venv, runs scripts/atom_token_parity.py for a DeepSeek-V4.1-Flash revision, and then cargo test --lib -- --ignored routers::ingress::token_parity on what the script writes ($ATOM_TOKEN_PARITY), within 20 minutes. No tokens are kept in the tree, so a change to ATOM's rendering and one to the router's are checked together.
  • ATOM's tokens. scripts/atom_token_parity.py sends the requests, or recorded ones, to ATOM's own /v1/chat/completions and /v1/completions in process, with an engine that keeps the prompt tokens it is given and generates nothing. It needs ATOM's Python dependencies but no GPU, and copies none of ATOM's rules. For a HuggingFace repo@revision it downloads the files ATOM and the router read, from HuggingFace or $HF_ENDPOINT: the tokenizer files, config.json, chat_template.jinja, and the chat encoder some models ship, which ATOM renders DeepSeek-V4.1's chats with. It stores the checkpoint's path absolute, as the test reads it from atom/mesh.
  • Docs: a README Tokenization section, the token parity test, and the metric. The help of --prepare-max-tokenize-bytes and --ext-proc-max-tokenize-bytes and the ext-proc README say which limit these models have, the fastokens options are under the Tokenizer heading, the --tokenizer-cache-enable-l0/l1 help says it is for the models fastokens does not encode, and the registration's log says which tokenizers fastokens encodes.

21 files, +2128 −65.

Cost

A tokenizer that fastokens encodes for is loaded twice, by HuggingFace and by fastokens, and probed once. fastokens splits a long text between special tokens across a pool of its own threads, one per logical core up to 32 (FASTOKENS_BPE_THREADS), next to the preparation pool, and its segment cache takes up to 1 GiB per tokenizer. The token parity step installs ATOM and a CPU torch, downloads 6.4 MB from HuggingFace, or $HF_ENDPOINT, and has ATOM tokenize the requests, which took 49 s and 1 GB on a CPU host.

Results on DeepSeek-V4.1-Flash

A release build, against ATOM's tokens, median of 5:

Request Bytes Tokens HuggingFace vs ATOM fastokens vs ATOM Encode, HuggingFace Encode, fastokens
Agentic history 2,169,062 628,295 Identical Identical 1.24 s 10.3 ms
Completion 2,153,305 624,123 Identical Identical 1.19 s 11.0 ms
5 chats with tools or tool history 316–690 296–388 Identical Identical 403–784 µs 9–14 µs
10 other chats 112–295 16–68 Identical Identical 21–102 µs 2–3 µs
A short completion 37 5 Identical Identical 10 µs Under 1 µs
A reasoning_effort ATOM refuses 139 Refused, as on ATOM Refused, as on ATOM

fastokens gives HuggingFace's tokens for every request, and encodes them 13.5x to 120x as fast (median 35.8x). #3597 adds 10 requests that set reasoning controls ATOM resolves under DeepSeek-V4.1's own rules, or send text blocks. The router renders those otherwise than ATOM before it, with either backend.

Tests

  • routers/prepare/fast_tokenizer.rs:
    • fastokens_encodes_as_huggingface_and_leaves_the_rest_to_it: texts with added tokens, digits and other scripts encode, one at a time and in a batch, as HuggingFace encodes them, with and without a BOS and EOS, and decoding, templates and lookups are HuggingFace's.
    • special_tokens_are_the_ones_huggingface_adds: DeepSeek-R1-0528's tokenizer.json adds no BOS and its tokenizer_config.json does, and fastokens adds the one HuggingFace adds.
    • tokens_only_tokenizer_config_declares_encode_as_huggingface_does: a token only tokenizer_config.json declares encodes as text, as HuggingFace encodes it, with special tokens and without.
    • probe_texts_keep_the_long_ones_and_the_chat: the probe texts keep the 1 MiB text, the 256 KiB one with no newline, with added tokens, and the chat.
    • the_chat_probe_needs_no_system_role: a template that refuses a system message is probed with a chat without one, and one that renders no chat is logged.
    • a_tokenizer_fastokens_encodes_differently_is_refused and tokenizers_fastokens_cannot_load_are_refused: the probe refuses a tokenizer with other merges, a Whitespace pre-tokenizer, which fastokens does not have, and a tokenizer that is not HuggingFace's.
    • listed_models_encode_with_fastokens: by name, source and *; the segment cache has the size --fastokens-segment-cache-mb gives, 1 GiB without it, and none with 0.
  • core/steps/tokenizer_registration.rs:
    • test_registration_encodes_listed_models_with_fastokens: the registered tokenizer is fastokens' and leaves the tokenizer cache out; a tokenizer fastokens cannot load keeps HuggingFace, or fails to register under --fastokens-strict with an error the workflow does not retry, where it retries a tokenizer that fails to load.
    • test_fastokens_download_failures_are_retried: with $HF_ENDPOINT at a closed port, a tokenizer.json fastokens cannot download fails a --fastokens-strict registration with an error the workflow retries, and otherwise keeps HuggingFace.
  • tests/routing/ingress_tests.rs:
    • fastokens_models_tokenize_up_to_their_own_limit: a completion and a chat over --prepare-max-tokenize-bytes are refused with HuggingFace and tokenize with fastokens, and over --fastokens-max-tokenize-bytes are refused with both.
  • test_requests_tokenize_as_on_atom (tests/routing/token_parity.rs, ignored by default): the requests tokenize as ATOM tokenizes them in the same job, with both backends, and a request ATOM refuses is refused.
  • cli_fastokens_options_map_to_router_config and fastokens_tokenize_limit_must_be_positive: the options and their validation.

The tests that set HF_ENDPOINT, and the token parity test, are #[serial]. The token parity test turns the segment cache off, as its timed encodes repeat a prompt.

Check Result
cargo test --lib --features atom-engine 1376 passed, 8 ignored
The token parity step, in a venv of only ATOM, a CPU torch and httpx: scripts/atom_token_parity.py deepseek-ai/DeepSeek-V4.1-Flash@314113f8a7da, then cargo test --lib --features atom-engine -- --ignored routers::ingress::token_parity on its output 19 of 19 requests as on ATOM with both backends; ATOM's tokens are the ones the fixture had
A token of ATOM's output changed, or $ATOM_TOKEN_PARITY unset The token parity test fails
cargo check --features ext-proc --tests Clean
CI's KV-events steps: cargo test --lib on its filters, and --test api_tests -- kv_events_test 268 and 6 passed
cargo fmt --check, and black and ruff on the script Clean
cargo clippy --lib --tests --features atom-engine No new warnings
Each of 17 mutations, one at a time: the post-processor's IDs left off, the probe skipped, the HuggingFace limit applied to fastokens models, the chat template's downcast refusing FastTokenizer, the registration not wrapping listed models, the test's synthetic lines changed, fastokens loaded with from_file, the 256 KiB probe dropped, the chat probe's retry without a system message dropped, an unrendered chat not logged, a strict refusal retried, its message reworded, a segment cache of 0 turned on, a download failure refused under --fastokens-strict or failing the registration without it, no limit for fastokens prompts in ingress, and the segment cache's default size dropped Each fails at least one test

--fastokens-models names the models, by the name or source their
tokenizer registers under, or `*`, whose prompts the router encodes with
fastokens 0.3.6 rather than HuggingFace `tokenizers`. Decoding, chat
templates and vocabulary lookups stay with the HuggingFace tokenizer.

A model encodes with fastokens only once fastokens encodes a set of
probe texts exactly as its HuggingFace tokenizer does, with special
tokens and without: added tokens, digits, whitespace, several scripts, a
chat and a 1 MiB text. The ids the HuggingFace post-processor puts
around a text are added to fastokens' own, so a tokenizer_config.json
that adds a BOS the tokenizer.json does not still gets it. Otherwise the
model keeps HuggingFace with a warning, or under --fastokens-strict its
tokenizer fails to register; mesh_fastokens_tokenizers_total{outcome}
counts tokenizers as loaded, fallback or refused. Tokens only
tokenizer_config.json declares encode as the tokens they declare, as in
transformers and so on the engine.

These models tokenize up to --fastokens-max-tokenize-bytes, /v1/tokenize
included: 64 MiB by default, or --prepare-max-tokenize-bytes if that is
larger. --fastokens-segment-cache-mb sizes fastokens' segment cache,
which takes the place of --tokenizer-cache-* for these models.

test_requests_tokenize_as_on_atom checks, with either backend, that the
DeepSeek-V4.1-Flash requests of tests/fixtures/atom_tokens tokenize for
routing as on ATOM, two prompts over 2 MiB among them, with the tokenizer
files of the revision recorded there, which it downloads.
scripts/atom_token_parity.py records the fixture, or another checkpoint's
requests, by sending them to ATOM's own chat and completion endpoints in
process, with an engine that keeps the prompt tokens it is given.

Co-authored-by: Cursor <cursoragent@cursor.com>
@wanzhenchn wanzhenchn added the ci:mesh Mesh-only PRs: pass the Accuracy checks on the ATOMesh CI label Nov 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every eligible PR before approval:

  • ✅ Pre Checkin: Black, Ruff, catalog schema validation, non-GPU unit tests

Heavy model tests:

  • ✅ Gate checks are published on every PR so required checks do not stay missing
  • ✅ Expensive jobs run only after the PR is approved, or when a matching ci:* label is present
  • ✅ Pre Checkin must pass before approved heavy jobs continue
  • ✅ Without a matching label, expensive jobs also require a relevant path
  • ✅ A matching ci:* label is an explicit request and can open the gate even when paths would otherwise skip it

Path scope:

  • Native ATOM, vLLM, and SGLang use ignore lists: docs/markdown and unrelated plugin or Mesh paths are skipped
  • ATOMesh uses an include list: Mesh code, ATOMesh scripts/workflows/catalogs, OpenAI entrypoints, and Slurm helpers
  • Relevant path alone does not start expensive jobs; approval still opens the automatic path-scoped gate
Label Tests
ci:full Run all heavy PR model tests: native ATOM, vLLM, SGLang, and ATOMesh
ci:atom Run native ATOM model accuracy tests
ci:vllm Run ATOM vLLM OOT model accuracy tests
ci:sglang Run ATOM SGLang model accuracy tests
ci:mesh Run ATOMesh accuracy/benchmark gates for Mesh-related changes

Without a matching ci:* label, heavy jobs are skipped when the path is not relevant or the PR is not approved.
Add labels via the sidebar or gh pr edit 3596 --add-label <label>

@valar-cop valar-cop left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a few small things..

ci green.

Comment thread atom/mesh/tests/routing/token_parity.rs Resolved
Comment thread atom/mesh/tests/routing/token_parity.rs Resolved
Comment thread atom/mesh/src/config/types.rs Resolved

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Action required before merge (7)

  1. Refuse tokens that only tokenizer_config.json declares unless their ids are the ones transformers assigns.
    • Where: routers/prepare/fast_tokenizer.rs:192-209 (check()).
    • What goes wrong: fastokens keeps each declared id. transformers (AutoTokenizer, which the engine uses) gives such tokens the next free ids instead. CPU probes on the Llama-4 tokenizer files:
      • a gap: declared 201140, transformers 201135;
      • a vocab collision: declared 1000, transformers 201135, and 1000 decodes as "ств".
    • Why nothing catches it: check() never compares ids, and it skips every probe text that contains such a token.
    • Where it lands: on gRPC/atom-engine, prepare_chat/prepare_generate (prepare/mod.rs:61-72,286-295) send these ids as the model prompt.
    • Fix: fall back (or fail under strict) unless the config-only ids, sorted, are exactly N, N+1, …, where N = tokenizer.json vocab size including its added tokens. Add gap and collision tests.
    • Docs: correct the README line "as transformers, and so the engine". Say that on gRPC the fastokens ids are the model input.
  2. Show that an llm-tokenizer bump does not already solve this before adding a second encoder.
    • mesh pins llm-tokenizer =1.4.2.
    • 1.11.0 (2026-11-03) has a native byte-level BPE path that produces HF-identical ids, names DeepSeek, and encodes inputs ≥64 KiB in parallel.
    • This PR adds a second encoder, a second cache (it switches CachedTokenizer off for listed models, tokenizer_registration.rs:142-145), a second byte limit and a new crate.
    • Please time the 2 MiB DeepSeek-V4.1 prompt with llm-tokenizer ≥1.11. Keep fastokens only if that misses the target, and give the numbers.
  3. Keep the HuggingFace download out of the default cargo test --lib run.
    • Where: tests/routing/token_parity.rs:41-72, which panics on any download failure (:66). It is compiled into the lib tests (ingress.rs:911-914).
    • Effect: CI runs it twice (the unit step, then the KV-events step's routers::ingress filter). An HF outage or an offline run fails every mesh PR.
    • Fix: mark it #[ignore] and run it in one dedicated CI step with --ignored. Don't just skip on failure, which would silently drop the only real-vocabulary check. Treat chat_template.jinja and config.json as optional (valar-cop threads 1–2).
  4. Split the PR (first review: +1982/−36 across 18 files, over 1000 lines / 15 files).
    • Move the parity harness to its own PR: token_parity.rs, the fixture, scripts/atom_token_parity.py, the README paragraph and the mod hook. That is about 830 lines.
    • Drop the duplicated tests: fast_tokenizer.rs:564-628 repeats tokenizer_registration.rs:399-459 and the ingress limit tests.
  5. Fix the help and docs text this PR made stale (Nit).
    • tokenizer_registration.rs:47,68-75,87-96,286-291 still say the tokenizer is wrapped in CachedTokenizer, or log "with caching".
    • The --prepare-max-tokenize-bytes help (config/types.rs:157), the --ext-proc-max-tokenize-bytes help (ext_proc/config.rs:48) and scripts/ext-proc/README.md:55-58 give a limit that no longer applies to fastokens models.
  6. Don't let one config-only token switch off the 1 MiB and chat probes (Nit).
    • Where: fast_tokenizer.rs:206-209 skips any probe text containing such a token, so a token like </s> or [INST] drops the long probe. The chat probe is also dropped silently when the template fails to render (:295-304).
    • Fix: strip those tokens from the probe texts instead of skipping them. Also add a probe of ≥256 KiB with no newlines.
  7. Count a --fastokens-strict refusal once (Nit).
    • LoadTokenizerStep retries it 3× (tokenizer_registration.rs:217-219,300-304). Each retry re-runs the 1 MiB probe and adds another {outcome="refused"}.
    • Fix: make the refusal non-retryable.

valar-cop thread 3: enable_segment_cache(0) does turn the cache off (fastokens lib.rs:1360). Please add a Some(0) assert and resolve the thread.


Reviewed at 8f929e0 (deep; 4 hunters, 2 verifiers, C2). Flag-off per-request cost was not measured (no Rust toolchain on this host); from reading the code it is one TypeId compare. CI unit lane is green, including all new tests.

@valar-cop

valar-cop commented Nov 19, 2026 •

Copy link
Copy Markdown

Tokens only tokenizer_config.json declares must have the ids
transformers gives them: the ones after the vocabulary's and the added
tokens', in the order of the ids they declare. fastokens gives them the
ids they declare, so a model whose tokens declare others is refused.
The probe texts leave those tokens out instead of being skipped where
they have one. The chat probe renders without a system message for a
template that has no system role, and a template that renders neither
is logged. A 256 KiB text with no newline makes fastokens search for
added tokens across its threads, which split a text only at newlines.

A --fastokens-strict refusal is what the probe found, so registering is
not retried. test_requests_tokenize_as_on_atom downloads, so it is
ignored by default and runs in a CI step of its own; a checkpoint may
have no config.json or chat_template.jinja. The help of the byte limits
fastokens models do not have names --fastokens-max-tokenize-bytes, and
the registration's docs and log say which tokenizers fastokens encodes.
A test checks that --fastokens-segment-cache-mb 0 turns the cache off,
and two tests the registration and ingress tests repeat are dropped.

Co-authored-by: Cursor <cursoragent@cursor.com>
@wanzhenchn

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Addressed in 0827639, a commit on top of 8f929e0, item by item:

  1. Config-only ids. check() now refuses, or fails under --fastokens-strict, unless the tokens only tokenizer_config.json declares, sorted by the ids they declare, have the ids transformers gives them: N, N+1, …, where N is the id tokenizers gives the next token it adds (one past the highest added id when that is above the model's vocabulary, else the vocabulary's size): the tokenizer.json vocabulary size with its added tokens, when those follow the vocabulary. tokens_only_tokenizer_config_declares_encode_as_declared now has two such tokens declared out of order, a gap (N+1) and a collision with the vocabulary (1). The README now says transformers gives those ids, and that with gRPC workers the ids the router encodes are the prompt the model runs.

  2. llm-tokenizer ≥1.11. Timed on a 64-core EPYC host, release builds with fat LTO, V4.1-Flash's files at the fixture's revision; every version gives ATOM's ids for the fixture's prompts:

    Encode 1.4.2 (mesh today) 1.11.0 2.0.0 fastokens 0.3.6
    Agentic history, 2.1 MB, 628,295 tokens, warm (median of 7) 1269 ms 16.2 ms 6.3–6.8 ms 10.0–10.7 ms
    Completion, 2.1 MB, warm 1225 ms 15.3 ms 4.8–5.7 ms 9.1–10.3 ms
    2 MiB of this repo's source, warm 1224 ms 11.0 ms 5.7 ms 2.1–2.3 ms
    A chat with parallel tool calls, 1.8 KB, warm 520–720 µs 42 µs 13 µs 13–15 µs
    Agentic history, first encode in a fresh process (median of 3) 1491 ms 25.0 ms 8.3 ms 118.6 ms
    The same on one thread (RAYON_NUM_THREADS=1, FASTOKENS_BPE_THREADS=1) 1479 ms 97.1 ms 21.8 ms 73.4 ms

    Warm, fastokens encodes about 1.6x as fast as 1.11.0 on the V4.1 prompts, 5x on source code and 3x on the short chat. Against 2.0.0 it is about 2.6x as fast on source code and even on the short chat, and 2.0.0 is about 1.6x as fast on the V4.1 prompts. fastokens' first encode in a fresh process is the slowest of the four.

    So on speed alone a bump meets the target too: warm, all three encode the V4.1 prompts in 6–16 ms, against 1.27 s today. It is not a drop-in for this model, though:

    • From 1.11, detect_renderer_from_config picks llm-tokenizer's built-in DeepSeek-V4.1 encoder from config.json (architectures or model_type), chat template or not. main's renders_without_template guard then marks the tokenizer, and every V4.1 chat gets 501 token_routing_unsupported, where with 1.4.2 it renders with the checkpoint's template.
    • With the guard lifted, 5 of fix(mesh): take DeepSeek-V4.1 reasoning efforts as ATOM does #3597's 29 V4.1 requests, the ones that turn thinking off (reasoning_effort: none, a disabled thinking, thinking_mode: chat), tokenize unlike ATOM, diverging at token 2, with either encoder: the built-in encoder does not read the template's thinking_mode.
    • It changes the encoder of every model, where fastokens is opt-in per model and off by default (and CacheConfig gains a field).

    So we'd like to keep fastokens here and take the bump on its own, with the renderer question; the token parity test this PR adds is what that bump would have to pass.

  3. HF download. test_requests_tokenize_as_on_atom is #[ignore]d, and the mesh workflow runs it once, in a new step right after the unit tests and with their build: cargo test … --profile ci --lib --features atom-engine -- --ignored routers::ingress::token_parity. A failed download still fails it; there is no skip. config.json and chat_template.jinja are optional: a 404 skips them, and any other failure fails.

  4. Split. We'd rather keep the parity harness with the encoder: it is the one check that the fastokens path gives ATOM's ids on a real vocabulary and on 2 MiB prompts, which the unit tests' small vocabularies cannot show, and fix(mesh): take DeepSeek-V4.1 reasoning efforts as ATOM does #3597 extends the same fixture. Ignored by default, it no longer costs the default run anything. The duplicated tests are gone: tokenize_limits_follow_the_tokenizer, and the fallback and strict half of only_listed_models_encode_with_fastokens, now listed_models_encode_with_fastokens, which keeps the matching by name, source and *, and the segment cache's size.

  5. Stale docs. The registration's docs say which tokenizers get CachedTokenizer and which fastokens' segment cache, and its log names the one it registered ("encoding with fastokens" or "with caching"). The help of --prepare-max-tokenize-bytes and --ext-proc-max-tokenize-bytes, and scripts/ext-proc/README.md, name --fastokens-max-tokenize-bytes for these models.

  6. Probes. Config-only tokens are stripped from the probe texts instead of skipping them, and the long texts are built from the stripped probes, so they keep their size. The chat probe renders again without the system message for a template that has no system role, and a template that renders neither is logged. A new 256 KiB probe has no newline: the probe texts with their newlines replaced, and the added tokens. Tests: probe_texts_leave_out_tokens_only_tokenizer_config_declares and the_chat_probe_needs_no_system_role.

  7. Strict refusal. LoadTokenizerStep::is_retryable is false for a --fastokens-strict refusal, so it is probed and counted once; other load errors are still retried. test_registration_encodes_listed_models_with_fastokens checks both.

valar-cop thread 3: listed_models_encode_with_fastokens now asserts that --fastokens-segment-cache-mb 0 leaves fastokens with no segment cache.

Locally, cargo test --lib --features atom-engine gives 1375 passed and 8 ignored, the new step's --ignored run passes, CI's KV-events steps give 268 and 6 passed, and fmt, clippy (no new warnings), black and ruff are clean. Each of 15 mutations, the 9 new ones covering the checks above, fails at least one test.

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Action required before merge (5)

  1. Retry source-resolution failures; add the strict prefix only to real probe refusals.
    • Where: fast_tokenizer.rs:80-88,111.
    • Problem: every with_fastokens error gets STRICT_REFUSAL, and that includes tokenizer_json()'s second hub call for HF ids (llm-tokenizer repo.info(), which always goes to the network). is_retryable (tokenizer_registration.rs:218-225) then never retries it.
    • Effect: under --fastokens-strict, one network blip leaves the model unregistered for good. Without strict, it falls back to HF for good, with the warning "fastokens cannot encode these prompts as HuggingFace does".
    • Fix: prefix only FastTokenizer::new (and JoinError) errors. Return tokenizer_json errors unprefixed, so strict retries them, and give non-strict an accurate fallback message.
    • Text and tests: fix the STRICT_REFUSAL doc (:40-42), the is_retryable comment, README "with no retries" and the squash text. Add a test for a download failure.
  2. Make config-only ids decodable, or document that they are not.
    • Where: fast_tokenizer.rs:408-441 sends decode, token_to_id and id_to_token to the HF inner tokenizer. The inner does not know these tokens (llm-tokenizer huggingface.rs:55-63) and silently drops their ids.
    • Effect: /v1/tokenize → /v1/detokenize now loses that text (probe v3/scripts/probe_decode.py), which never happened on main.
    • Fix: either decode them from fastokens' added-token table, or say so in the module doc, the README and the --fastokens-models help. Add a round-trip test either way.
  3. Fix the docs and help (Nit).
    • ext-proc limit: the fastokens limit is max(64 MiB, prepare limit), and the prepare limit falls back to --ext-proc-max-tokenize-bytes (types.rs:551-553,596-600). So "Neither byte limit applies…" (scripts/ext-proc/README.md:58-60, ext_proc/config.rs:49) and the README/help limit lines are wrong above 64 MiB.
    • Config-only ids: README:296-298 and the test doc at fast_tokenizer.rs:582-584 should say "after the vocabulary's and added tokens'".
    • Segment cache: tokenizer_registration.rs:47-49 says fastokens "has fastokens' segment cache instead", but that cache is off by default.
    • Help heading: use next_help_heading = "Tokenizer" (types.rs:181), not a second "Tokenization" heading, and note in the --tokenizer-cache-* help that it does not apply to these models.
  4. Close the test gaps (Nit).
    • Limit: fastokens_models_tokenize_up_to_their_own_limit never sends a fastokens prompt over its limit, so making ingress.rs:873 unlimited passes. Add one.
    • Some(0): with FASTOKENS_SEGMENT_CACHE unset the assert at fast_tokenizer.rs:743-746 cannot fail. Set the env in a #[serial] test.
    • Timeout: add a timeout to reqwest::get (token_parity.rs:61) or timeout-minutes to the new CI step.
  5. Small cleanups (Nit).
    • Delete the unreachable FastTokenizer::set_chat_template (:471-475) and the now-unused anyhow! import.
    • Have the recorder store an existing checkpoint path resolved (atom_token_parity.py:352). A relative path breaks the test, which runs from atom/mesh.
    • Refuse a config-only token whose added_tokens_decoder entry leaves out normalized when the tokenizer has a normalizer: transformers reads it as !special, fastokens as false.
    • Resolve TokenizeLimits once at build instead of per request (ingress.rs:650, tokenize.rs:132), which is zero-cost.

Not required here (pre-existing): the gRPC prepare path applies no tokenize byte limit (prepare/mod.rs:69,290).


Reviewed at 0827639 (deep; 3 hunters, 4 verifiers, C2). Already fixed: config-only id check, #[ignore] + one CI step (ran and passed), optional files, duplicated tests removed, stale docs at the named sites, probes stripped / 256 KiB flat / system-less chat, strict refusal not retried, valar-cop threads (all resolved). llm-tokenizer ≥1.11 numbers given; keeping fastokens is a design call. Items 2–5 were present at 8f929e0 and missed by our last round. Only CI failure: Slurm sbatch submission (infra).

A tokenizer.json fastokens cannot find or download says nothing of how
it encodes, so under --fastokens-strict the registration fails and is
retried, not refused, and without it the model keeps HuggingFace with a
warning that says so. Only what fastokens' probe finds is a refusal.

HuggingFace tokenizers does not have the tokens only
tokenizer_config.json declares and dropped their ids when decoding, so
/v1/detokenize lost the text /v1/tokenize encoded as them. fastokens
now looks them up and decodes the ids that include them, at once and
token by token, and a model with such tokens must also decode the probe
texts as HuggingFace does, keeping special tokens and skipping them. A
model with a normalizer and such a token that is not special and does
not say whether it is normalized is refused: transformers takes it as
normalized, fastokens as not.

The tokenization byte limits resolve once, as the app context is built.
The help and docs say fastokens models have the larger of 64 MiB and the
other models' limit, which falls back to --ext-proc-max-tokenize-bytes;
the fastokens options are under the Tokenizer heading, and the
--tokenizer-cache-* help says it is for the models fastokens does not
encode. A test sends a fastokens prompt over its own limit, one sets
FASTOKENS_SEGMENT_CACHE where --fastokens-segment-cache-mb 0 turns the
cache off, the parity test's downloads time out, and the recorder stores
a checkpoint path absolute. The unreachable set_chat_template is gone.

Co-authored-by: Cursor <cursoragent@cursor.com>
@wanzhenchn

Copy link
Copy Markdown
Contributor Author

Thanks. All five are in 11ca1b8, and #3597 is rebased on it.

  1. Retries. Only FastTokenizer::new and a JoinError get STRICT_REFUSAL now. A tokenizer_json error returns unprefixed under --fastokens-strict, so is_retryable retries it; without strict the model keeps HuggingFace with "Cannot find the tokenizer.json fastokens loads; encoding these prompts with HuggingFace" and a fallback count. The STRICT_REFUSAL doc, the is_retryable comment, the README and the PR text say so. test_fastokens_download_failures_are_retried points HF_ENDPOINT at a closed port: the strict error is retryable, and non-strict keeps the HuggingFace tokenizer.
  2. Config-only ids decode. FastTokenizer keeps those tokens by id. decode hands ids that include one to fastokens, whose decode does what tokenizers' does (added tokens first, special ones skipped on request, then the decoder chain), and so what transformers, which has the tokens, does. decode_step runs the trait's incremental algorithm over that decode for such models, and token_to_id and id_to_token fall back to them. Since fastokens then decodes whole sequences for those models, the probe also checks that it decodes every probe text as HuggingFace does, keeping and skipping special tokens, and refuses the model otherwise. Tests: the round trip in tokens_only_tokenizer_config_declares_encode_as_declared (at once, token by token, and the lookups); /v1/tokenize → /v1/detokenize in tokens_only_tokenizer_config_declares_detokenize; and a refusal where the decoders differ (with no decoder, HuggingFace joins tokens with spaces, fastokens without). V4.1-Flash has no such tokens, so it still decodes with HuggingFace.
  3. Docs. The prepare and ext-proc help and the ext-proc README say these models have the larger of that limit and 64 MiB unless --fastokens-max-tokenize-bytes sets theirs; that option's help and the README give its default as the larger of 64 MiB and the other models' limit. "and the added tokens'" is in the README and the test doc. The segment cache doc says the cache is off by default. The options are under Tokenizer, and the --tokenizer-cache-enable-l0/l1 help says it is for the models fastokens does not encode.
  4. Tests. fastokens_models_tokenize_up_to_their_own_limit also sends a 1,200-byte prompt, over the 1,024-byte fastokens limit, on both routes; making ingress.rs:873 unlimited now fails it. listed_models_encode_with_fastokens is #[serial] and sets FASTOKENS_SEGMENT_CACHE=1, so Some(0) has to turn the cache off, and a None case keeps it on. The parity downloads use a client with a 30 s connect and a 5 min request timeout, and that test is #[serial] too, as it reads HF_ENDPOINT.
  5. Cleanups. set_chat_template and anyhow! are gone, the recorder stores an existing checkpoint path resolved, and TokenizeLimits is built once into AppContext. The normalized refusal covers the case where the two disagree: a config-only token that is not special and has no normalized, under a normalizer (transformers reads it as !special, so true; fastokens as false). A special one reads as false in both, so it loads; tokens_only_tokenizer_config_declares_say_whether_they_are_normalized covers both.

Nine mutations, one per new behaviour, each fail at least one test. cargo test --lib --features atom-engine: 1379 passed; the token parity step: 1 passed; the KV-events steps: 271 and 6 passed; the ext-proc check, fmt, black, ruff and clippy are clean. The PR text has the new tests and checks.

wanzhenchn added a commit that referenced this pull request Nov 21, 2026
… its segment cache

These routers tokenize every prompt. fastokens encodes them as Hugging Face
does, and its segment cache, which checks every hit against the text it
keeps, takes the place of a prefix cache: 1 GiB, of which 72 sessions of up
to 1M tokens take about 0.6 GB. The options come with #3596.
…ture

The token parity step now has ATOM tokenize the requests in the job, with this
commit's code: it installs ATOM and a CPU torch in a venv, and
atom_token_parity.py downloads a DeepSeek-V4.1-Flash revision's tokenizer files
and chat encoder from HuggingFace and writes ATOM's tokens, which the test
compares the router's with. A change to ATOM's rendering and one to the
router's are checked together, where a fixture recorded from another ATOM
could go stale. The fixture and the test's own download are gone.

The script takes a HuggingFace repo@revision for the checkpoint and downloads
its tokenizer files and the chat encoder some models ship, which ATOM renders
DeepSeek-V4.1's chats with. The test reads $ATOM_TOKEN_PARITY only, and takes
the median of 5 encodes of every prompt.
wanzhenchn added a commit that referenced this pull request Nov 21, 2026
…-chat-controls

Brings in #3596's check of token parity against ATOM in CI, which replaces the
recorded fixture. This PR's 10 requests are in the script's built-in set, so CI
checks them too.
@wanzhenchn
wanzhenchn requested a review from valarLip November 21, 2026 03:38
An agent re-sends its history with every request, and fastokens encodes
the text between special tokens one segment after another on the calling
thread, so without its segment cache the router encodes the whole history
again on every turn. The cache keeps the ids of those segments, checked
against their text on every hit, so a turn encodes little more than its
newest segments.

--fastokens-segment-cache-mb now defaults to 1024 MiB per tokenizer, which
the cache grows into as it fills; 0 turns it off. The token parity test
turns it off, as its timed encodes repeat a prompt.
@wanzhenchn

Copy link
Copy Markdown
Contributor Author

Pushed 9d88181: fastokens' segment cache is on by default, 1 GiB per tokenizer, and --fastokens-segment-cache-mb 0 turns it off.

It follows new timings of the five encoders across prompt sizes, concurrent requests and an agent's session, with DeepSeek-V4.1-Flash's tokenizer on a 64-vCPU host, each library on its default threads and a new agentic text each encode. All five give the same tokens.

HF 0.23.2 llm-tokenizer 1.4.2 1.11.0 2.0.0 fastokens 0.3.6
16 KiB prompt 6.1 ms 6.0 ms 0.98 ms 0.15 ms 0.06 ms
256 KiB prompt 129 ms 124 ms 6.3 ms 2.3 ms 0.89 ms
2 MiB prompt 1.18 s 1.31 s 13.4 ms 4.8 ms 6.4 ms
Mean over an agentic trace's prompt sizes (median 262K tokens) 642 ms 689 ms 10.0 ms 3.6 ms 3.6 ms
Its CPU time 641 ms 723 ms 220 ms 95 ms 8.3 ms
p99 of a 256 KiB prompt, 32 at once 223 ms 460 ms 187 ms 3.4 ms
An agent's 127 turns to 2 MiB 72 s 1.14 s 478 ms 459 ms
The same with its cache (L1, or segment) 114 s 438 ms 243 ms 172 ms

2.0.0 leads only on one prompt of 2 MiB or more, by 1.3x to 1.8x, on about 25 cores to fastokens' 2.3. That is the case the earlier timings measured, and repeating one 2 MiB prompt still gives 6.0 ms to 9.8 ms. fastokens encodes a chat's text between special tokens one segment after another, so an agent's turn re-encodes the history it re-sends; with the segment cache, a turn at 2 MiB encodes in 1.6 ms instead of 6.4 ms. fastokens also loads in about 1 s, and its first encode takes 60 to 100 ms; registration does both, with the probe texts, before the router serves.

fastokens' `from_file` also adds the tokens only `tokenizer_config.json`
declares, which HuggingFace `tokenizers` encodes as text. Giving them the ids
`transformers` gives took an id check, a normalization check, a decode check
and a decode path through fastokens. Of 54 local checkpoints, only Qwen3.5
declares such tokens (7 audio and TTS tokens), and main's HuggingFace tokenizer
encodes them as text too.

Loading `tokenizer.json` alone keeps fastokens' tokens HuggingFace's, so
decoding and lookups stay with HuggingFace and the probe only compares
encodings. fast_tokenizer.rs goes from 944 to 664 lines.
@wanzhenchn

Copy link
Copy Markdown
Contributor Author

Pushed cfc168a: fastokens now loads tokenizer.json alone, as HuggingFace tokenizers does, not with from_file, which also adds the tokens only tokenizer_config.json declares. Those tokens encode as text with both backends, as on main. Of 54 local checkpoints, only Qwen3.5 declares any (7 audio and TTS tokens), and DeepSeek-V4.1-Flash, which CI checks against ATOM, declares none.

So the id, normalization and decode checks for those tokens, the decode path through fastokens, and their tests are gone. Decoding and lookups stay with HuggingFace, and the probe only compares encodings. fast_tokenizer.rs is 664 lines (was 944), and the PR is +2128 −65.

  • cargo test --lib --features atom-engine: 1376 passed, 8 ignored.
  • CI's KV-events filters and kv_events_test: 268 and 6 passed.
  • Loading with from_file again fails tokens_only_tokenizer_config_declares_encode_as_huggingface_does.

#3597 merges it as 51ad82f, with 1381 passed.

@wanzhenchn

Copy link
Copy Markdown
Contributor Author

@valarLip CI is green on cfc168a, including the DeepSeek-V4 1P1D smoke (run). Your five items are answered here; the two changes since then are described here and here. Could you take another look?

@Jasen2201 Jasen2201 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No blocking issues @ cfc168a: one stale comment, posted inline. Comment review, not a verdict.

Checked: the probe (texts, affixes, the 1 MiB and 256 KiB cases), strict refusal versus retried download, the per-tokenizer limits, and in fastokens 0.3.6 the segment cache (hits confirmed against the stored text, a byte budget per shard) and its single process-wide thread pool. I found no code defect.

Evidence for parity, beyond CI:

  • A review-only fuzz: 1500 random texts per tokenizer, with and without special tokens, each encoded twice so the second goes through a 256 MiB segment cache, plus a 64-text batch. 0 mismatches against HuggingFace on the 10 local checkpoints the probe accepts (DeepSeek-V4.1-Flash, R1-0528, Qwen3.5, GLM-5.2, GLM-4.7, MiniMax-M3.1, Llama-3.1, gpt-oss, Ling, diffusiongemma).
  • The owner's runs with this PR and #3597 merged: prompt tokens identical to ATOM's HTTP chat on 59 of 59 DeepSeek-V4.1-Flash prompts, up to 690K tokens, and 0 failed requests at 6P16D C1228.
More detail
  • Probe refusal works as meant: amd/DeepSeek-R1-0528-MXFP4-v2 ships a tokenizer.json with truncation.max_length: 512, and the probe refuses it ("fastokens encodes ... (special tokens: true) as [5822] from token 512, HuggingFace as []"). Not this PR's: on main the HuggingFace path truncates that model's prompts to 512 tokens too, where transformers in ATOM does not.
  • Owner's encode timing, single core, 512 MiB segment cache: 0.64 ms first turn and 0.15 ms later turns, against 126 ms and 5.3 ms for ATOM's Python front end, identical ids on 363 AgentX prompts.
  • cargo test --lib --features atom-engine at the #3597 head 51ad82f: 1381 passed.
  • For the author, merging with the owner's ATOM gRPC stack (#3672 to #3679, heads of jasen/atom-grpc-* today): this PR conflicts in tokenizer_registration.rs and chat_template.rs with #3676, and in cliargs.rs with #3679. #3676 sets a worker's inline chat template with Arc::get_mut(..).set_chat_template(..) on the loaded tokenizer; in the merge that has to run before with_fastokens, because FastTokenizer holds the inner Arc and keeps the trait's refusing set_chat_template.

@Jasen2201 Jasen2201 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@zhuyuhua-v
zhuyuhua-v merged commit 9f98bff into main Nov 23, 2026
119 of 120 checks passed
@zhuyuhua-v
zhuyuhua-v deleted the zwan/mesh-fastokens-encode branch November 23, 2026 06:27
Jasen2201 pushed a commit that referenced this pull request Nov 27, 2026
… its segment cache

These routers tokenize every prompt. fastokens encodes them as Hugging Face
does, and its segment cache, which checks every hit against the text it
keeps, takes the place of a prefix cache: 1 GiB, of which 72 sessions of up
to 1M tokens take about 0.6 GB. The options come with #3596.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci:mesh Mesh-only PRs: pass the Accuracy checks on the ATOMesh CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants