Skip to content

feat(fast): --compile-scope layer, one compiled decoder layer instead of the whole model (opt-in; your call on the default) - #49

Merged
rkinas merged 5 commits into
rkinas:mainfrom
Butterski:perf/compile-per-layer
Nov 2, 2026

Conversation

@Butterski

@Butterski Butterski commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds an opt-in and changes nothing by default (--compile-scope model, today's path, is untouched). The
question for you is whether it should stay opt-in or become the default for basal-2.0. It changes probabilities by
bf16 rounding, so that decision is yours. The measurements below are meant to help with it; the numbers you would
need for a default (H100, compact rows, dev v2) I could not produce.

Why

--mode fast spends most of a cold start compiling: on an RTX 4060 Ti the first calls of the plain graphs are 504 of
basal-2.0-4.5B's 515 s of graph warm-up (phase timers below). Dynamo compiles the plain forward only twice over the
169 grid shapes (one row is specialised, then one dynamic graph), so the time is two Inductor compiles of the whole
60-layer model.

Change

--compile-scope layer (basal-serve, GraphBackend(compile="layer")): the plain forward runs the transformers
decoder layers one at a time (_forward_layered, the long lane's loop) through one compiled function
(_layer_call), so Dynamo traces one layer and reuses it for every layer and shape (2 compiled graphs on 32 or 60
layers, as the whole-model compile has; CPU test). Each layer's K / V buffers are passed alone (basal_layer_kv):
read through basal_kv[module.layer_idx], the compiled layer specialised on its index and Dynamo compiled it once per
layer (12 graphs for 6 layers). The embeddings, the rotary tables and the final norm run uncompiled; pass 2 is not
touched (it was uncompiled already), nor are compact rows (their template-prefix path selects keys by layer index;
they keep the whole-model compile). Where it is not measured it is refused before anything is loaded: FP8 / NVFP4
weights, Gemma 4, Qwen3.5, --lean, and the uncompiled modes.

How it differs from --lean on: lean is basal's own layer code for both passes (you measured 2.4-3.4x faster start-up
and 7-8% slower under load on an H100, HARDWARE.md). This compiles the same transformers modules today's compile
traces; what changes is only where Inductor may fuse (within a layer, not across the residual add into the next
layer's norm).

Measurements

RTX 4060 Ti 16 GB, torch 2.13.0+cu130, main = b20f0f9 (2.4.1). Per configuration: gpu_mem_probe.py with cold
compile caches (warm() timed, per-phase timers, the 420 identity readouts of basal.identity.build), then
basal-serve (its start reuses the probe's compile cache), basal-loadtest single questions and five questions over
1.5k-token states (32 clients, each run twice), and 10 requests (compress over 1.5k-6k tokens, 5-40 questions).

warm-up, cold caches of it, first calls (compiling) serve ready, warm cache GiB after warm-up single questions, dec/s 5 questions, q/s
mini, whole model (today) 235 s 229 s 159 s 8.38 65.1 / 65.0 28.0 / 28.1
mini, --compile-scope layer 95 s 88 s 89 s 8.21 63.8 / 63.1 28.1 / 28.1
mini, --lean on 111 s 107 s 96 s 6.68 56.8 / 63.2 27.8 / 27.6
4.5B, whole model (today) 515 s 504 s 373 s 15.38 19.5 / 21.2 9.64 / 9.65
4.5B, --compile-scope layer 251 s 239 s 247 s 15.38 20.2 / 19.0 9.69 / 9.69
4.5B, --lean on 277 s 260 s 260 s 15.39 18.7 / 19.4 9.54 / 9.58

Speed on this card: mini answers 2-3% fewer single questions per second per layer (63.1-63.8 against 65.0-65.1, a
gap larger than its runs' spread) and the same five-question load; the 4.5B is the same on both within run-to-run
noise (its whole-model runs alone: 19.5 and 21.2 decisions/s). Not measured: an H100, where your lean numbers show a
cost under load that this card may hide.

Answers, against the whole-model compile (and, for mini, against fp32 on the CPU: the packed engine, the same items):

identity readouts: same top answer max / mean |dp| top answers that change: margin under the whole-model compile against fp32: same top, mean |dp| 10 requests: decisions that change
mini, whole model 416 / 420, 4.8e-3
mini, layer 416 / 420 0.060 / 4.9e-3 0.009, 0.024, 0.004, 0.004 (fp32 sides with today on 3, with layer on 1) 414 / 420, 4.7e-3 3 of 446
mini, lean 414 / 420 0.047 / 5.0e-3 6, all under 0.05 414 / 420, 4.8e-3 5 of 446
4.5B, layer 418 / 420 0.045 / 4.3e-3 0.072, 0.011 (fp32 does not fit 16 GB) 0 of 446
4.5B, lean 418 / 420 0.049 / 4.4e-3 0.006, 0.011 (compress ran out of memory)

So per layer, the probabilities move as much as they differ from fp32 either way: rounding, not a different model.

What I am asking

  1. Keep it opt-in (merge as is): faster restarts for those who choose it, nothing changes for anyone else.
  2. Make it the default for basal-2.0 (everywhere, or off Hopper): about half the cold start on consumer GPUs. That
    needs your gate (H100 start-up and speed with compact rows, dev v2 decisions), and on Hopper the gain is partial
    until compact rows compile per layer too, which I would add in a follow-up if you want this.
  3. Not wanted: close it; the start-up work in perf(fast): torch.compile's cache in ~/.cache/basal/torchinductor (starts after a reboot reuse the compiled code) #47 (the compile cache across reboots) stands on its own.

Tests

  • New test_per_layer_compiled_forward_equals_the_model_and_compiles_once (tests/test_engine16.py): through
    _forward_by_layer, at 5 shapes, the hidden states and K / V buffers equal the transformers forward's (fp32,
    backend eager: exact); the layer function runs once per layer and shape and is traced at most twice over 4 layers.
    It fails if the K / V come by layer index (one graph per layer), a layer's keys are not written, kv is not passed
    on, or the step is bypassed.
  • New test_per_layer_compile_refused_where_not_measured: NVFP4 weights and --lean are refused before loading.
  • tests/ (without test_gguf.py): CPU 756 passed, 81 skipped.

…d of the whole model (opt-in)

The plain forward one layer at a time (_forward_layered with a step),
the transformers layers called through one compiled function
(_layer_call) with each layer's K / V passed alone (basal_layer_kv), so
Dynamo traces one layer for every layer and shape: start-up compiles a
layer instead of the 60-layer model. Kernels then fuse within a layer
only (bf16 rounding). Off by default (--compile-scope model).
@sourcery-ai

sourcery-ai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR adds an opt-in --compile-scope layer implementation that compiles and reuses a single decoder-layer function instead of compiling the entire plain Llama model, roughly halving cold-start compilation on the reported consumer GPU with similar throughput but bf16-rounding-level probability changes; the existing whole-model behavior remains the default.

Flow diagram for compile-scope selection

flowchart TD
    Start["Compiled fast mode"] --> Scope{"--compile-scope"}
    Scope -->|model| Whole["torch.compile(_forward)"]
    Scope -->|layer| Layer["torch.compile(_layer_call)"]
    Layer --> Loop["_forward_layered invokes compiled layer per decoder layer"]
    Whole --> Model["Whole model graph"]
    Loop --> Result["Embeddings and final norm remain uncompiled"]
Loading

File-Level Changes

Change Details Files
Added an opt-in per-layer compilation path for plain Llama basal-2.0 forwards, reducing cold-start compilation while preserving the existing whole-model default.
  • Introduced `--compile-scope model
layer, with modelremaining the default and routing only eligible compiled Llama graph workloads to the new scope.</li><li>Added a compiled_layer_call` loop that reuses one dynamically compiled decoder-layer function across layers and shapes, leaving embeddings, rotary setup, final norm, pass 2, compact rows, and unsupported model/quantization paths unchanged.
  • Passed each layer’s K/V buffers directly so compiled code does not specialize on layer indices; retained indexed-buffer behavior for the existing whole-model path.
  • Documented expected startup, throughput, and bf16 probability tradeoffs and added release notes.
  • Added a CPU/Dynamo regression test covering hidden-state and K/V equivalence plus bounded graph compilation across layers and input shapes.

  • Tips and commands

    Interacting with Sourcery

    • Trigger a new review: Comment @sourcery-ai review on the pull request.
    • Continue discussions: Reply directly to Sourcery's review comments.
    • Generate a GitHub issue from a review comment: Ask Sourcery to create an
      issue from a review comment by replying to it. You can also reply to a
      review comment with @sourcery-ai issue to create an issue from it.
    • Generate a pull request title: Write @sourcery-ai anywhere in the pull
      request title to generate a title at any time. You can also comment
      @sourcery-ai title on the pull request to (re-)generate the title at any time.
    • Generate a pull request summary: Write @sourcery-ai summary anywhere in
      the pull request body to generate a PR summary at any time exactly where you
      want it. You can also comment @sourcery-ai summary on the pull request to
      (re-)generate the summary at any time.
    • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
      request to (re-)generate the reviewer's guide at any time.
    • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
      pull request to resolve all Sourcery comments. Useful if you've already
      addressed all the comments and don't want to see them anymore.
    • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
      request to dismiss all existing Sourcery reviews. Especially useful if you
      want to start fresh with a new review - don't forget to comment
      @sourcery-ai review to trigger a new review!

    Customizing Your Experience

    Access your dashboard to:

    • Enable or disable review features such as the Sourcery-generated pull request
      summary, the reviewer's guide, and others.
    • Change the review language.
    • Add, remove or edit custom review instructions.
    • Adjust other review settings.

    Getting Help

    @sourcery-ai sourcery-ai 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.

    Hey - I've found 4 issues

    Prompt for AI Agents
    Please address the comments from this code review:
    
    ## Individual Comments
    
    ### Comment 1
    <location path="basal/engine.py" line_range="1608" />
    <code_context>
    +        """The plain causal forward with each decoder layer compiled (--compile-scope layer): the same transformers
    +        layers as the model compiled as a whole, one compiled layer function for every layer and shape, so start-up
    +        compiles one layer instead of the whole model; the loop, the embeddings and the final norm stay uncompiled."""
    +        return self._forward_layered(ids, kv, step=self._layer_step)
    +
         def _capture(self, key, fn, *static):
    </code_context>
    <issue_to_address>
    **Branched answers use stale keys**
    
    When `--compile-scope layer` is enabled and a branched unit's root is run through a plain graph, `_graph` supplies `kv` to `_forward_by_layer`, but `_forward_by_layer` omits it when calling `_forward_layered`; each layer therefore receives no KV buffer and writes no root keys or values. `_tree_hidden` then uses those uninitialized or stale buffers for pass 2, producing incorrect branched-unit probabilities and potentially caching invalid state.
    
    Pass `kv` through in `_forward_by_layer`, for example by calling `_forward_layered(ids, kv, step=self._layer_step)`.
    </issue_to_address>
    
    ### Comment 2
    <location path="basal/server.py" line_range="823" />
    <code_context>
             else:
    -            self.backend = GraphBackend(md, a.dtype, quant, compile=comp, shared=shared, attn=attn,
    +            scope = getattr(a, "compile_scope", "model")
    +            self.backend = GraphBackend(md, a.dtype, quant, compile="layer" if comp and scope == "layer" else comp,
    +                                        shared=shared, attn=attn,
                                             state_cache_gb=getattr(a, "state_cache_gb", 0),
    </code_context>
    <issue_to_address>
    **FP8 paths enter layered compilation**
    
    When `--compile-scope layer` is used with `--mode fp8` or `--mode nvfp4`, `Server` passes `compile="layer"` for any compiled graph mode, and `_llama_init` installs `_layer_step` whenever it receives that value. Thus FP8 and NVFP4 Llama runs use a path the description says is untouched, without a guard or validation for those modes.
    
    Restrict layered compilation to the validated model and quantization paths, or explicitly test and document support for FP8 and NVFP4.
    
    Also at `basal/engine.py:1114-1116`.
    </issue_to_address>
    
    ### Comment 3
    <location path="tests/test_engine16.py" line_range="219-220" />
    <code_context>
    +    dynamo.reset()
    +    dynamo.utils.counters.clear()
    +    step = torch.compile(_layer_call, dynamic=True, backend="eager")
    +    for b, L in ((1, 16), (2, 16), (3, 32), (2, 64), (4, 24)):  # within the stub's 128-token key / value buffer
    +        be._forward_layered(torch.randint(3, 50, (b, L)), be._kv_views(b, L), step=step)
    +    assert dynamo.utils.counters["stats"]["unique_graphs"] <= 2 < len(m.model.layers)
    +
    </code_context>
    <issue_to_address>
    **Compiled results go unchecked**
    
    When the compiled step produces incorrect hidden states or KV buffers while still generating at most two graphs, `test_per_layer_compiled_forward_equals_the_model_and_compiles_once` passes if the compiled step produces incorrect hidden states or KV buffers: the comparisons at lines 214-215 use the earlier uncompiled call, while the compiled calls at lines 220-221 discard their results and only check the graph count.
    
    Compare the compiled forward’s hidden states and KV buffers against the reference, at least for representative compiled shapes.
    </issue_to_address>
    
    ### Comment 4
    <location path="tests/test_engine16.py" line_range="213-221" />
    <code_context>
    +    want = [(k.clone(), v.clone()) for k, v in be._kv_views(2, 24)]
    +    for k, v in be._kv_views(2, 24):
    +        k.zero_(), v.zero_()
    +    got = be._forward_layered(ids, be._kv_views(2, 24), step=_layer_call)
    +    assert torch.equal(got, ref)
    +    assert all(torch.equal(k, k0) and torch.equal(v, v0) for (k, v), (k0, v0) in zip(be._kv_views(2, 24), want))
    +    dynamo.reset()
    +    dynamo.utils.counters.clear()
    +    step = torch.compile(_layer_call, dynamic=True, backend="eager")
    +    for b, L in ((1, 16), (2, 16), (3, 32), (2, 64), (4, 24)):  # within the stub's 128-token key / value buffer
    +        be._forward_layered(torch.randint(3, 50, (b, L)), be._kv_views(b, L), step=step)
    +    assert dynamo.utils.counters["stats"]["unique_graphs"] <= 2 < len(m.model.layers)
    +
    +
    </code_context>
    <issue_to_address>
    **Layer compilation can be skipped**
    
    When `_forward_layered` bypasses the supplied `step` function, `test_per_layer_compiled_forward_equals_the_model_and_compiles_once` still passes if `_forward_layered` ignores `step`: its first call takes the correct direct-layer path, and the later calls’ outputs are unchecked. With no compiled graphs, the assertion at line 221 still passes because zero is at most two.
    
    Assert that the supplied step is invoked during the compiled calls, and exercise the production layered-forward entry point.
    </issue_to_address>

    Sourcery is free for open source - if you like our reviews please consider sharing them ✨

    Comment thread basal/engine.py Resolved
    Comment thread basal/server.py Resolved
    Comment thread tests/test_engine16.py Resolved
    Comment thread tests/test_engine16.py Resolved
    … checks every compiled shape
    
    - Refused before anything is loaded: FP8 / NVFP4 weights, Gemma 4,
      Qwen3.5, --lean (engine) and uncompiled modes (server).
    - test_per_layer_compiled_forward_equals_the_model_and_compiles_once goes
      through _forward_by_layer, compares hidden states and K / V buffers with
      the transformers forward at every compiled shape and counts the layer
      calls; a new test checks the refusals.
    - WHATS_NEW / SERVING: single questions 2-3% slower on mini (4060 Ti).
    @rkinas

    rkinas commented Oct 28, 2026

    Copy link
    Copy Markdown
    Owner

    Thank you, Miłosz! --compile-scope layer moves to basal 2.5.1. On one H100 (basal-2.0-mini, --mode fast) the top answer matched the whole-model compile on 829 of 840 readouts (98.7%), just under the 99% bar we fixed before testing; the 11 changes were near-ties (margins up to 0.044), and cold warm-up dropped from 228 s to 47 s. Your numbers agree with ours, so nothing looks broken. We will re-check it on more readouts for 2.5.1, opt-in first. Your branch is already merged with 2.5.

    @rkinas
    rkinas merged commit d547e3d into rkinas:main Nov 2, 2026
    1 check passed
    rkinas added a commit that referenced this pull request Nov 2, 2026
    rkinas added a commit that referenced this pull request Nov 2, 2026
    G49 put the top answer of the layer-scope compile against the whole-model compile at 829 of 840
    readouts (98.69%), under the 99% bar fixed before the run. Reverts the merge of #49 (d547e3d) with its
    WHATS_NEW entry and README credit; it is planned for 2.5.1.
    rkinas pushed a commit that referenced this pull request Nov 2, 2026
    …d of the whole model (opt-in) (#49)
    
    The plain forward one layer at a time (_forward_layered with a step), the transformers layers called through one
    compiled function (_layer_call) with each layer's K / V passed alone (basal_layer_kv), so Dynamo traces one layer
    for every layer and shape: start-up compiles a layer instead of the whole model. Kernels then fuse within a layer
    only (bf16 rounding). Refused for FP8 / NVFP4 weights, Gemma 4, Qwen3.5, --lean and uncompiled modes. Off by
    default (--compile-scope model).
    
    #49 as merged for 2.5 (5c09204, f4bbece, 7736709, 5db91e6, ef1e6ab), back after its revert (f04c4b3).
    @rkinas

    rkinas commented Nov 8, 2026

    Copy link
    Copy Markdown
    Owner

    Miłosz, here is the re-check of --compile-scope layer on more readouts that we promised here.

    How we measured. basal 3.0's engine, --mode fast, every start from empty compile caches. The engine was built as basal-serve builds it, and the identity check's synthetic items ran through it: single questions, five-question requests, long states, in both option orders, alone and batched. That gives 11,200 readouts per start. We compared the layer scope with the whole-model compile on:

    • basal-2.0-mini, 4.5B and max on an H100: its default compact rows with FlashAttention 3, plus --batches default for mini and 4.5B;
    • basal-2.0-mini and 4.5B on an RTX PRO 6000 Blackwell.

    That is 78,400 readouts in all.

    One thing changed since October. Cold starts are now reproducible: 2.6.0 stopped timing the pointwise kernels of the compiled Llama forward. Two whole-model cold starts now give byte-identical readouts, and so do two layer-scope cold starts. So every difference below comes from the compile scope alone. The 98.3-98.5 % agreement between two whole-model starts that we quoted in October is gone.

    model GPU rows top-1 same changed at margin >= 0.05 (largest) max |dp|
    basal-2.0-mini RTX PRO 6000 plain 98.46 % 0 0.058
    basal-2.0-4.5B RTX PRO 6000 plain 99.43 % 8 (0.110) 0.087
    basal-2.0-mini H100 compact 98.52 % * 6 (0.070) 0.065
    basal-2.0-mini H100 --batches default 98.50 % 6 (0.070) 0.065
    basal-2.0-4.5B H100 compact 99.15 % * 2 (0.056) 0.070
    basal-2.0-4.5B H100 --batches default 99.22 % 6 (0.069) 0.070
    basal-2.0-max H100 compact 98.93 % 22 (0.239) 0.185

    * Of the readouts the layer scope runs. With compact rows, single prompts keep the whole-model compile, and for mini and 4.5B they were byte-identical.

    Result. The bar we set before testing was the same top answer on at least 99 % of readouts and no change where the whole-model margin is 0.05 or more. Every configuration misses at least one of the two:

    • 98.9 % top-1 over the 70,200 readouts the layer scope runs;
    • 50 changes at a margin of 0.05 or more.

    These are bf16 rounding differences, as you described, not a broken path. But there are too many to change everyone's answers by default, and they grow with the model (max: up to 0.24). So --compile-scope layer stays opt-in in 3.0. --help and SERVING.md now carry these numbers instead of October's.

    Start-up. The start-up gain holds. Cold graph warm-up, whole model -> layer:

    model RTX PRO 6000 H100 (compact rows)
    basal-2.0-mini 164 -> 37 s 269 -> 90 s
    basal-2.0-4.5B 314 -> 74 s 498 -> 169 s
    basal-2.0-max not measured 422 -> 147 s

    With --batches default on the H100: mini 214 -> 40 s, 4.5B 402 -> 69 s. As you expected, on the H100 the gain is partial while the compact rows still compile the whole model. Single-client time per request was the same for both scopes.

    Thank you for the feature and the careful first measurements. Your RTX 4060 Ti numbers (416 / 420 and 418 / 420) are in line with what we see on more readouts.

    kardysm pushed a commit to kardysm/basal that referenced this pull request Dec 3, 2026
    …78,400 readouts
    
    The promised re-check of the per-layer compile (public rkinas#49), from empty
    compile caches: basal-2.0-mini, 4.5B and max on an H100 (compact rows;
    mini and 4.5B also with --batches default) and mini and 4.5B on an RTX
    PRO 6000 Blackwell, the identity check's items through the served engine.
    Two cold starts of either scope now give byte-identical readouts, so the
    differences are the scope alone: the same top answer on 98.5-99.4% of the
    70,200 readouts the layer scope runs, 50 changed at a margin of 0.05 or
    more (up to 0.24). That misses the bar for a default (99%, none at 0.05),
    so it stays opt-in. --help and SERVING.md had October's 840 readouts and
    a cold-start variation that 2.6.0 removed; they give the new numbers.
    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