Token导航 LogoToken导航

Agent Skill · 研究检索

cuda-kernel-refine(cuda 内核精炼)

cuda-kernel-refine 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

cuda-kernel-refine 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为调用外部服务;许可证信息还不明确,第三方扫描有未通过项,按安装量在研究检索类的 73,675 个 Skill 里排第 51,212。

总安装 588周安装 24GitHub Stars 7下载 190核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:cuda-kernel-refine(cuda 内核精炼)
来源仓库:https://github.com/trevors/dot-claude
仓库路径:skills/cuda-kernel-refine
安装命令:
npx skills add https://github.com/trevors/dot-claude --skill cuda-kernel-refine
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/trevors/dot-claude --skill cuda-kernel-refine

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

cuda-kernel-refine 提供 CUDA 内核优化的迭代循环方法,强调单变量渐进改进与基准对比。适用于需要对矩阵运算、归约操作等热点函数进行微调的深度学习或 HPC 项目。要求先建立性能基准,再分类瓶颈类型(计算/内存/同步),针对性实施优化策略。

每次仅修改一处代码,运行 benchmark 后判断效果,防止多变量干扰归因。若出现性能回退,应立即 revert 更改,确保稳定性后再继续迭代。

来源仓库内路径:skills/cuda-kernel-refine

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/trevors/dot-claude --skill cuda-kernel-refine;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要调用外部服务,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

cuda-kernel-refine 怎么安装?

在终端执行 npx skills add https://github.com/trevors/dot-claude --skill cuda-kernel-refine。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

cuda-kernel-refine 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

cuda-kernel-refine 需要什么权限?

权限级别是调用外部服务。该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

cuda-kernel-refine 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

cuda-kernel-refine 用的人多吗?

公开数据是累计安装 588 次,近一周安装 24 次,下载 190 次,GitHub 7 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

cuda-kernel-refine 安全吗?

第三方扫描有未通过项,风险较高。除非你确认过源码,否则不建议直接安装到常用环境。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
cuda-kernel-refine

cuda 内核精炼 · 本页

5887调用外部服务未明确未通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

CUDA Kernel Refinement Loop

One change per cycle: baseline → profile → classify → optimize → verify → compare → loop. Multiple simultaneous changes make it impossible to attribute improvement. Revert on regression.

1. Establish Baseline

Discover the project's benchmark infrastructure before running anything:

  1. Check Makefile for bench/profile targets (make bench, make profile, etc.)
  2. Check for benchmark binaries (cargo bench, pytest-benchmark, a custom e2e_bench binary)
  3. Look at CI scripts or README for the canonical benchmark invocation
  4. If no benchmark exists, write a minimal one that exercises the hot path with measurable output

Run with enough iterations for stable results — coefficient of variation <5%.

# Save baseline (JSON or structured output preferred for diff later)
./benchmark --iterations 5 --json-output /tmp/bench-baseline.json

Record: primary metric (tok/s, GFLOPS, GB/s, or latency ms), stddev, and workload parameters (input size, batch size, context depth). You need all three for meaningful comparison later.

2. Profile with nsys

Capture

nsys profile --stats=true -o /tmp/nsys-profile ./app [args]

Quick look (JSON)

# Kernel timing summary — sort by Time(%) to find hotspot
nsys stats -r cuda_gpu_kern_sum --format json /tmp/nsys-profile.nsys-rep

# CUDA API calls (spot synchronization overhead, excessive cudaMalloc)
nsys stats -r cuda_api_sum --format json /tmp/nsys-profile.nsys-rep

# Memory operations by size (spot unnecessary small D2H/H2D transfers)
nsys stats -r cuda_gpu_mem_size_sum --format json /tmp/nsys-profile.nsys-rep

Deep analysis (SQLite — the real power tool)

For custom queries, export to SQLite and use SQL directly. This is far more powerful than JSON for kernel-level analysis.

# Export nsys trace to SQLite
nsys export --type sqlite /tmp/nsys-profile.nsys-rep
# Creates /tmp/nsys-profile.sqlite

