[BUG]: CPU matmul leaves C unwritten when K == 0

Abierto
#7,737 0 comentarios 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
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
58/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python

Línea de trabajo

Start with the CPU matmul path in max/kernels/src/linalg/matmul/cpu/impl.mojo around lines 578-582, where work is sized as m * n * k, and with the early return in linalg/matmul/init.mojo around lines 298-299, which only handles M or N equal to 0. Run the Mojo K=0 reproducer from the issue, then the Python graph example. Done means C is set to zeros, with the epilogue applied, when K is 0 on CPU, including the batched and N == 1 paths.

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

Descripción

bug_feature_triaged

Bug description

# linalg.matmul on CPU leaves C unwritten when K = 0.
# (4 x 0) @ (0 x 8) is the 4 x 8 zero matrix; C starts as 7.0.
# Control: K = 1 with all-ones inputs must give 1.0.
from layout import TileTensor, row_major
from linalg.matmul import matmul


def c00(k: Int) raises -> Float32:
    var a = List[Float32](length=max(4 * k, 1), fill=1)
    var b = List[Float32](length=max(k * 8, 1), fill=1)
    var c = List[Float32](length=4 * 8, fill=7)
    matmul(
        TileTensor(c, row_major(4, 8)),
        TileTensor(a, row_major(4, k)).as_imm(),
        TileTensor(b, row_major(k, 8)).as_imm(),
    )
    return c[0]


def main() raises:
    print("K=0: C[0,0] =", c00(0), " right value 0.0")
    print("K=1: C[0,0] =", c00(1), " right value 1.0 (control)")
K=0: C[0,0] = 7.0  right value 0.0
K=1: C[0,0] = 1.0  right value 1.0 (control)

This came up in MojoProof, where I'm writing Lean specs for Mojo kernels: for matmul the K = 0 case should be the zero matrix, but on CPU linalg.matmul.matmul returns without touching C, so whatever was in the buffer comes back. batched_matmul and the N == 1 gemv path do the same. I used a bit of AI to help check the other paths and went through it myself.

Actual behavior

C keeps its old contents.

Expected behavior

The M x N zero matrix (with the epilogue applied to zeros), like NumPy and PyTorch.

Steps to reproduce

AI-generated analysis and reproduction

The CPU kernel sizes its work as m * n * k, so k = 0 means zero tasks (impl.mojo L578-L582), and matmul only returns early for M or N == 0 (init.mojo L298-L299). Zero-filling C when K == 0 would cover it. It also shows up through the graph API with a symbolic K that is 0 at run time, where ops.matmul(a, b) + 0.5 gives stale values or garbage instead of 0.5:

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

dev = DeviceRef.CPU()
types = [
    TensorType(DType.float32, ["M", "K"], device=dev),
    TensorType(DType.float32, ["K", "N"], device=dev),
]
with Graph("mm", input_types=types) as g:
    a, b = g.inputs
    g.output(ops.matmul(a, b) + ops.constant(0.5, DType.float32, device=dev))

model = InferenceSession(devices=[CPU()]).load(g)
for k in (1, 0, 1, 0, 1, 0):
    lhs = np.full((4, k), 3.0, np.float32)
    rhs = np.full((k, 8), 3.0, np.float32)
    out = model.execute(Buffer.from_numpy(lhs), Buffer.from_numpy(rhs))[0]
    print(f"K={k}: expected {9 * k + 0.5}, got {np.unique(out.to_numpy())[:3]}")
K=1: expected 9.5, got [9.5]
K=0: expected 0.5, got [9.]
K=1: expected 9.5, got [9.5]
K=0: expected 0.5, got [-1.7559357e+00  0.0000000e+00  9.6241179e-42]
K=1: expected 9.5, got [9.5]
K=0: expected 0.5, got [-1.7558594e+00  9.6241179e-42  9.0000000e+00]

(The K = 0 values change from run to run: it's whatever was in the buffer.)

GPU batched_matmul also returns early for k == 0 (bmm.mojo L989-L990); I haven't run that one. Is it meant to leave C alone? Happy to send a PR for the CPU side :)

System information

Mojo 1.3.0.dev2026112105 (f23ed0af)
MAX 26.8.0.dev2026112105
installed with pip from the nightly index (https://whl.modular.com/nightly/simple/)
Amazon Linux 2023, x86_64, Intel Xeon Platinum 8275CL
Python 3.12.13

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 Machine Learning

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.