[Bug] [Relax] nll_loss_backward skips negative ignore_index causing OOB read, wrong gradients, and SIGSEGV

Abierto
#21,068 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 3 días

@pierceluu10 ya está trabajando en esto.

Desde el 29/11/2026.

  • #21087 de @pierceluu10 — abierto

Evaluación

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

Línea de trabajo

Start in python/tvm/relax/transform/legalize_ops/grad.py at _grad_nll_loss_backward and trace how all_weights is built and used in the mean reduction. Check the NLL loss backward tests and add coverage for negative and out-of-range ignore_index values. Done means ignored targets never cause an out-of-bounds weight read and contribute zero to the weight sum and prediction gradient.

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

Descripción

needs-triage type: bug
Expected behavior

R.nn.nll_loss and R.grad.nll_loss_backward both document ignore_index: int = -100 as the default value (matching PyTorch). Any target entry equal to ignore_index (whether negative such as -100 or out-of-range non-negative such as 255) must be masked out before indexing weights, contributing 0 to weight_sum and 0 to pred_grad.

For lp of shape (2, 4), w = [1.0, 2.0, 3.0, 4.0], tgt = [1, -100], reduction="mean", ignore_index=-100, only sample 0 is active: L = (-lp[0, 1] * w[1]) / w[1] = -lp[0, 1], so dL/dlp[0, 1] must be -1.0.

Actual behavior

In python/tvm/relax/transform/legalize_ops/grad.py (_grad_nll_loss_backward, lines 56–63):

if ignore_index >= 0:
    weights = te.compute(
        weights.shape,
        lambda i: tirx.Select(i == ignore_index, tirx.const(0, weights.dtype), weights(i)),
        "weights_new",
    )

all_weights = te.compute(targets.shape, lambda *i: weights(targets(*i)), "all_weights")

Because of if ignore_index >= 0:, all negative ignore_index values (including the default -100) are completely skipped, and all_weights unconditionally emits an unguarded out-of-bounds memory load w[tgt[v_i0]] (e.g., w[-100]):

for i0 in range(T.int64(4)):
    with T.sblock("all_weights"):
        v_i0 = T.axis.spatial(T.int64(4), i0)
        all_weights[v_i0] = w[tgt[v_i0]]   # OOB heap read at w[-100]!

(Even for non-negative ignore_index >= num_classes, e.g., ignore_index=255 on a 4-class tensor, weights(targets(*i)) still reads out of bounds!)

Consequences:

  1. Silent wrong gradient: Reading garbage/adjacent memory at w[-100] corrupts weight_sum (all_weights_red) in reduction="mean". When memory at w[-100] holds 500.0, dL/dlp[0, 1] becomes -2.0 / (2.0 + 500.0) = -0.00398406 instead of -1.000000.
  2. Heap out-of-bounds SIGSEGV: With ignore_index=-10000000 and tgt=[0, -10000000], the process immediately crashes with SIGSEGV (exit code -11).
Environment
  • TVM version: apache-tvm==0.27.0.post1
  • OS: Linux (x86_64)
  • Python: 3.12.x
  • Target: llvm (backend-independent — the bug is in legalize_ops/grad.py)
Steps to reproduce
import numpy as np
import tvm
from tvm import relax
from tvm.script import ir as I, relax as R

@I.ir_module
class Module:
    @R.function
    def main(
        lp: R.Tensor((2, 4), "float64"),
        w: R.Tensor((4,), "float64"),
        tgt: R.Tensor((2,), "int64"),
    ) -> R.Tensor((), "float64"):
        with R.dataflow():
            s = R.nn.nll_loss(lp, tgt, w, reduction="mean", ignore_index=-100)
            R.output(s)
        return s

dev = tvm.cpu(0)
gmod = relax.transform.Gradient("main")(Module)
lgmod = relax.transform.LegalizeOps()(gmod)
vm = relax.VirtualMachine(tvm.compile(lgmod, target="llvm"), dev)

lp = np.array([[-1.0, -2.0, -3.0, -4.0], [-0.5, -1.5, -2.5, -3.5]], dtype="float64")
# Construct a 64-byte aligned zero-copy slice whose [-100] element is deterministically 500.0
big = np.full((300,), 500.0, dtype="float64")
offset = 128
while (big.ctypes.data + offset * 8) % 64 != 0:
    offset += 1
big[offset : offset + 4] = np.array([1.0, 2.0, 3.0, 4.0], dtype="float64")
w_tvm = tvm.runtime.from_dlpack(big[offset : offset + 4])
tgt = np.array([1, -100], dtype="int64")

_, (grad_lp, _, _) = vm["main_adjoint"](tvm.runtime.tensor(lp, dev), w_tvm, tvm.runtime.tensor(tgt, dev))
print("Expected dL/dlp[0, 1]              : -1.000000")
print("Actual TVM nll_loss_backward [0, 1]:", float(grad_lp.numpy()[0, 1]))
print("OOB formula -2.0 / (2.0 + 500.0)   :", -2.0 / 502.0)

Observed output on apache-tvm==0.27.0.post1:

Expected dL/dlp[0, 1]              : -1.000000
Actual TVM nll_loss_backward [0, 1]: -0.00398406374501992
OOB formula -2.0 / (2.0 + 500.0)   : -0.00398406374501992

Replacing ignore_index=-100 / tgt=[1, -100] with ignore_index=-10000000 / tgt=[0, -10000000] triggers an immediate SIGSEGV (exit code -11).

Suggested Fix

In te_nll_loss_backward, guard the all_weights load directly with tirx.if_then_else(targets(*i) == ignore_index, tirx.const(0, weights.dtype), weights(targets(*i))) (avoiding eager OOB memory evaluation on ignored indices regardless of whether ignore_index is negative or >= num_classes).

Triage
  • needs-triage
  • relax
Lenguaje dominante
Python
Estrellas
13.9k
Forks
4.1k
Merge medio
4 d 22 h
PR fusionados (30 d)
22

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

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 apache/tvm

Todos los issues de apache/tvm

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.