Skip to content
fn

compile

→CompiledModule
compile(model: Callable[P, R] | None = None, fullgraph: bool = False, dynamic: bool | None = None, backend: str | Callable[..., object] | None = None, mode: str | None = None, options: _CompileOptions | None = None, disable: bool = False)

Wrap model so calls are routed through cached MPSGraph executables.

Accepts three call styles:

  • Module wrapping — lucid.compile(model) returns a CompiledModule that delegates parameter walks / state_dict / device moves to model while routing __call__ through an executable cache.
  • Plain callable wrapping — lucid.compile(fn) where fn is a regular function or any callable. Returns a thin wrapper whose __call__ traces the function's body on the first invocation with a new input signature and caches an executable; it has no parameters of its own — pure tensor-in / tensor-out.
  • Decorator usage — @lucid.compile on a function (or @lucid.compile(dynamic=True) factory form) — identical to the plain-callable form above but lets the user opt-in inline.

Parameters

modelnn.Module or callable= None
Either an nn.Module instance (preferred when the compiled unit carries learnable parameters) or any callable whose signature is (*tensor_args) -> Tensor | tuple | dict. When None, returns a decorator factory.
fullgraphbool= False
Compatibility flag with the reference signature. Default False.
dynamicbool or None= None
Treat the leading (batch) axis as symbolic so calls differing only in batch size, other than a batch of one, share one executable (no recompile per batch). Default None (treated as False).
backendstr or callable or None= None
Compatibility flag with the reference signature. Default None.
modestr or None= None
Compatibility flag with the reference signature. Default None.
optionsdict or None= None
Compatibility flag with the reference signature. Default None.
disablebool= False
When True, makes compile a no-op returning model unchanged. Default False.

Returns

CompiledModule

A wrapper exposing the cache + run path. When model was a Module the wrapper re-exposes the inner module's parameters / state_dict / training mode; when it was a plain callable those return empty sequences.

Notes

  • A call the compiler cannot lower, or one that needs gradients (see CompiledModule), runs eagerly with a one-time UserWarning naming why; LUCID_COMPILE_VERBOSE=1 reports every occurrence.
  • Attention lowers to a matmul-softmax-matmul decomposition, which materialises the score matrix; eager Metal's fused kernel never does. A call whose attention would write more than 512 MiB of scores therefore runs eagerly, 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 MPSGraph's own fused attention (LUCID_COMPILE_FUSED_SDPA=1) did not close the gap. LUCID_COMPILE_LONG_ATTENTION=compile keeps such calls compiled.

Examples

Module form:

    compiled = lucid.compile(nn.Linear(8, 4).to('metal'))
    with lucid.no_grad():
        y = compiled(x)

Callable form:

    @lucid.compile
    def f(x, y):
        return (x @ y.T).relu()

    z = f(a, b)

Factory decorator with kwargs:

    @lucid.compile(dynamic=False)
    def attention(q, k, v):
        return F.scaled_dot_product_attention(q, k, v)

See Also

  • CompiledModule—the wrapper class returned by this function.
  • compile_optimizer—fused forward + backward + optimizer step
  • for an even tighter training loop.