Repository navigation
Conversation
`_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.
|
I independently reproduced the integer-target failure and checked the exact head of this PR, This was a CPU-only diagnostic, using PyTorch 2.9.0 / Python 3.12.14 on macOS arm64. I used the unchanged
One compatibility question: 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.") |
|
@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 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: |
Closes #151.
Summary
_process_input_tensorcurrently casts every input tensor to the configuredprecision(defaulttorch.float32). For tasks whoseget_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: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.
Test plan
level1/95_CrossEntropyLoss— fails before, passes after (ref impl now runs to completion)level1/98_KLDivLoss— samelevel1/1_Square_matrix_multiplication_and a few activation problems to confirm float behavior is unchanged_process_input_tensorneed updating; the signature is preservedAffects all 4 call sites in
eval.pyautomatically.CPU and optional CUDA regression coverage
Added
src/kernelbench/unit_tests/test_process_input_tensor.pycovering 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 whentorch.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.