Skip to content

fix(eval): preserve integer tensor dtype during precision cast - #152

Open
moria97 wants to merge 3 commits into
ScalingIntelligence:mainfrom
moria97:fix/preserve-int-dtype-precision-cast
Open

moria97 wants to merge 3 commits into
ScalingIntelligence:mainfrom
moria97:fix/preserve-int-dtype-precision-cast

Conversation

@moria97

@moria97 moria97 commented Apr 16, 2026 •

Copy link
Copy Markdown

Closes #151.

Summary

_process_input_tensor currently casts every input tensor to the configured precision (default torch.float32). For tasks whose get_inputs() returns integer class indices (e.g. torch.randint(0, num_classes, ...) in CrossEntropyLoss / NLLLoss / KLDivLoss problems), this turns the int64 target tensor into float32 and breaks PyTorch dispatch:

NotImplementedError: "nll_loss_forward_reduce_cuda_kernel_2d_index"
  not implemented for 'Float'

This regression was introduced by #80; earlier versions had explicit integer-dtype protection that was lost during the precision-support refactor.

Change

Skip the precision cast for integer and boolean tensors and only move them to the target device. Floating-point and complex tensors retain the existing conversion to the requested precision, including discarding the imaginary component when converting complex tensors to a real dtype. Full complex-number support is outside the scope of this fix.

if not input.is_floating_point() and not input.is_complex():
    return input.to(device=device)
input_tensor = input.to(dtype=precision)
return input_tensor.to(device=device)

Test plan

  • level1/95_CrossEntropyLoss — fails before, passes after (ref impl now runs to completion)
  • level1/98_KLDivLoss — same
  • Spot-checked level1/1_Square_matrix_multiplication_ and a few activation problems to confirm float behavior is unchanged
  • No callers of _process_input_tensor need updating; the signature is preserved

Affects all 4 call sites in eval.py automatically.

CPU and optional CUDA regression coverage

Added src/kernelbench/unit_tests/test_process_input_tensor.py covering integer/bool dtype and value preservation (including large int64 values), fp32/fp16/bf16 conversion, unchanged complex-to-real conversion, CrossEntropyLoss class-index inputs, and non-tensor passthrough.

Validation: PYTHONPATH=src python -m pytest src/kernelbench/unit_tests/test_process_input_tensor.py -q — 29 passed on Python 3.10.12 / PyTorch 2.14.1+cpu. The suite now runs each case on CPU and CUDA, skipping CUDA cases when torch.cuda.is_available() is false. CUDA cases check actual device transfer, dtype/value preservation, and CrossEntropyLoss execution on the GPU. Latest validation in the current container: 29 passed, 29 CUDA cases skipped (no exposed NVIDIA device; CPU-only PyTorch). CUDA execution and full-harness validation remain unverified here. Run the same command in a CUDA-enabled PyTorch environment to execute all 58 cases.

`_process_input_tensor` currently casts every input tensor to the
configured `precision` (default fp32). For tasks whose `get_inputs()`
returns integer class indices (e.g. `torch.randint(0, num_classes, ...)`
in CrossEntropyLoss / NLLLoss / KLDivLoss problems), this turns the
int64 target tensor into float32, breaking PyTorch dispatch and
surfacing as misleading errors like:

    NotImplementedError:
      "nll_loss_forward_reduce_cuda_kernel_2d_index" not implemented
      for 'Float'

The error looks like a CUDA arch coverage gap but is actually our cast.

Skip the precision cast for non-floating-point tensors and only move
them to the target device. Floating-point activations / weights still
get cast to the requested precision unchanged.

Repro on level1/95_CrossEntropyLoss with precision=fp32 fails before
this change and passes after.

Copy link
Copy Markdown

I independently reproduced the integer-target failure and checked the exact head of this PR, 7697fb876623fff7750634a605bcc4ebfe563d18, against base 423217d9fda91e0c2d67e4a43bf62f96f6d104f1.

This was a CPU-only diagnostic, using PyTorch 2.9.0 / Python 3.12.14 on macOS arm64. I used the unchanged 95_CrossEntropyLoss.Model with a deterministic 4×7 fixture, not the shipped 32768×4096 shape or the full official evaluation harness.

  • Base helper: int64 labels become float32; the reference raises RuntimeError: expected scalar type Long but found Float before a candidate kernel is involved.
  • Exact PR head: label values/dtype are preserved; loss is bit-identical to the direct reference (1.997776746749878 for seed 261024151).
  • 72 integer/bool cases and 36 floating-conversion cases passed on CPU. The four backend names were helper argument options, not executions of those GPU backends.
  • Additional controls covered large int64 values above float32's exact-integer range, noncontiguous/empty/scalar tensors and non-tensor inputs.

One compatibility question: not input.is_floating_point() also preserves complex tensors. Current main casts their real component to the requested floating dtype. Is preserving complex dtype intended? I am flagging the scope difference, not asserting that the PR's policy is wrong.

