Repository navigation
Studio: faster Laya inference (marker-only head, CUDA graphs) - #12224
Conversation
laya builds a randomly initialised fp32 encoder and then loads the checkpoint over it. For mmBERT's 256000 x 768 embedding that throwaway init alone needed about 3.2 GB of scratch RAM and 8 s, so loading a Laya model peaked at about 4.5 GB of host RAM even though it settles at about 1.7 GB. laya_runtime now builds the encoder with a placeholder vocabulary and swaps in an embedding created with torch.nn.utils.skip_init, in the dtype it will be served in, while laya's own strict load_state_dict fills every parameter from the checkpoint. The rest of the model, including the rotary buffers the checkpoint does not carry, is built as before. The swap goes through laya's private build_model hook under a lock and is always restored; the vendored laya files are unchanged. Load peak drops from 4.49 GB to 2.38 GB and load time from about 17 s to about 8.5 s, with every parameter and buffer identical to stock laya.load and logits bit-identical on CPU and CUDA.
The torch-less pytest legs (macOS staging) ran two of the new tests without a torch guard, so they failed with ModuleNotFoundError instead of skipping.
The placeholder was sized to hold every special token id, which for the ModernBERT-large checkpoints (laya-english, laya-typed-decisions, pad id 50283) kept it at 50284 of 50368 rows, so their embedding was still randomly initialised. Build it with one row and a stand-in padding id instead, check the placeholder was sized and padded from the config, and take padding_idx from the real config. English checkpoints now load in 13.4 s instead of 17.3 s, with every tensor identical to stock laya.load.
Short requests were launch-bound: about 2.5 ms of GPU work inside a 12 ms forward. Three changes, all in laya_runtime (the vendored laya is untouched): - The scorer only reads the option markers, so the last head layer runs its queries, residual and FFN at the markers alone (keys and values still span every token), through F.scaled_dot_product_attention, and the unused action head is skipped. Logits match laya's forward to 2e-6 in fp32. - CUDA graphs per padded (rows, tokens, options) bucket in one shared pool, capped at min(1 GiB, 10% of free memory), up to 8192 padded tokens; larger batches and stacks that cannot be captured run eagerly. - Collation fills numpy arrays instead of per-row tensor copies. UNSLOTH_SYSTEMONE_FAST=0 restores laya's forward and UNSLOTH_SYSTEMONE_CUDA_GRAPHS=0 turns off only the graphs.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
# Conflicts: # studio/backend/core/systemone/laya_runtime.py # studio/backend/tests/test_systemone.py
|
@codex review |
|
@codex security review |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cff576aff7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| torch.cuda.current_stream(device).wait_stream(self.stream) | ||
| graph = torch.cuda.CUDAGraph() | ||
| # thread_local: CUDA work on other Studio threads cannot break (or be broken by) this capture. | ||
| with torch.cuda.graph(graph, pool = self.pool, capture_error_mode = "thread_local"): |
There was a problem hiding this comment.
Give independently replayed graphs separate memory pools
When requests populate more than one shape bucket, each graph is captured into the same private CUDA memory pool, but later requests replay those graphs in arbitrary bucket order. PyTorch only permits a shared graph pool when graphs are always replayed in capture order and never concurrently; _run_lock guarantees only the latter. A request sequence such as A, B, A can therefore reuse graph-private storage with invalid lifetimes and produce corrupted logits or CUDA failures. Use independent pools, or otherwise enforce a supported replay schedule.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The shared-pool caveat is about tensors that stay live between replays. Here the only such tensors are each graph's static inputs (allocated outside capture, so not in the pool) and its output logits, which are copied to the host under _run_lock right after that graph's replay and before any other graph runs. Intermediates are rewritten on every replay. test_cuda_graphs_sharing_a_pool_replay_in_any_order captures four buckets and replays them as A C B D D A B A C, each bit-identical to the same padded bucket run eagerly.
| and device.type == "cuda" | ||
| and os.environ.get("UNSLOTH_SYSTEMONE_CUDA_GRAPHS", "") != "0" |
There was a problem hiding this comment.
On ROCm hosts, hardware detection deliberately exposes the device as cuda, while core/inference/diffusion_cuda_graph.py explicitly records that ROCm has no usable graph capture here. This condition nevertheless constructs _CUDAGraphs, whose graph_pool_handle() and Stream calls occur before the guarded capture; on ROCm builds where those graph APIs are absent or unsupported, the first System One request raises rather than continuing with eager GPU inference. Check the actual backend before constructing the graph manager.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 77753e4: graphs are skipped when torch.version.hip is set, same as diffusion_cuda_graph.py. Test: test_rocm_never_builds_cuda_graphs.
| if len(self.graphs) >= self.MAX_GRAPHS or self.pool_bytes >= self.max_pool_bytes: | ||
| return None | ||
| before = torch.cuda.memory_reserved(self.agent.device) | ||
| try: | ||
| entry = self._capture(key) |
There was a problem hiding this comment.
Enforce the graph-pool limit after each capture
The limit is checked only before capture, so the first graph is always accepted and every later graph may overshoot max_pool_bytes by its entire allocation. For example, a model with less than 2 GiB free can set a sub-200 MiB limit but still retain the observed 200–500 MiB first graph pool, consuming headroom that eager requests or other Studio workloads need and potentially forcing subsequent inference onto CPU. Reject or release a capture when its measured post-capture pool size crosses the limit.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 77753e4: a capture that takes the pool past the budget now drops every graph (the shared pool is only released with all of them) and runs eagerly. Test: test_cuda_graphs_over_the_memory_budget_run_eagerly.
ROCm reports its GPUs as cuda, and Studio treats graph capture as CUDA only (diffusion_cuda_graph.py), so skip the graph manager there. A capture that takes the pool past its budget now drops every graph and runs eagerly, since a shared pool is only released with all its graphs. Adds a test replaying four buckets from the shared pool out of capture order, each bit-identical to the same padded bucket run eagerly.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…hai#12224) * Studio: load Laya without randomly initialising its vocabulary embedding laya builds a randomly initialised fp32 encoder and then loads the checkpoint over it. For mmBERT's 256000 x 768 embedding that throwaway init alone needed about 3.2 GB of scratch RAM and 8 s, so loading a Laya model peaked at about 4.5 GB of host RAM even though it settles at about 1.7 GB. laya_runtime now builds the encoder with a placeholder vocabulary and swaps in an embedding created with torch.nn.utils.skip_init, in the dtype it will be served in, while laya's own strict load_state_dict fills every parameter from the checkpoint. The rest of the model, including the rotary buffers the checkpoint does not carry, is built as before. The swap goes through laya's private build_model hook under a lock and is always restored; the vendored laya files are unchanged. Load peak drops from 4.49 GB to 2.38 GB and load time from about 17 s to about 8.5 s, with every parameter and buffer identical to stock laya.load and logits bit-identical on CPU and CUDA. * Skip the Laya build tests where torch is not installed The torch-less pytest legs (macOS staging) ran two of the new tests without a torch guard, so they failed with ModuleNotFoundError instead of skipping. * Skip the speculative Laya build when laya's builder will run anyway * Size the Laya placeholder vocabulary at one row The placeholder was sized to hold every special token id, which for the ModernBERT-large checkpoints (laya-english, laya-typed-decisions, pad id 50283) kept it at 50284 of 50368 rows, so their embedding was still randomly initialised. Build it with one row and a stand-in padding id instead, check the placeholder was sized and padded from the config, and take padding_idx from the real config. English checkpoints now load in 13.4 s instead of 17.3 s, with every tensor identical to stock laya.load. * Speed up Laya inference in the Decision API Short requests were launch-bound: about 2.5 ms of GPU work inside a 12 ms forward. Three changes, all in laya_runtime (the vendored laya is untouched): - The scorer only reads the option markers, so the last head layer runs its queries, residual and FFN at the markers alone (keys and values still span every token), through F.scaled_dot_product_attention, and the unused action head is skipped. Logits match laya's forward to 2e-6 in fp32. - CUDA graphs per padded (rows, tokens, options) bucket in one shared pool, capped at min(1 GiB, 10% of free memory), up to 8192 padded tokens; larger batches and stacks that cannot be captured run eagerly. - Collation fills numpy arrays instead of per-row tensor copies. UNSLOTH_SYSTEMONE_FAST=0 restores laya's forward and UNSLOTH_SYSTEMONE_CUDA_GRAPHS=0 turns off only the graphs. * Keep Laya CUDA graphs off ROCm and inside their memory budget ROCm reports its GPUs as cuda, and Studio treats graph capture as CUDA only (diffusion_cuda_graph.py), so skip the graph manager there. A capture that takes the pool past its budget now drops every graph and runs eagerly, since a shared pool is only released with all its graphs. Adds a test replaying four buckets from the shared pool out of capture order, each bit-identical to the same padded bucket run eagerly. --------- Co-authored-by: Nilay Yadav <[email protected]>
Makes Decision API inference faster without
torch.compile. Everything is instudio/backend/core/systemone/laya_runtime.py; the vendored laya stays byte-identical.Where the time went
I profiled Studio's
_predictpath on real checkpoints with the TypeSafe cookbook workloads (guardrail, briefing, classification):Changes
TransformerEncoderLayercomputes queries, the residual and the FFN at the markers alone, with keys and values still spanning every token. Attention goes throughF.scaled_dot_product_attentionwith a boolean mask (True means attend, the inverse ofsrc_key_padding_mask) anddropout_p=0.0. With no padding, the mask is dropped. The action head, which Studio never returns, is skipped.model(...).capture_error_mode="thread_local".collate_items, built from numpy arrays instead of per-row tensor copies.Kill switches:
UNSLOTH_SYSTEMONE_FAST=0restores laya's forward.UNSLOTH_SYSTEMONE_CUDA_GRAPHS=0turns off only the graphs.Results
Studio
_predictend to end, B200, fp16 policy, median ms per request, old path (UNSLOTH_SYSTEMONE_FAST=0) vs new, interleaved:Accuracy on 48 requests (1048 rounded API fields), measured against laya's own fp32 forward on CPU:
Tried and left out
torch._addmm_activationbias+activation epilogueF.linearFLASH_ATTENTIONhas no kernel with ModernBERT's mask; cuDNN is already the default here;EFFICIENT_ATTENTIONis slower on long inputs;MATHis 3x slowerTests
tests/test_systemone.py:model(...)._place, skip large batches, and honour the kill switch.98 passed, 3 skippedon transformers 4.57.6, 5.5.0 and 5.17.