[Bug] [Relax] nll_loss_backward skips negative ignore_index causing OOB read, wrong gradients, and SIGSEGV
Los mantenedores suelen responder en 3 días
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
- Área
- machine-learning
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
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:
- Silent wrong gradient: Reading garbage/adjacent memory at
w[-100]corruptsweight_sum(all_weights_red) inreduction="mean". When memory atw[-100]holds500.0,dL/dlp[0, 1]becomes-2.0 / (2.0 + 500.0) = -0.00398406instead of-1.000000. - Heap out-of-bounds
SIGSEGV: Withignore_index=-10000000andtgt=[0, -10000000], the process immediately crashes withSIGSEGV(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 inlegalize_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
- 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 apache/tvm
-
[Bug] [Relax] `relax.op.unique(return_inverse=True)` returns an input-shaped inverse for N-D input when `axis` is NonePosiblemente ocupada Un pull request vinculado a esta issue está abierto o ya se fusionó. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 3 días
-
[Bug][TOPI] `topi.scanop` (`cumsum` / `cumprod`) performs out-of-bounds write/read on empty tensorsAbiertoneeds-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
Los mantenedores suelen responder en 3 días
-
[Bug] [Relax] take_backward does not normalize negative axis causing heap OOB write and wrong gradientsPosiblemente ocupada @pierceluu10 la tomó hace 4 días. Abiertoneeds-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 3 días
-
[Bug][Relax][ONNX] NonZero returns the wrong output shape for scalar inputsPosiblemente ocupada @tandede la tomó hace 9 días. Abiertoneeds-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
Los mantenedores suelen responder en 3 días
-
needs-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
apache/tvm#21043 · 1 comentario ·
Los mantenedores suelen responder en 3 días
Todos los issues de apache/tvm
Issues similares
-
Dificultad 1/5 1-3 horas Aptitud para principiantes 78/100
web-push-libs/pywebpush#216 · 1 comentario ·
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
AgriciDaniel/claude-seo#572 ·
Los mantenedores suelen responder en 5 días
-
area:print-dispatch
Dificultad 2/5 1-3 horas Aptitud para principiantes 92/100
Los mantenedores suelen responder en 1 día
-
area: docs domain: technical-writing good first issue type: documentation
Dificultad 2/5 1-3 horas Aptitud para principiantes 80/100
Deepak3699/Ai_Mentor#919 ·
Los mantenedores suelen responder en 2 días
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día