optimize-training-kernels — скилл для Claude Code: настройка ядер
Скилл optimize-training-kernels для Claude Code настраивает fusion и выбор attention backend, чтобы ускорить обучение без выхода за допуски численной точности. Запускается при разборе медленных ядер или проверке предложенной замены.
Apache-2.0 ★ 99 обновлён 2026-11-12
npx skills add TokenRhythm/InfraRSI --skill optimize-training-kernels -a claude-codeЧто делает optimize-training-kernels
Скилл помогает включать fusion-флаги и выбирать attention backend, а при открытом L2 — заменять разрешённые операторы. Для проверки сверяет реальные входы с построчным эталоном FP64 и отслеживает численные допуски на шагах обучения.
Для fusion из Megatron-Core 0.18.2 есть отдельные правила: например, для cross_entropy_loss_fusion допустима реализация native, а te отклоняется из-за нестабильности. Флаги сначала проверяются по одному, затем их можно включить вместе. Для замен ядер важны точность интерфейсов BF16 и вычисления softmax, LSE и накоплений в FP32.
Изменения точности через TF32, reduced-precision reductions и FP8 этот скилл не разрешает. CUDA-граф сам по себе не считается подтверждением ускорения: проверка включает точность и время шага.
Какие задачи решает
- включить fusion-флаги и проверить численную точность
- выбрать attention backend для конкретной формы входа
- сверить замену ядра с построчным эталоном FP64
- найти причину расхождения чисел после изменения ядра
Примеры запросов агенту
- Проверь, можно ли включить fusion-флаги в этой конфигурации обучения.
- Сравни новое attention-ядро с эталоном FP64 на реальных входах.
- Разбери численное расхождение после замены Triton-ядра.
Как установить optimize-training-kernels
1Через Skills CLI (Vercel)
npx skills add TokenRhythm/InfraRSI --skill optimize-training-kernels -a claude-code2Вручную: положить файлы
~/.claude/skills/optimize-training-kernels/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/optimize-training-kernels/
1Через Skills CLI (Vercel)
npx skills add TokenRhythm/InfraRSI --skill optimize-training-kernels -a codex2Вручную: положить файлы
.agents/skills/optimize-training-kernels/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add TokenRhythm/InfraRSI --skill optimize-training-kernels -a cursor2Вручную: положить файлы
.cursor/skills/optimize-training-kernels/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install TokenRhythm/InfraRSI skills/optimize-training-kernels2Вручную: положить файлы
.github/skills/optimize-training-kernels/SKILL.md1Через Skills CLI (Vercel)
npx skills add TokenRhythm/InfraRSI --skill optimize-training-kernels -a gemini-cli2Командой платформы
gemini skills install https://github.com/TokenRhythm/InfraRSI --path skills/optimize-training-kernelsВручную: положить файлы
.devin/skills/optimize-training-kernels/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Claude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы об optimize-training-kernels
Как установить optimize-training-kernels в Claude Code?
Выполни npx skills add TokenRhythm/InfraRSI --skill optimize-training-kernels -a claude-code. Файл скилла появится по пути ~/.claude/skills/optimize-training-kernels/SKILL.md.
Что делает optimize-training-kernels?
Скилл помогает настраивать fusion и attention backend, а в задачах с открытым L2 — проверять разрешённые замены ядер. Он сверяет численность результатов с эталоном FP64 и контролирует время шага.
Как скилл проверяет точность замен ядер?
Он сравнивает прямой проход поэлементно, а обратный — построчно с эталоном FP64 на реальных входах. При атомарных операциях нужны два эталона; выбранные строки не должны нарушать допуски.
Исходный текст
SKILL.md · Apache-2.0
--- name: optimize-training-kernels description: Use fused kernels and kernel-level changes without breaking numerics - L0 fusion flags, attention backends, and (where L2 is open) whitelisted kernel replacements gated by FP64 row-wise references on first real inputs. license: Apache-2.0 when_to_use: Fusion flags are off in the start config; attention or elementwise kernels dominate; a custom kernel is proposed; numerics drift after a kernel change; 'fusion', 'rope fusion', 'cross entropy fusion', 'attention backend', 'triton kernel', 'FP64 reference'. metadata: author: InfraRSI A0 (human-authored) source: human-authored (A0) version: 1 tags: [kernels, fusion, attention, numerics, triton, dense, moe, long-context] --- # Optimize training kernels ## Trigger conditions - FR/ED leave fusions off (apply_rope_fusion, bias_activation_fusion, masked_softmax_fusion, gradient_accumulation_fusion, cross_entropy_loss_fusion all false in fr_v0). - `profile.fwd_bwd_s` dominates with memory to spare and recompute already minimized. - L2 is open on this task (only some strong-model dev tasks) and a whitelisted op (swiglu, rmsnorm, rope, cross-entropy) is hot. ## Required observations (receipt fields) - `step_time`, `profile.fwd_bwd_s`, `numerics` (class, main_ce_rel_max, main_ce_rel_mean_window, grad_norm.first_update_rel, grad_norm.log_bias_window), `invariants.backends_flags`, `invariants.dtype_census`. ## Rules: L0 fusions (Megatron-Core 0.18.2) - apply_rope_fusion: fused RoPE (TE). bias_activation_fusion: fused bias+activation for gelu/swiglu. masked_softmax_fusion: only affects the unfused attention path. gradient_accumulation_fusion: wgrad GEMM accumulates directly into the fp32 main_grad (TE linears). cross_entropy_loss_fusion with impl 'native' (impl 'te' is rejected for stability). - These change kernels and reduction orders, not semantics: they are E1 candidates and must pass the numerics tolerance against FR plan A (main CE <= 0.5% per step, window mean CE <= 0.2%, grad norm <= 1% at update 1 and |mean ln(gn_c/gn_r)| <= 0.10 over the window). Per-step grad-norm differences after update 1 are report-only kernel noise (same-config runs differ by up to 56%): never tune against them. - attention_backend: auto lets TE pick (fused/flash); forcing flash or fused can help or fail per shape; unfused is a debugging path and slow. - Turn fusions on together only after each is known to work; one at a time when a run fails. ## Rules: exactness gates for kernels (L1 replay / L2) - Reference: forward elementwise and backward row-wise against an FP64 reference on the first real inputs, with two references when atomics are involved; zero selected-row violations, low and zero rows checked separately. - BF16 at interfaces, FP32 for softmax/LSE/accumulation/workspaces. Softmax backward: Delta = rowsum(P * dP) must be computed in FP32 from unrounded values; deriving it from the BF16-rounded output broke the gate. - Bitwise where the contract allows: repeated runs gave O and dQ bitwise; dK/dV with FP32 atomics relL2 4.43e-5 < 1e-4. - Launch counts and CUDA graphs are not speed by themselves: a selector CUDA graph was exact but missed the 0.16 s/update gate in all 48 full-cost scenarios. - Precision flags (TF32, reduced-precision reductions) and FP8 are not kernel choices here: they are silent precision drops and invalid. ## Allowed actions - L0: apply_rope_fusion, bias_activation_fusion, masked_softmax_fusion, gradient_accumulation_fusion, cross_entropy_loss_fusion, cross_entropy_fusion_impl (native), attention_backend. - L2 (only where the task opens it): whitelisted operator replacement with the gates above. ## Failure signals - numerics.passed false or class beyond E1; NaN/Inf; backends_flags or dtype_census changed. - Faster kernel, slower update (extra casts, re-quantization, lost overlap). ## Verification - First-use exactness gate passes; numerics within tolerance across all updates; StepTime beyond margin. ## Success case (real) - Route attention v2 on NeMo CP4: Delta = sum(P*dP) in FP32 over the normalized route set, dS = P*(dP - Delta), BF16 interfaces, FP32 softmax/LSE/accumulation/dK-dV workspaces. It passed the frozen FP64 row gate, real-input calibration and a held-back layer: 9.808943 -> 6.699462 s (+46.41%). (MANUSCRIPT.md 4.1, 6.2) - Smaller: lowering num_warps 8 -> 4 in three Triton kernels made them 37-40% faster, -0.81 s/step, bitwise. (flash_next_mfu_20261003/PROGRESS.md) ## Failure case (real) - Route v1 passed forward checks and an aggregate L2 test but had 8,676 dQ-row and 43 dK-row stable violations (per CP shard dQ 3229/2011/2224/1212, dK 17/12/8/6) of the bound eB <= max(0.02*normR, 1.25*eA) under two FP64 references. Cause: Delta derived from the BF16-rounded output. Aggregate norms hid row failures. (mfu_core_20260929/ROUTE_ATTENTION_V2_CALIBRATION_RESULT.md; RSI_TRACK.md T2) - FP8 fusion: see profile-whole-update and the negative-results catalogue (-4.62% / -3.89% vs BF16).
© InfraRSI A0 (human-authored) · Apache-2.0 · TokenRhythm/InfraRSI