Skip to content

Studio: faster Laya inference (marker-only head, CUDA graphs) - #12224

Merged
danielhanchen merged 7 commits into
mainfrom
laya-fast-infer
Sep 28, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
laya-fast-infer

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

Makes Decision API inference faster without torch.compile. Everything is in studio/backend/core/systemone/laya_runtime.py; the vendored laya stays byte-identical.

Where the time went

I profiled Studio's _predict path on real checkpoints with the TypeSafe cookbook workloads (guardrail, briefing, classification):

  • GPU, short requests: launch-bound. A 3x42 request took 12 ms, but the GPU was busy for only about 2.5 ms of that, across roughly 220 small kernels.
  • Everything else was small:
    • Allocation: 0.04% of CPU time.
    • Host post-processing (softmax, confidence): under 1%.
    • Host-to-device copy: 0.1 ms or less.
    • Collate: 1.7 ms on a 13x1024 batch.
  • Long inputs: the ModernBERT encoder dominates on both GPU and CPU. laya's two head layers are about 4% of the forward on GPU and about 15% on CPU.

Changes

  1. Marker-only last head layer. The scorer only reads the option markers. So the last TransformerEncoderLayer computes queries, the residual and the FFN at the markers alone, with keys and values still spanning every token. Attention goes through F.scaled_dot_product_attention with a boolean mask (True means attend, the inverse of src_key_padding_mask) and dropout_p=0.0. With no padding, the mask is dropped. The action head, which Studio never returns, is skipped.
    • Matches laya's forward to 2e-6 in fp32.
    • Any head that is not laya's pre-norm ReLU layer stack with a GELU scorer keeps model(...).
  2. CUDA graphs. One graph is captured per padded (rows, tokens, options) bucket, and all graphs share one pool.
    • Capture happens lazily after a warm-up on a side stream, with capture_error_mode="thread_local".
    • Graph memory is capped at min(1 GiB, 10% of free memory) and used up to 8192 padded tokens; past that the GPU is the bottleneck and padding costs more than launches save.
    • Moving or recasting the model, or the fp16 overflow rerun, drops the graphs.
    • On transformers 4.x, ModernBERT builds its sliding-window mask on the CPU every forward and cannot be captured. There the first failed capture turns graphs off for that model and it runs eagerly.
  3. Numpy collate. Produces the same tensors as collate_items, built from numpy arrays instead of per-row tensor copies.

Kill switches:

  • UNSLOTH_SYSTEMONE_FAST=0 restores laya's forward.
  • UNSLOTH_SYSTEMONE_CUDA_GRAPHS=0 turns off only the graphs.

Results

Studio _predict end to end, B200, fp16 policy, median ms per request, old path (UNSLOTH_SYSTEMONE_FAST=0) vs new, interleaved:

Checkpoint Guardrail, 3 questions Classification, 40 options Mixed 36-request set Briefing, 13 x 1024 tokens
multilingual 11.60 -> 2.83 (4.1x) 11.23 -> 3.48 (3.2x) 11.72 -> 2.84 (4.1x) 27.3 -> 26.3
english 13.56 -> 3.53 (3.8x) 13.10 -> 4.54 (2.9x) 13.58 -> 3.54 (3.8x) 24.0 -> 25.7 (noise, see below)
typed-decisions 13.10 -> 3.55 (3.7x) 12.91 -> 4.68 (2.8x) 13.31 -> 3.70 (3.6x) 48.3 -> 47.1
  • The long briefing batch runs eagerly. Its head is faster (1.86 -> 1.03 ms on the English checkpoint), but the roughly 42 ms encoder decides it.
  • Graph pool: 200 to 500 MiB per checkpoint.
  • CPU (fp16 policy on this host): 1.02x to 1.13x. The fp32 path: 1.02x to 1.22x.

Accuracy on 48 requests (1048 rounded API fields), measured against laya's own fp32 forward on CPU:

Max probability error, old Max probability error, new Changed answers, old / new
multilingual, CUDA fp16 0.0018 0.0022 0 / 0
english, CUDA fp16 0.0071 0.0068 1 / 1 (same near tie)
typed-decisions, CUDA fp16 0.0017 0.0016 0 / 0
multilingual, CPU fp16 0.0021 0.0021 0 / 0
multilingual, CPU fp32 0 0 0 / 0, all 1048 fields identical

Tried and left out

Idea Result
Native fp16 residual stream (no autocast) About the same speed once graphed, but the probability error goes from 1.8e-3 to 4.6e-3
Softmax, confidence and score on the device, one copy back No measurable gain (under 1%). The host path keeps the rounded API output exactly as before
torch._addmm_activation bias+activation epilogue No measurable gain over F.linear
SDPA backends FLASH_ATTENTION has no kernel with ModernBERT's mask; cuDNN is already the default here; EFFICIENT_ATTENTION is slower on long inputs; MATH is 3x slower
flash-attn 2 Not installed, and it has no sm100 kernels. Its varlen path would also rule out graphs
int8 dynamic quantization of the encoder on CPU 13% faster, but 30 of 36 answers flip
Pinned host memory The copy is 0.1 ms or less

Tests

  • New tests in tests/test_systemone.py:
    • The marker head matches laya's forward for 1, 2 and 3 head layers, padded and unpadded.
    • Unsupported heads and the kill switch keep model(...).
    • Collate matches laya.
    • CUDA graphs replay bit-identical logits to the same padded bucket run eagerly, replay new contents, are dropped on _place, skip large batches, and honour the kill switch.
  • Results: 98 passed, 3 skipped on transformers 4.57.6, 5.5.0 and 5.17.
  • Mutation check: passing no attention mask fails 4 of the new tests.

danielhanchen and others added 5 commits September 28, 2026 07:32
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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-28T21:38:00.107473Z 77753e4 Manual request
🔒 Security Review ✅ Completed 2026-09-28T21:18:30.635975Z cff576a Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 28, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 28, 2026
Base automatically changed from laya-fast-load to main September 28, 2026 21:03
# Conflicts:
#	studio/backend/core/systemone/laya_runtime.py
#	studio/backend/tests/test_systemone.py
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: cff576aff7

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +762 to +763
and device.type == "cuda"
and os.environ.get("UNSLOTH_SYSTEMONE_CUDA_GRAPHS", "") != "0"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Skip CUDA graph setup on ROCm

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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +1024 to +1028
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 77753e415f

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 4e8503e into main Sep 28, 2026
44 checks passed
@danielhanchen
danielhanchen deleted the laya-fast-infer branch September 28, 2026 23:57
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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]>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 29, 2026
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