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

Ouverte
#7,654 1 commentaire 0 réactions 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 2 jours

Personne n'a encore pris cette issue.

Évaluation

Difficulté
4/5
Temps estimé
3-5 jours
Accessibilité débutants
55/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Active
Stack technique
numpy
Domaine
backend, performance

Piste de recherche

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.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

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
Langage dominant
Mojo
Étoiles
30.2k
Forks
3.2k
Merge moyen
6 j 20 h
PR mergées (30 j)
25

Préparer son environnement

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de modular/modular

Toutes les issues de modular/modular

Issues similaires

Plus d'issues Backend & API Design

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.