Skip to content
Closed
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
13 changes: 13 additions & 0 deletions .github/actions/setup-tokenspeed/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
name: 'Setup TokenSpeed Backend'
description: 'Create Python venv and install TokenSpeed (engine + kernel + scheduler) from source.'

runs:
using: 'composite'
steps:
- name: Setup Python venv
shell: bash
run: bash scripts/ci_setup_python_venv.sh

- name: Install TokenSpeed
shell: bash
run: bash scripts/ci_install_tokenspeed.sh
6 changes: 5 additions & 1 deletion .github/workflows/e2e-gpu-job.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ on:
engine:
required: true
type: string
description: "Engine to test: sglang, vllm, or trtllm"
description: "Engine to test: sglang, vllm, trtllm, or tokenspeed"
gpu_tier:
required: true
type: string
Expand Down Expand Up @@ -68,6 +68,10 @@ jobs:
if: inputs.engine == 'trtllm'
uses: ./.github/actions/setup-trtllm

- name: Setup TokenSpeed backend
if: inputs.engine == 'tokenspeed'
uses: ./.github/actions/setup-tokenspeed

# Artifact downloads
- name: Download wheel artifact
uses: actions/download-artifact@v8
Expand Down
6 changes: 6 additions & 0 deletions .github/workflows/pr-test-rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ jobs:
- 'scripts/ci_setup_python_venv.sh'
- 'scripts/ci_install_sglang.sh'
- 'scripts/ci_install_vllm.sh'
- 'scripts/ci_install_tokenspeed.sh'
- 'scripts/ci_install_e2e_deps.sh'
- 'scripts/ci_killall_sglang.sh'
- 'scripts/ci_build_wheel.sh'
Expand All @@ -404,6 +405,7 @@ jobs:
- 'e2e_test/router/**'
- 'scripts/ci_install_vllm.sh'
- 'scripts/ci_install_trtllm.sh'
- 'scripts/ci_install_tokenspeed.sh'
agentic:
- 'crates/mcp/**'
- 'crates/data_connector/**'
Expand Down Expand Up @@ -445,6 +447,10 @@ jobs:
timeout: 20
- engine: trtllm
timeout: 90
# TokenSpeed builds kernel (CUDA) + scheduler (C++/CMake) from
# source, so first run takes ~30 min; cached runs are faster.
- engine: tokenspeed
timeout: 60
Comment on lines +450 to +453

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

LGTM — 60-min timeout reasonable for from-source builds; consider caching in a follow-up.

The matrix addition is well-scoped and the timeout budget matches the documented build cost. If the installer script ends up dominating CI time, a follow-up that caches the TokenSpeed kernel/scheduler build outputs (keyed on scripts/ci_install_tokenspeed.sh hash) would materially speed up most runs. Not a blocker for this PR.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/pr-test-rust.yml around lines 450 - 453, The workflow
currently sets a 60-minute timeout for the tokenspeed matrix entry (engine:
tokenspeed, timeout: 60) which is fine; as a follow-up optimization, add caching
around the TokenSpeed kernel/scheduler build by caching the build output keyed
on the installer script hash (scripts/ci_install_tokenspeed.sh) so repeated runs
skip rebuilding—implement a cache action step that saves/restores the built
artifacts using a cache key that includes the script file hash and relevant
platform identifiers.

uses: ./.github/workflows/e2e-gpu-job.yml
with:
engine: ${{ matrix.engine }}
Expand Down
23 changes: 23 additions & 0 deletions crates/grpc_client/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Rebuild triggers
println!("cargo:rerun-if-changed=proto/common.proto");
println!("cargo:rerun-if-changed=proto/sglang_scheduler.proto");
println!("cargo:rerun-if-changed=proto/tokenspeed_scheduler.proto");
println!("cargo:rerun-if-changed=proto/vllm_engine.proto");
println!("cargo:rerun-if-changed=proto/trtllm_service.proto");
println!("cargo:rerun-if-changed=proto/mlx_engine.proto");
Expand Down Expand Up @@ -44,5 +45,27 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
&["proto"],
)?;

// Pass 3: compile the TokenSpeed scheduler proto. It imports SGLang
// message types (see proto/tokenspeed_scheduler.proto), so we point
// tonic at the already-generated ``crate::sglang_scheduler::proto``
// module via ``extern_path`` — otherwise tonic would try to generate a
// parallel ``sglang.grpc.scheduler`` module under tokenspeed's output
// file and produce ``too many leading super keywords`` errors.
//
// Write into a dedicated sub-directory so this pass's ``extern_path``
// on the SGLang package doesn't clobber Pass 2's ``sglang.grpc.scheduler.rs``
// — tonic still emits a stub file for every compiled proto even when
// the message types inside are extern-pathed out.
let ts_out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?).join("tokenspeed");
std::fs::create_dir_all(&ts_out_dir)?;
tonic_prost_build::configure()
.build_server(true)
.build_client(true)
.out_dir(&ts_out_dir)
.extern_path(".smg.grpc.common", "crate::common_proto")
.extern_path(".sglang.grpc.scheduler", "crate::sglang_scheduler::proto")
.protoc_arg("--experimental_allow_proto3_optional")
.compile_protos(&["proto/tokenspeed_scheduler.proto"], &["proto"])?;

