Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: NVIDIA/recsys-examples
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v26.06
Choose a base ref
...
head repository: NVIDIA/recsys-examples
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: v26.07
Choose a head ref
  • 8 commits
  • 163 files changed
  • 5 contributors

Commits on Jul 22, 2026

  1. Reduce decode CUDA-graph memory with shared pool and shared logits bu…

    …ffer (#439)
    
    * Reduce SID-GR decode CUDA-graph memory with shared pool and shared logits buffer
    
    Capturing the SID-GR decode CUDA graph at beam_width=1024 reserved a
    private CUDA-graph memory pool and a [batch, beam, vocab] logits tensor
    per captured graph (~30 entries), raising idle GPU memory from ~24 GiB to
    ~45 GiB and OOM-ing decode at the configured beam width. Both are fixed
    without changing any computation, so outputs are numerically unchanged.
    
    1. Shared graph private pool (CudaGraphCacheMixin)
       The prefill piecewise runner already shared one graph_pool_handle()
       across its captures; the decode runner did not and got a fresh private
       pool per capture. Hoist the lazy handle + pool= kwargs + env opt-out
       onto CudaGraphCacheMixin (deduplicating the two runners' identical
       helpers), and have each runner set a _separate_pools_env class
       attribute. Decode captures now reuse one pool instead of ~30.
       Opt-out: GR_INFERENCE_DECODE_CUDA_GRAPH_SEPARATE_POOLS /
                GR_INFERENCE_PREFILL_CUDA_GRAPH_SEPARATE_POOLS.
    
    2. Shared logits output buffer
       lm_head logits ([batch, beam, vocab], ~batch*297 MiB at beam=1024) were
       held once per captured graph. Add an out= path to _linear_project
       (matmul out= into a caller buffer) and a logits_out= arg to
       forward_decode_step; the decode runner allocates one buffer per
       (active_beam_width, bucket) and writes every captured graph's logits
       into it, so the tensor lives once per shape rather than once per graph.
       Opt-out: GR_INFERENCE_DECODE_CUDA_GRAPH_SEPARATE_LOGITS.
    
    New /status fields: decode_cuda_graph_shared_pool,
    decode_cuda_graph_shared_output_buffers.
    
    Measured on NVIDIA L20 46GiB (beam=1024, context_len=4000):
    - idle after warmup: 45.4 -> 26.9 GiB (graph overhead ~21 -> ~3 GiB).
    - beam=1024 decode that previously OOM'd now succeeds.
    - graph-ON output_ids match the eager (graph-OFF) baseline token-for-token
      across single / batch2 / batch4 (24/24, 0 mismatch); replays confirm the
      shared path is hit.
    
    Tests: 9 CPU unit tests added (test_cuda_graph_shared_pool.py,
    test_decode_shared_logits.py) covering the pool-sharing helper (opt-out,
    handle reuse, dedup contract) and the shared-logits buffer (_linear_project
    out= correctness, per-(beam,bucket) caching).
    
    Signed-off-by: gameofdimension <[email protected]>
    Co-Authored-By: Claude Code
    Co-Authored-By: GLM-5.2
    
    * Free shared logits buffer when its decode shape is evicted
    
    The shared logits cache (_shared_logits, keyed by (beam_width, bucket)) is
    independent of the graph LRU, so a buffer allocated for a decode shape stayed
    resident for the runner lifetime after _store_graph() evicted the last graph
    using it. A transient large capture (high beam/bucket) could thus leave its
    [bucket, beam, vocab] tensor resident and re-grow idle memory after eviction,
    undermining the memory bound this change adds.
    
    Override _store_graph in GRDecodeCudaGraphRunner: after the base store (which
    performs LRU eviction), drop shared logits buffers whose (beam_width, bucket)
    shape has no live graph entry, tying buffer lifetime to graph lifetime.
    
    Tests: two CPU tests in test_decode_shared_logits.py — eviction frees the
    orphaned buffer, and a shape shared by multiple graphs is kept until its last
    graph is evicted.
    
    Signed-off-by: gameofdimension <[email protected]>
    Co-Authored-By: Claude Code
    Co-Authored-By: GLM-5.2
    
    * Keep shared logits buffer for the just-captured entry when caching is off
    
    With GR_INFERENCE_DECODE_CUDA_GRAPH_MAX_ENTRIES <= 0, the base _store_graph()
    clears _graphs and returns without retaining the newly captured entry, so the
    override's live_shapes set was empty and it deleted the shared logits buffer
    that _capture had just wired into entry.output. The buffer itself was not freed
    (the caller's immediate replay still reaches it via entry.output, which holds
    the same tensor), but the cache entry was dropped on every capture -- defeating
    per-shape reuse under max_entries=0 and leaving the override's correctness
    dependent on that external reference.
    
    Always add the just-stored entry's (beam_width, bucket) to live_shapes so its
    output buffer stays in the cache through the immediate replay regardless of
    whether the base store retained the entry. A no-op for max_entries > 0, where
    the entry is already live.
    
    Tests: test_shared_logits_buffer_kept_for_just_captured_entry_when_caching_disabled
    covers the max_entries=0 path (fails without this change).
    
    Signed-off-by: gameofdimension <[email protected]>
    Co-Authored-By: Claude Code
    Co-Authored-By: GLM-5.2
    
    ---------
    
    Signed-off-by: gameofdimension <[email protected]>
    gameofdimension authored Jul 22, 2026
    Configuration menu
    Copy the full SHA
    cf4588d View commit details
    Browse the repository at this point in the history

Commits on Jul 23, 2026

  1. Refactor KV Cache Manager with a new torch exportable KVCache backend (…

    …#400)
    
    * Refactor KV cache backend split
    
    Introduce KVCacheBackend, split the default Python backend from the public KVCacheManager facade, and add the initial export lookup path.
    
    * Add export kvcache design outlines (temp)
    
    * Support AOTI-compatible recsys kvcache ops
    
    * Add end-to-end AOTI support for HSTU+KV-Cache inference
    
    * Support PyTorch export and AOTI compile/package with test coverage.
    * Support C++ Torch runtime validation for AOTI-compiled KV-cache graphs.
    * Support Triton Inference Server validation using the PyTorch AOTI backend.
    * Add required KV-cache/runtime/custom-op plumbing and export fake-op shims.
    
    * Refactor KV-cache export/runtime cleanup and document AOTI flows
    
    * extract and simplify HSTU KV-cache export wrapper
    * remove stale debug instrumentation and export bring-up prints
    * standardize macro-gated logging in KV-cache runtime/binding/client code
    * rename AOTI ordering placeholder tensors consistently
    * clean C++ replay demo logging and CUDA check behavior
    * document end-to-end HSTU KV-cache AOTI C++ and Triton Server workflows
    
    * Updated the documents for KVcache with aoti support
    
    * Update Dockerfile with full aoti build
    
    * Fix pytorch Dockerfile
    
    * Fix Docker
    
    * Support SM120 for hstu inference
    
    * Setup folder for aoti related impl, and fix rebase conflicts
    
    * Fix hstu kernel build for aarch64.
    
    * Add code cleanup
    
    * Rename `offload_flush` api
    
    * Code cleanup
    
    * Fix CI tests
    
    * Fix review errors
    
    * Fix CI error
    
    * Update to formal fbgemm_hstu branch
    
    * Cleanup kvcache server env var
    
    * Fix CI error
    
    * Fix CI error
    
    * Fix CI error
    
    * Update readme for inference_aoti
    
    * Fix review error
    
    * Fix review error
    
    * Update documents with benchmark results
    
    * Update the readme and doc
    
    * Add tritonserver python backend as baseline
    
    * Apply code and document cleanup
    
    * Fix review errors
    geoffreyQiu authored Jul 23, 2026
    Configuration menu
    Copy the full SHA
    43465ae View commit details
    Browse the repository at this point in the history

Commits on Aug 6, 2026

  1. Feat/dynamicemb Implementation of LFU_DECAY by costimized JIT function (

    #437)
    
    * feat(dynamicemb): LRU_LFU score strategy with JIT custom eviction
    
    Express LRU+LFU eviction through the compound score strategy
    (TIMESTAMP, LFU) (either tuple order): word0 = last-access timestamp,
    word1 = frequency. By default eviction ranks by frequency with an
    older-timestamp tiebreak; it can be fully customized via a user-supplied
    score_function.
    
    - score_function(scores, cur_timestamp) -> float64 is numba-compiled to
      LTO-IR and nvJitLink-linked into a prebuilt custom eviction cubin at
      registration time; the driver launches it for all 2-word eviction.
    - The default path uses a prebuilt Lex (frequency -> older-timestamp)
      comparator cubin -- no numba required.
    - Users index `scores` in logical (tuple) order; subscripts must be
      integer constants and are statically remapped to physical device words
      via score_dump_permutation, so (LFU, TIMESTAMP) works transparently.
    - Custom cubins are cached per (device, function, score order).
    
    Two prebuilt fatbins (Lex + custom) are compiled per-arch at build time
    and shipped as package_data.
    
    Tests: 18 table-level tests including whole-set eviction oracles for the
    default timestamp tiebreak, custom decay, logical!=physical remap, and an
    end-to-end BatchedDynamicEmbeddingTablesV2 path.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * fix(dynamicemb): route plain insert's LruLfu eviction through the cubin
    
    A full bucket can be evicted by the plain insert path (table_insert), not
    just insert_and_evict. That path used DefaultEvictor -> the single-score
    reduce(), which cannot read the 2-word AoS LruLfu layout, so a plain insert
    that overflowed a bucket would pick a garbage victim (and ignore any custom
    score_function). Only insert_and_evict was wired to the eviction cubin.
    
    Route the num_scores==2 plain-insert eviction through the same cubin:
    
    - Factor table_insert_kernel's body into insert_body<Table,KernelTraits,Evictor>
      so both the AoT kernel (DefaultEvictor) and the cubin (RankedEvictor<Comparator>)
      share it.
    - Add a third cubin entry dyn_emb_insert_entry (reuses EvictParams; collects no
      evicted output) + demb_get_insert_fn(); resolved/cached like the evict entries.
    - launch_table_insert_kernel routes PolicyType==LruLfu to the cubin (default Lex
      when score_fn_key==0, else the custom evictor); thread score_fn_key through
      table_insert and ScoredHashTable.insert().
    
    The plain insert still drops the evicted key (unchanged semantics) but now
    selects the correct victim (freq->ts tiebreak by default, or the custom decay).
    
    Test: table.insert() overflowing a full bucket with _evict_high_freq_first must
    evict the hot keys (DefaultEvictor would have kept them).
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * fix(dynamicemb): align fatbin nvcc flags + close jit_link leak paths
    
    - compile_evict_fatbins: add --expt-relaxed-constexpr / --expt-extended-lambda
      so the fatbin TU compiles kernels.cuh (<cub/cub.cuh>, cooperative_groups) with
      the same flags as the main extension build, avoiding cross-CUDA-version skew.
    - jit_link.cpp load_from_image: cuModuleUnload the just-loaded module if any
      cuModuleGetFunction fails, instead of leaking it.
    - jit_link.cpp link_custom: destroy the nvJitLinkHandle on every exit path via
      an RAII guard (jl_check / load_from_image can throw), instead of leaking it
      when linking fails.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * fix(dynamicemb): pin score_function return type to float64
    
    cuda.compile was given only the argument types, so numba inferred the return
    type from the body. A score_function returning an integer expression (e.g.
    `return -scores[1]` without a float() cast) would compile to an integer-register
    return, which the C++ `extern "C" __device__ double user_score_fn(...)` caller
    reads as junk double bits -- a silent miscompile that degrades eviction to an
    arbitrary order. Pin the signature to float64(CPointer(uint64), uint64) so numba
    casts the return value to double instead.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * docs(dynamicemb): sync LruLfu comments/doc with the as-built code
    
    - evict_lrulfu.cu header: three entry points (evict ovf/noovf + plain insert),
      reuses insert_body too -- not "two entry points, insert_and_evict_body only".
    - score_jit.py docstring: register_score_function takes (cc_major, cc_minor).
    - lru_lfu_score_strategy_design.md: replace the stale "no code written yet"
      status with an as-built banner (compound tuple instead of an LRU_LFU enum, no
      gamma, three cubin entries, plain insert also routes through the cubin);
      keep the body as the original design rationale, code is the source of truth.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * docs(dynamicemb): document customized score_function + example
    
    - DynamicEmb_APIs.md: add a "Customized eviction via score_function" section
      under DynamicEmbScoreStrategy (signature, logical-order indexing, numba-cuda
      requirement, worked example) and a score_function field entry under
      DynamicEmbTableOptions. Make the constraint explicit: score_function is
      supported ONLY for the two-word {TIMESTAMP, LFU} compound (scores length 2);
      any other score_strategy with a score_function raises ValueError.
    - example/example.py: add an example lru_lfu_decay_score (time-decayed LFU) and a
      --score_strategy {step,timestamp,lru_lfu} flag that wires the compound
      (TIMESTAMP, LFU) tuple + score_function into DynamicEmbTableOptions.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * docs(dynamicemb): rewrite LruLfu design doc to reflect the as-built code
    
    Scrub the remaining proposal-era divergences so the design doc describes the
    shipped implementation (code stays the source of truth), keeping the rationale:
    
    - Drop `lfu_decay_gamma` and the `(scores, cur_timestamp, gamma)` signature
      everywhere; the score_function is `(scores, cur_timestamp) -> float64` with any
      decay constant written in the body.
    - No `LRU_LFU` enum: the strategy is the compound `(TIMESTAMP, LFU)` tuple;
      update the goal, API, example, and component table accordingly.
    - score_function indexes `scores` in logical (tuple) order with a static
      logical→physical remap (not "zero remapping").
    - Three cubin entries (`dyn_emb_evict_entry_ovf`/`_noovf` + `dyn_emb_insert_entry`)
      and plain insert also routes through the cubin (two call sites); fix the ABI
      struct (no gamma field), §11 entry/launch text, and the build-check.
    - cuda.compile pins the float64 return type; module cache keyed by (device, key).
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * docs(dynamicemb): README custom score_function + emphasize multi-score/order
    
    - README.md: add a "Customized Eviction Score" section under Usage Notes (compound
      (TIMESTAMP, LFU) + score_function example, numba-cuda requirement, pointer to the
      API doc).
    - DynamicEmb_APIs.md: add a "Compound (multi-score) strategies and score order"
      section that spells out, in user-facing terms, that a compound strategy keeps
      more than one score per key and that the tuple order controls two things that
      always agree — the score column order dumped to file, and how score_function
      indexes scores — while eviction is identical either way. Reword the
      score_function / score_strategy text to drop implementation details.
    - lru_lfu_score_strategy_design.md: fold in the remaining LRU_LFU -> compound-tuple
      precision fixes (LruLfu spec/strategy/table naming, device-keyed cache) that the
      prior design-doc rewrite commit missed.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * fix(dynamicemb): harden LruLfu eviction (NaN score clamp + num_scores guards)
    
    Two cheap defensive guards on the JIT eviction path:
    
    - UserFnComparator::rank clamps a NaN user score to -inf (evict-first). A NaN
      compares false against every candidate, so it could never be picked as the
      eviction minimum, and an all-NaN bucket would find no victim and silently drop
      the incoming key. Clamping keeps eviction deterministic and inserts progressing.
      Document the finite-return contract (comparator header + API doc).
    - reduce()/reduce_ranked() assert num_scores_ == 1 / == 2 respectively, so a
      misrouted call fails loud instead of silently misreading the layout (nvcc is not
      built with -DNDEBUG, so the device assert is live). Guards a future regression;
      after the plain-insert routing both paths already send num_scores==2 to the cubin.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * fix(dynamicemb): make score_function_key arch-aware (heterogeneous multi-GPU)
    
    score_function_key ignored the device compute capability, so on a single process
    driving GPUs of different arch the custom score_function registered only the first
    device's numba LTO-IR (the Python _registered_keys dedup short-circuited the
    others). A later different-arch device then linked that LTO-IR under the wrong
    -arch and cuModuleLoadData failed on its first custom-eviction insert.
    
    Include cc in the key so each arch gets a distinct key -> its own numba compile
    and C++ registration (cc is already stored per key, so link_custom picks the right
    -arch). No C++ change needed. Same-arch devices still share one key/compile with
    the module cached per device, so homogeneous setups are unaffected.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    ---------
    
    Co-authored-by: Claude Opus 4.8 <[email protected]>
    jiashuy and claude authored Aug 6, 2026
    Configuration menu
    Copy the full SHA
    2b7cac7 View commit details
    Browse the repository at this point in the history
  2. Add SGLang-compatible weight hot-update (disk + colocate CUDA-IPC) fo…

    …r RL integration with slime (#444)
    
    * Add Qwen3GRModel weight-update primitives
    
    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
    
    * Executor: weight hot-update from disk/tensor + cache invalidation
    
    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
    
    * Facade + Worker: weight-update delegation
    
    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
    
    * HTTP: /update_weights_from_disk + /get_weights_by_name (Slime-aligned)
    
    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
    
    * Tests: online RL weight hot-update
    
    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
    
    * Add SGLang-compatible disk coordination endpoints
    
    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
    
    * Fix test_real_weight_tiny_tool for allow_weight_update arg
    
    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
    
    * Add /update_weights_from_tensor (colocate CUDA-IPC, SGLang-compatible)
    
    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
    
    * Fix colocate tensor endpoint for slime chunked push
    
    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
    
    * Address review: pause docstring, secure default, in-flight guard
    
    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
    
    * Address review: flush_cache/get_weights_by_name alignment, test hardening, 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
    
    * Reframe weight-sync docs: trainer<->this engine; SGLang is the format 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
    
    * Address Greptile review: pickle allowlist (P1 RCE), errors->400, reduce guard, metric rename
    
    PR #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
    
    * Refactor: split test_weight_update.py into a helpers module + 4 files
    
    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
    
    * Reject inference requests (503) while generation is paused
    
    Addresses PR #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]>
    
    * Add weight hot-update user guide
    
    ---------
    
    Signed-off-by: gameofdimension <[email protected]>
    Co-authored-by: Claude <[email protected]>
    gameofdimension and claude authored Aug 6, 2026
    Configuration menu
    Copy the full SHA
    175bd98 View commit details
    Browse the repository at this point in the history
  3. Updated AOTI benchmarks (#448)

    * Refine the aoti implementations and benchmarks
    
    * Update the benchmark results
    
    * Updated the bench results
    
    * Update the benchmark readme
    
    * Update the benchmark readme
    
    * Fix KV-cache sequence length dtype
    
    * Fix default batch size
    geoffreyQiu authored Aug 6, 2026
    Configuration menu
    Copy the full SHA
    3118b5f View commit details
    Browse the repository at this point in the history

Commits on Aug 10, 2026

  1. Feat/dynamicemb retain evicted keys (#443)

    * feat(dynamicemb): retain evicted keys at last tier + pop_evicted_keys API
    
    Add an opt-in retain_evicted_keys table option so the last-tier storage records the keys it evicts (instead of silently dropping them), plus a pop_evicted_keys API to read them back per table, unique and incrementally.
    
    C++: insert_body gains a CollectEvicted template sink that compacts each Evict victim's (key, table_id); wired through a new AoT table_insert_collect_kernel and a dyn_emb_insert_collect_entry LruLfu cubin entry (reusing EvictParams, no ABI change), exposed as table_insert_collect_evicted. Covers all score policies. Only InsertResult::Evict is collected, not Busy.
    
    Python: retain_evicted_keys config (in get_grouped_key so retain-differing tables don't share storage); the last-tier state accumulates evicted (key, table_id) chunks, de-duplicated only on pop; DynamicEmbStorage / HybridStorage pop_evicted_keys; module- and model-level pop_evicted_keys with optional pg all_gather (else per-rank local, disjoint). Design doc under docs/.
    
    Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
    
    * test(dynamicemb): retain_evicted_keys suite + fix HBM-direct forward retain gap
    
    Non-caching training forward inserts through _prefetch_hbm_direct_path, which calls key_index_map.insert() directly (bypassing _insert_key_values), so its last-tier eviction was never retained. Add the collect_evicted branch there too. (Prefetched keys are ref-counter protected, so eviction only materializes across forward+backward steps.)
    
    New self-contained suite under test/unit_tests/retain_evicted_keys/ (12 cases): table (whole-set oracle for insert(collect_evicted=True) on LruLfu cubin + AoT, table_id routing, no-eviction, determinism raise); storage (DynamicEmbStorage end-to-end collect->pop unique->gone->incremental, retain=False empty, dedup/table_id-filter/clear-isolation unit); module (HBM-direct training retains = the gap above, disabled omitted, table_names filter); distributed model (row-wise sharded: pg=None disjoint per rank / pg union). Wired into unit_test.sh (fwd_bwd group).
    
    Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
    
    * docs(dynamicemb): translate retain_evicted_keys_design.md to English
    
    Also sync a few stale spots to the as-built code: retain buffers are tensor chunk lists (not ExtendableBuffer), pop returns host tensors, tests live under test/unit_tests/retain_evicted_keys/ (distributed test included), and the API lives in incremental_dump.py.
    
    Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
    
    * feat(dynamicemb): return DeltaDumpResult map from incremental_dump
    
    Refactor incremental_dump's return from (ret_tensors, ret_scores) to
    Dict[collection_path, DeltaDumpResult], packing per-collection
    column-aligned lists (table_names/keys/values/evicted_keys/meta) with a
    slot_index that pins each key to its physical row for a future precise
    replay_increment.
    
    - slot_index encoding: single-tier normal = key_slot (== value row);
      NO_EVICTION = (key_slot << 32) | value_row; HybridStorage = bit63 tier
      | bits0-62 key_slot.
    - HybridStorage + NO_EVICTION now raises (non-caching partial-HBM storage
      cannot host the NO_EVICTION auto-increment score policy).
    - pop_evicted_keys returns a host tensor (CUDA-accelerated internally).
    - incremental_dump accepts an optional pg; keys/values/evicted/slot_index
      are all_gathered within it (dist_type "continuous" unsupported -> raise).
    - meta.world_size records the table's ROW_WISE shard fan-out (global
      dist.get_world_size(), which equals input_dist's pg.size()).
    - Tests: DeltaDumpResult adaptations, HybridStorage tier slot_index test,
      skip NO_EVICTION+partial-HBM combo; docs: DeltaDumpResult design +
      DynamicEmb_APIs updates.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * fix(dynamicemb): make hybrid tier slot_index test world_size-agnostic
    
    test_hybrid_incremental_dump_slot_index_tier inserted a fixed 256 keys and
    asserted both tiers contribute dumped keys. But the HBM tier's per-rank
    capacity is global_capacity / world_size, so on a single GPU (world_size 1)
    the HBM tier holds all 256 keys, nothing is evicted, and the host tier stays
    empty -> the "host tier must contribute dumped keys" assert fails. The test
    only passed at world_size >= 2.
    
    Derive the insert count from the actual HBM capacity instead:
    n = hbm_cap + min(hbm_cap, host_cap). This fills the HBM tier and overflows
    enough to guarantee a spill into the host tier on any world_size. Verified
    passing on both nproc=1 and nproc=2.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * style(dynamicemb): apply black formatting via pre-commit
    
    Run black 23.9.1 (pre-commit) over the dynamicemb files this branch adds or
    modifies -- pure formatting, no logic changes. They were committed earlier
    without running black (local dev had no pre-commit hook).
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * docs(dynamicemb): fix stale need_incremental_dump refs + guard score_function closures
    
    Small PR#437-debt cleanups (these files landed via #437; touched here because
    this branch builds directly on them):
    
    - score.cuh: the LruLfu comment said tables are "created with
      need_incremental_dump=True", but that parameter no longer exists -- they are
      created with a compound (TIMESTAMP, LFU) score_strategy.
    - lru_lfu_score_strategy_design.md: replace all 13 stale need_incremental_dump
      references (a removed parameter, incl. a wrong get_score_policy signature)
      with the actual "(TIMESTAMP, LFU) / existing incremental-dump LruLfu" terms.
    - score_jit.py: _remap_score_function recompiles against fn.__globals__ only,
      silently dropping closure captures, so a factory/closure score_function later
      failed with an opaque numba NameError. Reject co_freevars up front with a
      clear ValueError. Verified on EOS: closure raises, plain fns unaffected,
      test_lru_lfu 19 passed.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * fix(dynamicemb): keep pop_evicted_keys empty/non-empty dtype consistent
    
    _pop_state_evicted_keys' empty guard hardcoded torch.int64, but the non-empty
    path returns torch.cat(chunks) whose dtype is key_index_map.key_type (== the
    table's index_type, which can be int32/uint32). For int32-key tables the two
    paths returned different dtypes, so a caller concatenating or comparing across
    empty and non-empty pops would hit a RuntimeError. Return
    state.key_index_map.key_type from the empty guard -- the same dtype the
    non-empty path carries.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * docs(dynamicemb): note incremental_dump does not support continuous dist_type
    
    incremental_dump's slot_index targets precise replay_increment, which
    reconstructs each key's owning rank via (key or hash(key)) % world_size --
    only defined for roundrobin / hash_roundrobin. A table sharded with
    dist_type="continuous" uses a range-based key->rank mapping this path does not
    implement and raises NotImplementedError. Document the limitation in the
    incremental_dump API section.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    * refactor(dynamicemb): replace retain_evicted_keys bool with EvictedItemMode enum
    
    Replace the boolean DynamicEmbTableOptions.retain_evicted_keys with an
    extensible enum EvictedItemMode { DISCARD (default), RETAIN_KEY }, leaving room
    for future modes (e.g. RETAIN_VALUE) without another API change. Unreleased in
    this branch, so no bool alias -- all usages updated: config (enum + field +
    get_grouped_key), state field + branches (key_value_table,
    batched_dynamicemb_{tables,function}), scored_hashtable message,
    incremental_dump docstrings, __init__ export, the three retain tests, and the
    API + design docs.
    
    Also finalizes the empty-pop dtype test from the earlier dtype fix (d53eb76):
    parametrized int64/uint64, empty-only -- a uint64 table's non-empty pop hits
    torch's unimplemented UInt64 GPU indexing, tracked separately.
    
    Verified on EOS: retain suite 8 + 5 + 1 passed.
    
    Co-Authored-By: Claude Opus 4.8 <[email protected]>
    
    ---------
    
    Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
    jiashuy and claude authored Aug 10, 2026
    Configuration menu
    Copy the full SHA
    9a3bf5d View commit details
    Browse the repository at this point in the history

Commits on Aug 12, 2026

  1. Fix hstu inference cudagraph capture on sm100 (#463)

    * Fix hstu inference cudagraph capture on sm100
    
    * Add fix for inference utest
    
    * Clean up code format
    geoffreyQiu authored Aug 12, 2026
    Configuration menu
    Copy the full SHA
    15b4184 View commit details
    Browse the repository at this point in the history

Commits on Aug 13, 2026

  1. release v26.07 (#464)

    shijieliu authored Aug 13, 2026
    Configuration menu
    Copy the full SHA
    6b94bbf View commit details
    Browse the repository at this point in the history
Loading