I retained pinned source identities, original input bytes, prepared labels, the original exception and both available loss outputs before assertions, plus regression controls. A separate local process recomputed the reference and verified the artifact hashes. This is not an external review or GPU/full-harness performance validation, and I have not checked the KLDivLoss claim.

Would you be willing to reproduce this CPU check and confirm the intended complex-dtype policy? Would a small regression test for integer/bool preservation be useful here? I can adapt the standalone reproduction to your preferred test layout. Credit for the original finding and fix remains with @moria97; I am not opening a competing fix.

Standalone pinned CPU reproduction (PyTorch required)

This quick diagnosis downloads three hash-pinned upstream files. It does not install the whole benchmark or capture the full durable evidence packet.

"""Quick CPU diagnosis. Full durable evidence is in the separate pilot packet."""
import ast
import hashlib
from pathlib import Path
import sys
import urllib.request
import warnings

import torch

BASE = "423217d9fda91e0c2d67e4a43bf62f96f6d104f1"
HEAD = "7697fb876623fff7750634a605bcc4ebfe563d18"


def source(repo, ref, path, local, expected):
    if len(sys.argv) > 1:
        data = (Path(sys.argv[1]) / local).read_bytes()
    else:
        url = f"https://raw.githubusercontent.com/{repo}/{ref}/{path}"
        data = urllib.request.urlopen(url, timeout=20).read()
    assert hashlib.sha256(data).hexdigest() == expected
    return data.decode()


def helper(text):
    node = next(n for n in ast.parse(text).body
                if isinstance(n, ast.FunctionDef) and n.name == "_process_input_tensor")
    namespace = {"torch": torch}
    exec(compile(ast.Module(body=[node], type_ignores=[]), "pinned-helper", "exec"), namespace)
    return namespace[node.name]


base = helper(source("ScalingIntelligence/KernelBench", BASE, "src/kernelbench/eval.py", "eval.py",
                     "b42ce1268ec64ee7274db307ab98945c1e868792b54689554014b28c41787ee6"))
head = helper(source("moria97/KernelBench", HEAD, "src/kernelbench/eval.py", "PR152-eval.py",
                     "dcab0c922c2a620966fa4610a727402f9901a451b5f9f3fe80ffd39055ec77cc"))
reference = source("ScalingIntelligence/KernelBench", BASE, "KernelBench/level1/95_CrossEntropyLoss.py",
                   "95_CrossEntropyLoss.py", "4cdfaaf1c2118369987c7a0c24b4487fee4bb90fdce50f592bded59cf61ae9bd")
namespace = {}
exec(compile(reference, "pinned-reference", "exec"), namespace)
model = namespace["Model"]().eval()
torch.set_num_threads(1)
torch.manual_seed(261024151)
x = torch.rand(4, 7)
labels = torch.randint(0, 7, (4,))
with torch.no_grad():
    expected = model(x, labels)
    bad_labels = base(labels, "cpu", precision=torch.float32)
    try:
        model(base(x, "cpu"), bad_labels)
    except RuntimeError as exc:
        print("base", bad_labels.dtype, type(exc).__name__, str(exc))
    else:
        raise AssertionError("base failure did not reproduce")
    good_labels = head(labels, "cpu", precision=torch.float32)
    actual = model(head(x, "cpu"), good_labels)
    assert good_labels.dtype == torch.int64 and torch.equal(good_labels, labels)
    assert torch.equal(expected, actual)
    print("PR152", good_labels.dtype, "loss", actual.item(), "bit-identical to direct CPU reference")
    with warnings.catch_warnings(record=True):
        z = torch.tensor([2 + 3j], dtype=torch.complex64)
        print("complex scope:", base(z, "cpu").dtype, "->", head(z, "cpu").dtype)
print("CPU helper diagnostic only; no GPU, full-shape, full-harness or performance result.")

moria97 commented Oct 26, 2026

Copy link
Copy Markdown
Author

@yoheinakajima Thanks for independently reproducing this and pointing out the complex-dtype scope change.

Preserving complex dtype was not intended as part of this integer/bool fix. Updated in 324f198: the guard is now not input.is_floating_point() and not input.is_complex(). Integer and boolean inputs retain their dtype and values; floating-point and complex inputs keep the existing precision conversion, including discarding the imaginary component for complex-to-real casts. This preserves compatibility; it is not a claim that discarding the imaginary component is the right long-term complex policy. Full complex support would need a separate policy covering both inputs and model parameters.

I also added CPU regression tests for integer/bool preservation (including large int64 values), floating-point conversion, existing complex-to-real behavior, non-tensor passthrough, and a small CrossEntropyLoss case. The CrossEntropyLoss test independently reproduces the core small-fixture CPU check through the actual helper; I did not rerun your exact pinned script or evidence-packet verification.

Validation: PYTHONPATH=src python -m pytest src/kernelbench/unit_tests/test_process_input_tensor.py -q — 29 passed with Python 3.10.12 / PyTorch 2.14.1+cpu. No new GPU/full-harness validation was performed. The PR description now reflects the narrowed scope and regression coverage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] precision cast in _process_input_tensor breaks integer target tensors (cross_entropy / nll_loss / kl_div)

2 participants