Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
8f929e0
feat(mesh): encode the prompts of listed models with fastokens
wanzhenchn Nov 19, 2026
0827639
fix(mesh): check fastokens' ids for config-only tokens, and probe more
wanzhenchn Nov 20, 2026
11ca1b8
fix(mesh): decode fastokens' config-only tokens, and retry downloads
wanzhenchn Nov 20, 2026
f56b46c
feat(mesh): render DeepSeek-V4.1 chats under ATOM's reasoning controls
wanzhenchn Nov 19, 2026
6849317
test(mesh): check token parity against ATOM in CI, not a recorded fix…
wanzhenchn Nov 21, 2026
f9809aa
Merge branch 'zwan/mesh-fastokens-encode' into zwan/mesh-deepseek-v41…
wanzhenchn Nov 21, 2026
9d881d8
perf(mesh): turn fastokens' segment cache on by default
wanzhenchn Nov 21, 2026
e2f4b0b
Merge remote-tracking branch 'origin/zwan/mesh-fastokens-encode' into…
wanzhenchn Nov 21, 2026
cfc168a
refactor(mesh): load fastokens from tokenizer.json alone
wanzhenchn Nov 21, 2026
51ad82f
Merge remote-tracking branch 'origin/zwan/mesh-fastokens-encode' into…
wanzhenchn Nov 21, 2026
5446339
docs(mesh): fastokens' segment cache is on by default
wanzhenchn Nov 23, 2026
725d90f
Merge branch 'zwan/mesh-fastokens-encode' into zwan/mesh-deepseek-v41…
wanzhenchn Nov 23, 2026
7da8f2b
fix(mesh): retry a registration whose tokenizer cannot be downloaded …
wanzhenchn Nov 23, 2026
c872a6d
Merge remote-tracking branch 'origin/main' into zwan/mesh-deepseek-v4…
wanzhenchn Nov 23, 2026
a655d0b
fix(mesh): take DeepSeek-V4.1 reasoning efforts as ATOM does
wanzhenchn Nov 23, 2026
4c421bc
Merge remote-tracking branch 'origin/main' into zwan/mesh-deepseek-v4…
wanzhenchn Nov 24, 2026
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
9 changes: 9 additions & 0 deletions atom/mesh/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,15 @@ chat template, such as DeepSeek V3.2 and V4
([#3377](https://github.com/ROCm/ATOM/issues/3377)). Use a policy that does not
need tokens, such as `cache_aware` or `round_robin`, for these models and APIs.

The router renders a chat it tokenizes with the model's chat template and the
request's `reasoning_effort` and `chat_template_kwargs`. For a checkpoint whose
`config.json` has `model_type` `deepseek_v41` (DeepSeek-V4.1), it takes the
effort as ATOM's V4.1 encoder does: `minimal` as `low`, `medium` and `xhigh` as
`high`, and `none` as chat mode. V4.1's template rejects `minimal`, `xhigh` and
`none`. Other controls, such as `thinking` and a message's list of text blocks,
can still render otherwise than on ATOM; ATOM renders the chat again, so the
difference costs prefix hits, not a different prompt.

## Tokenization

The router tokenizes requests with their model's HuggingFace tokenizer, or with
Expand Down
13 changes: 13 additions & 0 deletions atom/mesh/scripts/atom_token_parity.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,20 +197,33 @@ def default_requests() -> list[dict]:
chats = {
"plain": {},
"effort_low": {"reasoning_effort": "low"},
"effort_medium": {"reasoning_effort": "medium"},
"effort_high": {"reasoning_effort": "high"},
"effort_max": {"reasoning_effort": "max"},
"effort_minimal": {"reasoning_effort": "minimal"},
"effort_xhigh": {"reasoning_effort": "xhigh"},
"effort_none": {"reasoning_effort": "none"},
"effort_unknown": {"reasoning_effort": "ultra"},
"kwargs_thinking_on": {"chat_template_kwargs": {"enable_thinking": True}},
"kwargs_thinking_mode_chat": {
"chat_template_kwargs": {"thinking_mode": "chat"}
},
"thinking_enabled": {"thinking": {"type": "enabled"}},
"thinking_enabled_effort_none": {
"thinking": {"type": "enabled"},
"reasoning_effort": "none",
},
"tools_effort_high": {"tools": [TOOL], "reasoning_effort": "high"},
"tool_history": {
"tools": [TOOL],
"messages": [*MESSAGES, *called("README.md")],
},
"tool_history_reasoning": {"tools": [TOOL], "messages": reasoned_tool_history},
"tool_history_effort_none": {
"tools": [TOOL],
"messages": reasoned_tool_history,
"reasoning_effort": "none",
},
"parallel_tool_calls": {
"tools": [TOOL],
"messages": [*MESSAGES, *called("README.md", "LICENSE")],
Expand Down
10 changes: 8 additions & 2 deletions atom/mesh/src/app_context.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
collections::HashSet,
collections::{HashMap, HashSet},
sync::{Arc, OnceLock},
time::Duration,
};
Expand All @@ -24,7 +24,8 @@ use crate::{
policies::PolicyRegistry,
reasoning_parser::ParserFactory as ReasoningParserFactory,
routers::{
atom_bridge::AtomBridgeRuntime, prepare::fast_tokenizer::TokenizeLimits,
atom_bridge::AtomBridgeRuntime,
prepare::{chat_controls::ChatControls, fast_tokenizer::TokenizeLimits},
router_manager::RouterManager,
},
tokenizer::registry::TokenizerRegistry,
Expand Down Expand Up @@ -55,6 +56,10 @@ pub struct AppContext {
/// their Jinja template, found as each registers. HTTP routing does not
/// tokenize those chats.
pub chats_without_template: Arc<RwLock<HashSet<String>>>,
/// The reasoning controls ATOM renders a tokenizer's chats under, by
/// registry id, for the checkpoints that have their own; HTTP routing
/// takes the effort of those chats as ATOM does.
pub(crate) chat_controls: Arc<RwLock<HashMap<String, ChatControls>>>,
/// `router_config`'s tokenization byte limits.
pub(crate) tokenize_limits: TokenizeLimits,
pub reasoning_parser_factory: Option<ReasoningParserFactory>,
Expand Down Expand Up @@ -300,6 +305,7 @@ impl AppContextBuilder {
.tokenizer_registry
.ok_or(AppContextBuildError("tokenizer_registry"))?,
chats_without_template: Default::default(),
chat_controls: Default::default(),
tokenize_limits,
reasoning_parser_factory: self.reasoning_parser_factory,
tool_parser_factory: self.tool_parser_factory,
Expand Down
1 change: 1 addition & 0 deletions atom/mesh/src/core/job_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,7 @@ impl JobQueue {
if let Some(entry) = context.tokenizer_registry.remove_by_id(&request.id) {
crate::routers::prepare::thread_tokenizer::release_copies(&entry.id);
context.chats_without_template.write().remove(&entry.id);
context.chat_controls.write().remove(&entry.id);
info!(
"Successfully removed tokenizer '{}' (id: {})",
entry.name, entry.id
Expand Down
120 changes: 117 additions & 3 deletions atom/mesh/src/core/steps/tokenizer_registration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
//! (startup, worker connection, API) should use this workflow to ensure consistent
//! behavior (validation, caching, deduplication).

use std::{collections::HashSet, sync::Arc, time::Duration};
use std::{collections::HashSet, path::Path, sync::Arc, time::Duration};

use async_trait::async_trait;
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use serde_json::json;
use serde_json::{json, Value};
use tracing::{error, info, warn};
use wfaas::{
BackoffStrategy, FailureAction, RetryPolicy, StepDefinition, StepExecutor, StepId, StepResult,
Expand All @@ -23,7 +23,12 @@ use super::workflow_data::TokenizerWorkflowData;
use crate::{
app_context::AppContext,
config::TokenizerCacheConfig,
routers::prepare::fast_tokenizer::{with_fastokens, FastTokenizer, STRICT_REFUSAL},
routers::prepare::{
chat_controls::ChatControls,
fast_tokenizer::{
tokenizer_json, with_fastokens, FastTokenizer, DOWNLOAD_FAILURE, STRICT_REFUSAL,
},
},
tokenizer::{
cache::{CacheConfig, CachedTokenizer},
chat_template::ChatTemplateParams,
Expand Down Expand Up @@ -104,6 +109,7 @@ impl StepExecutor<TokenizerWorkflowData> for LoadTokenizerStep {
let chat_template = config.chat_template_path.clone();
let cache_config = config.cache_config.clone();
let chats_without_template = app_context.chats_without_template.clone();
let chat_controls = app_context.chat_controls.clone();
let fastokens = app_context.router_config.fastokens.clone();

// Load the tokenizer using the registry's load method
Expand All @@ -117,6 +123,7 @@ impl StepExecutor<TokenizerWorkflowData> for LoadTokenizerStep {
let chat_template = chat_template.clone();
let cache_cfg = cache_config.clone();
let chats_without_template = chats_without_template.clone();
let chat_controls = chat_controls.clone();
let fastokens = fastokens.clone();
async move {
// Load base tokenizer
Expand All @@ -136,6 +143,9 @@ impl StepExecutor<TokenizerWorkflowData> for LoadTokenizerStep {
chat_template.as_deref(),
)
.await;
if let Some(controls) = checkpoint_chat_controls(&name, &source).await? {
chat_controls.write().insert(id.clone(), controls);
}
// fastokens has its own segment cache
// (`--fastokens-segment-cache-mb`, 1 GiB by default).
if base_tokenizer.as_any().is::<FastTokenizer>() {
Expand Down Expand Up @@ -285,6 +295,38 @@ fn renders_without_template(tokenizer: &mut dyn Tokenizer) -> bool {
.is_ok_and(|text| text != PROBE)
}

/// The reasoning controls ATOM renders `source`'s chats under, by the
/// `model_type` in the `config.json` beside its `tokenizer.json`, if the
/// checkpoint has its own. A HuggingFace model ID's tokenizer that cannot be
/// downloaded fails the registration, to be retried, rather than leave the
/// model's chats rendered without them.
async fn checkpoint_chat_controls(
name: &str,
source: &str,
) -> Result<Option<ChatControls>, String> {
match tokenizer_json(source).await {
Ok(tokenizer) => Ok(controls_beside(name, &tokenizer).await),
Err(reason) if reason.starts_with(DOWNLOAD_FAILURE) => Err(reason),
Err(_) => Ok(None),
}
}

/// The reasoning controls for the `model_type` in the `config.json` beside
/// `tokenizer`, if there is one.
async fn controls_beside(name: &str, tokenizer: &Path) -> Option<ChatControls> {
let config = tokio::fs::read(tokenizer.with_file_name("config.json"))
.await
.ok()?;
let config: Value = serde_json::from_slice(&config).ok()?;
let model_type = config.get("model_type")?.as_str()?;
let controls = ChatControls::of_model_type(model_type)?;
info!(
tokenizer = name,
model_type, "HTTP routing takes the effort of these chats as ATOM does for the model"
);
Some(controls)
}

// ============================================================================
// Workflow Builder
// ============================================================================
Expand Down Expand Up @@ -411,6 +453,56 @@ mod tests {
assert!(!marked(&deepseek));
}

/// A tokenizer registers with the reasoning controls ATOM keeps for the
/// `model_type` in the `config.json` beside it, from its directory or its
/// `tokenizer.json`, and removing it drops them.
#[tokio::test]
async fn test_registration_finds_the_checkpoint_chat_controls() {
let checkpoint = |model_type: &str| {
let dir = tempfile::TempDir::new().unwrap();
std::fs::copy(hf_tokenizer_path(), dir.path().join("tokenizer.json")).unwrap();
std::fs::write(
dir.path().join("config.json"),
json!({"model_type": model_type}).to_string(),
)
.unwrap();
dir
};
let v41 = checkpoint("deepseek_v41");
let v41_file = v41.path().join("tokenizer.json");
let llama = checkpoint("llama");
let bare = tempfile::TempDir::new().unwrap();
std::fs::copy(hf_tokenizer_path(), bare.path().join("tokenizer.json")).unwrap();
let context = app_context();
let mut ids = Vec::new();
for (source, controls) in [
(v41.path(), Some(ChatControls::DeepseekV41)),
(v41_file.as_path(), Some(ChatControls::DeepseekV41)),
(llama.path(), None),
(bare.path(), None),
] {
let id = TokenizerRegistry::generate_id();
let config = TokenizerConfigRequest {
id: id.clone(),
name: id.clone(),
source: source.to_str().unwrap().to_string(),
chat_template_path: None,
cache_config: None,
fail_on_duplicate: false,
};
let mut workflow = WorkflowContext::new(
WorkflowInstanceId::new(),
create_tokenizer_workflow_data(config, context.clone()),
);
LoadTokenizerStep.execute(&mut workflow).await.unwrap();
let found = context.chat_controls.read().get(&id).copied();
assert_eq!(found, controls, "{}", source.display());
ids.push(id);
}
remove_tokenizer(&context, &ids[0]).await;
assert!(!context.chat_controls.read().contains_key(&ids[0]));
}

/// A model `--fastokens-models` lists encodes with fastokens, which leaves the
/// tokenizer cache out; one fastokens cannot load keeps HuggingFace, or fails
/// to register under `--fastokens-strict`, with no retries.
Expand Down Expand Up @@ -513,6 +605,28 @@ mod tests {
assert!(Arc::ptr_eq(&kept, &hf));
}

/// A HuggingFace model ID whose tokenizer cannot be downloaded fails the
/// lookup of its chat controls, and the registration is retried; a source
/// with no `tokenizer.json` has none.
#[tokio::test]
#[serial]
async fn test_chat_controls_download_failures_are_retried() {
let _endpoint = EnvVar::set("HF_ENDPOINT", "http://127.0.0.1:1");
let error = checkpoint_chat_controls("model", "org/model")
.await
.unwrap_err();
assert!(error.starts_with(DOWNLOAD_FAILURE), "{error}");
let error = WorkflowError::StepFailed {
step_id: StepId::new("load_tokenizer"),
message: error,
};
assert!(LoadTokenizerStep.is_retryable(&error), "{error}");

let empty = tempfile::TempDir::new().unwrap();
let empty = empty.path().to_str().unwrap();
assert_eq!(checkpoint_chat_controls("model", empty).await, Ok(None));
}

#[test]
fn test_tokenizer_config_request_serialization() {
let config = TokenizerConfigRequest {
Expand Down
1 change: 1 addition & 0 deletions atom/mesh/src/routers/comm/tokenize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ pub async fn remove_tokenizer(context: &Arc<AppContext>, tokenizer_id: &str) ->
if let Some(entry) = removed {
crate::routers::prepare::thread_tokenizer::release_copies(&entry.id);
context.chats_without_template.write().remove(&entry.id);
context.chat_controls.write().remove(&entry.id);
debug!("Removed tokenizer '{}' (id: {})", entry.name, entry.id);
(
StatusCode::OK,
Expand Down
28 changes: 23 additions & 5 deletions atom/mesh/src/routers/ingress.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Shared HTTP proxy contract. The routing view never replaces the original payload.
use std::{
collections::HashSet,
collections::{HashMap, HashSet},
sync::{Arc, LazyLock},
time::Instant,
};
Expand Down Expand Up @@ -28,15 +28,18 @@ use crate::{
ConnectionMode, Worker, WorkerRegistry, WorkerType,
},
policies::{LoadBalancingPolicy, PolicyRegistry},
protocols::chat::ChatCompletionRequest,
routers::{
comm::error::{IngressError, MeshLocalError},
prepare::{
chat_controls::ChatControls,
chat_template::process_chat_messages,
fast_tokenizer::TokenizeLimits,
inference::{InferenceMetadata, InferenceRequest, ParsedInference},
},
},
server::AppState,
tokenizer::TokenizerRegistry,
tokenizer::{registry::TokenizerEntry, TokenizerRegistry},
};

/// What a request's policies do with its tokens.
Expand Down Expand Up @@ -635,6 +638,7 @@ pub struct IngressRouting {
worker_registry: Arc<WorkerRegistry>,
tokenizer_registry: Arc<TokenizerRegistry>,
chats_without_template: Arc<RwLock<HashSet<String>>>,
chat_controls: Arc<RwLock<HashMap<String, ChatControls>>>,
pd: bool,
tokenize_limits: TokenizeLimits,
prefill_on_decode_rank: bool,
Expand All @@ -647,6 +651,7 @@ impl IngressRouting {
worker_registry: app.worker_registry.clone(),
tokenizer_registry: app.tokenizer_registry.clone(),
chats_without_template: app.chats_without_template.clone(),
chat_controls: app.chat_controls.clone(),
pd: app.router_config.mode.is_pd_mode(),
tokenize_limits: app.tokenize_limits,
prefill_on_decode_rank: app.router_config.prefill_on_decode_rank(),
Expand Down Expand Up @@ -883,9 +888,7 @@ impl IngressRouting {
if self.chats_without_template.read().contains(&entry.id) {
return Err(IngressError::new(http::StatusCode::NOT_IMPLEMENTED, "token_routing_unsupported", "this model's chats render with a built-in encoder whose defaults are not the engine's; use a policy that does not require exact tokens"));
}
super::prepare::chat_template::process_chat_messages(chat, &*entry.tokenizer)
.map_err(IngressError::invalid)?
.text
self.render_chat(&entry, chat)?
} else {
metadata.text.clone()
};
Expand All @@ -906,6 +909,21 @@ impl IngressRouting {
.record(encode_started.elapsed().as_secs_f64());
Ok(tokens)
}

/// The prompt the router renders `chat` to with `entry`'s template, under
/// the reasoning controls of its model where ATOM has its own.
fn render_chat(
&self,
entry: &TokenizerEntry,
chat: &ChatCompletionRequest,
) -> Result<String, IngressError> {
let controls = self.chat_controls.read().get(&entry.id).copied();
match controls {
Some(controls) => controls.render(chat, &*entry.tokenizer),
None => process_chat_messages(chat, &*entry.tokenizer).map(|rendered| rendered.text),
}
.map_err(IngressError::invalid)
}
}

#[cfg(test)]
Expand Down
Loading
Loading