Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions Source/MLX/Documentation.docc/Articles/compilation.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,68 @@ let c2b = c2(bias)
XCTAssertFalse(allClose(c2a, c2b).item())
```

The same rule applies to a `Module` that is captured (closed over) rather than
passed as an explicit function argument. `Module` conforms to ``Updatable``, so
its parameters count as implicit state, just like `MLXRandom.globalState` above.
If you compile a function that reads a module's parameters without listing that
module in `inputs:`/`outputs:`, the values are baked into the compiled graph the
first time it traces and later updates to the module (for example swapping in
new LoRA weights with `Module.update(parameters:)`) will be silently ignored:

```swift
class ScaleModule: Module, UnaryLayer {
var scale: MLXArray

init(_ value: Float) {
self.scale = MLXArray(value)
}

func callAsFunction(_ x: MLXArray) -> MLXArray {
x * scale
}
}

let model = ScaleModule(2.0)

// no inputs/outputs -- the module's parameters are captured as constants
let compiled = compile { (x: MLXArray) -> MLXArray in
model(x)
}

print(compiled(MLXArray(Float(3)))) // 6

// simulate a LoRA-style in place update of the module's weights
model.update(parameters: .unflattened([("scale", MLXArray(Float(10)))]))
eval(model)

// still 6 -- the compiled function never sees the update!
print(compiled(MLXArray(Float(3))))
```

To make the compiled function observe the update, pass the module via `inputs:`:

```swift
let compiled = compile(inputs: [model]) { (x: MLXArray) -> MLXArray in
model(x)
}

print(compiled(MLXArray(Float(3)))) // 6

model.update(parameters: .unflattened([("scale", MLXArray(Float(10)))]))
eval(model)

print(compiled(MLXArray(Float(3)))) // 30 -- now it sees the update
```

`inputs:` is what makes the compiled function observe external updates: on every
call the *current* values of the listed state are fed back into the compiled
graph. `outputs:` is the reverse direction -- it writes values back out of the
graph into the real arrays, and is only needed when the compiled closure itself
*mutates* the captured state (for example a training step that calls
`optimizer.update(model:gradients:)` inside the compiled function, as shown
below). Since `model(x)` above only reads `scale`, `inputs: [model]` alone is
enough; adding `outputs: [model]` would be harmless but unnecessary.

## Compiling Training Graphs

This section will step through how to use ``compile(inputs:outputs:shapeless:_:)-([Updatable],[Updatable],Bool,([MLXArray])->[MLXArray])``
Expand Down
7 changes: 7 additions & 0 deletions Source/MLXNN/Module.swift
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,13 @@ open class Module {
/// The ``apply(filter:map:)`` can be used for similar purposes to apply changes
/// in-place.
///
/// > If this module is used inside a compiled closure (`compile()`) that does not
/// list the module in `inputs:`, calling `update(parameters:)` after the first compiled call
/// will not be observed by the compiled function -- `inputs:` is what makes `compile` re-read
/// current parameter values on every call. `outputs:` is only needed in addition when the
/// compiled closure itself mutates this module's parameters and the mutation should be
/// written back.
///
/// If a parameter is missing from the update and validation indicates `.allModelKeysSet` this
/// will call ``updateMissing(parameter:verify:path:modulePath:)`` which will
/// throw an error. Subclasses can override this if needed.
Expand Down
59 changes: 59 additions & 0 deletions Tests/MLXTests/TransformTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,65 @@ class TransformTests: XCTestCase {
XCTAssertEqual(state.o!.item(Float.self), -8)
}

// https://github.com/ml-explore/mlx-swift-lm/issues/586 --
// compile can capture Module parameters
class ScaleModule: Module, UnaryLayer {
var scale: MLXArray

init(_ value: Float) {
self.scale = MLXArray(value)
}

func callAsFunction(_ x: MLXArray) -> MLXArray {
x * scale
}
}

func testCompileCapturesModuleParameterWithoutState() {
// verify the capture path happens

let model = ScaleModule(2.0)

let compiled = compile { (x: MLXArray) -> MLXArray in
model(x)
}

let r1 = compiled(MLXArray(Float(3)))
XCTAssertEqual(r1.item(Float.self), 6)

// simulate a LoRA-style in place update of the module's weights
model.update(parameters: .unflattened([("scale", MLXArray(Float(10)))]))
eval(model)

// Verify capture of Module parameters -- it doesn't see the update
let r2 = compiled(MLXArray(Float(3)))
XCTAssertEqual(
r2.item(Float.self), 6,
"compiled function incorrectly ignored the updated module parameter")
}

func testCompileWithStateObservesModuleParameterUpdates() {
// verify inputs correctly handles updated
// Module parameters

let model = ScaleModule(2.0)

let compiled = compile(inputs: [model]) { (x: MLXArray) -> MLXArray in
model(x)
}

let r1 = compiled(MLXArray(Float(3)))
XCTAssertEqual(r1.item(Float.self), 6)

// simulate a LoRA-style in place update of the module's weights
model.update(parameters: .unflattened([("scale", MLXArray(Float(10)))]))
eval(model)

// with state:, the compiled function observes the updated parameter
let r2 = compiled(MLXArray(Float(3)))
XCTAssertEqual(r2.item(Float.self), 30)
}

func testCompiledRandom() {
func f(_ bias: MLXArray) -> MLXArray {
MLXRandom.uniform(0 ..< 1, [4]) + bias
Expand Down
8 changes: 6 additions & 2 deletions skills/mlx-swift/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,12 @@ let compiledOp = compile { (a: MLXArray, b: MLXArray) -> MLXArray in
// Use compiled version
let output = compiledOp(arrayA, arrayB)

// Note: compile() works best with pure MLXArray functions.
// For models, call model methods directly (they can use internal compilation).
// compile() also supports compiling a Module/Optimizer training step: pass
// them via inputs:/outputs: (they conform to Updatable) so compile observes
// in-place updates (e.g. optimizer.update(model:gradients:), LoRA weight swaps).
// If a captured Module/Optimizer is left out of inputs:/outputs:, compile()
// silently freezes its parameter values at trace time -- see
// references/transforms.md for the full pitfall and example.
```

