[v0.5.10][2] Fix apply_chat_template behavior for transformers >=5.0#926
[v0.5.10][2] Fix apply_chat_template behavior for transformers >=5.0#926yueming-yuan merged 20 commits intomainfrom
Conversation
…ng-v0.5.10" This reverts commit d549b26.
There was a problem hiding this comment.
Code Review
This pull request introduces a utility function _apply_chat_template_ids to handle changes in the transformers library (version 5.0+) where apply_chat_template may return a dictionary instead of a list. All existing calls to the tokenizer have been updated to use this wrapper. Feedback suggests adding type hints to the new function and explicitly setting return_dict=False to improve robustness and maintainability.
| def _apply_chat_template_ids(tokenizer, messages, **kwargs) -> list[int]: | ||
| """Wrapper that always returns list[int] from apply_chat_template(tokenize=True). | ||
|
|
||
| transformers >=5.0 returns BatchEncoding instead of list[int].""" | ||
| result = tokenizer.apply_chat_template(messages, tokenize=True, **kwargs) | ||
| if isinstance(result, list): | ||
| return result | ||
| return result["input_ids"] |
There was a problem hiding this comment.
The _apply_chat_template_ids wrapper is a good addition for compatibility with transformers 5.0. However, it can be improved by adding type hints for better maintainability and consistency with the rest of the file. Also, explicitly setting return_dict=False via kwargs.setdefault ensures that current versions of transformers return the expected list type, while the isinstance check provides a robust fallback for future versions where the default might change or the flag might be ignored.
Note: Passing tokenize in kwargs to this function will cause a TypeError because it is already explicitly passed to apply_chat_template.
| def _apply_chat_template_ids(tokenizer, messages, **kwargs) -> list[int]: | |
| """Wrapper that always returns list[int] from apply_chat_template(tokenize=True). | |
| transformers >=5.0 returns BatchEncoding instead of list[int].""" | |
| result = tokenizer.apply_chat_template(messages, tokenize=True, **kwargs) | |
| if isinstance(result, list): | |
| return result | |
| return result["input_ids"] | |
| def _apply_chat_template_ids(tokenizer: AutoTokenizer, messages: list[dict], **kwargs) -> list[int]: | |
| """Wrapper that always returns list[int] from apply_chat_template(tokenize=True). | |
| transformers >=5.0 returns BatchEncoding instead of list[int].""" | |
| kwargs.setdefault("return_dict", False) | |
| result = tokenizer.apply_chat_template(messages, tokenize=True, **kwargs) | |
| if isinstance(result, list): | |
| return result | |
| return result["input_ids"] |
Remove models broken by transformers v5 tokenizer unification (DeepSeek-V3, step3, glm-4-9b-chat) and track them in a TOOL_CALL_KNOWN_FAILURES list with root cause comments. Add new passing models: Qwen3.5, Qwen3-Coder-Next, GLM-4.7-Flash, Kimi-K2.5, MiniMax-M2.5, Nemotron-3-Super. Clean up debug helpers. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
transformers >=5.0 changed apply_chat_template(tokenize=True) to return BatchEncoding instead of list[int]. Pass return_dict=False to all 6 call sites in mask_utils.py to ensure list[int] on both v4 and v5. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
775a86c to
f058d37
Compare
Move Step-3.5-Flash from known failures into active tool-call test models, and clarify comments for remaining transformers v5 tokenizer/template incompatibilities. Made-with: Cursor
|
A report generated by cc & codex and briefly reviewed by me. generally make sense. Transformers v5 Tokenizer Compatibility AnalysisBackground
i.e. the decode of the token delta should equal the text delta. For a few models, that assumption effectively relies on This document separates:
Root Cause 1: LlamaTokenizer Overwrites ByteLevel with MetaspaceDirectly affected models: What changedIn v4, In v5, self._tokenizer.pre_tokenizer = Metaspace(replacement="▁", prepend_scheme=always)
self._tokenizer.decoder = Sequence([Replace("▁", " "), ByteFallback(), Fuse(), Strip()])This happens because ConsequencesEncoding changed -- the Metaspace pre_tokenizer handles spaces differently from ByteLevel: Decoding changed -- Note: the token's stored text ( Why this explains the failing models
Upstream references
Root Cause 2: Legacy
|
| Model | Root Cause | Upstream Issue |
|---|---|---|
| deepseek-ai/DeepSeek-V3 | LlamaTokenizer overwrites ByteLevel with Metaspace | #43066 |
| deepseek-ai/DeepSeek-V3.1 | Tool-call chat template expects string function.arguments; current dummy tool-call shape provides a dict |
Model-side template issue |
| stepfun-ai/step3 | Same as above | Same |
| THUDM/glm-4-9b-chat | v5 removed legacy _decode segmentation, exposing custom tokenizer bug |
N/A (model-side bug) |
Summary of Passing Models
| Model | Tokenizer Class | Backend | Decoder | Why Unaffected |
|---|---|---|---|---|
| Qwen2.5-0.5B-Instruct | Qwen2Tokenizer | TokenizersBackend | ByteLevel | Hardcoded ByteLevel matches tokenizer.json |
| Qwen3-0.6B | Qwen2Tokenizer | TokenizersBackend | ByteLevel | Same |
| Qwen3-4B-Instruct-2507 | Qwen2Tokenizer | TokenizersBackend | ByteLevel | Same |
| Qwen3-Coder-30B-A3B-Instruct | Qwen2Tokenizer | TokenizersBackend | ByteLevel | Same |
| Qwen3.5-0.8B | Qwen2Tokenizer | TokenizersBackend | ByteLevel | Same |
| Qwen3-Coder-Next | Qwen2Tokenizer | TokenizersBackend | ByteLevel | Same |
| Mistral-7B-Instruct-v0.3 | TokenizersBackend | TokenizersBackend | Metaspace | Direct load from tokenizer.json, no overwrite |
| GLM-4.7-Flash | TokenizersBackend | TokenizersBackend | ByteLevel | Direct load from tokenizer.json; does not use the old ChatGLM Python decode path |
| Step-3.5-Flash | TokenizersBackend | TokenizersBackend | ByteLevel-compatible | Direct load; passes tool-response round-trip as of April 8, 2026 |
| Nemotron-3-Super-120B | TokenizersBackend | TokenizersBackend | ByteLevel | Direct load from tokenizer.json, no overwrite |
| MiniMax-M2 | GPT2Tokenizer | TokenizersBackend | ByteLevel | Hardcoded ByteLevel matches tokenizer.json |
| MiniMax-M2.5 | GPT2Tokenizer | TokenizersBackend | ByteLevel | Same |
| internlm3-8b-instruct | InternLM3Tokenizer | PythonBackend | N/A | Pure Python tokenizer, no Rust decode, no bug |
| Kimi-K2-Instruct | TikTokenTokenizer | PythonBackend | N/A | Pure Python tokenizer, no Rust decode, no bug |
| Kimi-K2.5 | TikTokenTokenizer | PythonBackend | N/A | Same |
| MiMo-7B-RL | Qwen2Tokenizer | TokenizersBackend | ByteLevel | Hardcoded ByteLevel matches tokenizer.json |
- Revert CI image back to radixark/miles:dev - Revert SGLANG_PR default back to sglang-miles - Revert SGLANG_BRANCH back to sglang-miles - Revert Megatron-Bridge back to merged-megatron-0.16.0rc0-miles
…adixark#926) Co-authored-by: guapisolo <guapisolo@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…region clusters (#10) * Revert "[BUGFIX] [P2PRDMA] Add rollout post-processing after P2PRDMA weight updates" (radixark#882) * [Fix] fix ci (radixark#894) * Avoid threading for ray getting object (radixark#886) * Add explicit errors for unsupported Megatron profiles (radixark#887) * Add nvfp4 quantizer files (radixark#907) * Bump flash-linear-attention version to 0.4.2 (radixark#892) * [BUGFIX] Invoke "post_process_quantization" by default after weight updating (radixark#890) Co-authored-by: Yueming Yuan <yym022502@gmail.com> * Add heartbeat and id to session server (radixark#866) * fix: adding thin glm5 image to docker build + latest tag sync (radixark#871) * Add consistent hashing routing policy for rollout (radixark#891) Co-authored-by: Yueming Yuan <yueming@Mac.attlocal.net> * [example] add retool v2 example with multi-turn framework interfaces (radixark#654) Co-authored-by: GuanxingLu <gxlu02@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * Expose rollout-batch-size, n-samples-per-prompt, global-batch-size as CLI args in swe-agent-v2 (radixark#954) Co-authored-by: Shi Dong <shi.dong@radixark.ai> * chore: remove obsolete swe-agent server.py and run-qwen3.sh (radixark#952) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * Add weight staleness control for fully async rollout (radixark#958) * Fix/pause generation mode (radixark#924) Co-authored-by: Yueming Yuan <yym022502@gmail.com> * [v0.5.10][1] Bump sglang to v0.5.10 (radixark#898) * [v0.5.10][2] Fix apply_chat_template behavior for transformers >=5.0 (radixark#926) Co-authored-by: guapisolo <guapisolo@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * [v0.5.10][3] Fix processor return_tensors duplicate kwarg for transformers >=5.0 (radixark#927) Co-authored-by: guapisolo <guapisolo@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * [v0.5.10][4] Fix _no_split_modules set not subscriptable in transformers >=5.0 (radixark#931) * [v0.5.10][5] Disable piecewise cuda graph to avoid NVLS oom (radixark#935) * [v0.5.10][6][FSDP] fix outdated weight update logic in FSDP (radixark#948) Co-authored-by: guapisolo <guapisolo@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: maocheng23 <35615230+maocheng23@users.noreply.github.com> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> * [v0.5.10][7][FSDP] move FSDP to experimental and disable by default (radixark#961) * Add skiplist and more robust calculation on val (radixark#965) * [fix] tiny fix debug rollout only in weight version check (radixark#967) * feat: real cp support with relayout fix for qwen3.5 train/rollout mismatch (radixark#885) * [AMD] Upgrade to sglv0.5.10 (radixark#973) * switch model to actor (radixark#756) * [fix] support general logic to bypass fp32 downcast and fix qwen35 A_log dtype (radixark#975) Co-authored-by: yueming-yuan <yym022502@gmail.com> * fix: populate prefix_cache_info in OpenAI/session rollout path (radixark#960) * Remove prepare_harbor_tasks.py; use harbor-private adapters (radixark#982) * [fix] Skip flush_cache in in_place mode and add fully async example (radixark#974) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * GLM47 full cmd for async and sync reasoning (radixark#986) Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: handle non-tool appended messages in TITO incremental tokenization (radixark#949) Co-authored-by: Yanbin Jiang <jybsuper@gmail.com> * [docker] Add sgl-model-gateway install and download .tar.gz assets (radixark#895) * [ci] fix hf rate limit error by caching tokenizer loading (radixark#1014) Co-authored-by: maocheng23 <35615230+maocheng23@users.noreply.github.com> * Use load_generate_function in legacy sglang_rollout path (radixark#1016) * Update CODEOWNERS to add new reviewers (radixark#1021) * Support moe lora for gpt-oss (radixark#798) Co-authored-by: Ethan (Yusheng) Su <yushengsu.thu@gmail.com> * [fix] restore expert_bias to fp32 before bridge weight export (radixark#811) * [chore] drop legacy transformers upgrade pin for glm47-flash and qwen35 (radixark#1018) * [fix] Enforce param dtype before wrap ddp (radixark#992) Co-authored-by: Zhichen Zeng <zczeng@uw.edu> * [upgrade] update Megatron-Bridge source and LoRA CI to megatron e2e tests and (radixark#1023) * [CI] Drop --use-miles-router from R3 tests and add r3 comparasion test between sgl & miles router (radixark#1015) * wandb: raise init_timeout, add retry wrapper, fix shared-mode init for cross-region clusters In online + shared mode, both `init_wandb_primary` and `init_wandb_secondary` make HTTPS round-trips to wandb cloud (login + run create/attach). On high-latency cross-region clusters (e.g. Abu Dhabi MBZUAI ↔ wandb-cloud US-West) with concurrent actor bursts, a single round-trip can exceed the wandb SDK's 90s default `init_timeout` — tearing down the whole run with a silent handshake abort. Observed on RL360 job 1564420, which forced `WANDB_MODE=offline` as a global default ever since (see https://github.com/LLM360/RL360/issues/87). The issue's original diagnosis assumed a local primary↔secondary socket handshake race. That's not how shared mode works — per wandb's own feature PR (wandb/wandb#6882), each writer spawns an independent wandb-core that talks to the cloud directly; aggregation is server-side by run_id. No local socket exists. The failure mode is pure network/latency, not a local readiness race. Changes ------- - Bump `init_timeout` to 300s for primary and secondary Settings. Configurable via `WANDB_INIT_TIMEOUT_SECS` env var for tuning. - Wrap both init paths in a bounded exponential-backoff retry (`_wandb_init_with_retry`) that re-attempts on wandb.errors.CommError and wandb.errors.UsageError. 3 attempts with 5→10→20s backoff by default, tunable via `WANDB_INIT_RETRY_ATTEMPTS` / `WANDB_INIT_RETRY_BACKOFF_SECS`. - Add `x_label` tagging per wandb distributed-training docs: primary gets `rank_<rank>_primary`, secondaries get `rank_<rank>_secondary`. Enables per-rank console-log filtering in the wandb UI. - Drop `reinit=True` from secondary init_kwargs. Shared mode natively supports concurrent writers on a single run; `reinit=True` triggered stale-state warnings on secondary actors without functional benefit. Followups this change enables ----------------------------- - `WANDB_MODE=offline` can be removed from scale.yaml's extra_env default once a pilot run confirms online mode boots cleanly. - The tmux-based `~/bin/wandb-sync-rl360.sh` workaround on David's M2 account becomes obsolete (no more offline-only default). - Near-realtime wandb dashboards replace the ~2-minute-lag offline sync; per-rank system metrics via x_label filtering. --------- Co-authored-by: JD <jaedon.guo@gmail.com> Co-authored-by: Ethan (Yusheng) Su <yushengsu.thu@gmail.com> Co-authored-by: fzyzcjy <5236035+fzyzcjy@users.noreply.github.com> Co-authored-by: Ziang Li <ziangli@umich.edu> Co-authored-by: Zhichen Zeng <zczeng@uw.edu> Co-authored-by: JensenFire <xinji1@microsoft.com> Co-authored-by: Yueming Yuan <yym022502@gmail.com> Co-authored-by: maocheng23 <35615230+maocheng23@users.noreply.github.com> Co-authored-by: Douglas Yang <douglasyang88@gmail.com> Co-authored-by: Yueming Yuan <yueming@Mac.attlocal.net> Co-authored-by: Huapeng Zhou <73010314+PopSoda2002@users.noreply.github.com> Co-authored-by: GuanxingLu <gxlu02@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: Shi-Dong <Shi-Dong@users.noreply.github.com> Co-authored-by: Shi Dong <shi.dong@radixark.ai> Co-authored-by: Jiajun Li <48857426+guapisolo@users.noreply.github.com> Co-authored-by: guapisolo <guapisolo@gmail.com> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> Co-authored-by: Yuzhen Zhou <82826991+zyzshishui@users.noreply.github.com> Co-authored-by: Yanbin Jiang <jybsuper@gmail.com> Co-authored-by: Ying Sheng <sqy1415@gmail.com> Co-authored-by: Yisheng Gong <yishenggong9437@gmail.com>
ci-sglang-pr: sglang-miles-v0.5.10
Summary
transformers5.x changedapply_chat_template(tokenize=True)to returnBatchEncodinginstead oflist[int]_apply_chat_template_ids()wrapper that normalizes the return typeReplaces #925 (was merged then reverted).