Skip to content

Training with nn.Embedding is not repeatable on the GPU for a fixed seed #4951

Open

Description

@nhz-io

With a fixed seed, training a model that uses nn.Embedding ends with different weights on each run on the GPU. On the CPU the runs agree. Replacing the lookup with a one-hot matrix product makes the GPU runs agree too, which points at the gradient of the lookup being accumulated in a varying order.

Is this expected? If so, is there a way to ask for a deterministic gradient for the lookup?

Environment: mlx 0.32.4, Python 3.12.16, macOS 27.2.1, Apple M4 Pro.

import hashlib
import sys

import mlx.core as mx
import mlx.nn as nn
import mlx.optimizers as optim
from mlx.utils import tree_flatten

VOCAB, WIDTH = 64, 64


class Model(nn.Module):
    def __init__(self, one_hot):
        super().__init__()
        self.one_hot = one_hot
        self.tokens = nn.Embedding(VOCAB, WIDTH)
        self.head = nn.Linear(WIDTH, 2)

    def __call__(self, x):
        if self.one_hot:
            tokens = (x[..., None] == mx.arange(VOCAB)).astype(mx.float32) @ self.tokens.weight
        else:
            tokens = self.tokens(x)
        return self.head(tokens.mean(axis=1))


def run(one_hot):
    mx.random.seed(0)
    model = Model(one_hot)
    optimizer = optim.AdamW(learning_rate=1e-3)

    def loss_fn(model, x, y):
        return nn.losses.cross_entropy(model(x), y, reduction="mean")

    loss_and_grad = nn.value_and_grad(model, loss_fn)
    for _ in range(40):
        x = mx.random.randint(0, VOCAB, (32, 16))
        y = (x[:, 0] >= VOCAB // 2).astype(mx.int32)
        _, grads = loss_and_grad(model, x, y)
        optimizer.update(model, grads)
        mx.eval(model.parameters(), optimizer.state)
    digest = hashlib.sha256()
    for name, value in sorted(tree_flatten(model.parameters())):
        digest.update(name.encode())
        digest.update(bytes(memoryview(value)))
    return digest.hexdigest()[:16]


if len(sys.argv) > 1:
    mx.set_default_device(mx.cpu)
print("mlx", mx.__version__, mx.default_device())
print("nn.Embedding lookup:", [run(False) for _ in range(3)])
print("one-hot product:    ", [run(True) for _ in range(3)])

Output on the GPU:

mlx 0.32.4 Device(gpu, 0)
nn.Embedding lookup: ['5fb409d561441bb6', '1cbee56e300d7149', '52fb0f2ce705556a']
one-hot product:     ['7680a9d69da96744', '7680a9d69da96744', '7680a9d69da96744']

Output with any argument, which selects the CPU:

mlx 0.32.4 Device(cpu, 0)
nn.Embedding lookup: ['49ce927977bbc079', '49ce927977bbc079', '49ce927977bbc079']
one-hot product:     ['49ce927977bbc079', '49ce927977bbc079', '49ce927977bbc079']

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions