[BUG]: CPU matmul epilogue reads a transposed operand wrongly after a reshape
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
- Área
- backend, performance
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 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
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de modular/modular
-
bug_feature_triaged Team: Mojo Libraries
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
Los mantenedores suelen responder en 2 días
-
[BUG]Incomplete Apache LicenseAbiertobug bug_feature_triaged documentation mojo
Dificultad 1/5 Menos de una hora Aptitud para principiantes 62/100
Los mantenedores suelen responder en 2 días
-
`Counter.lt()` and `Counter.gt()` disagree with `__eq__`, and `a.lt(a)` can be `True`Posiblemente ocupada @YidaWeng la tomó hace 2 días. Abiertobug_feature_triaged Team: Mojo Libraries
Dificultad 2/5 1-3 horas Aptitud para principiantes 67/100
modular/modular#7696 · 2 comentarios ·
Los mantenedores suelen responder en 2 días
-
[BUG] `Counter` `-=`, `+=` and `&=` leave keys behind when they remove many keysPosiblemente ocupada @Tharun-Kumar-McW la tomó hace 5 días. Abiertobug bug_feature_triaged mojo-stdlib Team: Mojo Libraries
Dificultad 2/5 1-3 horas Aptitud para principiantes 75/100
modular/modular#7658 · 1 comentario ·
Los mantenedores suelen responder en 2 días
-
[BUG] exp(NaN) returns infAbiertobug bug_feature_triaged mojo Team: Mojo Libraries
Dificultad 2/5 1-3 horas Aptitud para principiantes 74/100
modular/modular#7646 · 3 comentarios ·
Los mantenedores suelen responder en 2 días
Todos los issues de modular/modular
Issues similares
-
bug done
Dificultad 2/5 1-3 horas Aptitud para principiantes 65/100
neavo/LinguaGacha#1124 ·
Los mantenedores suelen responder en 1 día
-
module/http Type/Bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
ballerina-platform/ballerina-library#9868 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 62/100
symgraph/GhidrAssistMCP#84 ·
Los mantenedores suelen responder en 2 días
-
Command gate: one shared constant for the just-below-1e-9 MoveAxis stop epsilon (ZWO, Bisque)Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 74/100
open-astro/AlpacaBridge#2606 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
reasons-gate
Dificultad 2/5 1-3 horas Aptitud para principiantes 62/100
benthomasson/reasonsforge#100 ·
Los mantenedores suelen responder en 1 día