Skip to content
fn

save_compiled

→bool
save_compiled(cm: object, path: str)

Serialise a compiled forward graph to disk (AOT export).

Writes two files at path: <path>.mpsgraphpackage (Apple's native MPSGraphExecutable archive, macOS 14+) and <path>.meta (Lucid's I/O plan + dtype / shape / ABI metadata). A CompiledModule may hold multiple cached executables (one per input signature); this entry point serialises the most recently compiled one that has run — sufficient for AOT deployment where the production input shape is fixed.

The on-disk artifact is identical to the per-process cache used when LUCID_COMPILE_DISK_CACHE=1 is set — so calls save_compiled produces by hand are loadable by either load_compiled or the runtime cache machinery.

Warning:

Saving always succeeds; loading is what is restricted. A reloaded MPSGraph package does not report the feed order it expects, and that order only survives the round trip while every feed shares one shape and dtype. An executable whose feeds differ — which includes every lucid.nn.Module with parameters, since the weights and the activations rarely share a shape — is refused by load_compiled rather than bound wrongly. Until that is resolved, AOT export is usable for traced functions over uniform inputs, not for saving a trained model's forward pass. Weights are not in the package either way: use lucid.save / save_pretrained for those.

Parameters

A model wrapper returned by lucid.compile, called at least once on Metal under lucid.no_grad (or lucid.inference_mode): a call that needs gradients runs eagerly and compiles nothing to save.
pathstr
Filesystem prefix. Two files are written: f"{path}.mpsgraphpackage" and f"{path}.meta".

Returns

bool

True on success. Raises RuntimeError if no executable of cm has run yet.

Examples

>>> import lucid
>>> import lucid.compile as lc
>>> cm = lc.compile(lambda a, b: a * b + 1.0)
>>> a = lucid.randn(2, 8).to("metal")
>>> b = lucid.randn(2, 8).to("metal")
>>> _ = cm(a, b)                             # populate cache
>>> lc.save_compiled(cm, "/tmp/my_graph")    # writes .mpsgraphpackage + .meta
True