Skip to content

Add OpenRouter backend - #305

Closed
janimo wants to merge 3 commits into
sgl-project:mainfrom
janimo:openrouter
Closed

janimo wants to merge 3 commits into
sgl-project:mainfrom
janimo:openrouter

Conversation

@janimo

@janimo janimo commented Mar 15, 2024

Copy link
Copy Markdown
Contributor

@janimo

janimo commented Mar 22, 2024

Copy link
Copy Markdown
Contributor Author

The dep changes (numba, tqdm, tiktoken) are unrelated to openrouter functionality.

@merrymercy

Copy link
Copy Markdown
Collaborator

If OpenRouter uses OpenAI-compatible API, why do we need a new file openrouter.py? Can we just delete this file and make one usage example about OpenRouter? see

backend = sgl.OpenAI(
model_name="mistralai/Mixtral-8x7B-Instruct-v0.1",
base_url="https://api.together.xyz/v1",
api_key=os.environ.get("TOGETHER_API_KEY"),
)

@janimo

janimo commented Mar 22, 2024

Copy link
Copy Markdown
Contributor Author

That would indeed be much cleaner. I know that is what I tried first last week after seeing the together example but it did not work.
I'll need to retry with is_chat_model set.

Openrouter uses this lib for the HTTP message formats but otherwise it has some differences - only chat API (no legacy completions API) so no need for the is_chat_model flag.
For now the kwarg list is the same but their doc exposes more https://openrouter.ai/docs#requests

@merrymercy

Copy link
Copy Markdown
Collaborator

let us try to reuse OpenAI backend first. Could you help us fix the errors you see (for together)?
For more options, we can probably use these arguments to set more options

is_azure: bool = False,
*args,
**kwargs,

@janimo

janimo commented Mar 22, 2024

Copy link
Copy Markdown
Contributor Author

The together example worked. Just replacing the url and key with openrouter ones did not work. I have tried now with is_chat_model set to true and it is indeed better, but the model-specific chat template is applied (get_chate_template called by higher layers). In openrouter always messages are passed and no templates are used.
This is how the stream part of the example script shows up with the gemma model:

 ========== stream ==========

You are a helpful assistant.<start_of_turn>user
What is the capital of the United States?<end_of_turn>
<start_of_turn>model
Sure, here is the answer: Washington, D.C. (District of Columbia)<end_of_turn>
<start_of_turn>user
List two local attractions.<end_of_turn>
<start_of_turn>model
Sure, here are two local attractions in Washington, D.C.:

1. The Lincoln Memorial
2. The Washington Monument<end_of_turn>

whereas without the template it does not have the start of turn and end of turn markers. But maybe it is more correct with them in there, I don't know.

@janimo

janimo commented Mar 22, 2024

Copy link
Copy Markdown
Contributor Author

I remember now. I was trying the together_example_completion.py example and that did not work.
Together exposes both the OpenAI completions (legacy) and chat APIs. Openrouter only has the chat API.
These are selected by the is_chat_model flag in the backend and it is true for openrouter.
But that flag also selects whether it uses the text_ or messages_ field as prompt. And for the completion example, even if the API is chat only, text_ will be filled for the backend and messages_ is empty.
So I guess there is no need for a completions example for openrouter if it is for testing that API only.

@merrymercy

merrymercy commented Mar 23, 2024 •

Copy link
Copy Markdown
Collaborator

Yes. You can add a chat example. You do not need to worry about the chat template. We send a message list to OpenRouter and will let OpenRouter handle it.

Please follow up and fix this PR

@janimo

janimo commented Mar 23, 2024

Copy link
Copy Markdown
Contributor Author

Made a new PR with only the example script.