# Top kernels by time with full names
sqlite3 -header -column /tmp/nsys-profile.sqlite \
  "SELECT
     printf('%.1f%%', 100.0*sum(k.end-k.start)/(SELECT sum(end-start) FROM CUPTI_ACTIVITY_KIND_KERNEL)) as pct,
     count(*) as calls,
     printf('%.1f', sum(k.end-k.start)/1e6) as total_ms,
     printf('%.1f', avg(k.end-k.start)/1e3) as avg_us,
     s.value as kernel
   FROM CUPTI_ACTIVITY_KIND_KERNEL k
   JOIN StringIds s ON k.shortName = s.id
   GROUP BY s.value
   ORDER BY sum(k.end-k.start) DESC
   LIMIT 20"

# Per-token analysis (for inference: normalize by decode_tokens)
sqlite3 -header -column /tmp/nsys-profile.sqlite \
  "SELECT
     printf('%.0f', count(*) * 1.0 / <DECODE_TOKENS>) as 'launches/tok',
     printf('%.1f', sum(end-start)/1e6/<DECODE_TOKENS>) as 'ms/tok',
     printf('%.1f', avg(end-start)/1e3) as 'us/launch'
   FROM CUPTI_ACTIVITY_KIND_KERNEL"

# Kernel launch configs (grid, block, registers) — find dimension mismatches
sqlite3 -header -column /tmp/nsys-profile.sqlite \
  "SELECT s.value as kernel, k.gridX, k.gridY, k.gridZ,
     k.blockX, k.blockY, k.blockZ, k.registersPerThread as regs,
     count(*) as launches, printf('%.1f', avg(k.end-k.start)/1e3) as avg_us
   FROM CUPTI_ACTIVITY_KIND_KERNEL k
   JOIN StringIds s ON k.shortName = s.id
   GROUP BY s.value, k.gridX, k.gridY, k.gridZ, k.blockX, k.blockY, k.blockZ
   ORDER BY sum(k.end-k.start) DESC LIMIT 20"

Replace <DECODE_TOKENS> with the number of tokens generated in the trace.

Interpret the profile

  • High Instances + moderate Avg → per-layer kernel, fusion opportunity
  • Low Instances + high Avg → single expensive kernel, optimize internals
  • Many small kernels → launch overhead ("death by a thousand cuts"), count launches/token to quantify
  • High cudaMalloc count in API summary → framework allocator overhead, consider memory pools

3. Check Register Usage

nvcc -cubin -arch=<target_sm> -Xptxas=-v kernel.cu -o /tmp/kernel.cubin

Output format:

ptxas info    : Compiling entry function 'kernel_name' for 'sm_121a'
ptxas info    : Function properties for kernel_name
    0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads
ptxas info    : Used 29 registers, used 0 barriers

Key signals:

SignalMeaningAction
Spill stores/loads > 0Register pressure__launch_bounds__ or reduce live variables
Registers > 64Occupancy limited by registersCheck ncu Occupancy section
Stack frame > 0Function calls or array-to-local demotionInline functions, use shared memory
Barriers > 0Shared memory synchronizationExpected with __syncthreads()

4. Drill Down with ncu

Requires GPU performance counter permissions.

# Default sections (SOL + occupancy), fast
ncu -k "kernel_regex" -c 5 ./app [args]

# Full metrics including roofline
ncu -k "kernel_regex" --set full -o /tmp/ncu-report ./app [args]

# CSV for specific metrics
ncu --csv -k "kernel_regex" --metrics \
  sm__throughput.avg.pct_of_peak_sustained_elapsed,\
  dram__throughput.avg.pct_of_peak_sustained_elapsed \
  ./app [args]

If you get ERR_NVGPUCTRPERM, performance counters are restricted. Fix with:

# Option A: run ncu with sudo
sudo ncu -k "kernel_regex" -c 5 ./app [args]

# Option B: kernel module parameter (persistent, requires reboot)
sudo sh -c 'echo "options nvidia NVreg_RestrictProfilingToAdminUsers=0" > /etc/modprobe.d/ncu-permissions.conf'

Section sets (choose based on what you need):

  • Default (SpeedOfLight, Occupancy) — fast, answers "is this compute or memory bound?"
  • --set detailed — adds instruction mix, memory workload breakdown, warp scheduling. Use when default sections show a bottleneck but don't explain why.
  • --set full — adds roofline charts. 10-50x slower. Only use when you need the visual roofline or are writing up an analysis.

5. Classify Bottleneck

From ncu SpeedOfLight section (or infer from kernel type if ncu unavailable):

