Compile (JIT)
Capture a model or training step into a cached MPSGraph executable with lucid.compile — tracing, fused steps, AOT export, and coverage diagnosis.
lucid.compile traces a model — or a whole forward + backward + optimizer step — into a single cached Metal executable. Eager mode dispatches one kernel per op; the compiled path captures the entire graph once and replays it as one MPSGraph invocation, eliminating per-op Python and dispatch overhead on the hot loop.
When to compile
Compile pays off when the same shapes flow through the same graph thousands of times — i.e. a training loop. The first call traces and builds the executable (a one-time cost); every subsequent call with matching shapes hits the cache.
Eager mode stays the right default for research, debugging, and dynamic control flow. Reach for compile once the architecture is fixed and you are iterating on data, not code.
Compiling a model
lucid.compile(target) wraps a Module (or any callable) so calls route through cached executables:
import lucid
import lucid.nn as nn
model = nn.Sequential(
nn.Linear(784, 256), nn.ReLU(),
nn.Linear(256, 10),
)
fast_model = lucid.compile(model)
x = lucid.random.randn(64, 784)
y = fast_model(x) # 1st call: trace + build, then run
y = fast_model(x) # 2nd call onward: cached executableThe wrapper exposes the same interface as the underlying module — parameters, state_dict, and eval() all forward through.
Fused training step
The largest win comes from fusing forward, backward, and the optimizer update into one executable. fused_step returns a callable that runs the entire step:
import lucid.optim as optim
model = MyModel()
optimizer = optim.Adam(model.parameters(), lr=1e-3)
step = lucid.compile.fused_step(
model,
loss_fn=lambda out, target: nn.functional.cross_entropy(out, target),
optimizer=optimizer,
)
for x_batch, y_batch in loader:
loss = step(x_batch, y_batch) # fwd + bwd + opt.step(), one executablemake_step and compiled_step are the lower-level building blocks fused_step composes; reach for them when you need to drive forward and backward separately.
Compiling the optimizer alone
If you only want the parameter update fused — leaving forward/backward eager — wrap the optimizer:
optimizer = lucid.compile.compile_optimizer(optim.SGD(model.parameters(), lr=0.1))opt.step() then runs as a single MPSGraph executable instead of one kernel per parameter tensor.
Dynamic shapes
By default the cache keys on input shapes, so a new batch shape triggers a re-trace. If your batch size genuinely varies, pass dynamic=True to trace shape-polymorphic graphs and avoid re-compiling per shape:
fast_model = lucid.compile(model, dynamic=True)dynamic=True trades a small amount of per-call overhead for far fewer re-traces. Use it only when shapes really do change — a fixed-shape loop is faster without it.
BatchNorm and Dropout under compile
Stateful layers are handled transparently:
- BatchNorm running mean/variance are surfaced as extra executable outputs and written back into the live module buffers after each step, so
model.eval()reads fresh statistics. - Dropout masks are driven by the GPU RNG inside the captured graph, so training stays stochastic across steps without falling back to a CPU round-trip.
Compiled autoregressive decoding (StaticCache)
Standard KV caches (DynamicCache) grow by concatenation on every token, changing tensor shapes at each step and forcing a re-trace under static-shape compilation. StaticCache pre-allocates fixed (B, num_heads, max_cache_len, head_dim) buffers and writes each new token's K/V slice at a runtime cache_position tensor via lucid.index_copy, keeping the graph signature constant across all decode positions.
Pass cache_implementation="compiled" to generate() on any generative text model (GPTLMHeadModel, GPT2LMHeadModel, TransformerForSeq2SeqLM, T5ForSeq2SeqLM) to prefill the prompt eagerly and run every subsequent single-token decode step through one cached MPSGraphExecutable:
from lucid.models import create_model
model = create_model("gpt2_small_lm").eval().to("metal")
prompt = lucid.tensor([[15496, 995]], dtype=lucid.int64, device="metal")
out = model.generate(
prompt,
max_new_tokens=64,
cache_implementation="compiled",
max_cache_len=128,
)For custom decoding loops, lucid.compile._entry.decode_step.compiled_decode_step(forward_fn, static_cache) wraps any (input_ids, cache_position) -> logits callable and rolls the StaticCache (or EncoderDecoderCache) buffers forward in place after each executable invocation.
Custom Functions, linalg decompositions, and rsample()
Training steps (make_step, fused_step, compiled_step) compile end-to-end through:
- Linear-algebra decompositions & solvers:
lucid.linalg.cholesky,qr,svd,svdvals,eigh,eigvalsh,solve_triangular,pinv,slogdet, andmatrix_powerlower both their forward decomposition and their analytical backward into the compiledMPSGraphExecutable. - Reparameterised distributions (
rsample):Gamma,Beta,Dirichlet,Chi2,StudentT,FisherSnedecor,InverseGamma,MultivariateNormal,LowRankMultivariateNormal, andWisharttrace their implicit or covariance reparameterisation backward (_StandardGamma, Cholesky/triangular VJP) directly into the compiled training graph. - User-defined
autograd.Functionsubclasses: set_traced_backward = Trueon a customFunctionwhoseforwardandbackwardare pure traceable tensor ops to tracebackward(ctx, *grad_outputs)into aVjpRegioninside the compiled executable instead of falling back to eager execution.
Coverage diagnosis
Not every op has a manual vector-Jacobian product yet. diagnose traces your function and reports which ops are compile-backed and which would fall back:
report = lucid.compile.diagnose(model, x)
print(report.total_ops)
for op in report.registered:
print(op.name, op.count, op.sample_shape)Run diagnose first when a model compiles slower than expected — an unregistered op in the hot path forces a fallback and explains the gap.
A call the compiler cannot lower runs eagerly, and says so: the first fallback of each kind raises a one-time UserWarning naming the reason (set LUCID_COMPILE_VERBOSE=1 to see every occurrence). bfloat16 graphs are not lowered to MPSGraph yet, so a bfloat16 model is detected up front and runs eagerly without a failed trace.
Ahead-of-time export
A compiled forward graph can be serialised to disk and reloaded without re-tracing — useful for deployment or warm starts:
fast_model = lucid.compile(model)
fast_model(x) # build the executable
lucid.compile.save_compiled(fast_model, "model.lucidc")
restored = lucid.compile.load_compiled("model.lucidc")
y = restored(x) # no trace costWhat to expect
| Workload | Eager | Compiled |
|---|---|---|
| First call | runs immediately | trace + build (one-time) |
| Steady-state step | per-op dispatch | single executable replay |
| Best fit | dynamic / research code | fixed-shape training loops |
The compiled path is most effective on deep models with many small ops, where per-op dispatch dominates. For a handful of large matmuls the eager and compiled paths converge.
Attention is the exception the compiler handles for you. The compiled graph lowers it to matmul, softmax and matmul, which writes the whole score matrix to memory; eager Metal's fused kernel never does. When a call's attention would write more than 512 MiB of scores, it runs eagerly instead, with a one-time notice — on an M4 Max a diffusion-transformer block at 18 720 keys took 120.8 ms compiled and 87.5 ms eager, and runs at the eager speed now. Self-attention up to 4 096 tokens compiles as before. Set LUCID_COMPILE_LONG_ATTENTION=compile to keep such calls compiled anyway.
For runnable examples of each entry point, including what falls back on the CPU, see the Speed Up with lucid.compile tutorial. See the API reference for the full surface, and Training Loop for where a fused step slots into a real loop.