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

Aperta
#21,068 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 3 giorni

@pierceluu10 ci sta già lavorando.

Dal 29/11/2026.

  • #21087 di @pierceluu10 — aperta

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
68/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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
Lingua principale
Python
Stelle
13.9k
Fork
4.1k
Merge medio
4g 22h
PR unite (30g)
22

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di apache/tvm

Tutte le issue di apache/tvm

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.