MCPcopy Create free account
hub / github.com/ml-explore/mlx / test_compiled_optimizer

Method test_compiled_optimizer

python/tests/test_optimizers.py:336–392  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

334 optim_no_momentum.apply_gradients(grads, params)
335
336 def test_compiled_optimizer(self):
337 model = nn.Linear(10, 10)
338 x = mx.random.uniform(shape=(2, 10))
339 optim = opt.SGD(learning_rate=1e-2, momentum=0.9)
340
341 orig_params = model.parameters()
342
343 def loss(model, x):
344 return model(x).sum()
345
346 # Uncompiled version
347 def step(x):
348 _, grad = nn.value_and_grad(model, loss)(model, x)
349 optim.update(model, grad)
350
351 step(x)
352 uncompiled_params = model.parameters()
353
354 # Pure version
355 def loss(params, x):
356 model.update(params)
357 return model(x).sum()
358
359 model.update(orig_params)
360 optim = opt.SGD(learning_rate=1e-2, momentum=0.9)
361
362 @mx.compile
363 def step(params, opt_state, x):
364 grad = mx.grad(loss)(params, x)
365 optim.state = opt_state
366 params = optim.apply_gradients(grad, params)
367 return params, optim.state
368
369 optim.init(model.parameters())
370 pure_params, _ = step(model.parameters(), optim.state, x)
371 self.assertTrue(mx.allclose(pure_params["weight"], uncompiled_params["weight"]))
372 self.assertTrue(mx.allclose(pure_params["bias"], uncompiled_params["bias"]))
373
374 # Impure version
375 def loss(model, x):
376 return model(x).sum()
377
378 model.update(orig_params)
379 optim = opt.SGD(learning_rate=1e-2, momentum=0.9)
380 state = [model.state, optim.state]
381
382 @partial(mx.compile, inputs=state, outputs=state)
383 def step(x):
384 _, grad = nn.value_and_grad(model, loss)(model, x)
385 optim.update(model, grad)
386
387 step(x)
388 impure_params = model.parameters()
389 self.assertTrue(
390 mx.allclose(impure_params["weight"], uncompiled_params["weight"])
391 )
392 self.assertTrue(mx.allclose(impure_params["bias"], uncompiled_params["bias"]))
393

Callers

nothing calls this directly

Calls 4

parametersMethod · 0.80
stepFunction · 0.50
updateMethod · 0.45
initMethod · 0.45

Tested by

no test coverage detected