[BUG]: CPU matmul epilogue reads a transposed operand wrongly after a reshape

Abierto
#7,654 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 2 días

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
55/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
numpy

Línea de trabajo

Start with the reproduction script in the issue and compare the failing transposed, reshaped case with the two passing cases. Then read elementwise_epilogue_c_tile in max/kernels/src/linalg/matmul/cpu/impl.mojo around lines 151–168 and inspect the generated __matmul_static_reshape_* kernel for the failing shape. Done means the CPU result matches NumPy across the reported failing sizes and the reproduction cases still pass.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug bug_feature_triaged max
Bug description

On CPU, transpose(m) * reshape(w @ x) gives wrong values: garbage such as 1e35 or NaN, varying from run to run. Here w @ x is [dim, n * n], reshaped to [dim, n, n], and m is [n, n]. Without the transpose, or without the reshape (w @ x already [n, n]), the output matches numpy. It also matches at most lengths: of n = 1 to 40 with dim = 8, only 4, 5, 15, 33 and 38 give wrong values.

Expected: the same values as numpy for every n.

Claude suggested root cause

The graph compiler fuses the multiply into MatmulCPU's epilogue (a single __matmul_static_reshape_* kernel). In the IR, the epilogue maps the start of each SIMD chunk from the [8, 25] matmul coordinate to the [8, 5, 5] view with mogg.index.reshape. It then does one SIMD-wide mogg.tensor.load from the transposed (and broadcast) m at that 3D index:

%16 = mogg.index.reshape(%idx) <fromShape = #mosh<ape[8, 25]> : !mosh.ape, toShape = #mosh<ape[8, 5, 5]> : !mosh.ape> : !map.index<2> -> !map.index<3>
%17 = mogg.tensor.load %cap1[%16] : !mogg.tensor, !map.index<3> -> !mogg.simd<f32>
%18 = mogg.call.elementwise @builtin_kernels.elementwise.Mul(%17, %val) moOpName = "mo.mul" : !mogg.simd<f32>, !mogg.simd<f32> -> !mogg.simd<f32>
mogg.tensor.store %cap0[%16] = %18 : !mogg.tensor, !map.index<3>, !mogg.simd<f32>

elementwise_epilogue_c_tile vectorizes over the matmul's N columns (impl.mojo L151-L168), so a chunk can cross a row of the reshaped view. For a contiguous operand that happens to be harmless. For a transposed one, the load reads the wrong elements and runs past the row, which matches the garbage. In the wrong outputs, row 0 is correct and rows from 1 on are wrong.

Assisted-by: AI (investigation, repro and draft; reviewed by me)

Steps to reproduce
uv run repro.py
# /// script
# requires-python = ">=3.13"
# dependencies = ["max==26.8.0.dev2026111705", "numpy"]
# [tool.uv]
# extra-index-url = ["https://whl.modular.com/nightly/simple"]
# ///
"""CPU: transpose(m) * reshape(w @ x) is wrong; without the transpose or the reshape it is not."""

import numpy as np
from max.driver import CPU
from max.dtype import DType
from max.engine import InferenceSession
from max.graph import DeviceRef, Graph, TensorType, ops

session = InferenceSession(devices=[CPU()])
rng = np.random.default_rng(0)
dim = 8


def max_error(n: int, transpose: bool, reshape: bool) -> float:
    # With reshape, w @ x is [dim, n * n], viewed as [dim, n, n].
    # Without it, w @ x is already [n, n].
    shapes = [[n, n], [dim, dim], [dim, n * n]] if reshape else [[n, n], [n, dim], [dim, n]]
    types = [TensorType(DType.float32, s, DeviceRef.CPU()) for s in shapes]
    with Graph("g", input_types=types) as g:
        m, w, x = (v.tensor for v in g.inputs)
        y = w @ x
        if reshape:
            y = ops.reshape(y, [dim, n, n])
        if transpose:
            m = ops.transpose(m, 0, 1)
        g.output(m * y)
    m, w, x = (rng.standard_normal(s).astype(np.float32) for s in shapes)
    y = (w @ x).reshape(dim, n, n) if reshape else w @ x
    expected = (m.T if transpose else m) * y
    got = session.load(g).execute(m, w, x)[0].to_numpy()
    return float(np.abs(got - expected).max())


for n in (5, 16, 33):
    print(
        f"n={n:2}  transpose(m) * reshape(w @ x): {max_error(n, True, True):8.2e}"
        f"   m * reshape(w @ x): {max_error(n, False, True):8.2e}"
        f"   transpose(m) * (w @ x): {max_error(n, True, False):8.2e}"
    )

Output:

n= 5  transpose(m) * reshape(w @ x): 5.96e+32   m * reshape(w @ x): 0.00e+00   transpose(m) * (w @ x): 0.00e+00
n=16  transpose(m) * reshape(w @ x): 0.00e+00   m * reshape(w @ x): 0.00e+00   transpose(m) * (w @ x): 0.00e+00
n=33  transpose(m) * reshape(w @ x):      nan   m * reshape(w @ x): 0.00e+00   transpose(m) * (w @ x): 0.00e+00
System information
- MAX 26.8.0.dev2026111705 (latest nightly), installed with uv; source links at main `bbc13a719b`
- Linux x86_64, Intel Xeon with AVX-512 (target arch graniterapids), CPU only
- GPU not tested
Lenguaje dominante
Mojo
Estrellas
30.2k
Forks
3.2k
Merge medio
6 d 20 h
PR fusionados (30 d)
25

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de modular/modular

Todos los issues de modular/modular

Issues similares

Más issues de Backend & API Design

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.