Skip to content

feat(multimodal): configurable engine-agnostic tensor transport - #1892

Merged
slin1237 merged 3 commits into
mainfrom
feat/multimodal-transport-config
Jul 8, 2026
Merged

feat(multimodal): configurable engine-agnostic tensor transport#1892
slin1237 merged 3 commits into
mainfrom
feat/multimodal-transport-config

Conversation

@slin1237

@slin1237 slin1237 commented Jul 8, 2026

Copy link
Copy Markdown
Member

Description

Problem

Multimodal tensor transport (inline vs /dev/shm) was tunable only via
SMG_TOKENSPEED_MM_* environment variables, TokenSpeed-specific and env-only.
There was no CLI/YAML config, no per-worker control (co-located vs remote
workers can't differ), and the knob was framed as TokenSpeed-only even though
the transport is engine-agnostic.

Solution

Promote it to a first-class, engine-agnostic config surface with a clear
resolution precedence:

per-worker WorkerSpec override → router config / CLI → SMG_MM_* env
(legacy SMG_TOKENSPEED_MM_* aliases) → built-in default (inline, 64 KiB)

Router-level defaults are resolved once at startup (server::startup); the
per-request mode drives shm_enabled, and the resolved size threshold rides on
TokenSpeedMultimodalData so both write paths (encoder input in serialize.rs
and model-specific tensors in proto_wrapper.rs) honor it consistently.

Changes

  • openai-protocol: new TransportMode enum (inline|shm|auto), serde +
    JsonSchema + FromStr. WorkerSpec gains multimodal_tensor_transport +
    multimodal_shm_min_bytes overrides.
  • RouterConfig (config/types.rs, builder.rs): the two fields + builder
    methods + Default.
  • CLI (main.rs): --multimodal-tensor-transport (value_parser
    inline|shm|auto) + --multimodal-shm-min-bytes; wired into to_router_config.
  • transport.rs: resolvers renamed tokenspeed_* → mm_*; precedence logic;
    per-worker override readers; startup seed init_mm_transport_defaults.
  • Python SDK: RouterArgs dataclass + argparse + PyRouterConfig
    (bindings/python). (Go SDK is a request client — no router-config surface.)
  • Docs: generalized the "Multimodal Tensor Transport" reference section.

Behavior change (explicit shm only)

shm now forces SHM whenever SMG can write /dev/shm (operator asserts
co-location). Previously shm was identical to auto (both required verified
worker sharing), so shm was redundant. auto is unchanged. Default is
inline, so existing deployments are unaffected.

Test Plan

  • cargo clippy -p smg --all-targets -- -D warnings — clean (lib + tests + main.rs)
  • cargo check -p smg-python — clean (Python binding compiles)
  • cargo +nightly fmt — clean (scoped to the change set)
  • cargo test -p openai-protocol --lib — 77 pass
  • cargo test -p smg --lib — 1146 pass (one unrelated middleware::metrics
    interner test is a known parallel-test flake; passes in isolation)
  • cargo test -p smg --bins — new two-path guard
    multimodal_transport_flows_into_both_configs passes
  • python3 -m py_compile on router_args.py — OK

Checklist

  • Conventional commit + DCO sign-off
  • cargo +nightly fmt clean
  • cargo clippy -- -D warnings clean
  • Both config paths covered (to_router_config; to_server_config wraps it) + two-path test
  • CLI value_parser validation
  • Default + #[serde(default, skip_serializing_if)]
  • Python bindings (RouterArgs + PyRouterConfig) updated
  • Docs updated

Summary by CodeRabbit

  • New Features
    • Added configurable multimodal tensor transport (mode: inline/shm/auto) and multimodal_shm_min_bytes across router config, CLI, Python bindings, and per-worker overrides.
    • Added validation with user-facing errors for unsupported transport mode values.
  • Bug Fixes
    • Improved inline vs SHM decision-making to consistently apply the configured SHM minimum-byte threshold during multimodal tensor handling.
    • Preserved safe fallback behavior when shared memory is unavailable or not writable.
  • Documentation
    • Updated configuration docs with new precedence rules, new CLI flags, and migrated SMG_MM_* environment variables (legacy SMG_TOKENSPEED_MM_* aliases retained).
  • Tests
    • Added coverage to verify the new flags propagate into both router and server configuration outputs.

Promote multimodal tensor transport from TokenSpeed-only, env-only tuning to a
first-class, engine-agnostic config surface.

- Add `TransportMode` enum (inline|shm|auto) to openai-protocol.
- RouterConfig gains `multimodal_tensor_transport` + `multimodal_shm_min_bytes`,
  exposed via `--multimodal-tensor-transport` / `--multimodal-shm-min-bytes`
  (CLI, with value_parser), YAML config, and the Python router SDK
  (RouterArgs + PyRouterConfig).
- Per-worker `WorkerSpec` overrides (`multimodal_tensor_transport`,
  `multimodal_shm_min_bytes`) let co-located and remote workers differ.
- Resolution precedence: per-worker override → router config → `SMG_MM_*` env
  (legacy `SMG_TOKENSPEED_MM_*` kept as deprecated aliases) → default
  (`inline`, 64 KiB). Router defaults are seeded once at startup
  (server::startup); the per-request mode drives `shm_enabled` and the resolved
  threshold rides on `TokenSpeedMultimodalData` so both write paths
  (encoder input + model-specific tensors) honor it.
- Rename the transport resolvers `tokenspeed_* -> mm_*` (in
  `multimodal/transport.rs`).

Behavior change for explicit `shm` users: `shm` now forces SHM whenever SMG can
write `/dev/shm` (the operator asserts co-location). Previously `shm` behaved
identically to `auto` (both required verified worker sharing), making `shm`
redundant. `auto` is unchanged (verifies the worker shares `/dev/shm` via its
advertised namespace token). The default is `inline`, so existing deployments
are unaffected.

Groundwork for engine-neutral SHM (vLLM next).

Signed-off-by: Simo Lin <25425177+slin1237@users.noreply.github.com>
@github-actions github-actions Bot added documentation Improvements or additions to documentation python-bindings Python bindings changes grpc gRPC client and router changes protocols Protocols crate changes model-gateway Model gateway crate changes labels Jul 8, 2026
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: c2b24cea-cb45-4d51-9fcd-69975393e0eb

📥 Commits

Reviewing files that changed from the base of the PR and between 145613e and d2ef4bb.

📒 Files selected for processing (1)
  • model_gateway/src/routers/grpc/multimodal/transport.rs

📝 Walkthrough

Walkthrough

This PR adds multimodal transport mode and SHM threshold configuration, threads them through router setup and runtime resolution, and updates multimodal assembly and proto conversion to use the new values.

Changes

Multimodal Transport Configuration

Layer / File(s) Summary
TransportMode and config fields
crates/protocols/src/worker.rs, model_gateway/src/config/types.rs, model_gateway/src/config/builder.rs
Adds TransportMode, multimodal transport fields on WorkerSpec and RouterConfig, default initialization, and builder setters.
CLI, Python, and startup wiring
model_gateway/src/main.rs, model_gateway/src/server.rs, bindings/python/src/lib.rs, bindings/python/src/smg/router_args.py, docs/reference/configuration.md, model_gateway/src/routers/grpc/multimodal/mod.rs
Adds CLI and Python parameters, parses transport mode values, seeds startup defaults, and updates configuration documentation and env var names.
Runtime transport resolution
model_gateway/src/routers/grpc/multimodal/transport.rs
Replaces TokenSpeed-specific resolution with multimodal defaults, per-worker overrides, and updated encoder dtype selection.
Assembly, serialization, and encode dispatch
model_gateway/src/routers/grpc/multimodal/assemble.rs, model_gateway/src/routers/grpc/multimodal/serialize.rs, model_gateway/src/routers/grpc/epd_encode.rs
Threads shm_min_bytes through multimodal assembly, tensor serialization, and prepared encode dispatch.
Proto wrapper threshold plumbing
model_gateway/src/routers/grpc/proto_wrapper.rs
Adds shm_min_bytes to multimodal proto data, updates conversion helpers, removes obsolete env-reading helpers, renames the SHM probe, and updates tests.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • lightseekorg/smg#1515: Touches the same TokenSpeed multimodal gRPC payload and tensor conversion path.
  • lightseekorg/smg#1604: Implements the same multimodal transport and SHM threshold plumbing.
  • lightseekorg/smg#1890: Changes the same multimodal transport module set under model_gateway/src/routers/grpc/multimodal/.

Suggested labels: multimodal

Suggested reviewers: CatherineSue, key4ng

Poem

A bunny hops through config light,
With SHM thresholds set just right.
Inline or shm, the path is new,
And transport modes now guide the queue.
🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding configurable engine-agnostic multimodal tensor transport.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/multimodal-transport-config

Comment @coderabbitai help to get the list of available commands.

Comment thread bindings/python/src/lib.rs Outdated

@claude claude Bot 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.

Clean PR — the config plumbing is thorough (CLI, Python bindings, per-worker overrides, env fallback with legacy aliases) and the resolution precedence is correctly implemented. The OnceLock-based startup seeding in server.rs avoids per-request env reads while keeping the test fallback path sane. One 🟡 nit on silent parse failure in the Python bindings' direct API path.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces configurable multimodal tensor transport modes (inline, shm, auto) and size thresholds (multimodal_shm_min_bytes) across the router, CLI, and per-worker specifications, replacing legacy SMG_TOKENSPEED_MM_* environment variables with SMG_MM_* fallbacks. The review feedback highlights two key issues: first, in disaggregated mode, primary_worker incorrectly returns the prefill worker instead of the encode worker, which bypasses encode-specific overrides; second, invalid transport mode strings passed from Python are silently ignored rather than raising a configuration error.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread model_gateway/src/routers/grpc/multimodal/transport.rs
Comment thread bindings/python/src/lib.rs Outdated

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
model_gateway/src/routers/grpc/multimodal/assemble.rs (1)

521-551: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing test coverage for the shm_min_bytes threshold boundary.

All tests (here and in serialize.rs/proto_wrapper.rs) pin shm_min_bytes to 0, so the new nbytes >= shm_min_bytes gating condition added in serialize_array_as_tokenspeed_tensor is never exercised at/around the threshold. Consider adding a case with a non-zero shm_min_bytes where nbytes falls just below and just at the threshold to confirm the SHM/inline split is correct.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@model_gateway/src/routers/grpc/multimodal/assemble.rs` around lines 521 -
551, Add test coverage for the new shm_min_bytes boundary in the multimodal
assembly and serialization tests, since current cases only use zero. Update the
tests around pending_tokenspeed_shm_assembly and the
serialize_array_as_tokenspeed_tensor path to use a non-zero shm_min_bytes and
verify behavior when nbytes is just below and exactly at the threshold. Assert
that the SHM vs inline tensor encoding switches correctly at the boundary.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@bindings/python/src/lib.rs`:
- Around line 845-846: The new _Router constructor parameters were inserted in
the middle of the Python argument list, which shifts later positional arguments
and breaks compatibility. Update the constructor definition in the
_Router-related code so multimodal_tensor_transport and multimodal_shm_min_bytes
are appended to the end of the parameter list instead of being placed after
dp_aware, keeping existing positional callers stable.
- Around line 790-794: The multimodal tensor transport parsing in the Python
bindings is silently accepting invalid values by converting parse failures into
None, which causes fallback to env/default behavior. Update the builder path
around multimodal_tensor_transport and config::TransportMode::parse to reject
bad strings explicitly by returning a ConfigError::InvalidValue when parsing
fails, matching the CLI/Rust parsing contract instead of using a silent
fallback.

In `@model_gateway/src/routers/grpc/multimodal/transport.rs`:
- Around line 101-120: The SHM transport resolution currently reads overrides
from the prefill-side worker selection, so pixel tensors can inherit the wrong
mode/threshold when the receiving encode workers differ. Update
resolve_mm_shm_enabled and resolve_mm_shm_min_bytes to use the worker assignment
that actually receives the tensor for pixel values, and fall back conservatively
when the encode workers disagree; keep the existing helper flow around
worker_transport_mode_override, worker_shares_dev_shm, and
worker_shm_min_bytes_override but apply them to the receiving leg rather than
primary_worker().

---

Outside diff comments:
In `@model_gateway/src/routers/grpc/multimodal/assemble.rs`:
- Around line 521-551: Add test coverage for the new shm_min_bytes boundary in
the multimodal assembly and serialization tests, since current cases only use
zero. Update the tests around pending_tokenspeed_shm_assembly and the
serialize_array_as_tokenspeed_tensor path to use a non-zero shm_min_bytes and
verify behavior when nbytes is just below and exactly at the threshold. Assert
that the SHM vs inline tensor encoding switches correctly at the boundary.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: f8ba016b-5f20-4a48-93b3-21e7d30cd36b

📥 Commits

Reviewing files that changed from the base of the PR and between 58150cf and acb6602.

📒 Files selected for processing (14)
  • bindings/python/src/lib.rs
  • bindings/python/src/smg/router_args.py
  • crates/protocols/src/worker.rs
  • docs/reference/configuration.md
  • model_gateway/src/config/builder.rs
  • model_gateway/src/config/types.rs
  • model_gateway/src/main.rs
  • model_gateway/src/routers/grpc/epd_encode.rs
  • model_gateway/src/routers/grpc/multimodal/assemble.rs
  • model_gateway/src/routers/grpc/multimodal/mod.rs
  • model_gateway/src/routers/grpc/multimodal/serialize.rs
  • model_gateway/src/routers/grpc/multimodal/transport.rs
  • model_gateway/src/routers/grpc/proto_wrapper.rs
  • model_gateway/src/server.rs

Comment thread bindings/python/src/lib.rs Outdated
Comment thread bindings/python/src/lib.rs Outdated
Comment thread model_gateway/src/routers/grpc/multimodal/transport.rs
…validation

Follow-up on the transport config change addressing bot review plus
deprecated-env handling:

- transport.rs: warn once when a legacy `SMG_TOKENSPEED_MM_*` env var is read.
  The aliases stay for backward compat; the warning nudges migration to
  `SMG_MM_*` so they can be removed in a future major.
- transport.rs: `primary_worker` now returns the encode worker in EPD (where the
  multimodal tensors are actually sent), so per-worker overrides configured on
  the encode spec are honored instead of the prefill spec's.
- bindings/python: reject invalid `multimodal_tensor_transport` strings with a
  `ConfigError::InvalidValue` instead of silently defaulting, matching the
  CLI/Rust parsing contract for direct programmatic `RouterArgs` use; and append
  the new `_Router` constructor params (not mid-list) per the file's documented
  positional-compatibility convention.
- serialize.rs: add a `shm_min_bytes` threshold boundary test (inline below,
  SHM at/above) so the new gating condition is exercised.

Signed-off-by: Simo Lin <25425177+slin1237@users.noreply.github.com>
@slin1237

slin1237 commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

Thanks for the reviews. Addressed in 145613e:

  • Invalid multimodal_tensor_transport silently defaulting (claude, gemini, coderabbit) — fixed: direct programmatic RouterArgs use now returns ConfigError::InvalidValue on a bad mode string, matching the CLI (value_parser) and Rust parsing contract instead of falling back to inline.
  • primary_worker uses prefill, not the encode worker, in EPD (gemini, coderabbit) — fixed: it now returns the first encode worker when encode_assignments is present, so per-worker overrides on the encode spec (transport mode / shm-min-bytes / encoder dtype) are honored where the tensors actually land. Plain PD still falls back to prefill.
  • _Router constructor params inserted mid-list (coderabbit) — fixed: moved multimodal_tensor_transport / multimodal_shm_min_bytes to the end of the struct, #[pyo3(signature)], new() params, and body, per the file's documented positional-compatibility convention. (The Python RouterArgs dataclass is kwargs-only, so its field order is left grouped.)
  • Missing shm_min_bytes boundary coverage (coderabbit) — added shm_min_bytes_threshold_gates_inline_vs_shm: inline just below the threshold, SHM at/above.

Also added (independent of the review): a one-time deprecation warning when a legacy SMG_TOKENSPEED_MM_* env var is read — the aliases stay for backward compatibility, the warning nudges migration to SMG_MM_* so they can be dropped in a future major.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@model_gateway/src/routers/grpc/multimodal/transport.rs`:
- Around line 81-90: The mm_shm_min_bytes_from_env helper is silently ignoring
malformed values by converting parse failures to None, unlike
mm_tensor_transport_mode_from_env which reports invalid input. Update
mm_shm_min_bytes_from_env to detect a parse error from the env value returned by
env_with_deprecated_alias and log an unknown/invalid configuration once (reuse
the same logging pattern used by log_unknown_transport_once or a similar
helper), then fall back to None so the default router config still applies.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 18207f53-a980-42e7-b015-edc4de64e3ed

📥 Commits

Reviewing files that changed from the base of the PR and between acb6602 and 145613e.

📒 Files selected for processing (3)
  • bindings/python/src/lib.rs
  • model_gateway/src/routers/grpc/multimodal/serialize.rs
  • model_gateway/src/routers/grpc/multimodal/transport.rs

Comment thread model_gateway/src/routers/grpc/multimodal/transport.rs
mm_shm_min_bytes_from_env silently swallowed unparseable values via .ok(),
unlike mm_tensor_transport_mode_from_env which warns. A typo like "64k" now
logs a one-time warning before falling back to the default, matching the mode
reader. Addresses CodeRabbit review.

Signed-off-by: Simo Lin <25425177+slin1237@users.noreply.github.com>
@slin1237

slin1237 commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

Addressed in d2ef4bb: mm_shm_min_bytes_from_env now logs a one-time warning on an unparseable SMG_MM_SHM_MIN_BYTES (or legacy alias) value before falling back to the default, matching mm_tensor_transport_mode_from_env's behavior. Good catch — thanks.

@slin1237
slin1237 merged commit 9b64940 into main Jul 8, 2026
20 of 38 checks passed
@slin1237
slin1237 deleted the feat/multimodal-transport-config branch July 8, 2026 20:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation grpc gRPC client and router changes model-gateway Model gateway crate changes protocols Protocols crate changes python-bindings Python bindings changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant