cuda-index-width

작성자: pytorch

PyTorch CUDA 커널에서 32비트 대 64비트 인덱스 수학을 선택합니다. 대규모 텐서 인덱싱 오버플로우를 수정하거나 int64_t 사용 여부를 결정할 때 사용합니다.

npx skills add https://github.com/pytorch/pytorch --skill cuda-index-width

CUDA Index Width in PyTorch

Use this skill when a CUDA kernel overflows int indexing, fails near 2^31 elements, or needs a review of int vs int64_t index math.

Start with the overflow site

Do not blindly convert all index variables to int64_t. Find the expression that can exceed 32 bits and classify where it runs:

  • One-time setup per CTA or per output element group: prefer one local 64-bit cast at the first multiply.
  • Hot per-element linear indexing: template the kernel on index_t and dispatch int vs int64_t.
  • Unsupported algorithm with 32-bit-only assumptions: add a clear TORCH_CHECK(canUse32BitIndexMath(...)) instead of silently overflowing.
  • Grid dimension overflow: changing arithmetic type is not enough; add tiling/striding over that dimension.

Canonical utilities

Include/use the existing PyTorch utilities instead of ad hoc checks:

#include <ATen/native/CanUse32BitIndexMath.h>
#include <ATen/cuda/detail/KernelUtils.h>
  • at::native::canUse32BitIndexMath(tensor, INT_MAX) checks both numel and maximum storage offset.
  • For CUDA files that already include cuda detail wrappers, at::cuda::detail::canUse32BitIndexMath may be available as an alias.
  • AT_DISPATCH_INDEX_TYPES(cond ? ScalarType::Int : ScalarType::Long, "name", [&] { ... }); provides index_t.
  • CUDA_KERNEL_LOOP_TYPE(index, nthreads, index_t) keeps grid-stride loops correct for either width.

Check every tensor whose offsets are computed with the selected index type, not just the output tensor.

Fix patterns

1. Localized base-offset overflow

If only a base pointer offset can overflow and it is computed outside the hot loop, keep the kernel otherwise unchanged:

int64_t plane = blockIdx.x;
input = input + plane * strideD;
output = output + plane * osizeH * osizeW;

This avoids doubling kernel instantiations and keeps inner-loop arithmetic 32-bit. Use this when dimensions inside the tile still fit in int.

2. Grid-stride linear kernels

If the loop index, modulo/division decomposition, or final data[index] access can exceed 32 bits, template the kernel:

template <typename scalar_t, typename index_t>
__global__ void kernel(index_t n, const scalar_t* in, scalar_t* out) {
  CUDA_KERNEL_LOOP_TYPE(index, n, index_t) {
    out[index] = in[index];
  }
}

AT_DISPATCH_INDEX_TYPES(
    canUse32BitIndexMath(out, INT_MAX) && canUse32BitIndexMath(in, INT_MAX)
        ? ScalarType::Int
        : ScalarType::Long,
    "kernel_index_type",
    [&] {
      kernel<scalar_t, index_t><<<blocks, threads, 0, stream>>>(n, in, out);
      C10_CUDA_KERNEL_LAUNCH_CHECK();
    });

Prefer this over unconditionally changing the loop index to int64_t, because 64-bit division/modulo in a hot CUDA loop can be measurable.

3. TensorInfo/accessor or strided kernels

When offsets are computed from sizes/strides, dispatch on an index type only if all participating tensors pass canUse32BitIndexMath for that type. Remember that a small numel() tensor can still need 64-bit offsets if it is a large strided view.

4. 32-bit-only kernels

If supporting 64-bit indexing would require a larger algorithm rewrite or would exceed CUDA launch limits, fail early:

TORCH_CHECK(
    canUse32BitIndexMath(input) && canUse32BitIndexMath(output),
    "op_name: tensors must fit into 32-bit index math");

Only use this when the operator already has a documented or accepted size limitation; do not turn a reported correctness bug into an unnecessary limitation.

Binary-size and performance tradeoffs

Templating on index_t duplicates each affected kernel for every scalar dtype and memory-format specialization. Before adding index dispatch to several kernels, ask whether the overflow is in a hot path or only in one setup expression.

A/B candidate fixes when the choice is not obvious:

  1. Build each candidate from a clean diff using the same build environment.
  2. Record changed CUDA object and library sizes:
    stat -c '%s %n' build/aten/src/ATen/CMakeFiles/torch_cuda.dir/native/cuda/<file>.cu.o torch/lib/libtorch_cuda.so
    
  3. Check symbol multiplication for the kernel name:
    nm -S --size-sort -C torch/lib/libtorch_cuda.so | rg '<kernel_name>|index_t|long|int'
    
  4. If hot-loop arithmetic changed, benchmark representative small and large tensors; do not report performance from sanitizer runs.

Default decision:

  • One or two 64-bit setup multiplies: prefer the local cast.
  • Per-element indexing may exceed 32 bits: prefer index_t dispatch.
  • Existing kernel family already dispatches index_t: extend the existing pattern.
  • Changing many scalar-specialized kernels: consider binary size before templating all of them.

Tests for large-index fixes

Add a regression that crosses the exact boundary that failed:

  • Use the smallest dtype and output size that still exercises the overflow.
  • Assert tensor.numel() > torch.iinfo(torch.int32).max or assert the specific offset boundary.
  • Sample values from both below and above the boundary; avoid full-tensor CPU comparisons for huge tensors.
  • Run the original repro under compute-sanitizer for memory bugs:
    CUDA_LAUNCH_BLOCKING=1 PYTORCH_NO_CUDA_MEMORY_CACHING=1 compute-sanitizer --tool memcheck --error-exitcode=99 <python> repro.py
    

For PyTorch tests, prefer adding the regression near related pooling/indexing tests and guard expensive cases with @largeTensorTest and the relevant device decorator.

Review checklist

  • The exact overflowing expression is identified.
  • 64-bit math is limited to the expressions that need it, or the kernel is templated when the hot index needs it.
  • canUse32BitIndexMath considers every tensor whose offsets use the selected type.
  • CUDA launch dimensions still fit hardware limits.
  • The test fails before the fix and passes after it, or the report explains why pre-fix failure was not rerun.
  • Binary-size/performance impact is mentioned if new index_t dispatch duplicates kernels.

pytorch의 다른 스킬

zephyr
pytorch
임베디드 보드용 Zephyr RTOS 모듈로 ExecuTorch를 빌드하고 구성합니다. ET로 Zephyr 워크스페이스를 설정하거나 보드 지원(오버레이 등)을 추가할 때 사용합니다.
aoti-debug
pytorch
AOTInductor(AOTI) 오류 및 충돌을 디버깅합니다. AOTI 세그폴트, 장치 불일치 오류, 상수 로딩 실패 또는 런타임 오류가 발생할 때 사용하세요.
skill-writer
pytorch
Claude Code를 위한 잘 구조화된 Agent Skill 생성 가이드로, 모범 사례와 검증을 포함합니다. Skill의 전체 수명 주기(범위 설정, 파일 구조, YAML 프론트매터 검증, 콘텐츠 구성, 테스트 절차)를 다룹니다. 엄격한 명명 규칙(소문자, 하이픈, 최대 64자)과 설명 요구 사항(특정 트리거, 파일 유형, "무엇" 및 "언제" 절)을 적용합니다. 읽기 전용 Skill, 스크립트 기반 Skill, 다중 파일 Skill 등 일반적인 패턴에 대한 템플릿을 제공합니다.
triaging-issues
pytorch
GitHub 이슈를 분류하여 온콜 팀에 라우팅하고, 레이블을 적용하며, 질문을 종료합니다. 새로운 PyTorch 이슈를 처리하거나 이슈 분류를 요청받았을 때 사용하세요.
wheel-size-analyzer
pytorch
PyTorch nightly wheel 크기를 GitHub Actions 아티팩트 API를 사용하여 날짜 범위에 걸쳐 분석합니다. 바이너리 크기 변경 추적, wheel 크기 식별에 사용합니다…
release-go-live-binary-build-matrix
pytorch
tools/scripts/generate_binary_build_matrix.py를 PyTorch 릴리스가 라이브될 때 업데이트합니다. CURRENT_STABLE_VERSION을 새로운 안정 버전으로 올리고, 해당…
pr-review
pytorch
PyTorch 풀 리퀘스트의 코드 품질, 테스트 커버리지, 보안 및 하위 호환성을 검토합니다. PR을 검토할 때, 코드 변경 사항을 검토하도록 요청받았을 때 사용합니다.
qualcomm
pytorch
QNN(Qualcomm AI Engine Direct) 백엔드를 빌드, 테스트 또는 개발합니다. backends/qualcomm/에서 작업하거나 QNN을 빌드할 때 사용합니다(계속…).