[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M736HP0VFFWT2PYTJ6BA14E4":3,"skill-same:01M736HP0VFFWT2PYTJ6BA14E4":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":6,"ownerHtmlUrl":42,"ownerBlogUrl":43,"ownerDescription":6,"updatedAt":44,"install":45,"resources":58},"01M736HP0VFFWT2PYTJ6BA14E4","analyze-kernel-bottleneck",null,"Systematically identify whether a GPU kernel is compute-bound, memory-bound, or latency-bound using roofline analysis, occupancy calculations, compute\u002Fload ratio per tile, and SASS instruction inspection. Produces a decision matrix for optimization strategy selection (cp.async, warp interleaving, tiling, double-buffering, or CuAssembler hand-tuning).","roohe\u002Fagentic-super-skills","roohe","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99054084?v=4","01M734WCDFP6RZVT5CNM00QR26","01M734WCE4BD0T4NZS5PCV9V5F",10,"MIT","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fanalyze-kernel-bottleneck\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: analyze-kernel-bottleneck\nlocale: caveman-lite\nsource_locale: en\nsource_commit: 82c77053\ntranslator: \"Julius Brussee homage — caveman\"\ntranslation_date: \"2026-04-19\"\ndescription: >\n  Systematically identify whether a GPU kernel is compute-bound, memory-bound,\n  or latency-bound using roofline analysis, occupancy calculations, compute\u002Fload\n  ratio per tile, and SASS instruction inspection. Produces a decision matrix\n  for optimization strategy selection (cp.async, warp interleaving, tiling,\n  double-buffering, or CuAssembler hand-tuning).\nlicense: MIT\nallowed-tools: Read Grep Glob Bash\nmetadata:\n  author: Philipp Thoss\n  version: \"1.0\"\n  domain: gpu-optimization\n  complexity: advanced\n  language: CUDA\n  tags: gpu, roofline, occupancy, sass, tensor-core, bottleneck-analysis, compute-load-ratio\n---\n\n# Analyze Kernel Bottleneck\n\nSystematically identify whether a GPU kernel is compute-bound, memory-bound, or latency-bound by measuring baseline performance, classifying on the roofline, computing occupancy and compute\u002Fload ratio per tile, inspecting SASS instruction mix and stall codes, checking the shared memory cliff, and applying a decision matrix to select the right optimization strategy.\n\n## When to Use\n\n- Before optimizing any CUDA kernel -- establish baseline and classify bottleneck type\n- After writing a first working version of a kernel to identify the optimization path\n- When a kernel underperforms expectations relative to theoretical peak\n- When deciding between cp.async, larger tiles, or algorithmic restructuring\n\n## Inputs\n\n- **Required**: Compiled kernel (`.cubin` or `.cu` source with build command)\n- **Required**: Benchmark harness that launches the kernel with CUDA event timing\n- **Required**: Problem dimensions (e.g., M, N, K for GEMM; seq_len, heads, head_dim for attention)\n- **Optional**: Target GPU architecture (default: GA104 \u002F sm_86 \u002F RTX 3070 Ti)\n- **Optional**: Expected peak utilization percentage for comparison\n- **Optional**: Prior profiling data (Nsight Compute reports)\n\n## Procedure\n\n### Step 1: Measure Baseline Performance\n\nRun the kernel with CUDA events (`BenchTimer`), record time in milliseconds. Calculate effective throughput metrics:\n\n1. **Compile** the kernel if not already built:\n   ```bash\n   nvcc --cubin -arch=sm_86 -O2 -o kernel.sm_86.cubin kernel.cu\n   nvcc -arch=sm_86 -O2 -o bench bench.cu -lcuda -I..\u002F..\u002Fphase2\u002Fcommon\n   ```\n2. **Run** with representative problem sizes, ensuring warmup runs precede measurement:\n   ```bash\n   .\u002Fbench 4096 4096 4096\n   ```\n3. **Record** kernel time in ms from CUDA events (not wall-clock).\n4. **Calculate** effective GFLOPS and effective bandwidth:\n   - GEMM: `effective_gflops = (2 * M * N * K) \u002F (time_ms \u002F 1000) \u002F 1e9`\n   - Bandwidth-limited kernels: `effective_bw = total_bytes \u002F (time_ms \u002F 1000) \u002F 1e9`\n   - Flash Attention: `effective_gflops = (4 * batch * heads * seq_len^2 * head_dim) \u002F (time_ms \u002F 1000) \u002F 1e9`\n\n**Got:** Baseline numbers: kernel time in ms, effective GFLOPS, and effective bandwidth.\n\n**If fail:** Check that the kernel launches without error (`CHECK_CU` macro). Verify warmup runs precede measurement. Ensure problem dimensions are large enough to saturate the GPU (small problems may bottleneck on launch overhead).\n\n### Step 2: Classify on the Roofline\n\nCompute arithmetic intensity and compare against the machine balance point to classify the kernel:\n\n1. **Calculate arithmetic intensity**: `AI = FLOPs \u002F bytes_loaded_from_global_memory`. Count only unique bytes loaded from DRAM (not shared memory or register reuse).\n2. **Look up machine balance point**: `balance = peak_compute \u002F peak_bandwidth`.\n3. **Classify**: If `AI \u003C balance`, the kernel is memory-bound. If `AI > balance`, the kernel is compute-bound.\n\n**GA104 (RTX 3070 Ti) Reference Values:**\n\n| Resource | Peak | Unit |\n|----------|------|------|\n| FP32 FFMA | 21.7 | TFLOPS |\n| FP16 Tensor Core (HMMA) | 174 | TFLOPS |\n| INT8 Tensor Core (IMMA) | 696 | TOPS |\n| DRAM Bandwidth | 608 | GB\u002Fs |\n| L2 Cache | 4 | MB |\n| SMs | 48 | |\n\n**Derived Balance Points:**\n\n| Precision | Balance Point (FLOP\u002Fbyte) |\n|-----------|--------------------------|\n| FP32 FFMA | 21700 \u002F 608 = 35.7 |\n| FP16 TC | 174000 \u002F 608 = 286.2 |\n| INT8 TC | 696000 \u002F 608 = 1144.7 |\n\n4. **Compute attained fraction**: `attained = effective_throughput \u002F peak_throughput`. If memory-bound: compare effective bandwidth to 608 GB\u002Fs. If compute-bound: compare effective GFLOPS to the relevant peak.\n\n**Got:** Classification as compute-bound, memory-bound, or latency-bound (low occupancy causing neither compute nor memory saturation) with numerical justification.\n\n**If fail:** Recheck byte counting. Watch for redundant re-reads (e.g., 9x in direct conv2d without im2col). If neither compute nor memory is saturated, the kernel is likely latency-bound (see Step 3).\n\n### Step 3: Calculate Occupancy\n\nDetermine active warps per SM from the launch configuration and resource usage:\n\n1. **Extract resource usage**:\n   ```bash\n   nvcc --cubin -arch=sm_86 -O2 --resource-usage -o kernel.sm_86.cubin kernel.cu 2>&1 | grep -E 'registers|smem'\n   ```\n2. **From launch config**: `warps_per_block = threads_per_block \u002F 32`.\n3. **Compute blocks\u002FSM** from each limiting factor:\n   - Register limit: `floor(65536 \u002F (registers_per_thread * threads_per_block))`\n   - Smem limit: `floor(available_smem_per_SM \u002F smem_per_block)` -- see Step 6 for cliff\n   - Warp limit: `floor(48 \u002F warps_per_block)` (GA104 max: 48 warps\u002FSM)\n   - Block limit: 16 blocks\u002FSM max on GA104\n4. **Actual blocks\u002FSM** = `min(register_limit, smem_limit, warp_limit, block_limit)`.\n5. **Active warps\u002FSM** = `blocks_per_SM * warps_per_block`.\n6. **Key threshold**: 8 warps\u002FSM is sufficient for latency hiding on GA104. Below 8 = structural problem causing latency-bound behavior.\n\n**Got:** Occupancy table showing blocks\u002FSM, active warps\u002FSM, and the limiting factor (registers, smem, or warps).\n\n**If fail:** Check `cuFuncSetAttribute` for dynamic shared memory. Verify `--resource-usage` reports match the actual launch configuration. If register count is unexpectedly high, try `--maxrregcount=N` to cap registers (trading register spills for occupancy).\n\n### Step 4: Compute the Compute\u002FLoad Ratio Per Tile\n\nCount compute instructions and load bytes per K-tile from SASS (not source code):\n\n1. **Disassemble**:\n   ```bash\n   cuobjdump -sass kernel.sm_86.cubin > kernel.sass\n   ```\n2. **Count compute instructions per tile** (the inner loop over one K-tile):\n   - `grep -c 'HMMA' kernel.sass` -- FP16 Tensor Core ops\n   - `grep -c 'IMMA' kernel.sass` -- INT8 Tensor Core ops\n   - `grep -c 'FFMA' kernel.sass` -- FP32 fused multiply-add\n3. **Count global loads per tile**:\n   - `grep -c 'LDG' kernel.sass` -- global memory loads\n   - Multiply by bytes per load (typically 16 bytes for LDG.128)\n4. **Calculate ratio**: `compute_ops \u002F load_ops` per tile.\n5. **Classify** using the cp.async decision threshold (from gpu_reflections.md Insight 2):\n   - **High** (>20:1): cp.async is net-negative; warp interleaving already hides DRAM latency. Focus on algorithmic changes. Reference: Flash Attention has 64 HMMA per tile = high ratio, cp.async measured -5%.\n   - **Medium** (5-20:1): cp.async may help, benchmark both paths.\n   - **Low** (\u003C5:1): cp.async strongly beneficial; loads dominate and async copy hides latency. Reference: IGEMM has 8 IMMA per tile = low ratio, cp.async measured +35%.\n\n**Got:** Compute\u002Fload ratio with classification (high\u002Fmedium\u002Flow) and cp.async recommendation.\n\n**If fail:** Count from SASS disassembly, not source code -- the compiler may fuse, eliminate, or reorder instructions. Ensure you are counting instructions within the inner loop only (the K-tile iteration), not the entire kernel.\n\n### Step 5: Inspect SASS Instructions\n\nExamine the full SASS instruction mix and stall codes:\n\n1. **Disassemble** (if not done in Step 4):\n   ```bash\n   cuobjdump -sass kernel.sm_86.cubin > kernel.sass\n   ```\n2. **Count key instruction types**:\n   ```bash\n   grep -c 'HMMA.16816' kernel.sass      # FP16 Tensor Core\n   grep -c 'IMMA.16816' kernel.sass      # INT8 Tensor Core\n   grep -c 'FFMA' kernel.sass            # FP32 fused multiply-add\n   grep -c 'LDGSTS' kernel.sass          # cp.async (global->shared)\n   grep -c 'LDG' kernel.sass             # Global load\n   grep -c 'STS' kernel.sass             # Shared store\n   grep -c 'LDS' kernel.sass             # Shared load\n   grep -c 'BAR.SYNC' kernel.sass        # Barrier synchronization\n   grep -c 'SHFL' kernel.sass            # Warp shuffle (reductions)\n   grep -c 'MUFU' kernel.sass            # Special function unit\n   ```\n3. **Check stall codes** on critical instructions:\n   ```bash\n   grep 'HMMA' kernel.sass | head -5     # Expect S08 minimum (hardware constraint)\n   grep 'IMMA' kernel.sass | head -5     # Compiler emits S04, reducible to S02 via CuAssembler\n   grep 'FFMA' kernel.sass | head -5     # Check for S04 (reducible to S01 on independent FFMAs)\n   ```\n4. **Identify optimization targets**:\n   - HMMA S08 stalls: hardware minimum on Ampere, cannot be reduced. Focus elsewhere.\n   - IMMA S04 stalls: compiler is conservative. CuAssembler can tighten to S02 (measured 15-20% gain).\n   - FFMA S04 stalls: if independent, reducible to S01 via CuAssembler.\n   - Excessive BAR.SYNC: may indicate over-synchronization between pipeline stages.\n\n**Got:** Instruction count table and stall code summary with identified optimization targets.\n\n**If fail:** Ensure `cuobjdump` architecture matches the kernel compilation target (both must be sm_86). If SASS output is empty, the cubin may be corrupt -- recompile.\n\n### Step 6: Check the Smem Cliff\n\nDetermine whether shared memory usage crosses the architecture-specific occupancy cliff:\n\n1. **Read smem\u002Fblock** from `--resource-usage` output (Step 3) or `cuobjdump --res-usage kernel.sm_86.cubin`.\n2. **Compare against cliff threshold**:\n   - GA104 (sm_86): 100 KB max smem\u002FSM. Cliff at 50 KB\u002Fblock.\n   - Confirmed empirically: 48 KB\u002Fblock -> 2 blocks\u002FSM (good), 56 KB\u002Fblock -> 1 block\u002FSM (2x regression).\n3. **If above cliff** (smem > 50 KB\u002Fblock):\n   - Blocks\u002FSM drops to 1, active warps drop to warps_per_block (typically 4).\n   - 2x performance regression expected from exposed DRAM stalls.\n4. **Check double-buffering impact**: Double-buffering doubles smem usage. If current smem is 30 KB, double-buffered = 60 KB, which crosses the cliff. Evaluate whether the async benefit outweighs the occupancy loss.\n5. **Record** smem\u002Fblock, blocks\u002FSM, and whether the cliff is crossed.\n\n**Got:** Smem\u002Fblock value with blocks\u002FSM count and explicit statement of whether the 50 KB cliff is crossed.\n\n**If fail:** If above cliff and occupancy is the bottleneck, the optimization strategy must change: reduce tile size to get smem under 50 KB, or accept 1 block\u002FSM and compensate with higher compute\u002Fload ratio per tile (more register reuse, longer K-tiles).\n\n### Step 7: Build the Decision Matrix\n\nSynthesize findings from Steps 2-6 into an optimization strategy:\n\n| Condition | Strategy |\n|-----------|----------|\n| Memory-bound + low compute\u002Fload ratio (\u003C5:1) + smem under cliff | Software pipelining with cp.async (LDGSTS). Overlap global loads with compute. |\n| Memory-bound + high compute\u002Fload ratio (>20:1) + 8+ warps | Warp interleaving already hides latency. Focus on algorithmic changes: implicit GEMM, split-Q, im2col. |\n| Compute-bound + FFMA-heavy | CuAssembler stall code tightening: S04 -> S01 on independent FFMAs. |\n| Compute-bound + HMMA-heavy | S08 is hardware minimum, cannot reduce. Increase tile reuse (larger M\u002FN tiles, longer K-loop). |\n| Compute-bound + IMMA-heavy | CuAssembler: S04 -> S02 on IMMA instructions (compiler is conservative). |\n| Latency-bound (low occupancy, neither saturated) | Reduce smem or registers to get more blocks\u002FSM. Get above 8 warps\u002FSM. |\n| Smem above cliff | Reduce tile size or restructure to get smem\u002Fblock under 50 KB (GA104). |\n\n1. **Rank** applicable strategies by expected gain, using the compute\u002Fload ratio and occupancy data.\n2. **Estimate gain range** for each strategy based on how far the kernel is from the relevant ceiling.\n3. **Flag conflicts**: e.g., cp.async doubles smem (may cross cliff), larger tiles increase register pressure (may reduce occupancy).\n\n**Got:** Ranked list of recommended optimizations with predicted gain range and potential conflicts.\n\n**If fail:** If no clear winner emerges, run micro-benchmarks isolating each strategy (e.g., test cp.async alone, test reduced tile size alone) to measure actual impact before combining.\n\n### Step 8: Document Findings\n\nProduce a structured bottleneck report:\n\n1. **Baseline**: kernel time, effective GFLOPS, effective bandwidth, problem dimensions.\n2. **Roofline position**: arithmetic intensity, classification, attained fraction of peak.\n3. **Occupancy**: blocks\u002FSM, active warps\u002FSM, limiting factor.\n4. **Compute\u002Fload ratio**: ratio value, classification (high\u002Fmedium\u002Flow), cp.async recommendation.\n5. **SASS summary**: instruction counts table, stall code findings, CuAssembler targets.\n6. **Smem cliff**: smem\u002Fblock, blocks\u002FSM, cliff status.\n7. **Recommendation**: ranked optimization strategies with gain estimates.\n\n```markdown\n## Bottleneck Analysis Report: [kernel_name]\n\n### Baseline\n- Problem: [dimensions]\n- Kernel time: [X] ms\n- Effective GFLOPS: [Y] | Effective BW: [Z] GB\u002Fs\n\n### Roofline Classification\n- Arithmetic intensity: [AI] FLOP\u002Fbyte\n- Balance point: [BP] FLOP\u002Fbyte ([precision])\n- Classification: **[compute|memory|latency]-bound**\n- Attained fraction: [X]% of peak\n\n### Occupancy\n| Resource | Per Block | Limit\u002FSM | Blocks\u002FSM |\n|----------|-----------|----------|-----------|\n| Registers | [N]\u002Fthread | 65536 | [B] |\n| Shared mem | [X] KB | 100 KB (cliff: 50 KB) | [B] |\n| Warps | [W] | 48 | [B] |\n| **Limiting** | | | **[min(B)]** |\n- Active warps\u002FSM: [W] ([sufficient|insufficient] for latency hiding)\n\n### Compute\u002FLoad Ratio\n- Compute ops\u002Ftile: [N] [HMMA|IMMA|FFMA]\n- Load bytes\u002Ftile: [N] bytes ([N] LDG x [N] bytes)\n- Ratio: [X]:1 — **[high|medium|low]**\n- cp.async recommendation: [beneficial|neutral|detrimental]\n\n### SASS Instruction Mix\n| Instruction | Count | Notes |\n|-------------|-------|-------|\n| HMMA.16816 | [N] | Stall: S08 (hardware min) |\n| IMMA.16816 | [N] | Stall: S04 (reducible to S02) |\n| FFMA | [N] | Stall: S04 (reducible to S01) |\n| LDG | [N] | |\n| LDGSTS | [N] | cp.async |\n| BAR.SYNC | [N] | |\n\n### Smem Cliff\n- Smem\u002Fblock: [X] KB — [under|over] 50 KB cliff\n- Blocks\u002FSM: [B] — [no occupancy loss|occupancy halved]\n\n### Recommended Optimizations (ranked)\n1. [Strategy] — estimated [X-Y]% gain\n2. [Strategy] — estimated [X-Y]% gain\n3. [Strategy] — estimated [X-Y]% gain\n```\n\n**Got:** Complete markdown report consumable by a kernel-optimizer agent or human developer.\n\n**If fail:** Re-run with different problem sizes (e.g., 1024, 2048, 4096, 8192) to confirm findings are not size-specific. Small problems may appear latency-bound when the real bottleneck at scale is memory bandwidth.\n\n## Validation\n\n- [ ] Baseline measured with CUDA events (not wall-clock)\n- [ ] Roofline classification determined (compute\u002Fmemory\u002Flatency bound)\n- [ ] Occupancy computed with limiting factor identified\n- [ ] Compute\u002Fload ratio per tile calculated from SASS\n- [ ] SASS instruction mix and stall codes documented\n- [ ] Smem cliff checked against architecture threshold\n- [ ] Decision matrix applied with strategy recommendation\n- [ ] Findings documented in structured report\n\n## Pitfalls\n\n- **Re-read multiplication**: Direct conv2d reads each weight 9x without im2col, inflating the byte count by 9x. Use actual unique bytes loaded from DRAM, not total load instructions, when computing arithmetic intensity.\n- **Confusing FP16 Tensor Core peak with FP32 peak**: FP16 TC peak is 174 TFLOPS, FP32 FFMA peak is 21.7 TFLOPS -- an 8x difference. Using the wrong peak makes roofline classification meaningless.\n- **Using 64 KB as smem cliff instead of 50 KB on GA104**: GA104 (sm_86) has 100 KB max smem\u002FSM. The cliff is at 100\u002F2 = 50 KB\u002Fblock, not 64 KB. This is architecture-specific; other GPUs differ.\n- **Ignoring warp interleaving when evaluating cp.async**: 8 warps with long compute phases (high compute\u002Fload ratio) already hide DRAM latency through warp scheduling. Adding cp.async in this regime adds smem pressure and barrier overhead for no benefit (measured -5% on Flash Attention).\n- **Counting instructions from source code instead of SASS**: The compiler may fuse operations, eliminate dead code, unroll loops differently, or reorder instructions. Always count from `cuobjdump -sass` output.\n- **Not running warmup iterations**: The first kernel launch includes JIT compilation overhead and cold cache effects. Always run 2-5 warmup iterations before the measured run.\n\n## Related Skills\n\n- `pipeline-gpu-kernel` -- implement software pipelining with cp.async when analysis identifies a memory-bound kernel with low compute\u002Fload ratio\n- `simulate-cpu-architecture` -- complementary architecture analysis for CPU-side bottlenecks in host-device workflows\n","# Analyze Kernel Bottleneck\n\nSystematically identify whether a GPU kernel is compute-bound, memory-bound, or latency-bound by measuring baseline performance, classifying on the roofline, computing occupancy and compute\u002Fload ratio per tile, inspecting SASS instruction mix and stall codes, checking the shared memory cliff, and applying a decision matrix to select the right optimization strategy.\n\n## When to Use\n\n- Before optimizing any CUDA kernel -- establish baseline and classify bottleneck type\n- After writing a first working version of a kernel to identify the optimization path\n- When a kernel underperforms expectations relative to theoretical peak\n- When deciding between cp.async, larger tiles, or algorithmic restructuring\n\n## Inputs\n\n- **Required**: Compiled kernel (`.cubin` or `.cu` source with build command)\n- **Required**: Benchmark harness that launches the kernel with CUDA event timing\n- **Required**: Problem dimensions (e.g., M, N, K for GEMM; seq_len, heads, head_dim for attention)\n- **Optional**: Target GPU architecture (default: GA104 \u002F sm_86 \u002F RTX 3070 Ti)\n- **Optional**: Expected peak utilization percentage for comparison\n- **Optional**: Prior profiling data (Nsight Compute reports)\n\n## Procedure\n\n### Step 1: Measure Baseline Performance\n\nRun the kernel with CUDA events (`BenchTimer`), record time in milliseconds. Calculate effective throughput metrics:\n\n1. **Compile** the kernel if not already built:\n   ```bash\n   nvcc --cubin -arch=sm_86 -O2 -o kernel.sm_86.cubin kernel.cu\n   nvcc -arch=sm_86 -O2 -o bench bench.cu -lcuda -I..\u002F..\u002Fphase2\u002Fcommon\n   ```\n2. **Run** with representative problem sizes, ensuring warmup runs precede measurement:\n   ```bash\n   .\u002Fbench 4096 4096 4096\n   ```\n3. **Record** kernel time in ms from CUDA events (not wall-clock).\n4. **Calculate** effective GFLOPS and effective bandwidth:\n   - GEMM: `effective_gflops = (2 * M * N * K) \u002F (time_ms \u002F 1000) \u002F 1e9`\n   - Bandwidth-limited kernels: `effective_bw = total_bytes \u002F (time_ms \u002F 1000) \u002F 1e9`\n   - Flash Attention: `effective_gflops = (4 * batch * heads * seq_len^2 * head_dim) \u002F (time_ms \u002F 1000) \u002F 1e9`\n\n**Got:** Baseline numbers: kernel time in ms, effective GFLOPS, and effective bandwidth.\n\n**If fail:** Check that the kernel launches without error (`CHECK_CU` macro). Verify warmup runs precede measurement. Ensure problem dimensions are large enough to saturate the GPU (small problems may bottleneck on launch overhead).\n\n### Step 2: Classify on the Roofline\n\nCompute arithmetic intensity and compare against the machine balance point to classify the kernel:\n\n1. **Calculate arithmetic intensity**: `AI = FLOPs \u002F bytes_loaded_from_global_memory`. Count only unique bytes loaded from DRAM (not shared memory or register reuse).\n2. **Look up machine balance point**: `balance = peak_compute \u002F peak_bandwidth`.\n3. **Classify**: If `AI \u003C balance`, the kernel is memory-bound. If `AI > balance`, the kernel is compute-bound.\n\n**GA104 (RTX 3070 Ti) Reference Values:**\n\n| Resource | Peak | Unit |\n|----------|------|------|\n| FP32 FFMA | 21.7 | TFLOPS |\n| FP16 Tensor Core (HMMA) | 174 | TFLOPS |\n| INT8 Tensor Core (IMMA) | 696 | TOPS |\n| DRAM Bandwidth | 608 | GB\u002Fs |\n| L2 Cache | 4 | MB |\n| SMs | 48 | |\n\n**Derived Balance Points:**\n\n| Precision | Balance Point (FLOP\u002Fbyte) |\n|-----------|--------------------------|\n| FP32 FFMA | 21700 \u002F 608 = 35.7 |\n| FP16 TC | 174000 \u002F 608 = 286.2 |\n| INT8 TC | 696000 \u002F 608 = 1144.7 |\n\n4. **Compute attained fraction**: `attained = effective_throughput \u002F peak_throughput`. If memory-bound: compare effective bandwidth to 608 GB\u002Fs. If compute-bound: compare effective GFLOPS to the relevant peak.\n\n**Got:** Classification as compute-bound, memory-bound, or latency-bound (low occupancy causing neither compute nor memory saturation) with numerical justification.\n\n**If fail:** Recheck byte counting. Watch for redundant re-reads (e.g., 9x in direct conv2d without im2col). If neither compute nor memory is saturated, the kernel is likely latency-bound (see Step 3).\n\n### Step 3: Calculate Occupancy\n\nDetermine active warps per SM from the launch configuration and resource usage:\n\n1. **Extract resource usage**:\n   ```bash\n   nvcc --cubin -arch=sm_86 -O2 --resource-usage -o kernel.sm_86.cubin kernel.cu 2>&1 | grep -E 'registers|smem'\n   ```\n2. **From launch config**: `warps_per_block = threads_per_block \u002F 32`.\n3. **Compute blocks\u002FSM** from each limiting factor:\n   - Register limit: `floor(65536 \u002F (registers_per_thread * threads_per_block))`\n   - Smem limit: `floor(available_smem_per_SM \u002F smem_per_block)` -- see Step 6 for cliff\n   - Warp limit: `floor(48 \u002F warps_per_block)` (GA104 max: 48 warps\u002FSM)\n   - Block limit: 16 blocks\u002FSM max on GA104\n4. **Actual blocks\u002FSM** = `min(register_limit, smem_limit, warp_limit, block_limit)`.\n5. **Active warps\u002FSM** = `blocks_per_SM * warps_per_block`.\n6. **Key threshold**: 8 warps\u002FSM is sufficient for latency hiding on GA104. Below 8 = structural problem causing latency-bound behavior.\n\n**Got:** Occupancy table showing blocks\u002FSM, active warps\u002FSM, and the limiting factor (registers, smem, or warps).\n\n**If fail:** Check `cuFuncSetAttribute` for dynamic shared memory. Verify `--resource-usage` reports match the actual launch configuration. If register count is unexpectedly high, try `--maxrregcount=N` to cap registers (trading register spills for occupancy).\n\n### Step 4: Compute the Compute\u002FLoad Ratio Per Tile\n\nCount compute instructions and load bytes per K-tile from SASS (not source code):\n\n1. **Disassemble**:\n   ```bash\n   cuobjdump -sass kernel.sm_86.cubin > kernel.sass\n   ```\n2. **Count compute instructions per tile** (the inner loop over one K-tile):\n   - `grep -c 'HMMA' kernel.sass` -- FP16 Tensor Core ops\n   - `grep -c 'IMMA' kernel.sass` -- INT8 Tensor Core ops\n   - `grep -c 'FFMA' kernel.sass` -- FP32 fused multiply-add\n3. **Count global loads per tile**:\n   - `grep -c 'LDG' kernel.sass` -- global memory loads\n   - Multiply by bytes per load (typically 16 bytes for LDG.128)\n4. **Calculate ratio**: `compute_ops \u002F load_ops` per tile.\n5. **Classify** using the cp.async decision threshold (from gpu_reflections.md Insight 2):\n   - **High** (>20:1): cp.async is net-negative; warp interleaving already hides DRAM latency. Focus on algorithmic changes. Reference: Flash Attention has 64 HMMA per tile = high ratio, cp.async measured -5%.\n   - **Medium** (5-20:1): cp.async may help, benchmark both paths.\n   - **Low** (\u003C5:1): cp.async strongly beneficial; loads dominate and async copy hides latency. Reference: IGEMM has 8 IMMA per tile = low ratio, cp.async measured +35%.\n\n**Got:** Compute\u002Fload ratio with classification (high\u002Fmedium\u002Flow) and cp.async recommendation.\n\n**If fail:** Count from SASS disassembly, not source code -- the compiler may fuse, eliminate, or reorder instructions. Ensure you are counting instructions within the inner loop only (the K-tile iteration), not the entire kernel.\n\n### Step 5: Inspect SASS Instructions\n\nExamine the full SASS instruction mix and stall codes:\n\n1. **Disassemble** (if not done in Step 4):\n   ```bash\n   cuobjdump -sass kernel.sm_86.cubin > kernel.sass\n   ```\n2. **Count key instruction types**:\n   ```bash\n   grep -c 'HMMA.16816' kernel.sass      # FP16 Tensor Core\n   grep -c 'IMMA.16816' kernel.sass      # INT8 Tensor Core\n   grep -c 'FFMA' kernel.sass            # FP32 fused multiply-add\n   grep -c 'LDGSTS' kernel.sass          # cp.async (global->shared)\n   grep -c 'LDG' kernel.sass             # Global load\n   grep -c 'STS' kernel.sass             # Shared store\n   grep -c 'LDS' kernel.sass             # Shared load\n   grep -c 'BAR.SYNC' kernel.sass        # Barrier synchronization\n   grep -c 'SHFL' kernel.sass            # Warp shuffle (reductions)\n   grep -c 'MUFU' kernel.sass            # Special function unit\n   ```\n3. **Check stall codes** on critical instructions:\n   ```bash\n   grep 'HMMA' kernel.sass | head -5     # Expect S08 minimum (hardware constraint)\n   grep 'IMMA' kernel.sass | head -5     # Compiler emits S04, reducible to S02 via CuAssembler\n   grep 'FFMA' kernel.sass | head -5     # Check for S04 (reducible to S01 on independent FFMAs)\n   ```\n4. **Identify optimization targets**:\n   - HMMA S08 stalls: hardware minimum on Ampere, cannot be reduced. Focus elsewhere.\n   - IMMA S04 stalls: compiler is conservative. CuAssembler can tighten to S02 (measured 15-20% gain).\n   - FFMA S04 stalls: if independent, reducible to S01 via CuAssembler.\n   - Excessive BAR.SYNC: may indicate over-synchronization between pipeline stages.\n\n**Got:** Instruction count table and stall code summary with identified optimization targets.\n\n**If fail:** Ensure `cuobjdump` architecture matches the kernel compilation target (both must be sm_86). If SASS output is empty, the cubin may be corrupt -- recompile.\n\n### Step 6: Check the Smem Cliff\n\nDetermine whether shared memory usage crosses the architecture-specific occupancy cliff:\n\n1. **Read smem\u002Fblock** from `--resource-usage` output (Step 3) or `cuobjdump --res-usage kernel.sm_86.cubin`.\n2. **Compare against cliff threshold**:\n   - GA104 (sm_86): 100 KB max smem\u002FSM. Cliff at 50 KB\u002Fblock.\n   - Confirmed empirically: 48 KB\u002Fblock -> 2 blocks\u002FSM (good), 56 KB\u002Fblock -> 1 block\u002FSM (2x regression).\n3. **If above cliff** (smem > 50 KB\u002Fblock):\n   - Blocks\u002FSM drops to 1, active warps drop to warps_per_block (typically 4).\n   - 2x performance regression expected from exposed DRAM stalls.\n4. **Check double-buffering impact**: Double-buffering doubles smem usage. If current smem is 30 KB, double-buffered = 60 KB, which crosses the cliff. Evaluate whether the async benefit outweighs the occupancy loss.\n5. **Record** smem\u002Fblock, blocks\u002FSM, and whether the cliff is crossed.\n\n**Got:** Smem\u002Fblock value with blocks\u002FSM count and explicit statement of whether the 50 KB cliff is crossed.\n\n**If fail:** If above cliff and occupancy is the bottleneck, the optimization strategy must change: reduce tile size to get smem under 50 KB, or accept 1 block\u002FSM and compensate with higher compute\u002Fload ratio per tile (more register reuse, longer K-tiles).\n\n### Step 7: Build the Decision Matrix\n\nSynthesize findings from Steps 2-6 into an optimization strategy:\n\n| Condition | Strategy |\n|-----------|----------|\n| Memory-bound + low compute\u002Fload ratio (\u003C5:1) + smem under cliff | Software pipelining with cp.async (LDGSTS). Overlap global loads with compute. |\n| Memory-bound + high compute\u002Fload ratio (>20:1) + 8+ warps | Warp interleaving already hides latency. Focus on algorithmic changes: implicit GEMM, split-Q, im2col. |\n| Compute-bound + FFMA-heavy | CuAssembler stall code tightening: S04 -> S01 on independent FFMAs. |\n| Compute-bound + HMMA-heavy | S08 is hardware minimum, cannot reduce. Increase tile reuse (larger M\u002FN tiles, longer K-loop). |\n| Compute-bound + IMMA-heavy | CuAssembler: S04 -> S02 on IMMA instructions (compiler is conservative). |\n| Latency-bound (low occupancy, neither saturated) | Reduce smem or registers to get more blocks\u002FSM. Get above 8 warps\u002FSM. |\n| Smem above cliff | Reduce tile size or restructure to get smem\u002Fblock under 50 KB (GA104). |\n\n1. **Rank** applicable strategies by expected gain, using the compute\u002Fload ratio and occupancy data.\n2. **Estimate gain range** for each strategy based on how far the kernel is from the relevant ceiling.\n3. **Flag conflicts**: e.g., cp.async doubles smem (may cross cliff), larger tiles increase register pressure (may reduce occupancy).\n\n**Got:** Ranked list of recommended optimizations with predicted gain range and potential conflicts.\n\n**If fail:** If no clear winner emerges, run micro-benchmarks isolating each strategy (e.g., test cp.async alone, test reduced tile size alone) to measure actual impact before combining.\n\n### Step 8: Document Findings\n\nProduce a structured bottleneck report:\n\n1. **Baseline**: kernel time, effective GFLOPS, effective bandwidth, problem dimensions.\n2. **Roofline position**: arithmetic intensity, classification, attained fraction of peak.\n3. **Occupancy**: blocks\u002FSM, active warps\u002FSM, limiting factor.\n4. **Compute\u002Fload ratio**: ratio value, classification (high\u002Fmedium\u002Flow), cp.async recommendation.\n5. **SASS summary**: instruction counts table, stall code findings, CuAssembler targets.\n6. **Smem cliff**: smem\u002Fblock, blocks\u002FSM, cliff status.\n7. **Recommendation**: ranked optimization strategies with gain estimates.\n\n```markdown\n## Bottleneck Analysis Report: [kernel_name]\n\n### Baseline\n- Problem: [dimensions]\n- Kernel time: [X] ms\n- Effective GFLOPS: [Y] | Effective BW: [Z] GB\u002Fs\n\n### Roofline Classification\n- Arithmetic intensity: [AI] FLOP\u002Fbyte\n- Balance point: [BP] FLOP\u002Fbyte ([precision])\n- Classification: **[compute|memory|latency]-bound**\n- Attained fraction: [X]% of peak\n\n### Occupancy\n| Resource | Per Block | Limit\u002FSM | Blocks\u002FSM |\n|----------|-----------|----------|-----------|\n| Registers | [N]\u002Fthread | 65536 | [B] |\n| Shared mem | [X] KB | 100 KB (cliff: 50 KB) | [B] |\n| Warps | [W] | 48 | [B] |\n| **Limiting** | | | **[min(B)]** |\n- Active warps\u002FSM: [W] ([sufficient|insufficient] for latency hiding)\n\n### Compute\u002FLoad Ratio\n- Compute ops\u002Ftile: [N] [HMMA|IMMA|FFMA]\n- Load bytes\u002Ftile: [N] bytes ([N] LDG x [N] bytes)\n- Ratio: [X]:1 — **[high|medium|low]**\n- cp.async recommendation: [beneficial|neutral|detrimental]\n\n### SASS Instruction Mix\n| Instruction | Count | Notes |\n|-------------|-------|-------|\n| HMMA.16816 | [N] | Stall: S08 (hardware min) |\n| IMMA.16816 | [N] | Stall: S04 (reducible to S02) |\n| FFMA | [N] | Stall: S04 (reducible to S01) |\n| LDG | [N] | |\n| LDGSTS | [N] | cp.async |\n| BAR.SYNC | [N] | |\n\n### Smem Cliff\n- Smem\u002Fblock: [X] KB — [under|over] 50 KB cliff\n- Blocks\u002FSM: [B] — [no occupancy loss|occupancy halved]\n\n### Recommended Optimizations (ranked)\n1. [Strategy] — estimated [X-Y]% gain\n2. [Strategy] — estimated [X-Y]% gain\n3. [Strategy] — estimated [X-Y]% gain\n```\n\n**Got:** Complete markdown report consumable by a kernel-optimizer agent or human developer.\n\n**If fail:** Re-run with different problem sizes (e.g., 1024, 2048, 4096, 8192) to confirm findings are not size-specific. Small problems may appear latency-bound when the real bottleneck at scale is memory bandwidth.\n\n## Validation\n\n- [ ] Baseline measured with CUDA events (not wall-clock)\n- [ ] Roofline classification determined (compute\u002Fmemory\u002Flatency bound)\n- [ ] Occupancy computed with limiting factor identified\n- [ ] Compute\u002Fload ratio per tile calculated from SASS\n- [ ] SASS instruction mix and stall codes documented\n- [ ] Smem cliff checked against architecture threshold\n- [ ] Decision matrix applied with strategy recommendation\n- [ ] Findings documented in structured report\n\n## Pitfalls\n\n- **Re-read multiplication**: Direct conv2d reads each weight 9x without im2col, inflating the byte count by 9x. Use actual unique bytes loaded from DRAM, not total load instructions, when computing arithmetic intensity.\n- **Confusing FP16 Tensor Core peak with FP32 peak**: FP16 TC peak is 174 TFLOPS, FP32 FFMA peak is 21.7 TFLOPS -- an 8x difference. Using the wrong peak makes roofline classification meaningless.\n- **Using 64 KB as smem cliff instead of 50 KB on GA104**: GA104 (sm_86) has 100 KB max smem\u002FSM. The cliff is at 100\u002F2 = 50 KB\u002Fblock, not 64 KB. This is architecture-specific; other GPUs differ.\n- **Ignoring warp interleaving when evaluating cp.async**: 8 warps with long compute phases (high compute\u002Fload ratio) already hide DRAM latency through warp scheduling. Adding cp.async in this regime adds smem pressure and barrier overhead for no benefit (measured -5% on Flash Attention).\n- **Counting instructions from source code instead of SASS**: The compiler may fuse operations, eliminate dead code, unroll loops differently, or reorder instructions. Always count from `cuobjdump -sass` output.\n- **Not running warmup iterations**: The first kernel launch includes JIT compilation overhead and cold cache effects. Always run 2-5 warmup iterations before the measured run.\n\n## Related Skills\n\n- `pipeline-gpu-kernel` -- implement software pipelining with cp.async when analysis identifies a memory-bound kernel with low compute\u002Fload ratio\n- `simulate-cpu-architecture` -- complementary architecture analysis for CPU-side bottlenecks in host-device workflows\n",{"name":5,"locale":23,"license":14,"metadata":24,"translator":31,"description":32,"allowed-tools":33,"source_commit":34,"source_locale":35,"translation_date":36},"caveman-lite",{"tags":25,"author":26,"domain":27,"version":28,"language":29,"complexity":30},"gpu, roofline, occupancy, sass, tensor-core, bottleneck-analysis, compute-load-ratio","Philipp Thoss","gpu-optimization","1.0","CUDA","advanced","Julius Brussee homage — caveman","Systematically identify whether a GPU kernel is compute-bound, memory-bound, or latency-bound using roofline analysis, occupancy calculations, compute\u002Fload ratio per tile, and SASS instruction inspection. Produces a decision matrix for optimization strategy selection (cp.async, warp interleaving, tiling, double-buffering, or CuAssembler hand-tuning).\n","Read Grep Glob Bash","82c77053","en","2026-04-19","master","f483e54f3ad5f202a77d45f2e57f8d970b71195f","skills_library\u002Fanalyze-kernel-bottleneck",2,"https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills","https:\u002F\u002Fgithub.com\u002Froohe","yoou.link","2026-05-19 15:56:07",{"source":8,"skillName":5,"commands":46,"prompt":56,"zipAvailable":57},[47,50,53],{"tool":48,"command":49},"npx","npx skills add roohe\u002Fagentic-super-skills --skill analyze-kernel-bottleneck",{"tool":51,"command":52},"bunx","bunx skills add roohe\u002Fagentic-super-skills --skill analyze-kernel-bottleneck",{"tool":54,"command":55},"pnpm","pnpm dlx skills add roohe\u002Fagentic-super-skills --skill analyze-kernel-bottleneck","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fanalyze-kernel-bottleneck\u002FSKILL.md",true,[],[60,67,74,81,88,95],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":18},"01M73D865CZME2FCMKA4PQM348","zarr-python","Chunked N-D arrays for cloud storage. Compressed arrays, parallel I\u002FO, S3\u002FGCS integration, NumPy\u002FDask\u002FXarray compatible, for large-scale scientific computing pipelines.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M73D7Z64J4ABWZJD7P44XBBF","youtube-downloader","Download and process YouTube content for research. Use when: downloading competitor videos for analysis; extracting audio for podcasts; getting transcripts for content repurposing; archiving webinars; research content curation","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":18},"01M73D7K8778TGZV3GJFR3703D","yc-pitch-deck","Create a compelling startup pitch deck that follows the structure proven to raise billions from top investors. Master the YC and Sequoia formats that get founders funded. Use when: **Fundraising** to create investor pitch decks; **YC application** to structure your narrative; **Demo Day prep** to craft your 2-minute pitch; **Angel investors** to communicate your opportunity; **Partnership pitches** to structure compelling asks","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyc-pitch-deck\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":18},"01M73D70KJSE0E8Z28YMNNRT04","x-twitter-scraper","Use when the user needs X (Twitter) data or confirmation-gated X actions through Xquik: tweet search, user lookup, follower extraction, media download, monitoring, webhooks, MCP, SDKs, posting, likes, DMs, and profile updates. Requires a Xquik API key. Never ask for X login material.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fx-twitter-scraper\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":18},"01M73D6ED01GV077R7K4NZNFZJ","write-vignette","Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-vignette\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":18},"01M73D69YJR0BK3NFHE0CYG3EF","write-validation-documentation","Write IQ\u002FOQ\u002FPQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-validation-documentation\u002FSKILL.md",[],[]]