## Quaternary Workflow: Wired Memory Coordination
Expand Down
3 changes: 2 additions & 1 deletion skills/mlx-swift/references/optimizers.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,8 @@ import MLXOptimizers
let model = MLP(inputDim: 784, hiddenDim: 256, outputDim: 10)
let optimizer = AdamW(learningRate: 0.001, weightDecay: 0.01)

// Training loop (compile only works with pure MLXArray functions, not models)
// Training loop. compile() can compile the full step, but only if the
// model/optimizer are declared via inputs:/outputs: -- see references/transforms.md.
func loss(model: MLP, x: MLXArray, y: MLXArray) -> MLXArray {
let logits = model(x)
return crossEntropy(logits: logits, targets: y, reduction: .mean)
Expand Down
38 changes: 31 additions & 7 deletions skills/mlx-swift/references/transforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,12 +203,13 @@ let compiledF = compile(f)
let result = compiledF(a, b)
```

### compile Limitations
### compile Limitations and Module/Optimizer State

**Important:** `compile()` only works with pure `MLXArray` functions. It does NOT support:
- Model objects as parameters
- Optimizer objects as parameters
- Any non-MLXArray inputs
`compile()` traces a function that takes/returns `MLXArray` values (or tuples/arrays
of them) -- it can't take a `Module` or `Optimizer` as a parameter directly. But it
CAN compile closures that capture and mutate a `Module`/`Optimizer`, as long as any
mutable state they touch is declared via `inputs:`/`outputs:`. Both `Module` and
`Optimizer` conform to `Updatable`, so they can be passed there directly:

```swift
// CORRECT: compile with pure MLXArray functions
Expand All @@ -217,12 +218,35 @@ let compiledOp = compile { (a: MLXArray, b: MLXArray) -> MLXArray in
return sum(x * x)
}

// For model training, call model methods directly without compile:
// ALSO CORRECT: compile a full training step by capturing model/optimizer
// and declaring them as inputs/outputs so compile observes their updates
func loss(model: MyModel, x: MLXArray, y: MLXArray) -> MLXArray {
mseLoss(predictions: model(x), targets: y, reduction: .mean)
}
let lossAndGradFn = valueAndGrad(model: model, loss)
let (lossValue, grads) = lossAndGradFn(model, x, y)

let step = compile(inputs: [model, optimizer], outputs: [model, optimizer]) { x, y in
let (loss, grads) = lossAndGradFn(model, x, y)
optimizer.update(model: model, gradients: grads)
return loss
}

// PITFALL: if you close over a Module but omit it from inputs/outputs,
// compile() bakes in its parameter values at trace time. Later in-place
// updates to the module (e.g. swapping LoRA weights) will be silently
// ignored by the compiled function until it is recompiled for another
// reason (e.g. a shape change).
let compiled = compile { (x: MLXArray) -> MLXArray in model(x) }
_ = compiled(x)
model.update(parameters: newParameters)
eval(model)
_ = compiled(x) // still uses the OLD parameters

// FIX: `inputs:` is what makes compile() re-read current state on every call;
// `outputs:` is only needed when the compiled closure itself mutates the
// state (as `optimizer.update(...)` does in the `step` example above) and
// you need that mutation written back to the real arrays.
let fixed = compile(inputs: [model]) { (x: MLXArray) -> MLXArray in model(x) }
optimizer.update(model: model, gradients: grads)
eval(model, optimizer)
```
Expand Down
Loading