Synthèse automatique
Guide la décision entre arithmétique d'index 32 bits et 64 bits dans les kernels CUDA PyTorch, afin de corriger les débordements sur les très grands tenseurs sans dégrader les performances.
Points forts
- Classe le site de débordement (offset calculé une seule fois, boucle chaude par élément, dimensions de grille) et évite la conversion réflexe de tous les index en int64_t
- S'appuie sur les utilitaires PyTorch existants : canUse32BitIndexMath, AT_DISPATCH_INDEX_TYPES, CUDA_KERNEL_LOOP_TYPE
- Fournit des patrons de correctif concrets, y compris l'échec explicite via TORCH_CHECK pour les kernels limités à 32 bits
- Signale les pièges classiques : petites vues strided à grands offsets, dépassement des dimensions de grille, duplication des instantiations de kernel
Limites
- Se concentre uniquement sur la largeur des index : pas de conseil sur le tuning CUDA global ni sur la correction algorithmique
- Suppose une bonne familiarité avec le code natif ATen/PyTorch et la compilation CUDA
- Le traitement du compromis taille binaire / performance est esquissé plutôt que détaillé, et les limites de grille ne sont mentionnées que brièvement
À utiliser quand un kernel CUDA PyTorch renvoie des résultats erronés au-delà de 2^31 éléments ou quand il faut trancher entre int et int64_t pour l'indexation.
À éviter pour des problèmes de performance CUDA sans lien avec la largeur des index, ou pour du code PyTorch Python de haut niveau.
Analyse de sécurité
SûrThis is technical documentation for PyTorch CUDA index-width choices. It includes only read-only build inspection and sanitizer commands, with no destructive, exfiltration, obfuscation, or safety-disabling behavior.
Aucun point d'attention détecté
Comment cette analyse est faiteExemples
My custom CUDA kernel in aten/src/ATen/native/cuda produces wrong results once the input has more than 2^31 elements. Find the index expression that overflows and tell me whether to use a localized int64_t base-offset cast or to template the kernel on index_t.Convert this grid-stride elementwise CUDA kernel to dispatch on index type using AT_DISPATCH_INDEX_TYPES and CUDA_KERNEL_LOOP_TYPE, with canUse32BitIndexMath checks on every participating tensor. Show the full host-side dispatch code.Review this strided CUDA kernel: it computes offsets from sizes and strides of several tensors, and some are large views with small numel(). Decide whether 32-bit index math is safe and add a TORCH_CHECK if it isn't.name: cuda-index-width description: Choose 32-bit vs 64-bit index math in PyTorch CUDA kernels. Use when fixing large-tensor indexing overflows, deciding whether to use int64_t, canUse32BitIndexMath, CUDA_KERNEL_LOOP_TYPE, or AT_DISPATCH_INDEX_TYPES, and when considering binary-size or performance impact of index-type templating.
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_tand dispatchintvsint64_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 bothnumeland maximum storage offset.- For CUDA files that already include cuda detail wrappers,
at::cuda::detail::canUse32BitIndexMathmay be available as an alias. AT_DISPATCH_INDEX_TYPES(cond ? ScalarType::Int : ScalarType::Long, "name", [&] { ... });providesindex_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:
- Build each candidate from a clean diff using the same build environment.
- 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 - Check symbol multiplication for the kernel name:
nm -S --size-sort -C torch/lib/libtorch_cuda.so | rg '<kernel_name>|index_t|long|int' - 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_tdispatch. - 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).maxor 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.
- [ ]
canUse32BitIndexMathconsiders 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_tdispatch duplicates kernels.
Du fichier au premier essai
Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.
Consulter la source et ses fichiers annexesCe téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.
1. Télécharger le fichier
Télécharger SKILL.mdDepuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/cuda-index-width-in-pytorch-mte1lflv/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.
Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.
mkdir -p '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/cuda-index-width-in-pytorch-mte1lflv/download' --output '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv/SKILL.md.part' && mv '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv/SKILL.md.part' '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv/SKILL.md'2. Vérifier les prérequis
Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.
Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.
Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.
3. Charger la skill
Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.
Claude Code
test -f '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv/SKILL.md' && test -s '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/cuda-index-width' && cp -R '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv' '.claude/skills/cuda-index-width'Cursor
test -f '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv/SKILL.md' && test -s '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/cuda-index-width' && cp -R '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv' '.cursor/skills/cuda-index-width'Codex
test -f '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv/SKILL.md' && test -s '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/cuda-index-width' && cp -R '.skill-downloads/cuda-index-width-in-pytorch-mte1lflv' '.agents/skills/cuda-index-width'OpenSkills
OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.
Installation officielle d’OpenSkillsopenskills install './.skill-downloads/cuda-index-width-in-pytorch-mte1lflv'openskills read 'cuda-index-width-in-pytorch-mte1lflv'La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.
Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.
openskills syncMode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.
4. Faire un premier essai
Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :
Lis .skill-downloads/cuda-index-width-in-pytorch-mte1lflv/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.
Bonnes pratiques React Hook Form
Developpement
Maîtrisez React Hook Form : évitez les anti-patterns, gérez les abonnements, et traitez correctement reset, dirty state et entrées contrôlées.
Migration Emotion vers Mantine
Developpement
Migrer les styled-components Emotion vers des composants Mantine avec style props et modules CSS. Pour convertir .styled.tsx ou supprimer les imports @emotion.
Détecteur de dérive de périmètre
Developpement
Analyse les diffs git par rapport à une intention pour détecter la dérive de périmètre, fichiers non liés et PR trop larges, puis suggère de garder, diviser ou justifier.