Repository navigation
feat(fast): --compile-scope layer, one compiled decoder layer instead of the whole model (opt-in; your call on the default) - #49
Conversation
…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).
Reviewer's GuideThis PR adds an opt-in Flow diagram for compile-scope selectionflowchart 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"]
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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>… 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).
|
Thank you, Miłosz! |
…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).
|
Miłosz, here is the re-check of How we measured. basal 3.0's engine,
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.
* 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:
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 Start-up. The start-up gain holds. Cold graph warm-up, whole model -> layer:
With 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. |
…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.
This PR adds an opt-in and changes nothing by default (
--compile-scope model, today's path, is untouched). Thequestion 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 fastspends most of a cold start compiling: on an RTX 4060 Ti the first calls of the plain graphs are 504 ofbasal-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 transformersdecoder 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 60layers, 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 perlayer (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-upand 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.pywith coldcompile caches (
warm()timed, per-phase timers, the 420 identity readouts ofbasal.identity.build), thenbasal-serve(its start reuses the probe's compile cache),basal-loadtestsingle questions and five questions over1.5k-token states (32 clients, each run twice), and 10 requests (compress over 1.5k-6k tokens, 5-40 questions).
--compile-scope layer--lean on--compile-scope layer--lean onSpeed 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):
layerlayeron 1)leanlayerleanSo per layer, the probabilities move as much as they differ from fp32 either way: rounding, not a different model.
What I am asking
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.
Tests
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,
kvis not passedon, or the step is bypassed.
test_per_layer_compile_refused_where_not_measured: NVFP4 weights and--leanare refused before loading.tests/(withouttest_gguf.py): CPU 756 passed, 81 skipped.