Test MLX loss masking and valid-token normalization on a cloud Mac

Test MLX loss masking and valid-token normalization on a cloud Mac

Test MLX loss masking and valid-token normalization on a cloud Mac

The fine-tuning data stays the same, but padding sequences to a greater length makes the average loss drop noticeably. Change the length-bucketing rules, and the curve suddenly jumps again. Before adjusting the learning rate, check the loss denominator. When running MLX experiments on a cloud Mac, validate the label-masking logic with a few fixed tensors before loading the actual model. This helps avoid spending time chasing a curve whose aggregation is wrong.

Define the valid-token contract

These checks validate the loss calculation after prediction, not the attention mask. The input logits have shape [B,T,V], and the labels have shape [B,T], where V is the number of classes. The ignore label is -100. Sum the losses at valid positions, then divide by the number of valid tokens—not by B×T.

When training with supervision only on the answer, prompt positions can also use the ignore label. Valid positions therefore cannot be identified simply by checking whether a token is padding. They must be determined from the supervision labels generated during data processing.

The attention mask determines what the model can see; the loss mask determines which predictions contribute to learning. They solve different problems and are not interchangeable.

Another prerequisite is that predictions and targets are already aligned. For next-token prediction, apply the shift before calling the loss function and verify both ends of the sequence. The small test fixture below deliberately leaves out this step so that shift errors do not get mixed into the denominator test.

Implement an inspectable reference loss

Use a native Python environment with MLX installed, and save the code as loss_contract.py. First run python -m pip show mlx to confirm the environment, then execute python loss_contract.py. This implementation is intended for small-scale validation. Its label checks synchronously retrieve values, so it should not be copied unchanged into the hot path of a high-throughput training loop.

import mlx.core as mx

IGNORE = -100


def masked_loss(logits, labels):
    if logits.ndim != 3 or labels.shape != logits.shape[:2]:
        raise ValueError("Invalid tensor shapes")
    if labels.dtype != mx.int32:
        raise ValueError("Labels must be int32")

    vocab = logits.shape[-1]
    if vocab < 1:
        raise ValueError("Empty vocabulary")

    valid = labels != IGNORE
    invalid = valid & ((labels < 0) | (labels >= vocab))
    if bool(mx.any(invalid).item()):
        raise ValueError("Label out of range")

    count = int(mx.sum(valid).item())
    if count == 0:
        raise ValueError("No supervised tokens")

    safe = mx.where(valid, labels, mx.zeros_like(labels))
    scores = logits.astype(mx.float32)
    selected = mx.take_along_axis(
        scores, safe[..., None], axis=-1
    ).squeeze(-1)
    losses = mx.logsumexp(scores, axis=-1) - selected
    return mx.sum(mx.where(valid, losses, 0.0)) / count

Replace ignored labels before indexing, not afterward. Even if the result will later be multiplied by zero, an out-of-range index may already have caused an error. The implementation also uses the numerically stable logsumexp rather than computing exponentials directly and then taking their logarithm, which can cause unnecessary overflow.

The reference fixture uses finite logits. A real pipeline should also check for non-finite values separately. Masking is not a tool for fixing numerical problems, nor should it silently zero out invalid numerical values at valid positions.

Catch an incorrect denominator with padding invariance

Append the following code to the same file. Both valid tokens have all-zero logits across three classes, so the theoretical loss at each position is ln(3). Adding an ignored position should leave the result unchanged.

import math

base = mx.zeros((1, 2, 3))
target = mx.array([[0, 2]], dtype=mx.int32)
padded = mx.zeros((1, 3, 3))
padded_target = mx.array([[0, 2, IGNORE]], dtype=mx.int32)

first = masked_loss(base, target)
second = masked_loss(padded, padded_target)

assert abs(first.item() - math.log(3)) < 1e-6
assert abs(first.item() - second.item()) < 1e-6

gradient = mx.grad(
    lambda value: masked_loss(value, padded_target)
)(padded)
mx.eval(gradient)

assert mx.max(mx.abs(gradient[:, 2, :])).item() == 0.0
assert mx.max(mx.abs(gradient[:, :2, :])).item() > 0.0

If masked positions are set to zero and the entire tensor is then averaged, the added position dilutes the result. This test requires no model weights and directly distinguishes an average over valid tokens from an average over all positions after padding.

The gradient check matters just as much. Looking only at the final scalar can miss implementation errors that still allow masked positions to contribute to backpropagation. The test also requires a nonzero gradient at valid positions, so a completely disconnected computation graph cannot be mistaken for correct masking.

Reject empty supervision and invalid labels

Add negative test cases that require the function to fail explicitly rather than return a plausible-looking number.

for bad in (
    [[IGNORE, IGNORE]],
    [[0, 3]],
    [[0, -1]],
):
    try:
        masked_loss(base, mx.array(bad, dtype=mx.int32))
    except ValueError:
        pass
    else:
        raise AssertionError("Invalid labels accepted")

A batch containing only ignored labels must not be papered over by adding a tiny constant to the denominator. The training loop should either reject the data or skip the entire update step and record why it was skipped. Simply setting the loss to zero while still running the optimizer may continue to advance momentum, weight decay, and the update-step count.

Also add a set of nonuniform logits. Manually create positions where the correct class has a higher score and positions where it has a lower score, then check that the former have lower loss. The all-zero fixture is useful for testing the denominator, but cannot by itself prove that the correct class indices were selected.

Checks before integrating into an experiment

Run the tests in a separate process and block training from starting if the exit code is nonzero. Record the Python and MLX versions, the script version, and the rules used to generate supervision labels. Rerun the tests after dependency upgrades rather than relying on a previous pass.

  • Append different numbers of ignored positions to the same valid sequence and verify that the loss stays unchanged.
  • When mixing long and short samples, normalize by the total number of valid tokens rather than averaging each sequence first.
  • After changing how batches are split, recompute the aggregate from the loss sums and valid-token counts.
  • After truncation, confirm that supervised tokens remain so that the entire answer has not been cut off.
  • Apply the next-token shift exactly once, and ensure that labels and logits have matching time-axis lengths.

Finally, run the loss implementation used in actual training through the same fixtures and compare it with the reference function. The goal is not to make two curves look similar. It is to obtain reproducible evidence for valid positions, class indexing, the denominator, and gradients. Only once these contracts are established is the training curve a reliable basis for comparing experiments.

Frequently asked questions

Can an ignored label go directly into an indexing operation?

Do not rely on negative-index behavior. Build a validity mask, replace ignored labels with a valid index, gather the losses, and apply the mask afterward. Reject other out-of-range labels.

What should happen when a batch has no valid tokens?

Reject it explicitly or skip the entire update in the training loop. Returning zero loss alone does not prevent momentum, weight decay, or the optimizer step counter from changing.

Choose a cloud Mac by model and memory

Dedicated Apple Silicon M4 / M4 Pro machines with 16 GB, 24 GB, or 64 GB of unified memory. Pay by the day, week, month, or quarter; service stops at the end of your term unless you renew.

Verify your experiment requirements

Compare model size, unified memory, and billing period, then choose a dedicated physical machine.