@janimo janimo closed this Mar 23, 2024
@janimo
janimo deleted the openrouter branch September 17, 2024 12:29
vschandramourya pushed a commit to vschandramourya/sglang that referenced this pull request Feb 3, 2026
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
zhaozx-cn pushed a commit to zhaozx-cn/sglang that referenced this pull request Apr 9, 2026
efschu added a commit to efschu/htsglang that referenced this pull request Jul 31, 2026
…ltimodal_classes.md 1745 lines — headline discovery: python/sglang/multimodal_gen/ (upstream SGLang Diffusion, ~430 files, ~22 pipeline families incl. FLUX/Wan/Qwen-Image, dynamic batching with resolution-aware admission) is ALREADY IN THE TREE: class 2 is integration not greenfield; the fork's genuine C2 delta is uneven sequence parallel (build_shard_plan ceil-divides equal-only — same argument as rank-tp-ratio) plus a VRAM budget model (it has none) and the process-global is_generation split; architecture: three schedulers one arbiter (per-GPU ledger + deficit tick broker, seam below the schedulers), class boundary = admission contract not modality, process isolation for C2/C3 which earns sgl-project#305 for free (memory-saver tags are process-wide); registry spec: M derived from ledger not configured, reservation store keyed by NVML UUID with lease+heartbeat, informative rejection; K3: resize is NOT optional (x4 fixed -> 8K), resize-before-RIFE beats pre-resize, regime B arithmetically excluded pre-resize, back-pressure spec against slow-client OOM, P1-P7 measurement posts, 8-bit matrix separates compute (deferred) from transport (free); prior-art: multimodal_gen + PyNvVideoCodec as dependencies, diffusers NOT direct, xDiT already vendored, vs-mlrt STANDALONE MISREAD corrected (means no-TRT-pure-Lanczos, not no-VapourSynth; trt_utils.h already VS-free); embeddings better than assumed (gaps: mean/max pooling, ColBERT, /v1/batches); plan M0-M5 with gates, M2 pullable ahead of M1
efschu added a commit to efschu/htsglang that referenced this pull request Jul 31, 2026
…odel with no model architecture anywhere (EngineSpec/Instance/Slot/ResourceProfile), three class adapters (class1 srt with HOT/WARM_GPU/COLD ladder and WARM_HOST refused loudly; class3 as srt-pooling OR opaque process tenant so the M2 video executor can enter; class2 estimate-only pointing at M3), control plane python -m sglang.srt.registry, planner bridge; M IS DERIVED (hot_capacity simulates admission in real promotion order — three 16 GiB engines on 32 GiB -> M=1, at 15 GiB -> M=2), --registry-max-hot applies after; LEDGER UNIFIED with M2: reservation.py moved to registry/ledger.py behaviour-unchanged, M2 re-exports, its 251 tests green unmodified, co-tenancy proven through the M2 import path; plan_reservation read-only pricing, MultiCardReservation all-or-nothing with rollback, adopt(); card window: engine HOT in 109.1 s on the correct card, ledger reserved/measured/waste honest, demote parked 7.18 GB via sgl-project#89 with UUID in the shard filename; hot-switch resume time NOT obtained (host-OOM + rig contention, named open item); rejection message verbatim informative; TWO card-found defects fixed: --rank-gpu-id is a CUDA index (5090 is CUDA 0 / NVML 1 — child now pinned via CUDA_VISIBLE_DEVICES in placement order, correct in every enumeration) and --enable-memory-saver silently exits 127 on this host (cu13 preload shim needs libcudart.so.13 — site-packages nvidia libs first on the child loader path; without it WARM_GPU and sgl-project#89 park are no-ops reporting success); 108 new tests, 359 with M2 suite, failure set byte-identical; honest limitation written: plan-time card choice reads the ledger not the driver (undeclared foreign process invisible), corridor check reads the driver

# Conflicts:
#	docs/dev/INTEGRATION_R3_VALIDATION.md
efschu added a commit to efschu/htsglang that referenced this pull request Jul 31, 2026
efschu added a commit to efschu/htsglang that referenced this pull request Aug 2, 2026
Desk design only, no cards (CUDA_VISIBLE_DEVICES=99), no implementation.