SM SOL %Memory SOL %ClassificationOptimization Direction
LowHigh (>60%)Memory-boundReduce traffic, wider loads, fuse ops
High (>60%)LowCompute-boundFast math, ILP, tensor cores
LowLowLatency-boundOccupancy, reduce sync, overlap
HighHighWell-optimizedAlgorithmic changes or accept

Bandwidth utilization (memory-bound kernels)

For inference workloads, compute bandwidth utilization directly — this is more actionable than abstract roofline:

data_per_step = weight_bytes + activation_bytes + KV_cache_bytes  (read + write)
theoretical_min_time = data_per_step / hw_bandwidth
utilization = theoretical_min_time / actual_time

Example: FP4 weights read 5.1 GB/token on 273 GB/s → theoretical min 18.7ms, actual 24ms → 78% utilization. The 22% gap is your optimization headroom.

Without ncu

If no counter permissions, infer from kernel behavior:

  • Elementwise ops (activation functions, normalization) → almost always memory-bound
  • Reductions with few output elements (layernorm, softmax) → likely compute-bound on the reduction
  • Large matmuls → compute-bound
  • Many tiny kernels with low total time → latency-bound (launch overhead)

Identify host-side bottlenecks

Not all overhead lives in GPU kernels. Check for:

  • D2H synchronization points: search for device-to-host copies in the codebase — cudaMemcpy(..., DeviceToHost), cudaStreamSynchronize, and framework-specific equivalents (PyTorch: .item(), .cpu(), .numpy(); Candle: .to_vec1(); CUDA C++: cudaMemcpyAsync with sync). Each one stalls the GPU pipeline. Count them per inference step — eliminating unnecessary D2H syncs is often the single biggest win.
  • Excessive allocations: check cudaMalloc count in nsys stats -r cuda_api_sum. ML frameworks (Candle, PyTorch eager) often allocate fresh GPU buffers for every intermediate tensor. Hundreds of allocations per step is a sign of framework overhead.
  • CPU-side compute: sampling, tokenization, or postprocessing running on CPU while GPU idles. Shows up as gaps between kernel launches in the nsys timeline.

6. Optimization Strategies

Memory-bound

Goal: reduce bytes moved per operation.

  • Kernel fusion (see latency-bound for prioritization): every intermediate tensor written to global memory and read back is wasted bandwidth
  • Vectorized loads: uint4 (128-bit) = 8 BF16 or 4 FP32 per load. Requires pointer alignment. Verify with SASS (LDG.E.128).
  • Shared memory reuse: cache data accessed by multiple threads (use stride D+1 to avoid bank conflicts)
  • Reduce precision: FP8/FP4 weights cut memory traffic 2-4x with minimal accuracy loss. Keep accumulation in FP32.

Compute-bound

Goal: do more useful math per cycle.

  • Fast math intrinsics: __expf(), __rsqrtf(), __fdividef() — lower precision but 2-4x faster than full-precision equivalents
  • Warp shuffle: __shfl_down_sync(0xffffffff, val, offset) for intra-warp reductions — avoids shared memory round-trip
  • ILP: interleave independent operations so the scheduler can hide latency. #pragma unroll for known-trip-count loops.
  • Tensor cores: WMMA/MMA for matrix ops — 8-16x throughput over FP32 CUDA cores but requires specific data layouts and alignment

Latency-bound (launch overhead)

  • Kernel fusion — the primary remedy. Prioritize candidates by:

1. launches_per_step × layers — a 3-kernel sequence in a 32-layer model eliminates 96 launches when fused 2. Memory traffic eliminated — fusing residual_add + rmsnorm saves one full tensor round-trip per layer 3. Implementation complexity — simple elementwise fusions (sigmoid×mul, silu×mul) are easy wins; attention-level fusions require careful shared memory management

  • Eliminate D2H sync points — move computation to GPU, batch device-to-host transfers to end of step (see section 5 "host-side bottlenecks" for how to find them)
  • Increase occupancy — __launch_bounds__(maxThreads, minBlocks) when ncu shows low occupancy limiting throughput

7. SASS Inspection (optional)

Use when profiling shows an unexplained gap between expected and actual performance, or to verify the compiler is generating what you intended (vectorized loads, no spills, etc.).

cuobjdump -sass /tmp/kernel.cubin     # SASS disassembly
nvdisasm /tmp/kernel.cubin            # SASS with control flow

Quick checks (you don't need to read every instruction):

  • Grep for STL/LDL — local memory access means register spills. If present, reduce register pressure.
  • Grep for LDG.E.128/STG.E.128 — confirms vectorized 128-bit loads/stores are being generated. If you wrote uint4 loads but see LDG.E.32, alignment or type issues prevented vectorization.
  • Count BAR.SYNC — compare to your __syncthreads() count. More barriers than expected means the compiler inserted extra synchronization.

8. Verify Correctness

Always verify before benchmarking. A faster kernel that produces wrong results is not an optimization.

# Project tests
cargo test / pytest / make test

# Memory errors (out-of-bounds, leaks, misaligned access)
compute-sanitizer --tool memcheck ./app [args]

# Shared memory data races
compute-sanitizer --tool racecheck ./app [args]

# Uninitialized device memory reads
compute-sanitizer --tool initcheck ./app [args]

# Sync hazards (divergent __syncthreads)
compute-sanitizer --tool synccheck ./app [args]

compute-sanitizer has significant overhead (10-100x). Use small inputs for correctness checks, full inputs for benchmarks.

9. Compare Results

Run the same benchmark as baseline — same workload, same iteration count, same GPU state (no other processes competing for bandwidth).

./benchmark --iterations 5 --json-output /tmp/bench-after.json

Compare against the baseline numbers you recorded in step 1:

Metric           Baseline    After       Delta
─────────────    ────────    ────────    ──────
Throughput       37.1 tok/s  39.8 tok/s  +7.3%
Stddev           ±0.4        ±0.5
Launches/token   622         478         -23%
GPU ms/token     26.2        24.1        -8.0%

Decision framework:

  • Delta < stddev of either run → indistinguishable from noise. Run more iterations (10+) or use a longer workload before concluding.
  • Delta > stddev and > 3% → real improvement, accept the change
  • Any regression in throughput → revert, then analyze why (check if a different kernel got slower — fusion can shift pressure)

Also check for side effects:

  • Peak GPU memory (fusion can increase shared memory or register usage)
  • Correctness (re-run tests if not done in step 8)
  • Performance at different workloads (a prefill optimization might hurt decode, or vice versa)

Common Pitfalls

  • Grid dimension limits: y and z max at 65535; only x supports 2^31-1. Use blockIdx.x for sequence/batch dimensions that can exceed 65535.
  • Shared memory bank conflicts: 32 banks x 4 bytes. Power-of-2 column strides cause conflicts. Pad to stride D+1.
  • Divergent __syncthreads(): undefined behavior. All threads in a block must reach the same barrier. Use compute-sanitizer --tool synccheck to detect.
  • Vectorized load alignment: uint4 loads require 16-byte aligned pointers. Verify alignment before using wide loads.
  • Profiling overhead: nsys adds ~5-10% overhead, ncu adds 10-50x. Profile numbers are relative (compare before/after), not absolute production performance.
  • __launch_bounds__ vs --maxrregcount: --maxrregcount is per-file (all kernels); __launch_bounds__ is per-kernel. Prefer per-kernel control.
  • Occupancy chasing: >60% occupancy is usually sufficient. Maximizing occupancy by forcing lower register counts can cause spills that hurt more than the occupancy helps.
  • Unified memory systems (Grace Hopper, DGX Spark): no PCIe transfer overhead, but bandwidth can be 3-7x lower than discrete GDDR7. This means batch=1 decode is almost always memory-bound — prioritize weight compression (FP8/FP4) and fusion over compute optimizations.
  • Hidden D2H syncs in hot loops: check section 5 "host-side bottlenecks" — a single unnecessary GPU→CPU sync per layer × 32 layers = 32 pipeline stalls per step. Often the biggest win before touching any kernel code.
  • Framework allocator overhead: eager-mode ML frameworks allocate/free GPU buffers for every intermediate tensor. At 600+ allocations per inference step, cudaMalloc overhead itself becomes measurable. Check cuda_api_sum for cudaMalloc call counts.
  • Fusing the wrong thing: profile first. A kernel taking 0.1% of GPU time isn't worth fusing no matter how many launches it has. Focus on the top-3 time consumers and the top launch-count contributors.

平台分布

Codex

33.92%
按下载量换算64

Claude

30.57%
按下载量换算58

Cursor

18.6%
按下载量换算35

Gemini CLI

8.03%
按下载量换算15

安全审计

Gen Agent Trust Hub

未通过

Socket

通过

Snyk

可疑

权限和风险

调用外部服务

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills