Skip to content
Merged
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
5 changes: 0 additions & 5 deletions bindings/python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,6 @@ struct Router {
model_path: Option<String>,
tokenizer_path: Option<String>,
chat_template: Option<String>,
served_model_name: Option<String>,
tokenizer_cache_enable_l0: bool,
tokenizer_cache_l0_max_entries: usize,
tokenizer_cache_enable_l1: bool,
Expand Down Expand Up @@ -658,7 +657,6 @@ impl Router {
.maybe_model_path(self.model_path.as_ref())
.maybe_tokenizer_path(self.tokenizer_path.as_ref())
.maybe_chat_template(self.chat_template.as_ref())
.maybe_served_model_name(self.served_model_name.as_ref())
.maybe_oracle(oracle)
.maybe_postgres(postgres_config)
.maybe_redis(redis_config)
Expand Down Expand Up @@ -751,7 +749,6 @@ impl Router {
model_path = None,
tokenizer_path = None,
chat_template = None,
served_model_name = None,
tokenizer_cache_enable_l0 = false,
tokenizer_cache_l0_max_entries = 10000,
tokenizer_cache_enable_l1 = false,
Expand Down Expand Up @@ -844,7 +841,6 @@ impl Router {
model_path: Option<String>,
tokenizer_path: Option<String>,
chat_template: Option<String>,
served_model_name: Option<String>,
tokenizer_cache_enable_l0: bool,
tokenizer_cache_l0_max_entries: usize,
tokenizer_cache_enable_l1: bool,
Expand Down Expand Up @@ -947,7 +943,6 @@ impl Router {
model_path,
tokenizer_path,
chat_template,
served_model_name,
tokenizer_cache_enable_l0,
tokenizer_cache_l0_max_entries,
tokenizer_cache_enable_l1,
Expand Down
25 changes: 9 additions & 16 deletions bindings/python/src/smg/router_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,6 @@ class RouterArgs:
model_path: str | None = None
tokenizer_path: str | None = None
chat_template: str | None = None
# Override/alias the model name exposed to clients (while backend loads from model_path)
served_model_name: str | None = None
# Tokenizer cache configuration
tokenizer_cache_enable_l0: bool = False
tokenizer_cache_l0_max_entries: int = 10000
Expand Down Expand Up @@ -670,6 +668,7 @@ def add_cli_args(
# Tokenizer configuration
tokenizer_group.add_argument(
f"--{prefix}model-path",
f"--{prefix}model",
type=str,
default=None,
help="Model path for loading tokenizer (HuggingFace model ID or local path)",
Expand All @@ -686,17 +685,6 @@ def add_cli_args(
default=None,
help="Chat template path (optional)",
)
tokenizer_group.add_argument(
f"--{prefix}served-model-name",
type=str,
default=None,
help=(
"Override the model name exposed to clients. When set, requests using this "
"name are routed to the worker even though the backend was loaded from "
"model_path. Both the original name (from backend discovery) and this alias "
"will be accepted."
),
)
tokenizer_group.add_argument(
f"--{prefix}tokenizer-cache-enable-l0",
action="store_true",
Expand Down Expand Up @@ -988,9 +976,14 @@ def from_cli_args(cls, args: argparse.Namespace, use_router_prefix: bool = False
args_dict = {}

for attr in dataclasses.fields(cls):
# Auto strip prefix from args
if f"{prefix}{attr.name}" in cli_args_dict:
args_dict[attr.name] = cli_args_dict[f"{prefix}{attr.name}"]
# Auto strip prefix from args.
# Prefer the prefixed version (e.g. --router-model-path) when
# explicitly set, but fall back to the unprefixed version
# (e.g. --model-path from the backend) when the prefixed key
# exists but is None (argparse default).
prefixed_key = f"{prefix}{attr.name}"
if prefixed_key in cli_args_dict and cli_args_dict[prefixed_key] is not None:
args_dict[attr.name] = cli_args_dict[prefixed_key]
elif attr.name in cli_args_dict:
args_dict[attr.name] = cli_args_dict[attr.name]

Expand Down
19 changes: 16 additions & 3 deletions bindings/python/src/smg/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ def build_command(
sys.executable,
"-m",
"tensorrt_llm.commands.serve",
getattr(args, "model", ""),
getattr(args, "model_path", ""),
"--grpc",
"--host",
host,
Expand All @@ -232,7 +232,14 @@ def build_command(
]

# Add optional config file
cmd.extend(self._filter_backend_args(backend_args, ["--model", "--host", "--port"]))
# TRT-LLM Click options use underscores (e.g. --tensor_parallel_size)
# while SGLang/vLLM use hyphens. Normalize so users can pass either form.
normalized = [
"--" + a[2:].replace("-", "_") if a.startswith("--") else a for a in backend_args
Comment thread
slin1237 marked this conversation as resolved.
Resolved
]
cmd.extend(
self._filter_backend_args(normalized, ["--model", "--model_path", "--host", "--port"])
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

return cmd

Expand Down Expand Up @@ -372,7 +379,13 @@ def _add_trtllm_stub_args(parser: argparse.ArgumentParser) -> None:
TP size is read from the config file, not passed as CLI argument.
"""
group = parser.add_argument_group("TensorRT-LLM Options")
group.add_argument("--model", type=str, help="Model path (HuggingFace ID or local path)")
group.add_argument(
"--model",
"--model-path",
dest="model_path",
type=str,
help="Model path (HuggingFace ID or local path)",
)
group.add_argument("--tp_size", type=int, help="Tensor parallel size (overrides config file)")


Expand Down
16 changes: 8 additions & 8 deletions bindings/python/tests/test_serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def test_trtllm_adds_model_arg(self):
args, backend_args = parser.parse_known_args(
["--model", "/path/to/model", "--config", "/path/to/config.yml"]
)
assert args.model == "/path/to/model"
assert args.model_path == "/path/to/model"
assert "--config" in backend_args
assert "/path/to/config.yml" in backend_args

Expand All @@ -199,13 +199,13 @@ def test_adds_model_arg(self):
parser = argparse.ArgumentParser()
_add_trtllm_stub_args(parser)
args = parser.parse_args(["--model", "/tmp/model"])
assert args.model == "/tmp/model"
assert args.model_path == "/tmp/model"

def test_model_default_is_none(self):
parser = argparse.ArgumentParser()
_add_trtllm_stub_args(parser)
args = parser.parse_args([])
assert args.model is None
assert args.model_path is None


class TestParseServeArgs:
Expand All @@ -217,7 +217,7 @@ def test_trtllm_basic(self):
)
assert backend == "trtllm"
assert args.backend == "trtllm"
assert args.model == "/tmp/m"
assert args.model_path == "/tmp/m"
assert "--config" in backend_args # config should be in backend_args
assert "/tmp/config.yml" in backend_args

Expand Down Expand Up @@ -314,7 +314,7 @@ def test_two_pass_extracts_backend_first(self):
]
)
assert backend == "trtllm"
assert args.model == "/some/path"
assert args.model_path == "/some/path"

def test_unknown_arg_rejected_in_pass2(self):
"""Unknown args should be rejected by the full parser in pass 2."""
Expand Down Expand Up @@ -533,7 +533,7 @@ def test_health_check_delegates_to_grpc(self):
def test_build_command_http_mode(self):
"""When connection_mode is http, --grpc-mode should not be present."""
launcher = VllmWorkerLauncher()
args = argparse.Namespace(model="/tmp/model", connection_mode="http")
args = argparse.Namespace(model_path="/tmp/model", connection_mode="http")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Use model in this vLLM launcher test to avoid coverage drift.

Line 536 passes model_path, but VllmWorkerLauncher.build_command() reads args.model. This test now misses model propagation validation for vLLM.

Proposed fix
-        args = argparse.Namespace(model_path="/tmp/model", connection_mode="http")
+        args = argparse.Namespace(model="/tmp/model", connection_mode="http")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
args = argparse.Namespace(model_path="/tmp/model", connection_mode="http")
args = argparse.Namespace(model="/tmp/model", connection_mode="http")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@bindings/python/tests/test_serve.py` at line 536, The test instantiates args
with the wrong key: it sets model_path but VllmWorkerLauncher.build_command()
reads args.model, so update the test to pass the expected attribute (e.g., args
= argparse.Namespace(model="/tmp/model", connection_mode="http")) and ensure the
assertion that validates model propagation into
VllmWorkerLauncher.build_command() still runs; look for the test function around
the args assignment and the VllmWorkerLauncher.build_command() call to change
the Namespace key and preserve the existing propagation assertion.

backend_args = ["--trust-remote-code"]
cmd = launcher.build_command(args, backend_args, "127.0.0.1", 31000)
assert "vllm.entrypoints.openai.api_server" in cmd
Expand Down Expand Up @@ -563,7 +563,7 @@ class TestTrtllmWorkerLauncher:

def test_build_command(self):
launcher = TrtllmWorkerLauncher()
args = argparse.Namespace(model="/tmp/model", connection_mode="grpc")
args = argparse.Namespace(model_path="/tmp/model", connection_mode="grpc")
backend_args = ["--config", "/tmp/config.yml"]
cmd = launcher.build_command(args, backend_args, "0.0.0.0", 50051)
assert "tensorrt_llm.commands.serve" in cmd
Expand All @@ -578,7 +578,7 @@ def test_build_command(self):

def test_build_command_rejects_http_mode(self):
launcher = TrtllmWorkerLauncher()
args = argparse.Namespace(model="/tmp/model", connection_mode="http")
args = argparse.Namespace(model_path="/tmp/model", connection_mode="http")
backend_args = ["--config", "/tmp/config.yml"]
with pytest.raises(ValueError, match="TensorRT-LLM backend only supports grpc"):
launcher.build_command(args, backend_args, "0.0.0.0", 50051)
Expand Down
11 changes: 0 additions & 11 deletions model_gateway/src/config/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,17 +531,6 @@ impl RouterConfigBuilder {
self
}

pub fn served_model_name<S: Into<String>>(mut self, name: S) -> Self {
self.config.served_model_name = Some(name.into());
self
}

/// Set served_model_name if Some, clear if None.
pub fn maybe_served_model_name(mut self, name: Option<impl Into<String>>) -> Self {
self.config.served_model_name = name.map(|n| n.into());
self
}

pub fn maybe_oracle(mut self, oracle: Option<OracleConfig>) -> Self {
if let Some(cfg) = oracle {
self.config.history_backend = HistoryBackend::Oracle;
Expand Down
4 changes: 0 additions & 4 deletions model_gateway/src/config/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,6 @@ pub struct RouterConfig {
/// Overrides model_path tokenizer if provided
pub tokenizer_path: Option<String>,
pub chat_template: Option<String>,
/// Client-facing model name override; both this and the backend-reported name are accepted.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub served_model_name: Option<String>,
#[serde(default = "default_history_backend")]
pub history_backend: HistoryBackend,
/// Required when history_backend = "oracle"
Expand Down Expand Up @@ -531,7 +528,6 @@ impl Default for RouterConfig {
model_path: None,
tokenizer_path: None,
chat_template: None,
served_model_name: None,
history_backend: default_history_backend(),
oracle: None,
postgres: None,
Expand Down
25 changes: 3 additions & 22 deletions model_gateway/src/core/steps/worker/local/create_worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,8 @@ impl StepExecutor<LocalWorkerWorkflowData> for CreateLocalWorkerStep {
let kv_connector = labels.remove("kv_connector");
let kv_role = labels.remove("kv_role");

// Determine backend-reported model_id:
// config.models > discovered labels["served_model_name"] > labels["model_id"] > labels["model_path"]
let backend_model_id = config
// Determine model_id: config.models > discovered labels > UNKNOWN_MODEL_ID
let model_id = config
.models
.primary()
.map(|m| m.id.clone())
Expand All @@ -65,25 +64,7 @@ impl StepExecutor<LocalWorkerWorkflowData> for CreateLocalWorkerStep {
.or_else(|| labels.get("model_path").cloned())
.unwrap_or_else(|| UNKNOWN_MODEL_ID.to_string());

// Build the card from backend_model_id so any user-configured metadata
// (context_length, tokenizer_path, model_type, …) keyed by the backend ID is preserved.
let mut model_card = build_model_card(&backend_model_id, config, &labels);

// Apply router-level served_model_name: rename the card's primary ID and keep
// the backend-reported name as an alias so both names continue to work.
// Skip aliasing UNKNOWN_MODEL_ID to avoid a meaningless "unknown" alias.
match app_context.router_config.served_model_name.as_deref() {
Some(sname)
if !sname.is_empty()
&& sname != backend_model_id
&& backend_model_id != UNKNOWN_MODEL_ID =>
{
model_card.aliases.push(backend_model_id);
model_card.aliases.retain(|a| a != sname);
model_card.id = sname.to_string();
}
_ => {}
};
let model_card = build_model_card(&model_id, config, &labels);

let runtime_type = match context.data.detected_runtime_type.as_deref() {
Some(s) => s.parse::<RuntimeType>().unwrap_or(config.runtime_type),
Expand Down
52 changes: 25 additions & 27 deletions model_gateway/src/core/steps/worker/local/submit_tokenizer_job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,6 @@ impl StepExecutor<LocalWorkerWorkflowData> for SubmitTokenizerJobStep {
for worker in workers {
let model_id = worker.model_id().to_string();

// Register tokenizer under primary name and all aliases.
let all_names = worker.model_names();

// Get tokenizer path with fallback chain:
// 1. Worker labels: tokenizer_path
// 2. Worker labels: model_path
Expand Down Expand Up @@ -99,31 +96,32 @@ impl StepExecutor<LocalWorkerWorkflowData> for SubmitTokenizerJobStep {
// The registry.load() handles deduplication gracefully (returns AlreadyExists).
// This simplifies the code and ensures consistent behavior.

for name in all_names {
info!(
"Submitting tokenizer registration job for model '{}' (source: {})",
name, tokenizer_path
);

// Create tokenizer config request
let config = TokenizerConfigRequest {
id: TokenizerRegistry::generate_id(),
name: name.clone(),
source: tokenizer_path.clone(),
chat_template_path: chat_template.clone(),
cache_config: cache_config.clone(),
fail_on_duplicate: false,
};
info!(
"Submitting tokenizer registration job for model {} from {}",
model_id, tokenizer_path
);

// Create tokenizer config request
let config = TokenizerConfigRequest {
id: TokenizerRegistry::generate_id(),
name: model_id.clone(),
Comment thread
slin1237 marked this conversation as resolved.
Resolved
source: tokenizer_path,
chat_template_path: chat_template.clone(),
cache_config: cache_config.clone(),
fail_on_duplicate: false,
};

// Submit job (fire-and-forget, don't wait for completion)
if let Err(e) = job_queue
.submit(Job::AddTokenizer {
config: Box::new(config),
})
.await
{
warn!("Failed to submit tokenizer job for model '{}': {}", name, e);
}
// Submit job (fire-and-forget, don't wait for completion)
if let Err(e) = job_queue
.submit(Job::AddTokenizer {
config: Box::new(config),
})
.await
{
warn!(
"Failed to submit tokenizer job for model {}: {}",
model_id, e
);
}
}

Expand Down
10 changes: 0 additions & 10 deletions model_gateway/src/core/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,16 +256,6 @@ pub trait Worker: Send + Sync + fmt::Debug {
.unwrap_or(UNKNOWN_MODEL_ID)
}

/// All names (primary model ID + aliases) this worker should be indexed/registered under.
fn model_names(&self) -> std::collections::HashSet<String> {
let primary = self.model_id().to_string();
let mut names = std::collections::HashSet::from([primary.clone()]);
if let Some(card) = self.metadata().spec.models.primary() {
names.extend(card.aliases.iter().cloned());
}
names
}

/// Get the priority of this worker (higher value = higher priority)
fn priority(&self) -> u32 {
self.metadata().spec.priority
Expand Down
Loading