Verdict: sgl-project#407 is not a new abstraction, it is a NODE layer plus a
reconciliation. The edge half — what does it cost to move a byte from here
to there — already exists FOUR times with four readers and four absent-value
rules: cost_model.PairMatrix (#348b, UUID-keyed), barlink_path_rates.
PathProfile (sgl-project#279, affine per route), offload_movement.PeerPathCapability
(sgl-project#286, CUDA-ordinal-keyed) and card_probe h2d/d2h (sgl-project#271). E2 and E3 both want
the effective BAR1 aperture from p2p_readiness/capability_matrix.json and only
E2 has a loader. What exists nowhere is the node layer, and in its place the
tree carries four disjoint tier vocabularies (PARK_TARGETS sgl-project#286;
LOCAL_DESTINATION/SUPPORTED_PARK_BACKENDS sgl-project#224; StorageMedium telemetry;
HiCache choices=). Expert offload, the largest byte mover in the fork, is in
none of them: its tier is device="cpu" + .pin_memory() written out five times.

Two shipped contradictions the design bends around, both stated up front:

C1 — two opposite total orders over one axis. sgl-project#224's destinations_error makes
'local' first a hard validation law ("a remote tier is a tier BELOW local,
never above it"); sgl-project#286's ladder puts peer_vram ABOVE host_ram. Resolved by
making the order a shortest path over a STAGING GRAPH: 'local first' is
recovered as reachability (the only edge out of a device tier toward a blob
tier runs through host), peer_vram is recovered because vram->vram is a direct
edge. Neither consumer's shipped behaviour changes.

C2 — the one existing tier ledger is positionally keyed. CapacityLedger keys
peer-VRAM budgets by CUDA ordinal; AUDIT_331 calls that SCOPED and legitimate
until it crosses a process boundary, which is exactly what sgl-project#305 §6 ("one
ledger, no second accounting") asks for. On this rig the 5090 is CUDA ordinal
0 and NVML index 1, so the failure is silent card-swapping.

Honesty correction on three numbers the brief assumed measured: the peer-VRAM
1-3 us posted-write class is an explicit ASSUMPTION (EVAL_p2p §"Tragende
Annahmen"), NVMe latency does not exist in the tree in any unit, and host DRAM
38 GB/s is derived from an ASSUMED DDR4-3200 peak (the VM hides SPD). They
ship as ESTIMATE/ABSENT under #348b's measured-or-named rule. Everything else
in the inventory is sourced: 5090 32607 MiB / 3080 20480 MiB, membw 1558/723
GB/s, BAR1 256 MiB nominal but 96 MiB contiguous with 1.13-1.34x vs NCCL at
20 KiB-16 MiB, H2D 6.4/13/13 GB/s gen4 x4/x8/x8, NVMe 1.8 GB/s cold (ARC rows
excluded), rig-2 2.07-2.83 GB/s with 1.47 us at 8 B and ~89/202 us serving
collectives.

Consumer survey, eight consumers read in their target-selection code:
sgl-project#77/sgl-project#123 expert offload MECHANICAL for the UUID-vector half (it revives sgl-project#394's
merged-but-starved link-proportional sharding, 145 -> 86 ms/token, 1.69x) and
REBUILD for a third rung (two dicts, binary resident|spill, UVA aliasing);
HiCache MECHANICAL for backends, ladder EXCLUDED (it is the type signature of
every controller method, not configuration); sgl-project#224 MECHANICAL for the list,
REBUILD for the ordering law, victim half untouched; sgl-project#89 MECHANICAL-PLUS
(needs a persistence class or a tmpfs --hibernate-dir is a silent regression,
and a driver-free arg-parse-time query); sgl-project#305 NO MIGRATION, it is the awaited
mechanism; sgl-project#286 MECHANICAL and the donor — lift _select_target and
CapacityLedger rather than write new ones; sgl-project#389 and sgl-project#306 greenfield.

Cut plan, no big bang: 1 registry + read-only enumeration + GateRow dashboard
row (S); 2 publish the rank->card-UUID vector without a collective so sgl-project#394
comes alive (S, the only cut whose yield is already measured); 3 sgl-project#224 consumes
it (S-M); 4 CapacityLedger becomes a view of registry/ledger.py, keys widen to
TierId (M); 5-9 expert offload, hibernate, sgl-project#305 transitions, HiCache backends,
NVMe/sgl-project#306 declaration. Exclusions with hard reasons only: the HiCache ladder,
GDN state (DEVICE_BOUND_ONLY admission, a refusal not an omission), cross-rig
GPU-to-GPU (driver guard, sgl-project#280 closed in userspace), compute placement (sgl-project#302).

Measurement plan names six gaps, five of them S, three of them new arms in the
existing comm-suite which today has no BAR1, storage or host-DRAM arm.

codespell clean; ruff not applicable (documentation only).
efschu added a commit to efschu/htsglang that referenced this pull request Aug 3, 2026
…roject#488)

Desk investigation against the runtime, ahead of any Phase 3 building.

The blocker is not what it looked like. "The decode loop assumes one token per
step" is wrong in both directions: the append side is already N-per-step
because speculative decoding put it there, and the KV/position side is strictly
one-per-step -- which is exactly right, because sixteen codebook entries are one
audio frame at one sequence position, not sixteen positions. The residual codes
must never enter the KV sequence. The real blocker is a single line that clears
input_embeds on entry to decode, while the talker's next input is a summed
embedding vector rather than a token id. The CUDA-graph side already carries
embeds, so this is a scheduler unblock rather than a graph rewrite.

The speculative stack is the wrong vehicle and is rejected on the record: a
draft head is the right shape and the wrong contract -- nothing to verify, no
target distribution, no accept length, and spec exists to ADD sequence
positions. Smuggling a depth transformer through CustomSpecAlgo would poison
the spec metrics, the adaptive-draft ladder and the cross-algo bandit for the
rest of the fork's life. The precedent that fits is the dLLM lane: a
non-speculative custom decode regime, 935 lines plus wiring, with full_logits
as the precedent for a non-standard logits shape and customized_info as a
wired-but-unused transport for the extra codes.

No host exists. sgl-project#274 is a dual lane within one model's world, sgl-project#305 is
design-only, DESIGN_333 M5 is unformulated, and ANALYSE_334 already priced this
family HARD/L.

Effort against the only complete implementation (5192 lines plus a 2102-line
bespoke runner, whose authors also could not host it in a stock decode loop):
~16 days. Seven buys a boot-proven model file, desk parity for the trunk, a
harness-driven code predictor and a written hook design -- not streaming decode,
graph coverage, the vocoder, or the native speech endpoint. The translator
cannot move to the native lane before 08-10, so the ladder's rung B ships.

Three traps pre-registered, the sharpest being that the checkpoint writes
rope_scaling "interleaved" while the factory reads "mrope_interleaved": passed
through, the model loads, runs, emits plausible codec tokens and sounds wrong.

Also preserves the vLLM-Omni 0.24.0 reference outside the venv being deleted.
It is the only source of truth for the 1596-line prompt builder, the predictor
loop and the vocoder, and losing it would have cost more than any other
artifact here.
efschu added a commit to efschu/htsglang that referenced this pull request Aug 3, 2026
…r instrument that can refute it

Three things, all desk-executable, ahead of the GPU window.

The TP=3 rejection is now a register row (planner/rejected.py,
tts_talker_tensor_parallel) rather than only a paragraph, so the wizard cannot
propose what the arithmetic already settled. NOT_DEFAULT, not BLOCKED: the
shard is representable and correct, it simply loses -- so it stays offerable
with the counter-number attached, unlock line included. Scope is "rig", because
the collective term is a rig property while the 192-steps-per-audio-second
shape is architectural; the verdict is the two together. The register's own
brevity contract caught the first draft (gain/cost <= 120 chars) -- the row was
shortened, not the contract widened.

The precursor instrument (scripts/dev/488_talker_profile/) decomposes a talker
forward into wall / kernel-covered / gap / kernels-per-iteration / syncs, and
projects the RTF that would remain if the gap went to zero. It runs against an
ALREADY LOADED module inside the tenant process -- no second load, no server
boot, ~6 minutes, every loop bounded by both an iteration count and a wall
deadline.

It is built so it can tell us we are wrong: at >= 70 % kernel coverage it
prints PREMISE FALSIFIED and says ANALYSE_488's redirect needs revisiting.
And it refuses to testify at all unless two known-answer calibration arms
separate by >= 0.40 gap fraction AND the known GPU-bound arm stays under a 0.35
ceiling. The second condition is the one that matters here: the card is
currently held by a resident serving instance, and on a saturated box EVERY arm
looks overhead-bound -- a separation-only gate would have let contention
manufacture the answer we expect. Both refusals are executed as tests, as is
the falsified verdict wording.

Reach correction, cited rather than assumed: "sgl-project#274 lanes carry multi-instance
naturally" does not hold at the code level. dual_group_lane.py:35 says the
scheduler holds a list of lanes and "Slice B instantiates exactly one lane";
:16-25 make a lane a full-width shell tree over the SERVING model's own parts,
not a slot a different model occupies; server_args.py:9524 requires an explicit
--rank-tp-ratio because "the lane shares the plan's rank-0 segment". One talker
instance per card is sgl-project#305 shaped, and sgl-project#305 is design-only. What slice 1 can
honestly claim is that the model file holds no process-global state -- every
geometry decision comes from the parallel context at construction, the same
axis sgl-project#274's overlays already substitute -- so N instances stay a host problem
rather than a model-file rewrite. Written into ANALYSE_488 §6a.

Tests: 25 hermetic across the two sgl-project#488 files (13 lane + 12 instrument), plus
190 green on the register's consumers (wizard, wizard_v2, planner generality,
rig coupling). ruff + codespell clean on every touched file. No GPU touched:
the arb request is rewritten to the one short in-process arm and the TP=3 arm
is withdrawn from it.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 17, 2026
The analysis's tenant-COLD row named the gap exactly: parking 'works for the
translator (ledger.park_all) and for GDN slots (sgl-project#364). No generic per-tenant
mover; no single caller that can address tenant X.' The first half wired the two
byte probes so the bridge stops answering all-unavailable; this is the actuator
a cold event calls once that bridge has ranked a plan.

I CHECKED THE TABLE'S GATING COLUMN RATHER THAN TRUSTING IT, because §10 had
just caught the same table lying about numbering. test_ledger.py runs 22 passed
under CUDA_VISIBLE_DEVICES=: the ledger's park/restore is already exercised
hermetically with CPU tensors, so a mover over the same protocol is desk-
provable and the marking holds. Had those tests needed a device this would have
been a window item and the table would have been wrong twice.

NOT A SECOND LEDGER. AudioAssetLedger already parks and restores and its
ParkRoute protocol is already generic; what was missing was never the parking.
TenantMover registers TENANTS over that same protocol and reimplements nothing.
A parallel asset ledger would have been the two-authorities defect the sgl-project#553
bridge exists to reconcile.

The vocabulary is per tenant, which is the whole factoring: the translator's
ASR -> talker -> codec order is one tenant's physics, not a property of moving
tenants. register(tenant, routes, ranks=...) takes it as configuration, and a
test asserts a second tenant restoring y, x -- nonsense for the translator,
correct for that tenant. An unranked route sorts last: unlisted is unknown, not
urgent.

Stranding keeps the shape the policy layer already uses. Released bytes come
from what a route RETURNED (sgl-project#694); a route that reports nothing, or raises, is
STRANDED and never zero, while a route reporting 0 is an accounting.
release_fn() hands cold_event a None in exactly that case, which is how that
layer reads 'did not report', so a stranded tenant surfaces there instead of
being counted as a delivered zero. parked_bytes_by_device() omits a device with
nothing parked rather than reporting 0 (sgl-project#606).

An unknown tenant RAISES and names who is registered: 'no such tenant' and 'that
tenant had nothing to give' are different answers.

A defect in my own test, recorded in the analysis: the first _Route stub used
parked_bytes=None for 'not specified', so 'reports nothing' was inexpressible
and two stranding tests failed against correct code. A stub whose default and
whose absence-case share a value cannot test an absence rule.

12 tests red first, mutation-proven (collapsing stranding to zero reds the two
stranding pins; ignoring the supplied ranks reds all three vocabulary pins).
57 passed across the mover, the rung executor, the coresidency policy and the
translator ledger -- the ledger's 22 unchanged, it was not touched. ruff clean.
Desk only, no boots.

sgl-project#553's desk surface is now exhausted: cut 4 is gated on sgl-project#305's multi-model
binding, cut 5 is rig-gated by its own text, G1 is filed, and the live bindings
plus any live number's correctness remain the named window items.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants