Nnx Optimizers change model sharding
Here's a Jax example of sharding optimizer state differently from model state:
import optax
import itertools as it
import functools as ft
from jax.sharding import PartitionSpec as P, AxisType, get_abstract_mesh, reshard
keys = map(ft.partial(jax.random.fold_in, jax.random.key(0)), it.count())
def make_linear(size, keys, **kwargs):
return {
'w': param_init(next(keys), size, **kwargs),
'b': jnp.zeros(size[1])
}
def jax_params(keys, **kwargs):
return [make_linear((2, 8), keys), make_linear((8, 8), keys, **kwargs)]
def jax_model(params, x):
for p in params[:-1]:
x = jax.nn.relu(x @ p['w'] + p['b'])
for p in params[-1:]:
return x @ p['w'] + p['b']
def jax_loss_fn(params, x, y):
return jnp.sum((y - jax_model(params, x))**2)
x = jax.random.normal(next(keys), (32, 2))
y = jax.random.normal(next(keys), (32, 8))
mesh = jax.make_mesh((2, 4), ("x", "y"),
axis_types=(AxisType.Explicit, AxisType.Explicit))
jax.set_mesh(mesh)
optimizer = optax.adam(1e-3)
opt_state = optimizer.init(jax.eval_shape(lambda: jax_params(keys, out_sharding=P('x', 'y'))))
params = jax_params(keys)
@jax.jit
def train_step(opt_state, params, x, y):
loss, grads = jax.value_and_grad(jax_loss_fn)(params, x, y)
updates, opt_state = optimizer.update(grads, opt_state)
params = optax.apply_updates(params, updates)
return opt_state, params, loss
losses = []
for _ in range(50):
opt_state, params, loss = train_step(opt_state, params, x, y)
losses.append(loss)
The same model in Flax complains about inconsistent sharding:
nnx_keys = nnx.Rngs(0)
def nnx_model(rngs, **kwargs):
return nnx.Sequential(
nnx.Linear(2,8, rngs=rngs, kernel_init=ft.partial(param_init, **kwargs)),
nnx.relu,
nnx.Linear(8,8, rngs=rngs, kernel_init=ft.partial(param_init, **kwargs)))
def nnx_loss_fn(model, x, y):
return jnp.sum((model(x) - y) ** 2)
ghost_model = jax.eval_shape(lambda: nnx_model(nnx.Rngs(0), out_sharding=P('x', 'y')))
nnx_optimizer = nnx.Optimizer(ghost_model, optax.adam(1e-3), wrt=nnx.Param)
model = nnx_model(nnx.Rngs(0))
@nnx.jit
def nnx_train_step(model, nnx_optimizer, x, y):
loss, grads = nnx.value_and_grad(nnx_loss_fn)(model, x, y)
nnx_optimizer.update(model, grads)
return loss
losses = []
for _ in range(50):
loss = nnx_train_step(model, nnx_optimizer, x, y)
losses.append(loss)
Something about the use of the nnx.Optimizer is breaking things here.
Hi @samanklesaria, I saw this pop up and I've been studying how nnx handles sharding compared to standard JAX/Optax, so I'll be following this fix closely to learn how the state inconsistency is resolved. Good luck with the fix.
Interestingly, everything works for when the model is a single linear layer. Only when I use Sequential here do things break.
The first time we call the nnx_train_step function, everything works great. The kernel params have type JitTracer(float32[2,8]). The second time, however, they are JitTracer(float32[2@x,8@y]). So the optimizer.update call must change the sharding.
Oops: I realized this was an error on my part. The jax_params definition in Jax should have been
def jax_params(keys, **kwargs):
return [make_linear((2, 8), keys, **kwargs), make_linear((8, 8), keys, **kwargs)]
With this change, both throw the error. The state needs to be manually resharded, which makes sense.
Ah, interesting catch on the jax_params. So if I understand correctly, the optimizer update is implicitly changing the sharding layout (to @x, @y), and we have to explicitly enforce the original layout after the step to prevent that drift? Thanks for debugging this out in the open—it’s really helpful to see.
@ayulockedin exactly!