Ok(())
}
45 changes: 45 additions & 0 deletions crates/grpc_client/proto/tokenspeed_scheduler.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
syntax = "proto3";

package tokenspeed.grpc.scheduler;

import "sglang_scheduler.proto";
import "common.proto";

// Service definition for TokenSpeed scheduler communication.
//
// Wire-level identity (package, service name) is distinct from SGLang so the
// gateway's backend detector, metrics, and operator tooling can tell a
// TokenSpeed worker apart from a real SGLang worker. Messages currently
// piggy-back on the SGLang proto via ``import`` because the two backends
// happen to share the same tokenized-request shape, sampling-param naming,
// and output-dict layout today — any future divergence (new fields, changed
// semantics) should land as a TokenSpeed-specific message defined here, not
// by mutating the shared SGLang message in-place.
service TokenSpeedScheduler {
rpc Generate(sglang.grpc.scheduler.GenerateRequest)
returns (stream sglang.grpc.scheduler.GenerateResponse);

rpc Embed(sglang.grpc.scheduler.EmbedRequest)
returns (sglang.grpc.scheduler.EmbedResponse);

rpc HealthCheck(sglang.grpc.scheduler.HealthCheckRequest)
returns (sglang.grpc.scheduler.HealthCheckResponse);

rpc Abort(sglang.grpc.scheduler.AbortRequest)
returns (sglang.grpc.scheduler.AbortResponse);

rpc GetModelInfo(sglang.grpc.scheduler.GetModelInfoRequest)
returns (sglang.grpc.scheduler.GetModelInfoResponse);

rpc GetServerInfo(sglang.grpc.scheduler.GetServerInfoRequest)
returns (sglang.grpc.scheduler.GetServerInfoResponse);

rpc GetLoads(sglang.grpc.scheduler.GetLoadsRequest)
returns (sglang.grpc.scheduler.GetLoadsResponse);

rpc GetTokenizer(smg.grpc.common.GetTokenizerRequest)
returns (stream smg.grpc.common.GetTokenizerChunk);

rpc SubscribeKvEvents(smg.grpc.common.SubscribeKvEventsRequest)
returns (stream smg.grpc.common.KvEventBatch);
}
6 changes: 5 additions & 1 deletion crates/grpc_client/python/smg_grpc_proto/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""SMG gRPC Proto - Protocol definitions for SGLang, vLLM, and TRT-LLM."""
"""SMG gRPC Proto - Protocol definitions for SGLang, TokenSpeed, vLLM, and TRT-LLM."""

from importlib.metadata import version

Expand All @@ -12,6 +12,8 @@
sglang_encoder_pb2_grpc,
sglang_scheduler_pb2,
sglang_scheduler_pb2_grpc,
tokenspeed_scheduler_pb2,
tokenspeed_scheduler_pb2_grpc,
trtllm_service_pb2,
trtllm_service_pb2_grpc,
vllm_engine_pb2,
Expand All @@ -23,6 +25,8 @@
"sglang_scheduler_pb2_grpc",
"sglang_encoder_pb2",
"sglang_encoder_pb2_grpc",
"tokenspeed_scheduler_pb2",
"tokenspeed_scheduler_pb2_grpc",
"vllm_engine_pb2",
"vllm_engine_pb2_grpc",
"trtllm_service_pb2",
Expand Down
4 changes: 4 additions & 0 deletions crates/grpc_client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub mod common_proto {
pub mod mlx_engine;
pub mod sglang_scheduler;
pub mod tokenizer_bundle;
pub mod tokenspeed_scheduler;
pub mod trtllm_service;
pub mod vllm_engine;

Expand All @@ -19,6 +20,9 @@ use std::sync::Arc;
pub use mlx_engine::{proto as mlx_proto, MlxEngineClient};
pub use sglang_scheduler::{proto as sglang_proto, SglangSchedulerClient};
use tonic::metadata::MetadataMap;
// TokenSpeed reuses ``sglang_proto`` for message types today; the module
// below owns the ``tokenspeed.grpc.scheduler`` service stub and its client.
pub use tokenspeed_scheduler::{tokenspeed_proto, TokenSpeedSchedulerClient};
pub use trtllm_service::{proto as trtllm_proto, TrtllmServiceClient};
pub use vllm_engine::{proto as vllm_proto, VllmEngineClient};

Expand Down
59 changes: 38 additions & 21 deletions crates/grpc_client/src/sglang_scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ pub mod proto {
// The generated module structure depends on the package name in the .proto file
// package sglang.grpc.scheduler; generates a nested module structure

/// Fire-and-forget abort sender used by [`AbortOnDropStream`]. The closure
/// captures whichever scheduler client (SGLang / TokenSpeed / future) created
/// the stream, so a single generic wrapper can serve both engines without
/// being parameterised over the client type. The closure is expected to
/// spawn its own async task and return immediately — ``Drop`` is sync.
pub type AbortDispatcher = Arc<dyn Fn(String) + Send + Sync>;

/// A smart wrapper around Streaming<GenerateResponse> that automatically
/// sends abort when dropped (e.g., due to client disconnection or early termination).
///
Expand All @@ -40,22 +47,27 @@ pub mod proto {
pub struct AbortOnDropStream {
inner: Streaming<proto::GenerateResponse>,
request_id: String,
client: SglangSchedulerClient,
abort_dispatcher: AbortDispatcher,
aborted: Arc<AtomicBool>,
}

impl AbortOnDropStream {
/// Create a new auto-aborting stream wrapper
/// Create a new auto-aborting stream wrapper.
///
/// ``abort_dispatcher`` is invoked from ``Drop`` with the request id when
/// the stream is dropped without a prior ``mark_completed`` call. It must
/// handle its own async dispatch (e.g. ``tokio::spawn``) since ``Drop``
/// cannot ``await``.
pub fn new(
stream: Streaming<proto::GenerateResponse>,
request_id: String,
client: SglangSchedulerClient,
abort_dispatcher: AbortDispatcher,
) -> Self {
debug!("Created AbortOnDropStream for request {}", request_id);
Self {
inner: stream,
request_id,
client,
abort_dispatcher,
aborted: Arc::new(AtomicBool::new(false)),
}
}
Expand Down Expand Up @@ -83,22 +95,27 @@ impl Drop for AbortOnDropStream {
{
return;
}
debug!(
"Stream dropped without completion for request {}, sending abort",
self.request_id
);
(self.abort_dispatcher)(self.request_id.clone());
}
}

let client = self.client.clone();
let request_id = self.request_id.clone();

// Spawn a background task to send abort (since Drop is sync but abort_request is async)
/// Build the default abort dispatcher for [`SglangSchedulerClient`]. Spawned
/// task calls ``abort_request`` on the original client (so the abort RPC goes
/// over the same SGLang service the generate call used). TokenSpeed has an
/// analogous helper in ``tokenspeed_scheduler.rs``.
fn sglang_abort_dispatcher(client: SglangSchedulerClient) -> AbortDispatcher {
Arc::new(move |request_id: String| {
let client = client.clone();
let request_id_for_log = request_id.clone();
#[expect(
clippy::disallowed_methods,
reason = "fire-and-forget abort on Drop is intentional"
)]
tokio::spawn(async move {
debug!(
"Stream dropped without completion for request {}, sending abort",
request_id
);
// Clone request_id for the error message since abort_request takes ownership
let request_id_for_log = request_id.clone();
if let Err(e) = client
.abort_request(request_id, "Stream dropped".to_string())
.await
Expand All @@ -109,7 +126,7 @@ impl Drop for AbortOnDropStream {
);
}
});
}
})
}

// Implement Stream trait to make AbortOnDropStream work like the original Streaming
Expand Down Expand Up @@ -200,7 +217,7 @@ impl SglangSchedulerClient {
Ok(AbortOnDropStream::new(
response.into_inner(),
request_id,
self.clone(),
sglang_abort_dispatcher(self.clone()),
))
}

Expand Down Expand Up @@ -434,7 +451,7 @@ impl SglangSchedulerClient {
}

/// Build gRPC SamplingParams from ChatCompletionRequest
fn build_grpc_sampling_params_from_chat(
pub(crate) fn build_grpc_sampling_params_from_chat(
request: &ChatCompletionRequest,
tool_call_constraint: Option<(String, String)>,
) -> Result<proto::SamplingParams, String> {
Expand Down Expand Up @@ -542,7 +559,7 @@ impl SglangSchedulerClient {
}

/// Build gRPC SamplingParams from ResponsesRequest
fn build_grpc_sampling_params_from_responses(
pub(crate) fn build_grpc_sampling_params_from_responses(
request: &ResponsesRequest,
constraint: Option<(String, String)>,
) -> Result<proto::SamplingParams, String> {
Expand Down Expand Up @@ -635,7 +652,7 @@ impl SglangSchedulerClient {
}

/// Build gRPC SamplingParams from CreateMessageRequest
fn build_grpc_sampling_params_from_messages(
pub(crate) fn build_grpc_sampling_params_from_messages(
request: &CreateMessageRequest,
tool_call_constraint: Option<(String, String)>,
) -> Result<proto::SamplingParams, String> {
Expand Down Expand Up @@ -698,7 +715,7 @@ impl SglangSchedulerClient {
Ok(grpc_request)
}

fn build_grpc_sampling_params_from_completion(
pub(crate) fn build_grpc_sampling_params_from_completion(
request: &CompletionRequest,
) -> Result<proto::SamplingParams, String> {
let stop_sequences = match &request.stop {
Expand Down Expand Up @@ -781,7 +798,7 @@ impl SglangSchedulerClient {
}
}

fn build_sampling_params_from_plain(
pub(crate) fn build_sampling_params_from_plain(
params: Option<&GenerateSamplingParams>,
) -> Result<proto::SamplingParams, String> {
let mut sampling = proto::SamplingParams {
Expand Down
Loading
Loading