Skip to content

[BUG] array.at[2D-slice].add(values) silently drops updated values when the values tensor is sparse #3477

Closed

Description

@AlexisGoodfellow

Describe the bug

Given a float array T of shape (H, W) and a 2D scatter-add via slice:
T_new = T.at[py_s:py_e, px_s:px_e].add(delta)
where delta has the same shape as the slice (py_e-py_s, px_e-px_s),
the operation works correctly when delta is dense (every entry
non-zero) but silently drops most updates when delta is sparse
(mostly zero with isolated non-zero values).

To Reproduce

"""
Minimal repro for an MLX 0.31.2 bug in `array.at[2D-slice].add(values)`
when the values tensor is mostly zeros (sparse).

Summary
-------
The worked example below:
  - T  = ones(32, 32)
  - delta has a single nonzero at delta[8, 8] = -0.212
  - We expect T_new[8, 8] = 1 + (-0.212) = 0.788
  - We observe T_new[8, 8] = 1.0 (the update was silently dropped)

A constant delta (all -0.212 throughout) returns the correct result.
The bug is sparsity-dependent.
"""
import mlx.core as mx
import numpy as np


def case_sparse_delta_drops_updates() -> None:
    """Sparse delta — bug fires."""
    T = mx.ones((32, 32))
    delta_np = np.zeros((16, 16), dtype=np.float32)
    delta_np[8, 8] = -0.212
    delta = mx.array(delta_np)

    T_new = T.at[0:16, 0:16].add(delta)
    mx.eval(T_new)

    actual = float(T_new[8, 8])
    expected = 1.0 + (-0.212)
    print(f"[sparse delta]  T_new[8,8] = {actual:.6f}  (expected {expected:.6f})  "
          f"{'PASS' if abs(actual - expected) < 1e-5 else 'FAIL — bug'}")


def case_dense_delta_works() -> None:
    """Same shape, but every position is non-zero — works correctly."""
    T = mx.ones((32, 32))
    delta = mx.full((16, 16), -0.212)

    T_new = T.at[0:16, 0:16].add(delta)
    mx.eval(T_new)

    actual = float(T_new[8, 8])
    expected = 1.0 + (-0.212)
    print(f"[dense delta]   T_new[8,8] = {actual:.6f}  (expected {expected:.6f})  "
          f"{'PASS' if abs(actual - expected) < 1e-5 else 'FAIL — bug'}")


def case_sparse_via_pure_mlx_ops() -> None:
    """Constructing the sparse delta entirely with MLX ops (no numpy bridge)
    — bug still fires, so it's not a numpy-import-time issue."""
    T = mx.ones((32, 32))
    zeros = mx.zeros((16, 16))
    delta = zeros.at[8, 8].add(mx.array(-0.212))   # 1D scatter to build sparse delta

    T_new = T.at[0:16, 0:16].add(delta)
    mx.eval(T_new)

    actual = float(T_new[8, 8])
    expected = 1.0 + (-0.212)
    print(f"[sparse via mlx] T_new[8,8] = {actual:.6f}  (expected {expected:.6f})  "
          f"{'PASS' if abs(actual - expected) < 1e-5 else 'FAIL — bug'}")


def case_three_isolated_nonzeros() -> None:
    """Three nonzero positions — only the first one gets applied."""
    T = mx.ones((32, 32))
    delta_np = np.zeros((16, 16), dtype=np.float32)
    delta_np[0, 0] = -0.5
    delta_np[8, 8] = -0.212
    delta_np[15, 15] = -0.3
    delta = mx.array(delta_np)

    T_new = T.at[0:16, 0:16].add(delta)
    mx.eval(T_new)

    print(f"[three nonzeros] T_new[0,0]   = {float(T_new[0, 0]):.6f}   (expected 0.500)")
    print(f"                  T_new[8,8]   = {float(T_new[8, 8]):.6f}   (expected 0.788)")
    print(f"                  T_new[15,15] = {float(T_new[15, 15]):.6f} (expected 0.700)")


def case_workaround_via_concat() -> None:
    """Workaround: rebuild T via concatenation instead of scatter-add.
    This avoids the bug entirely."""
    T = mx.ones((32, 32))
    tile_T_np = np.ones((16, 16), dtype=np.float32)
    tile_T_np[8, 8] = 0.788
    tile_T = mx.array(tile_T_np)

    # Replace slice [0:16, 0:16] with tile_T via concat
    new_row = mx.concatenate([tile_T, T[0:16, 16:32]], axis=1)
    T_new = mx.concatenate([new_row, T[16:32]], axis=0)
    mx.eval(T_new)

    actual = float(T_new[8, 8])
    expected = 0.788
    print(f"[concat workaround] T_new[8,8] = {actual:.6f}  (expected {expected:.6f})  "
          f"{'PASS' if abs(actual - expected) < 1e-5 else 'FAIL'}")


if __name__ == "__main__":
    print(f"mlx version: {mx.__version__ if hasattr(mx, '__version__') else 'unknown'}")
    import mlx
    print(f"mlx package: {mlx.__version__ if hasattr(mlx, '__version__') else 'unknown'}\n")

    case_sparse_delta_drops_updates()
    case_dense_delta_works()
    case_sparse_via_pure_mlx_ops()
    case_three_isolated_nonzeros()
    case_workaround_via_concat()

Expected behavior
Expected and observed behavior in the example code provided

Desktop (please complete the following information):

  • OS Version: 26.4.1 (M5)
  • Version: mlx==0.31.2, mlx-metal==0.31.2, Python 3.12

Activity

  1. changed the title [-][BUG][/-] [+][BUG] `array.at[2D-slice].add(values)` silently drops updated when the values tensor is sparse[/+] on May 4, 2026
  2. changed the title [-][BUG] `array.at[2D-slice].add(values)` silently drops updated when the values tensor is sparse[/-] [+][BUG] `array.at[2D-slice].add(values)` silently drops updated values when the values tensor is sparse[/+] on May 4, 2026
  3. zcbenz commented on May 5, 2026

    @zcbenz
    Member

    Thanks for reporting, I confirm that this is a v0.31.2 only bug. Might be related to #3266 /cc @angeloskath.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions