Repository navigation
Add SGLang-compatible weight hot-update (disk + colocate CUDA-IPC) for RL integration with slime - #444
Conversation
Add the model-layer primitives for RL weight hot-update: - update_weights_from_tensor(named_tensors, strict): in-place copy of parameters identified by module parameter name (SGLang load_format=direct contract). Validate-then-copy so a bad update never partially mutates. - validate_logical_weights / load_logical_weights(dry_run=True): shape/presence validation without copying, enabling atomic validate-then-copy for the disk path. dry_run threaded through layer ops _copy_weight/_copy_tensor. - get_parameter_by_name: helper for get_weights_by_name + tests. Refs: SGLang update_weights_from_tensor/disk, Slime external-engine pattern. Signed-off-by: gameofdimension <[email protected]> Co-Authored-By: Claude Code Co-Authored-By: GLM-5.2
GRContinuousServingExecutor gains the RL weight-sync surface: - update_weights_from_disk(model_dir, flush_cache, abort_all_requests, weight_version, token_step): validate-then-load an HF checkpoint in place (Slime external-engine cross-process pattern). Structural config check + materialize_qwen3_checkpoint + validate_logical_weights before any copy. - update_weights_from_tensor(...): internal in-process primitive (atomic validate-then-copy). Kept for tests/future colocate transport. - get_weights_by_name: SGLang-style truncated param sample. - _abort_in_flight (abort_all_requests mirrors SGLang pause/abort semantics; update runs while idle), _invalidate_weight_dependent_state (flush prefill/ batched-prefill cache; CUDA graphs stay valid since copy is in-place), weight_version/token_step/weight_update_count bookkeeping in status/metrics. Signed-off-by: gameofdimension <[email protected]> Co-Authored-By: Claude Code Co-Authored-By: GLM-5.2
GRInProcessServingFacade exposes update_weights_from_disk / update_weights_from_tensor / get_weights_by_name, delegating to the executor (RuntimeError when the facade wraps a bare scheduler with no engine). GRServingWorker mirrors them under self._lock so the in-place swap is serialized against the background tick loop (thread-safe periodic RL sync). Signed-off-by: gameofdimension <[email protected]> Co-Authored-By: Claude Code Co-Authored-By: GLM-5.2
Expose the cross-process RL weight-sync surface over HTTP (the engine runs
standalone; the trainer writes a checkpoint to a shared path and calls
/update_weights_from_disk). Aligns with SGLang/Slime external-engine disk
transport.
- GRHTTPValidationPolicy.allow_weight_update (default True at the policy
level; the launcher opts in via --allow-weight-update / GR_ALLOW_WEIGHT_UPDATE=1,
mirroring --allow-catalog-reload).
- POST /update_weights_from_disk {model_path|model_dir, flush_cache,
abort_all_requests, weight_version, token_step}.
- GET|POST /get_weights_by_name?name=...&truncate_size= (query-string parsing
added for GET routes with no JSON body).
- Weight version/token_step/update_count surfaced via /status (executor).
- /update_weights_from_tensor is intentionally NOT exposed over HTTP: Slime's
colocate path is NCCL/IPC, not HTTP tensor POST; the tensor primitive stays
in-process for tests/future colocate.
- serve_qwen3_gr_http(.py/.sh): wire --allow-weight-update + GR_ALLOW_WEIGHT_UPDATE.
Signed-off-by: gameofdimension <[email protected]>
Co-Authored-By: Claude Code
Co-Authored-By: GLM-5.2
Add tests/test_weight_update.py covering the full stack: - Model: update_weights_from_tensor by module name (output changes, untouched params stable), atomic validate-then-copy (bad shape/unknown name leave the model intact), validate_logical_weights dry-run no-mutation + disk round-trip. - Executor: update_weights_from_disk swaps + records weight_version/token_step + flushes prefill cache; incompatible config rejected before any copy; abort in-flight; get_weights_by_name truncated sample; no-engine guard. - Facade + Worker: delegation + lock; bare-scheduler guard. - HTTP: POST /update_weights_from_disk (200, weights change, version in /status), GET|POST /get_weights_by_name, allow_weight_update=False -> 403, missing model_path -> 400. Also return get_weights_by_name shape as a list (matches HTTP JSON form). Signed-off-by: gameofdimension <[email protected]> Co-Authored-By: Claude Code Co-Authored-By: GLM-5.2
For seamless Slime integration: slime's trainer drives weight reload as four
separate HTTP calls (actor_group._reload_rollout_weights_from_disk):
pause_generation -> flush_cache -> update_weights_from_disk -> continue_generation,
plus get_weight_version for CI. Add them with SGLang-compatible shapes:
- POST /pause_generation {mode: abort|retract|in_place=abort}: abort in-flight,
set is_paused so the background worker stops advancing ticks.
- POST /continue_generation: clear is_paused.
- GET|POST /flush_cache {timeout_s?}: drop prefix/prefill cache entries.
- GET /get_weight_version: {weight_version, token_step, weight_update_count}.
- is_paused surfaced in /status; worker tick loop gated on facade.is_paused.
- pause/continue/get_weight_version gated by allow_weight_update; flush_cache
stays open (SGLang parity). update_weights_from_disk remains pause/lock-safe
for both the self-contained (abort_all_requests flag) and external-pause flows.
Signed-off-by: gameofdimension <[email protected]>
Co-Authored-By: Claude Code
Co-Authored-By: GLM-5.2
The HTTP commit added allow_weight_update=args.allow_weight_update to _make_http_validation_policy, but the two tests that build a mock args Namespace for the validation policy / adapter did not include the new field, so they raised AttributeError. Add allow_weight_update to both mock Namespaces (matching the existing allow_manual_tick/allow_catalog_reload fields) and assert the policy default. Signed-off-by: gameofdimension <[email protected]> Co-Authored-By: Claude Code Co-Authored-By: GLM-5.2
Receive SGLang's colocate weight-sync payload so a SGLang/Slime trainer on the same GPU can push weights over HTTP with zero-copy CUDA IPC, matching SGLang's update_weights_from_tensor exactly. New src/gr_inference/gr_serving/weight_ipc.py (Apache-2.0, attributed to SGLang): - monkey_patch_torch_reductions (CUDA device UUID<->index remap, len-guarded so CPU tensors work too). - MultiprocessingSerializer (ForkingPickler serialize / base64; custom unpickler that remaps any FlattenedTensorMetadata to our dataclass, no sglang dep). - FlattenedTensorBucket / FlattenedTensorMetadata (flatten same-dtype tensors into one uint8 buffer -> one IPC handle). - reconstruct_named_tensors: pick this rank's entry; flattened_bucket or direct. Executor/facade/worker.update_weights_from_tensor now take the SGLang serialized form (serialized_named_tensors, load_format, flush_cache, abort_all_requests, weight_version, token_step): deserialize -> HF->logical name map -> atomic validate-then-load. HTTP POST /update_weights_from_tensor mirrors the SGLang endpoint shape. Note: CUDA IPC handles cannot be reconstructed same-process (by design); the non-IPC pipeline is unit-tested on CPU, and the IPC receive is vendored verbatim from SGLang for colocate (same-GPU, separate-process) use. Signed-off-by: gameofdimension <[email protected]> Co-Authored-By: Claude Code Co-Authored-By: GLM-5.2
slime does not POST the whole model at once: it pushes weights in chunks
(update_weight_from_tensor.py, one flattened bucket per chunk via
_send_to_colocated_engine) and sends empty alignment buckets
(_empty_flattened_tensor_data) for ranks with fewer buckets. The tensor path
called model.validate_logical_weights(logical) (strict, requires the full
logical tensor set), so slime's first partial chunk raised KeyError -> HTTP 404
and aborted the sync; an empty bucket crashed validate_logical_weights({}).
Switch the tensor path to partial semantics mirroring SGLang's per-chunk
model.load_weights: validate the shapes of the tensors PRESENT in the payload
(load_logical_weights strict=False dry_run; missing names skipped), then copy
only those. An empty bucket is a no-op success. Full all-or-nothing validation
stays on the disk path (validate_logical_weights), which loads the whole
checkpoint in one shot.
slime sends flush_cache=false per chunk and flushes separately after pause, so
partial-izing does not change cache timing. The colocate payload is HF-split
names (q/k/v, gate/up) needing packing into qkv_proj/gate_up_proj, so the
logical loader is the right vehicle (not the module-name
update_weights_from_tensor, which resolves against packed named_parameters()).
Tests: chunked sequence applies the full model across chunks; empty alignment
bucket is a no-op; a bad-shape tensor in a chunk fails before any tensor in
that chunk is copied (validate-then-copy, atomic within the chunk).
Signed-off-by: gameofdimension <[email protected]>
Co-Authored-By: Claude Code
Co-Authored-By: GLM-5.2
Three high-priority review items on the weight-hot-update tensor branch: 1. pause_generation in_place/retract docstring claimed in-flight decode "finishes on its own", but is_paused=True makes the worker skip ticks, so in-flight requests are frozen (not advanced) and resume on continue_generation. Fixed the wording; behavior is unchanged and matches SGLang's in_place (paused, resume later). slime uses default abort, so this is doc-only. 2. Security default: GRHTTPValidationPolicy.allow_weight_update defaulted True, inconsistent with the serve CLI (off unless --allow-weight-update) -- other instantiation paths (tests/embedded) would expose the privileged surface (arbitrary caller-supplied checkpoint path + tensor IPC-handle unpickling) by default. Flip the dataclass default to False and document that it must run on a trusted intranet behind --api-key. Serve CLI behavior is unchanged (still opts in via --allow-weight-update / GR_ALLOW_WEIGHT_UPDATE). 3. In-flight mixing guard: without pause/abort, a bare update with in-flight requests swapped weights mid-decode -> old KV + new weights = mixed-policy output. slime always pause(abort)s first so integration was unaffected, but a bare caller could hit it. update_weights_from_disk/tensor now refuse when there are in-flight requests and abort_all_requests is False (RuntimeError -> HTTP 409), directing the caller to pause_generation or abort_all_requests. The guard runs before any IO; the disk path's full atomic validate is unchanged. Tests: update with in-flight + no abort is rejected on both paths; abort=true bypasses the guard and clears in-flight first. (24 tests.) Signed-off-by: gameofdimension <[email protected]> Co-Authored-By: Claude Code Co-Authored-By: GLM-5.2
…ning, low-prio
Medium (alignment with SGLang/slime):
- flush_cache: query key timeout_s -> timeout (upstream query name; io_struct
field stays timeout_s); return HTTP 400 (not 200) when there are running or
waiting requests, so slime's 60x retry loop (sglang_engine.py) behaves as
expected. Under the slime flow pause(abort) clears in-flight first, so it
still returns 200 there.
- get_weights_by_name: return SGLang shape {"parameter": [first truncate_size
rows along dim0]} instead of a wrapped dict. Name input stays the model's
parameter names (module paths); upstream accepts HF names but our qkv/gate_up
are packed so HF split names don't map 1:1 -- documented. Diagnostic only;
slime does not call this endpoint.
- /get_weight_version kept (upstream deprecated it for /model_info but slime
still calls it). token_step is a local superset field, slime doesn't send it.
Tests:
- Add a real CUDA IPC cross-process round-trip (spawn producer serializes a CUDA
tensor via ForkingPickler + device-UUID remap; this process reconstructs it via
CUDA IPC). This is the only test exercising reduce_tensor's CUDA branch and the
UUID remap -- the existing tests serialize CPU tensors (bytes inline) and never
hit it.
- Fix tautological assert in test_validate_logical_weights_does_not_mutate
(compared a tensor to itself); now verifies load actually applies weights.
Low:
- _record_weight_version: token_step now defaults None and is preserved when
omitted (symmetric with weight_version=None), instead of clobbering to 0.
- Document monkey_patch_torch_reductions as process-global/irreversible with the
hasattr guard for sglang coexistence.
- Note disk path's materialize_qwen3_checkpoint host-memory peak (~checkpoint
size) in the update_weights_from_disk docstring.
26 tests pass (incl. the CUDA IPC round-trip).
Signed-off-by: gameofdimension <[email protected]>
Co-Authored-By: Claude Code
Co-Authored-By: GLM-5.2
… reference sid-gr-inference plays the rollout-engine role that SGLang plays in slime's native setup -- SGLang is not a participant in this flow. Fix the docstrings/ comments that framed SGLang as the actor (sender/receiver): - update_weights_from_tensor: 'receive SGLang serialized CUDA-IPC tensors' -> 'reconstruct tensors from the trainer's IPC handles'; lead with 'this engine plays the rollout-engine role... speaks SGLang's wire format', and make the slime trainer the sender. - weight_ipc.py module + monkey_patch docstrings: 'a SGLang/Slime trainer' -> 'a slime trainer'; note this engine is the rollout-engine stand-in for SGLang. - flush_cache (continuous.py / http.py): 'SGLang refuses/returns' -> 'SGLang's flush_cache refuses/returns' (cite the reference behavior, not an actor in our flow). SGLang stays mentioned only as the wire-format / API / provenance reference we mirror for slime compatibility; all action subjects are now the trainer, slime, or this engine. No behavior change. Signed-off-by: gameofdimension <[email protected]> Co-Authored-By: Claude Code Co-Authored-By: GLM-5.2
Greptile SummaryThis PR adds SGLang-compatible online weight hot-update to the sid-gr-inference serving engine, enabling it to act as a rollout engine for RL frameworks (slime). Weights can be swapped in place either from an on-disk HF checkpoint (cross-process, validate-then-copy atomicity) or from CUDA-IPC tensor payloads pushed by a colocated trainer (zero-copy, same GPU). The implementation is gated behind
Confidence Score: 4/5Safe to merge with awareness of two minor design concerns that do not affect correctness. The core correctness properties are solid: the disk path is validate-before-copy atomic, the tensor path uses an allowlisted unpickler that converts all decode failures to 400s, the worker lock prevents weight updates from overlapping inference ticks, and the dry-run mechanism makes shape mismatches fail before any copy. Two concerns hold the score below maximum: (1) flush_cache is reachable by authenticated callers even when allow_weight_update=False, inconsistently with the other three coordination routes that do gate on that flag; (2) with abort_all_requests=True, in-flight requests are frozen silently for the entire disk materialization window before the abort is issued — clients using that shortcut path could see connection timeouts. Neither affects the slime-recommended flow. Files Needing Attention: continuous.py (disk-path abort ordering) and http.py (flush_cache gating) are the two files worth a second look before merge. Important Files Changed
Reviews (4): Last reviewed commit: "Add weight hot-update user guide" | Re-trigger Greptile |
…ce guard, metric rename PR NVIDIA#444 review (greptile bot, confidence 3/5). Four findings on the tensor endpoint, all fixed: P1 security (weight_ipc.py): _WeightUnpickler.find_class fell through to super() for anything except FlattenedTensorMetadata, so a crafted pickle could instantiate arbitrary classes (os.system) -- pickle RCE for any caller with the API key. Restrict find_class to an allowlist of module roots (torch, numpy, builtins, collections, multiprocessing.reduction, ...) plus name-based remaps for FlattenedTensorMetadata and the CUDA rebuild callable. The rebuild remap always resolves to OUR reviewed _rebuild_cuda_tensor_modified regardless of which module patched reductions (ours / SGLang's / a slime-vendored copy), so the producer's module is irrelevant and a crafted payload cannot substitute a malicious rebuild callable. Blocked modules raise UnpicklingError. P2 (continuous.py): deserialize failures (malformed pickle, bad base64, the new allowlist reject, CUDA-IPC rebuild errors) escaped the HTTP handler's try/except as a connection reset. Wrap reconstruct_named_tensors in try/except -> ValueError (-> HTTP 400). P2 (weight_ipc.py): _REDUCE_TENSOR_ARG_DEVICE_INDEX=6 is a hardcoded protocol constant copied from SGLang. Add an isinstance(int) guard so a future PyTorch reduce-protocol change (reordered/added args) fails loud instead of silently UUID-encoding the wrong element and misrouting the CUDA device. P2 (continuous.py): params_updated counted HF-split tensors (q/k/v = 3) not packed model parameters (qkv_proj = 1); rename to tensors_loaded in both update paths so the metric is unambiguous (tensors in the payload). Tests: a pickle-RCE probe (canary function that must never be invoked -> 400); malformed payload -> 400; tensors_loaded rename. 28 pass; broader suites green. Signed-off-by: gameofdimension <[email protected]> Co-Authored-By: Claude Code Co-Authored-By: GLM-5.2
The 890-line monolith had grown to 28 tests across model primitives, disk,
tensor/colocate, coordination, security, and CUDA-IPC. Split for readability +
maintainability, preserving every test verbatim (same logic/assertions):
- tests/_weight_update_helpers.py: shared factories/fixtures (tiny CPU model +
continuous-serving stack, HTTP adapter, HF-named tensor sets with split q/k/v,
flattened-bucket serialization, real-safetensors checkpoint writer). Underscore
prefix so pytest does not collect it; imported after importorskip('torch').
- tests/test_weight_update_model.py: model-layer primitives + pure unit tests
(update by name, atomic validate-then-copy, dry-run no-mutation, bucket
round-trip, HF->logical name mapping). [5]
- tests/test_weight_update_disk.py: update_weights_from_disk executor/HTTP +
get_weights_by_name + guards (swap/version/cache/abort, incompatible-config
reject, no-engine guard, 200/400/403). [10]
- tests/test_weight_update_tensor.py: colocate path -- facade/worker delegation,
HTTP route, slime chunked + empty-bucket partial semantics, in-flight guard,
pickle-RCE allowlist (canary), malformed-400, real CUDA-IPC cross-process
round-trip. [9]
- tests/test_weight_update_coordination.py: pause/continue/flush_cache/
get_weight_version + the full slime HTTP flow + gating + flush-400. [4]
All 28 pass; broader serving suites green.
Signed-off-by: gameofdimension <[email protected]>
Co-Authored-By: Claude Code
Co-Authored-By: GLM-5.2
|
@shijieliu @cb521 Do the training support features introduced in this PR align with your roadmap? |
|
@gameofdimension Hi THX for your feedback. Could we either reject new inference requests with HTTP 503 while generation is paused, or guarantee that no new traffic will be routed to the server during a weight update, or have a backup weight to response cusromers' request? I am worried about that new requests will queue in the queue for too long, causing timeout. |
Addresses PR NVIDIA#444 review (cb521): while paused for a weight update, new inference requests were still accepted (HTTP 200) and silently queued in the worker's pending buffer / scheduler waiting queue. Because the worker skips ticks while is_paused, those requests cannot progress until continue_generation, risking client-side timeouts. - worker.py: add is_paused proxy so the HTTP adapter (which holds the worker as its facade) can read the executor's pause state. - http.py: /submit, /submit_many, and /generate now reject with 503 (code=paused, retryable) when paused; /ready reports a "paused" reason so a polling load balancer can drain traffic during the update window. - tests: unit test (bare scheduler) + end-to-end test (real worker, pause_generation over HTTP) covering 503 admission, /ready, recovery. Co-Authored-By: Claude <[email protected]>
Addresses PR NVIDIA#444 review (cb521): while paused for a weight update, new inference requests were still accepted (HTTP 200) and silently queued in the worker's pending buffer / scheduler waiting queue. Because the worker skips ticks while is_paused, those requests cannot progress until continue_generation, risking client-side timeouts. - worker.py: add is_paused proxy so the HTTP adapter (which holds the worker as its facade) can read the executor's pause state. - http.py: /submit, /submit_many, and /generate now reject with 503 (code=paused, retryable) when paused; /ready reports a "paused" reason so a polling load balancer can drain traffic during the update window. - tests: unit test (bare scheduler) + end-to-end test (real worker, pause_generation over HTTP) covering 503 admission, /ready, recovery. Co-Authored-By: Claude <[email protected]>
Nice catch! That's definitely a bug. I'll get it fixed. |
|
After the pause,
new requests will no longer be accepted.
|
Description
Summary
Adds online weight hot-update to the sid-gr-inference serving engine so it can
act as the rollout engine for RL frameworks (target: slime), mirroring SGLang's
weight-sync API surface. Weights can now be swapped in place without a process
restart, either from an on-disk HF checkpoint (cross-process) or from
CUDA-IPC tensor payloads pushed by a colocated trainer (zero-copy, same GPU).
Endpoints (all gated behind
--allow-weight-update/GR_ALLOW_WEIGHT_UPDATE=1)POST /update_weights_from_disk— validate-then-load an HF checkpoint in place(structural config check + full logical-tensor validation before any copy, so a
bad checkpoint leaves the previous policy intact)
POST /update_weights_from_tensor— receive SGLangMultiprocessingSerializer/
FlattenedTensorBucketpayloads (load_format="flattened_bucket"or direct);CUDA tensors arrive as IPC handles and are remapped by device UUID, vendored
from SGLang (
weight_ipc.py, Apache-2.0, attributed)POST /pause_generation(abort/retract/in_place),POST /continue_generation,GET|POST /flush_cache,GET /get_weight_version,GET|POST /get_weights_by_name—SGLang-compatible coordination surface; supports slime's flow
pause_generation → flush_cache → update_weights_from_* → continue_generationDesign notes
POST per chunk) plus empty alignment buckets, so the tensor path validates +
copies only the tensors present in each payload (per-chunk, like SGLang's
model.load_weights); an empty bucket is a no-op. Full all-or-nothing atomicvalidation stays on the disk path.
(
q/k/v_proj,gate/up_proj); the logical loader packs them into the fusedqkv_proj/gate_up_projparameters, so split tensors may arrive across chunks.abort_all_requests=true(HTTP 409) — updating mid-decode would mix old KVwith new weights. In-place copies keep captured CUDA graphs valid.
flush_cachereturns 400 while requests are running/waiting (SGLang semantics;drives slime's retry loop). The weight-update surface is opt-in
(
allow_weight_updatedefaults toFalse).weight_version/token_stepbookkeeping surfaced in/statusand/metrics(superset of upstream; slime only sends
weight_version).Testing
tests/test_weight_update.py, incl. a real cross-process CUDA IPCround-trip (spawn producer →
ForkingPickler+ device-UUID remap → reconstructvia CUDA IPC), chunked-push application, per-chunk validate-then-copy atomicity,
disk swap + incompatible-config rejection, HTTP gating (400/403/409), and the
full slime coordination flow.
Checklist