[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M69AH9J5EQS7AC7ZJQVVAZ3Y":3,"skill-same:01M69AH9J5EQS7AC7ZJQVVAZ3Y":81},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":52,"linkOnly":53,"markdownContent":54,"markdownBody":55,"frontMatter":56,"refName":57,"commitSha":58,"skillDirectory":59,"forksCount":60,"repositoryHtmlUrl":61,"repositoryHomepageUrl":62,"ownerHtmlUrl":63,"ownerBlogUrl":64,"ownerDescription":65,"updatedAt":66,"install":67,"resources":80},"01M69AH9J5EQS7AC7ZJQVVAZ3Y","cuda-attention-kernel-patterns","CUDA Attention 内核模式与陷阱","Patterns and pitfalls for the ONNX domain Attention operator (opset 23\u002F24) CUDA implementation. Use when modifying the dispatch cascade in core\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention.cc, writing mask\u002Fbias CUDA kernels, debugging attention test routing, or adding features to the ONNX Attention op. NOT for contrib domain MultiHeadAttention\u002FGroupQueryAttention.","ONNX 领域 Attention 算子（opset 23\u002F24）CUDA 实现的模式与陷阱。在修改 core\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention.cc 中的 dispatch cascade、编写 mask\u002Fbias CUDA 内核、调试 attention 测试路由，或为 ONNX Attention 算子添加功能时使用。不适用于 contrib 领域的 MultiHeadAttention\u002FGroupQueryAttention。","microsoft\u002Fonnxruntime","microsoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6154722?v=4","01M698VYDXZ6JW5WH3CRV650R8","Microsoft","01M69AGY0EW9AJXAH7HK223SQZ",22306,"MIT",null,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fonnxruntime\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fcuda-attention-kernel-patterns\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQ6TKQDF2K4KQS863Q79P4","开发参考","SCENARIO","使用场景",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BRZZF9D7PVFN5MXSPWWD61","AI 工程师","PROFESSION","适用职业",[31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],"kernel","cuda attention kernel patterns","cuda","patterns","attention","when","writing","contrib","features","for","mask","pitfalls","bias","domain","cc","Providers","operator","core","debugging","onnx","test","2026-11-10 10:12:30",false,"---\nname: cuda-attention-kernel-patterns\ndescription: Patterns and pitfalls for the ONNX domain Attention operator (opset 23\u002F24) CUDA implementation. Use when modifying the dispatch cascade in core\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention.cc, writing mask\u002Fbias CUDA kernels, debugging attention test routing, or adding features to the ONNX Attention op. NOT for contrib domain MultiHeadAttention\u002FGroupQueryAttention.\n---\n\n# ONNX Domain Attention (Opset 23\u002F24) CUDA Patterns\n\nReusable knowledge from ONNX Attention CUDA development in ORT.\n\n> **Scope**: This skill covers the **ONNX domain** `Attention` operator (opset 23\u002F24)\n> implemented at `core\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention.cc`. This is **separate from** the\n> contrib domain `MultiHeadAttention` \u002F `GroupQueryAttention` at `contrib_ops\u002Fcuda\u002Fbert\u002F`.\n> They share some underlying kernels (CUTLASS FMHA, Flash Attention) and infrastructure\n> (`attention_softmax.h`) but have **different dispatch logic, parameter structs, and eligibility checks**.\n>\n> - **Shared infrastructure**: CUTLASS FMHA kernel, Flash kernel, unified unfused kernel\n>   (`unfused_attention.cu`), `attention_softmax.h`, `attention_impl.cu` (contrib only)\n> - **ONNX-specific**: Dispatch cascade in `attention.cc`, `ConvertAttnMaskToBias`,\n>   `mask_filter_value` cap, parameter bridge to contrib structs, `attention_mask_impl.cu`\n> - **Contrib-specific**: Own dispatch in contrib MHA\u002FGQA ops, uses `contrib::AttentionParameters`\n>   directly, has XQA kernel, past-present buffer sharing\n\n## 1. Runner Dispatch Cascade\n\nCUDA attention dispatches in priority order: **Flash → MEA (Memory Efficient) → Unified Unfused Attention**.\n\n```\n\u002F\u002F onnxruntime\u002Fcore\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention.cc — ComputeInternal()\nFlash eligible?      → RunFlashAttention()\n  ↓ no\nMEA eligible?        → RunMemoryEfficientAttention()\n  ↓ no\nUnified Unfused      → RunUnfusedAttention()\n  (handles both MHA and GQA via reshape-Q trick)\n```\n\n### Eligibility anchors (symbols are stable; line numbers as of cc34d0b914)\n\n| Stage | Decision symbol | Hard caps | Dispatch gate |\n|---|---|---|---|\n| Flash | `flash::is_supported\u003CT>` (`flash_api.cc:414`) | fp16\u002Fbf16 only, SM≥8.0, `head_size%8==0`, **`head_size\u003C=256`** | `attention.cc:1385` `flash_eligible` (fp32 excluded at :1387) |\n| MEA | `has_memory_efficient_attention` (`memory_efficient_attention.h:68`) | `(head_size&7)==0` **and `head_size\u003C=kEfficientAttentionMaxHeadSize` (1024)**; **NO shared-memory feasibility check** (see #28388 + the head_size=512 caveat below) | `attention.cc:1415` `mea_eligible`; bias-stride `%4` at :1436 |\n| Unfused | (none — catch-all) | all dtypes\u002Fshapes | `attention.cc:1485` `RunUnfusedAttention` |\n\n**`head_size=512` IS routed to MEA, but its MEA kernel is NOT portably launchable — so it\nis not a robust test probe.**\nBy the predicate, 512 > 256 fails Flash and 512 ≤ 1024 with `512 & 7 == 0` passes the MEA\npredicate, **so dispatch selects MEA** — but the MEA eligibility check\n(`memory_efficient_attention.h:68-73`) gates only on SM +\n`head&7==0` + `head\u003C=1024`, with **no shared-memory check**. For `head_size=512` FP16 the\nCUTLASS MEA `SharedStorage` exceeds the dynamic-smem opt-in cap on capacity-limited arches\n(sm86 ~99KB, sm80 ~163KB, sm90 ~227KB — **non-monotonic**, no clean SM-version guard).\n`fmha_launch_template.h` calls `cudaFuncSetAttribute(..., cudaFuncAttributeMaxDynamicSharedMemorySize, ...)`\nbut **ignores its return value and launches anyway**, so on sm86 the kernel dies at launch\nwith `CUDA failure 1: invalid argument` — there is **no fallback to unfused** (live bug\n#28388; its fix PR #28383 was never merged). So `head_size=512`'s MEA kernel launches only\non large-smem arches like sm90\u002FH100.\n\n**To force the MEA path portably in a test, use `ORT_DISABLE_FLASH_ATTENTION=1` with a small\n`head_size` (e.g. 64) whose SharedStorage fits every target arch — NOT `head_size=512`.**\nAlso guard with `SKIP_IF_MEA_NOT_COMPILED` (see §7) so a MEA-OFF build SKIPs rather than\nfalse-greens via the (correct) unfused fallback.\n\n**Flash eligibility**: fp16\u002Fbf16 only, SM≥8.0 (Ampere+), `head_size == v_head_size`, `head_size \u003C= 256`, no `output_qk`, `attn_mask == nullptr`. Uses `mha_fwd` \u002F `mha_fwd_kvcache`.\n\n> **QUICK_BUILD caveat (false hypothesis trap).** *(General principle — build flags can\n> silently reroute kernel dispatch — lives in the `ort-build` skill, \"Agent tips\". The\n> attention-specific instance:)* With `onnxruntime_QUICK_BUILD=ON`\n> (`-DORT_QUICK_BUILD`), Flash is compiled for **head_dim 128 only**:\n> `flash_api.h:147` `is_supported\u003CT>` returns false for `head_size != 128`, and\n> `static_switch.h:80` `HEADDIM_SWITCH` only instantiates `kHeadDim=128`. So under\n> QUICK_BUILD nearly every shape routes to **MEA**, not FlashAttention-2. If a\n> `head_size!=128` test \"fails only on some SM\", suspect **MEA** (CUTLASS,\n> arch-independent), NOT a Flash\u002FFA2 hardware bug. `head_size=512` **is routed to MEA** in all\n> MEA-enabled builds (Flash caps at 256), but its MEA kernel **fails to launch** on\n> small-smem GPUs — see the `head_size=512` caveat above (#28388).\n\n**MEA eligibility**: SM50+\u002F53+\u002F80+ by dtype, `head_size \u003C= 1024` and divisible by 8 (enforced by `has_memory_efficient_attention`), no `output_qk`. GQA additionally requires `head_size == v_head_size` (for `LaunchUngroup`); decode also requires it (for `LaunchConcatNewToPastKV`). Bias stride must satisfy `total_sequence_length % 4 == 0`. GQA with FP32 is excluded (LaunchUngroup only has fp16\u002Fbf16 instantiations). Supports `softcap + attn_mask` — CUTLASS applies softcap before bias in kernel tiles, matching ONNX spec ordering (onnx\u002Fonnx#7867, supersedes the now-closed onnx\u002Fonnx#7865 issue).\n\n**Unified Unfused Attention**: Always available as the final fallback. Handles both MHA (`num_heads == kv_num_heads`, group=1) and GQA (`num_heads != kv_num_heads`, group>1) via a reshape-Q trick with stride-based cuBLAS batched GEMM (no K\u002FV head replication). Uses FP32 QK scratch for precision. Supports all features:\n- softcap + attn_mask (spec-correct ordering)\n- output_qk (kQK mode: copies raw QK before softcap\u002Fmask mutations)\n- past_key + past_value with `head_size != v_head_size` (separate K\u002FV concat)\n- causal masking, nonpad_kv_seqlen, all dtypes (fp16\u002Fbf16\u002Ffp32)\n\n## 2. CUTLASS kLog2e Overflow\n\nCUTLASS `iterative_softmax` multiplies all attention scores by `kLog2e ≈ 1.4427` internally (for `exp2f` instead of `expf`). For float\u002Fbf16:\n\n```\nmask_filter_value = std::numeric_limits\u003Cfloat>::lowest() ≈ -3.40e+38\n-3.40e+38 × 1.4427 ≈ -4.91e+38  →  overflows fp32  →  -inf\n```\n\nWhen all values become `-inf`, CUTLASS's special-case path produces `s_prime=0` → `1\u002Fs_prime=inf` → `0 × inf = NaN`.\n\n**Fix**: Cap `mask_filter_value` to `-1.0e+30f` in `ConvertAttnMaskToBias`. This value is safe: `1e30 × 1.4427 ≈ 1.4e30 \u003C\u003C FLT_MAX`, and `exp(-1e30) ≈ 0` (effectively masked).\n\n**fp16 is NOT affected**: `lowest() = -65504`, and `-65504 × 1.4427 ≈ -94500` stays within fp32 range.\n\nThis cap is ONLY applied in MEA paths. The unfused path uses `lowest()` directly (its softmax subtracts max first, avoiding overflow).\n\n**Subtlety**: When bias is present (`kSupportsBias=true`), CUTLASS pre-applies `p.scale` to QK (line 858) and uses `scaling=1.0f` in the softmax loop (line 981). So the full `kLog2e` multiplier hits the bias-dominated values — the overflow is head_size-independent. Without bias, `scaling = p.scale * kLog2e = kLog2e\u002Fsqrt(head_size)`, which is much smaller.\n\n## 3. Bias Alignment\n\nCUTLASS FMHA requires the attention bias row stride to satisfy minimum alignment. The bias has shape `[B, H, S, T]` where `T = total_sequence_length` is the row stride.\n\n```cpp\nconstexpr int min_bias_align = 4;  \u002F\u002F elements, not bytes\nif (parameters.total_sequence_length % min_bias_align != 0) {\n    mea_eligible = false;  \u002F\u002F fall through to unfused\n}\n```\n\n**Impact on tests**: If a test uses `total_sequence_length` not divisible by 4 (e.g., past=5 + new=6 = 11), MEA is rejected and unfused handles it. To test MEA with bias, ensure `total_sequence_length % 4 == 0`.\n\n## 4. Softcap Ordering\n\nONNX Attention opset 23\u002F24 spec ordering (per onnx\u002Fonnx#7867, which superseded\nthe now-closed onnx\u002Fonnx#7865 issue, and onnx\u002Fonnx#7913 which swapped\n`qk_matmul_output_mode` values 1 and 2 to align with the corrected pipeline):\n\n```\nscale * (Q @ K^T)        # stage 0: raw scaled QK\n    |\nsoftcap (if > 0)         # stage 1: tanh(qk \u002F softcap) * softcap\n    |\n+ attn_bias \u002F + attn_mask # stage 2: additive (mask -inf survives to stage 3)\n    |\nsoftmax                  # stage 3\n    |\n@ V\n```\n\n`qk_matmul_output_mode` integer values follow pipeline stage order:\n0 = raw scale*QK, 1 = post-softcap (pre-mask), 2 = post-mask\u002Fbias (pre-softmax),\n3 = post-softmax.\n\nCUDA implementation status (all spec-correct):\n- **MEA (CUTLASS)**: `kernel_forward.h` applies softcap inside the score-compute\n  tile loop BEFORE `attn_bias` is added.\n- **Flash**: `mha_fwd` \u002F `mha_fwd_kvcache` handle softcap natively; reject\n  explicit `attn_mask`, so ordering with float mask is moot for this path.\n- **Unfused**: `UnfusedSoftmaxKernel` does `QK -> scale -> softcap -> add bias -> softmax`\n  (all fused).\n\nCPU implementation status: `core\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention.cc::ComputeAttentionProbs\u003CT>`\napplies softcap BEFORE the mask add (post-fix; pre-fix it inverted the order\nand leaked probability through masked positions).\n\nWhy this ordering matters: a -inf in `attn_mask` must survive to softmax. If\nsoftcap were applied AFTER the mask-add, then `tanh(-inf\u002Fsoftcap) * softcap = -softcap`\n(a finite value), and softmax would assign non-zero weight to the masked\nposition — leaking poison V values into the output. The CUDA-side guard tests\nat `test_onnx_attention\u002Ftest_gqa.py:1501` and `:1761`, and the CPU-side guards\nat `TestONNXAttentionCPUSoftcapMaskOrdering` in the same file, exercise this\nproperty by combining small softcap, a -inf mask entry, and a poison V value.\n\n## 5. Grid-Stride Loops for CUDA Kernels\n\nAlways cap grid size to prevent exceeding `gridDim.x` limits, and use grid-stride loops for large workloads:\n\n```cpp\nconstexpr int64_t kMaxGridDimX = 65535;\nint threads = static_cast\u003Cint>(std::min(static_cast\u003Cint64_t>(max_threads_per_block), total));\nint64_t blocks = (total + threads - 1) \u002F threads;\nunsigned int grid_size = static_cast\u003Cunsigned int>(std::min(blocks, kMaxGridDimX));\n\nMyKernel\u003C\u003C\u003Cgrid_size, threads, 0, stream>>>(...);\n\n\u002F\u002F Inside the kernel:\nfor (int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;\n     idx \u003C total;\n     idx += static_cast\u003Cint64_t>(gridDim.x) * blockDim.x) {\n    \u002F\u002F work\n}\n```\n\n**Never** cast `int64_t` block count directly to `unsigned int` without capping — it silently truncates.\n\nAlways call `CUDA_CALL(cudaGetLastError())` after kernel launches in standalone helper functions. This is the established pattern in the file (see `ConcatPastToPresent`, `PastPresentBufferShare`).\n\n## 6. Fully-Masked Rows and Batches\n\nAll-false bool masks, an all-`-inf` `attn_mask` row, or a causal\u002Fnonpad frontier\nwith no allowed key produce NaN in CUTLASS MEA (the uniform\u002Fempty softmax degenerates:\n`s_prime=0` → `1\u002Fs_prime=inf` → `0 × inf = NaN`). Per onnx\u002Fonnx#8068 (Bug-2), a\n**fully-masked query row** — one with no key allowed by the composed causal + nonpad +\nmask constraints — must output a **zero row** (`Y = 0`), **not** mean-of-V.\n\n**This `Y = 0` behavior is now consistent on BOTH EPs** (the earlier mean(V)-vs-zero\ncross-EP divergence is RESOLVED — there is no longer an open TODO here):\n\n- **CUDA**: `ZeroFullyMaskedRowsKernel` (in `attention_mask_impl.cu`) runs after the\n  MEA\u002FCUTLASS output and zeros each fully-masked row with a **select** (not multiply,\n  so `0 @ V = 0` even when V is poisoned). It detects a fully-masked row with an exact\n  per-key predicate (within the causal\u002Fnonpad frontier AND the additive-bias slot is\n  above the mask sentinel), matching the onnx#8068 `isneginf`-of-row-max reference. A\n  finite (even very negative) user bias is not the sentinel, so its key stays unmasked\n  and the row is left untouched.\n- **CPU**: `core\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention.cc` applies the same Bug-2 guard — after\n  softmax it zeros any row whose composed frontier admitted no unmasked key.\n\n**Additive-bias path** (bool mask converted to bias): `mask_filter_value` is capped to\n`-1e+30f` (see section 2) so CUTLASS does not overflow to NaN; a row that is nonetheless\nfully masked is then zeroed by the per-row guard above.\n\n**Whole-batch empty (`seqlens_k[b] == 0`)**: the structural case where an entire batch\nhas zero valid keys is additionally handled by `ZeroOutputForFullyMaskedBatches`, which\nzeros that batch's output. (The per-row guard covers the finer-grained case where only\nsome query rows are fully masked.)\n\n**`qk_matmul_output_mode` (mode 3 \u002F post-softmax debug output)**: for a fully-masked row\nthe mode-3 snapshot is **mandated to be `0`** (zero row), consistent with `Y = 0`, per the\nonnx#8068 SIG decision (this superseded the earlier \"unspecified\" proposal). The CPU\npost-softmax snapshot is taken **after** the row-zeroing guard — matching the onnx\nreference and the v23\u002Fv24 function bodies, where the guard runs before the mode-3\ncapture — so the debug tensor reflects the same zero row as the output. Note this\nmode-3=0 behavior is served by the **CPU** path: CUDA `qk_matmul_output_mode` beyond\n`kNone`\u002F`kQK` (i.e. `kPostSoftCap`\u002F`kPostMaskBias`\u002F`kPostSoftMax`) returns\n`NOT_IMPLEMENTED` (`attention.cc`), so an agent must not assume CUDA produces mode-3=0.\n\n## 7. Test Runner Targeting\n\nUse `ScopedEnvironmentVariables` to force specific CUDA runners:\n\n```cpp\n\u002F\u002F Force MEA (disable Flash)\nScopedEnvironmentVariables scoped_env({\n    {\"ORT_DISABLE_FLASH_ATTENTION\", \"1\"},\n});\n\n\u002F\u002F Force Unfused (disable both Flash and MEA)\nScopedEnvironmentVariables scoped_env({\n    {\"ORT_DISABLE_FLASH_ATTENTION\", \"1\"},\n    {\"ORT_DISABLE_MEMORY_EFFICIENT_ATTENTION\", \"1\"},\n});\n```\n\n**Always verify which runner a test actually hits.** A test designed for MEA may silently fall to unfused if:\n- `total_sequence_length % 4 != 0` (bias alignment)\n- `head_size != v_head_size` (decode path)\n- fp32 dtype with GQA (LaunchUngroup fp16\u002Fbf16 only)\n- fp32 dtype on SM \u003C 80\n\nEnable verbose logging to confirm: `LOGS_DEFAULT(VERBOSE) \u003C\u003C \"ONNX Attention: using ...\"`.\n\n**`SKIP_IF_MEA_NOT_COMPILED`** is a local gtest macro (defined in\n`test\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention_op_test.cc`) that `GTEST_SKIP`s — rather than silently\npasses — when `USE_MEMORY_EFFICIENT_ATTENTION` is OFF, so an MEA-targeted test cannot\nfalse-green via the (correct) unfused fallback. Use it in any test that must prove the MEA\npath ran (see the `ort-test` skill → \"Verify which path\u002Fkernel actually executed\").\n\n## 8. Cross-EP Consistency\n\nCPU is the spec reference implementation. CUDA outputs should match CPU for all valid inputs.\n\n- CPU uses `mask_filter_value = std::numeric_limits\u003CT>::lowest()` (finite, not `-inf`)\n- CPU softmax: subtract-max-first → works correctly with extreme finite values\n- CPU zeros fully-masked query rows (onnx#8068 Bug-2 guard) — output `Y = 0`, matching\n  CUDA's `ZeroFullyMaskedRowsKernel`. (Earlier docs claimed CPU produced mean(V) here;\n  that divergence is resolved — both EPs now emit a zero row.)\n\nRun tests with `disable_cpu=false` to always validate against CPU. The C++ test framework (`RunTest4D`) supports `disable_cpu`, `disable_cuda`, `disable_dml` flags.\n\n## 9. File Locations\n\n### ONNX Domain (this op's code)\n\n| File | Purpose |\n|------|---------|\n| `core\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention.cc` | ONNX Attention CUDA dispatch: Flash\u002FMEA\u002FUnfused cascade, `ConvertAttnMaskToBias`, parameter setup |\n| `core\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention_mask_impl.cu` | ONNX-specific mask\u002Fbias CUDA kernels: bool→bias, nonpad→seqlens_k, ZeroOutput, bias composition |\n| `core\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention_mask_impl.h` | Declarations for ONNX mask\u002Fbias kernels |\n| `core\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention.cc` | CPU reference implementation (ONNX domain) |\n| `core\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention_helper.h` | ONNX parameter validation and shape computation |\n| `test\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention_op_test.cc` | C++ tests for the **ONNX-domain** `Attention` op — suite `AttentionTest.*`, runs in `onnxruntime_provider_test` (all EPs). NOT to be confused with the contrib `test\u002Fcontrib_ops\u002Fattention_op_test.cc` (`ContribOpAttentionTest.*`); see `ort-test` skill. |\n| `test\u002Fpython\u002Ftransformers\u002Ftest_onnx_attention\u002Ftest_mha.py` | Python parity tests |\n| `test\u002Fpython\u002Ftransformers\u002Ftest_onnx_attention\u002Fcommon.py` | Python test utilities and reference `attention_ref()` |\n\n### Shared Infrastructure (used by both ONNX and contrib ops)\n\n| File | Purpose |\n|------|---------|\n| `contrib_ops\u002Fcuda\u002Fbert\u002Funfused_attention.cu` | Unified unfused attention: QK GEMM (FP32), fused softmax kernel (scale+softcap+bias+causal), V GEMM. Handles MHA and GQA. |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Funfused_attention.h` | `UnfusedAttentionParams`, `LaunchUnfusedAttention`, workspace size |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fattention_impl.cu` | Legacy unfused `QkvToContext` (contrib MHA only). Also `ApplySoftcap`, `ConcatPastToPresent` |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fattention_softmax.h` | CUDA softmax kernels (`ComputeSoftmax`, `ComputeSoftmaxWithRawMask`) — used by legacy contrib path |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fcutlass_fmha\u002F` | CUTLASS FMHA (Memory Efficient Attention) kernels |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fflash_attention\u002F` | Flash Attention kernels |\n\n### Contrib Domain (separate ops, NOT covered by this skill)\n\n| File | Purpose |\n|------|---------|\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fmultihead_attention.cu` | Contrib `MultiHeadAttention` — own dispatch, uses `contrib::AttentionParameters` directly |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fgroup_query_attention.cu` | Contrib `GroupQueryAttention` — has XQA kernel, past-present buffer sharing |\n\n## 10. Parameter Bridge (ONNX → Contrib)\n\nThe ONNX Attention op uses `attention_helper::AttentionParameters` (in `core\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention_parameters.h`). The unified unfused kernel (`LaunchUnfusedAttention`) uses its own `UnfusedAttentionParams` struct populated directly from ONNX parameters in `RunUnfusedAttention`.\n\nThe contrib `QkvToContext` function (used by contrib MHA, NOT by ONNX Attention) uses `contrib::AttentionParameters`. ONNX Attention does **not** bridge to `contrib::AttentionParameters` — it routes through the unified unfused kernel instead.\n\n## 11. Causal Alignment\n\nThe ONNX spec defines two causal alignment modes based on where query positions sit in the full attention matrix:\n\n- **Upper-left** (a.k.a. *top-left*): `q_i` attends to `kv[0..i]`. Query positions start at 0 in the full matrix.\n- **Bottom-right** (a.k.a. *lower-right*): `q_i` attends to `kv[0 .. kv_len - q_len + i]` — i.e. keys `j` with `j \u003C= i + offset`, where `offset = kv_len - q_len` (clamped `>= 0`). The causal diagonal is anchored at the end of the key axis. This is the term onnx\u002Fonnx#8068 uses; kernel flags spell it `CausalFromBottomRight`.\n\n**ONNX spec rule**: causal alignment depends on how the KV context is supplied.\n\n- **Internal cache \u002F no cache** (`past_key`, or plain self-attention): `is_causal=1`\n  is upper-left in the full matrix. When `past_key` provides context,\n  `past_sequence_length` shifts the query start position forward — the resulting\n  `[S_q × total_kv]` sub-matrix is effectively bottom-right.\n- **External \u002F static cache** (`nonpad_kv_seqlen`, no `past_key`, opset 24): per\n  onnx\u002Fonnx#8068, `is_causal=1` uses **bottom-right** (offset-aware) alignment —\n  query in-block index `i` attends key `j` iff `j \u003C= i + offset[b]`, where\n  `offset[b] = nonpad_kv_seqlen[b] - q_sequence_length` (clamped to `>= 0`).\n\n### Per-kernel behavior\n\n| Kernel | Alignment | Mechanism |\n|--------|-----------|-----------|\n| **Flash** | Bottom-right only | `is_causal` flag → `seqlen_k - seqlen_q` offset in kernel. No upper-left option. |\n| **MEA (CUTLASS)** | Both | `causal_from_top_left` flag in `MemoryEfficientAttentionParams`. `true` → `CausalFromTopLeft` (offset=0). `false` → `CausalFromBottomRight` (offset = num_keys - num_queries). |\n| **Unfused** | Both | `past_kv_length` param. `0` → upper-left. `total_kv - S_q` → bottom-right. |\n\n### Dispatch logic in attention.cc\n\n```cpp\n\u002F\u002F Pure cross-attention with NO external cache (S_q != S_kv, no past, no nonpad):\n\u002F\u002F this is the upper-left case Flash cannot express.\nbool causal_cross_no_past = parameters.is_causal &&\n    parameters.q_sequence_length != parameters.total_sequence_length &&\n    parameters.past_sequence_length == 0;\n\n\u002F\u002F Flash: eligible UNLESS (causal_cross_no_past && nonpad_kv_seqlen == nullptr).\n\u002F\u002F   - No external cache  -> upper-left required -> skip Flash (no upper-left support).\n\u002F\u002F   - External cache (nonpad_kv_seqlen != nullptr) -> required frontier IS bottom-right\n\u002F\u002F     (onnx#8068), so Flash IS eligible and produces it natively via seqlens_k.\n\u002F\u002F MEA: external cache -> causal_from_top_left = false (bottom-right, offset = num_keys -\n\u002F\u002F   num_queries == nonpad_kv_seqlen[b] - q_len per batch); otherwise causal_from_top_left\n\u002F\u002F   = (past_sequence_length == 0).\n\u002F\u002F Unfused: always correct via past_kv_length (0 -> upper-left; total_kv - S_q -> bottom-right).\n```\n\n### When S_q == S_kv\n\nUpper-left and bottom-right produce **identical** results when `S_q == S_kv` (the offset is 0 either way). The alignment distinction only matters for cross-attention shapes (`S_q != S_kv`).\n\n### TensorScatter decode (opset 24 external KV cache)\n\nTensorScatter manages KV cache externally — `past_key` is nullptr but K\u002FV already\ncontain the full sequence, with `nonpad_kv_seqlen[b]` giving each batch's valid\n(non-padded) key count. Per onnx\u002Fonnx#8068, `is_causal=1` with an external\u002Fstatic KV\ncache (no `past_key`) uses **bottom-right** (offset-aware) alignment: query in-block\nindex `i` attends key `j` iff `j \u003C= i + offset[b]`, where\n`offset[b] = nonpad_kv_seqlen[b] - q_sequence_length` (clamped to `>= 0`). For decode\n(`q_sequence_length == 1`) the single query row therefore attends all\n`nonpad_kv_seqlen[b]` valid keys — the meaningful, spec-correct result (not the\ndegenerate \"q[0] sees only kv[0]\" of upper-left).\n\n**Correct pattern**: `is_causal=1` with TensorScatter + `nonpad_kv_seqlen` (no `past_key`)\nis **valid and supported** for both decode and continued-prefill — it yields bottom-right\ncausal attention bounded by the per-batch valid-key count. (`is_causal=0` is also valid\nwhere a model wants no causal masking.) The earlier `is_causal=1` NOT_IMPLEMENTED reject\nwas **removed** in the onnx#8068 alignment work; the only still-invalid combination is\n`nonpad_kv_seqlen` together with `past_key` (mutually exclusive internal-vs-external\ncache, enforced at validation in `attention_helper.h`).\n\n## 12. Signed Offsets in CUTLASS FMHA (uint wrap hazard)\n\nThis is a specific instance of the general **signed-vs-unsigned wrap** bug class — see\n`AGENTS.md` → \"Signed vs unsigned on negative-capable differences\" for the principle. Below\nare the **attention-specific** fix sites in `cutlass_fmha\u002Fkernel_forward.h`. See §11 for what\nthe offset *means* (bottom-right alignment); this section is purely the signed-arithmetic\nhazard.\n\nAny FMHA offset computed as a difference of counts — canonically\n`causal_diagonal_offset = num_keys - num_queries` (`CausalFromBottomRight`) — is\n**negative** whenever `num_keys \u003C num_queries` (cross-attention \u002F KV-trimmed \u002F\n`nonpad_kv_seqlen[b] \u003C q_len`, onnx#8068 \u002F ORT #28904). It **must** be stored and\ncompared as `int32_t`; a `uint32_t` wraps the negative value to ~4.29e9 (`0xFFFFFFFE`),\nthe causal-mask guard `min(iter_key_start + kKeysPerBlock, num_keys) >= query_start + offset`\nbecomes permanently false, the per-element causal mask is **silently skipped**, and boundary\nquery rows over-attend one extra key.\n\n### Fix sites in `cutlass_fmha\u002Fkernel_forward.h` (symbols are stable; lines as of cc34d0b914)\n\n| Symbol \u002F guard | Line | What it must do |\n|---|---|---|\n| `int32_t causal_diagonal_offset` (field decl) | ~206 | Stay **`int32_t`** so the negative offset is preserved (rationale comment ~202-205). |\n| `causal_diagonal_offset = num_keys - num_queries;` | ~354 | Set point for `CausalFromBottomRight`; may be negative (comment ~353). |\n| `int32_t(query_start + causal_diagonal_offset + kQueriesPerBlock)` | ~366 | First (AttentionKernel) `num_keys` clamp. The inner sum **does** wrap to `0xFFFFFFFE`-style values in unsigned arithmetic when the offset is negative, but casting the **whole sum** to `int32_t` recovers the correct value by two's-complement modular arithmetic, and the result is consumed **arithmetically** (as a `fast_min` operand), so the wrap is harmless. Contrast the ~924 guard, where the value feeds a **relational** comparison — there the unsigned wrap flips the comparison result, so the operand `query_start` must be cast to `int32_t` **before** the compare. |\n| \"Mask out last if causal\" guard: `static_cast\u003Cint32_t>(query_start) + p.causal_diagonal_offset` | ~924-926 | `query_start` is `uint32_t` (~707) — cast it to `int32_t` so the comparison is signed (rationale ~919-923). |\n| Sliding-window guard (\"L957\"): `static_cast\u003Cint32_t>(query_start) + p.causal_diagonal_offset ...` | ~962-963 | Same cast hardening (rationale ~956-961). |\n\n### Rules when editing `kernel_forward.h` (or any FMHA kernel)\n\n- Keep `causal_diagonal_offset` **`int32_t`**.\n- `query_start` in the iteration kernels is **`uint32_t`** — `static_cast\u003Cint32_t>(query_start)`\n  before adding the offset in ANY relational guard.\n- The same hazard is **dormant but real** at the `window_size > 0` guard: harden it the\n  same way even though opset-24 Attention currently pins `window=-1` (a future\n  sliding-window \u002F KV-trim caller could combine `window_size>0` with a negative offset).\n- Tests that exercise this need a **negative** offset: `num_keys \u003C num_queries`. Force the\n  MEA path **portably** with `ORT_DISABLE_FLASH_ATTENTION=1` + a small `head_size` (e.g. 64)\n  — **not** `head_size=512`, whose MEA launch is arch-fragile on small-smem GPUs (#28388,\n  see §1). The regression tests live in `test\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention_op_test.cc`\n  (`Attention_Causal_NonPadKVSeqLen_MEA_*`), guarded by `SKIP_IF_MEA_NOT_COMPILED`.\n","# ONNX Domain Attention (Opset 23\u002F24) CUDA Patterns\n\nReusable knowledge from ONNX Attention CUDA development in ORT.\n\n> **Scope**: This skill covers the **ONNX domain** `Attention` operator (opset 23\u002F24)\n> implemented at `core\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention.cc`. This is **separate from** the\n> contrib domain `MultiHeadAttention` \u002F `GroupQueryAttention` at `contrib_ops\u002Fcuda\u002Fbert\u002F`.\n> They share some underlying kernels (CUTLASS FMHA, Flash Attention) and infrastructure\n> (`attention_softmax.h`) but have **different dispatch logic, parameter structs, and eligibility checks**.\n>\n> - **Shared infrastructure**: CUTLASS FMHA kernel, Flash kernel, unified unfused kernel\n>   (`unfused_attention.cu`), `attention_softmax.h`, `attention_impl.cu` (contrib only)\n> - **ONNX-specific**: Dispatch cascade in `attention.cc`, `ConvertAttnMaskToBias`,\n>   `mask_filter_value` cap, parameter bridge to contrib structs, `attention_mask_impl.cu`\n> - **Contrib-specific**: Own dispatch in contrib MHA\u002FGQA ops, uses `contrib::AttentionParameters`\n>   directly, has XQA kernel, past-present buffer sharing\n\n## 1. Runner Dispatch Cascade\n\nCUDA attention dispatches in priority order: **Flash → MEA (Memory Efficient) → Unified Unfused Attention**.\n\n```\n\u002F\u002F onnxruntime\u002Fcore\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention.cc — ComputeInternal()\nFlash eligible?      → RunFlashAttention()\n  ↓ no\nMEA eligible?        → RunMemoryEfficientAttention()\n  ↓ no\nUnified Unfused      → RunUnfusedAttention()\n  (handles both MHA and GQA via reshape-Q trick)\n```\n\n### Eligibility anchors (symbols are stable; line numbers as of cc34d0b914)\n\n| Stage | Decision symbol | Hard caps | Dispatch gate |\n|---|---|---|---|\n| Flash | `flash::is_supported\u003CT>` (`flash_api.cc:414`) | fp16\u002Fbf16 only, SM≥8.0, `head_size%8==0`, **`head_size\u003C=256`** | `attention.cc:1385` `flash_eligible` (fp32 excluded at :1387) |\n| MEA | `has_memory_efficient_attention` (`memory_efficient_attention.h:68`) | `(head_size&7)==0` **and `head_size\u003C=kEfficientAttentionMaxHeadSize` (1024)**; **NO shared-memory feasibility check** (see #28388 + the head_size=512 caveat below) | `attention.cc:1415` `mea_eligible`; bias-stride `%4` at :1436 |\n| Unfused | (none — catch-all) | all dtypes\u002Fshapes | `attention.cc:1485` `RunUnfusedAttention` |\n\n**`head_size=512` IS routed to MEA, but its MEA kernel is NOT portably launchable — so it\nis not a robust test probe.**\nBy the predicate, 512 > 256 fails Flash and 512 ≤ 1024 with `512 & 7 == 0` passes the MEA\npredicate, **so dispatch selects MEA** — but the MEA eligibility check\n(`memory_efficient_attention.h:68-73`) gates only on SM +\n`head&7==0` + `head\u003C=1024`, with **no shared-memory check**. For `head_size=512` FP16 the\nCUTLASS MEA `SharedStorage` exceeds the dynamic-smem opt-in cap on capacity-limited arches\n(sm86 ~99KB, sm80 ~163KB, sm90 ~227KB — **non-monotonic**, no clean SM-version guard).\n`fmha_launch_template.h` calls `cudaFuncSetAttribute(..., cudaFuncAttributeMaxDynamicSharedMemorySize, ...)`\nbut **ignores its return value and launches anyway**, so on sm86 the kernel dies at launch\nwith `CUDA failure 1: invalid argument` — there is **no fallback to unfused** (live bug\n#28388; its fix PR #28383 was never merged). So `head_size=512`'s MEA kernel launches only\non large-smem arches like sm90\u002FH100.\n\n**To force the MEA path portably in a test, use `ORT_DISABLE_FLASH_ATTENTION=1` with a small\n`head_size` (e.g. 64) whose SharedStorage fits every target arch — NOT `head_size=512`.**\nAlso guard with `SKIP_IF_MEA_NOT_COMPILED` (see §7) so a MEA-OFF build SKIPs rather than\nfalse-greens via the (correct) unfused fallback.\n\n**Flash eligibility**: fp16\u002Fbf16 only, SM≥8.0 (Ampere+), `head_size == v_head_size`, `head_size \u003C= 256`, no `output_qk`, `attn_mask == nullptr`. Uses `mha_fwd` \u002F `mha_fwd_kvcache`.\n\n> **QUICK_BUILD caveat (false hypothesis trap).** *(General principle — build flags can\n> silently reroute kernel dispatch — lives in the `ort-build` skill, \"Agent tips\". The\n> attention-specific instance:)* With `onnxruntime_QUICK_BUILD=ON`\n> (`-DORT_QUICK_BUILD`), Flash is compiled for **head_dim 128 only**:\n> `flash_api.h:147` `is_supported\u003CT>` returns false for `head_size != 128`, and\n> `static_switch.h:80` `HEADDIM_SWITCH` only instantiates `kHeadDim=128`. So under\n> QUICK_BUILD nearly every shape routes to **MEA**, not FlashAttention-2. If a\n> `head_size!=128` test \"fails only on some SM\", suspect **MEA** (CUTLASS,\n> arch-independent), NOT a Flash\u002FFA2 hardware bug. `head_size=512` **is routed to MEA** in all\n> MEA-enabled builds (Flash caps at 256), but its MEA kernel **fails to launch** on\n> small-smem GPUs — see the `head_size=512` caveat above (#28388).\n\n**MEA eligibility**: SM50+\u002F53+\u002F80+ by dtype, `head_size \u003C= 1024` and divisible by 8 (enforced by `has_memory_efficient_attention`), no `output_qk`. GQA additionally requires `head_size == v_head_size` (for `LaunchUngroup`); decode also requires it (for `LaunchConcatNewToPastKV`). Bias stride must satisfy `total_sequence_length % 4 == 0`. GQA with FP32 is excluded (LaunchUngroup only has fp16\u002Fbf16 instantiations). Supports `softcap + attn_mask` — CUTLASS applies softcap before bias in kernel tiles, matching ONNX spec ordering (onnx\u002Fonnx#7867, supersedes the now-closed onnx\u002Fonnx#7865 issue).\n\n**Unified Unfused Attention**: Always available as the final fallback. Handles both MHA (`num_heads == kv_num_heads`, group=1) and GQA (`num_heads != kv_num_heads`, group>1) via a reshape-Q trick with stride-based cuBLAS batched GEMM (no K\u002FV head replication). Uses FP32 QK scratch for precision. Supports all features:\n- softcap + attn_mask (spec-correct ordering)\n- output_qk (kQK mode: copies raw QK before softcap\u002Fmask mutations)\n- past_key + past_value with `head_size != v_head_size` (separate K\u002FV concat)\n- causal masking, nonpad_kv_seqlen, all dtypes (fp16\u002Fbf16\u002Ffp32)\n\n## 2. CUTLASS kLog2e Overflow\n\nCUTLASS `iterative_softmax` multiplies all attention scores by `kLog2e ≈ 1.4427` internally (for `exp2f` instead of `expf`). For float\u002Fbf16:\n\n```\nmask_filter_value = std::numeric_limits\u003Cfloat>::lowest() ≈ -3.40e+38\n-3.40e+38 × 1.4427 ≈ -4.91e+38  →  overflows fp32  →  -inf\n```\n\nWhen all values become `-inf`, CUTLASS's special-case path produces `s_prime=0` → `1\u002Fs_prime=inf` → `0 × inf = NaN`.\n\n**Fix**: Cap `mask_filter_value` to `-1.0e+30f` in `ConvertAttnMaskToBias`. This value is safe: `1e30 × 1.4427 ≈ 1.4e30 \u003C\u003C FLT_MAX`, and `exp(-1e30) ≈ 0` (effectively masked).\n\n**fp16 is NOT affected**: `lowest() = -65504`, and `-65504 × 1.4427 ≈ -94500` stays within fp32 range.\n\nThis cap is ONLY applied in MEA paths. The unfused path uses `lowest()` directly (its softmax subtracts max first, avoiding overflow).\n\n**Subtlety**: When bias is present (`kSupportsBias=true`), CUTLASS pre-applies `p.scale` to QK (line 858) and uses `scaling=1.0f` in the softmax loop (line 981). So the full `kLog2e` multiplier hits the bias-dominated values — the overflow is head_size-independent. Without bias, `scaling = p.scale * kLog2e = kLog2e\u002Fsqrt(head_size)`, which is much smaller.\n\n## 3. Bias Alignment\n\nCUTLASS FMHA requires the attention bias row stride to satisfy minimum alignment. The bias has shape `[B, H, S, T]` where `T = total_sequence_length` is the row stride.\n\n```cpp\nconstexpr int min_bias_align = 4;  \u002F\u002F elements, not bytes\nif (parameters.total_sequence_length % min_bias_align != 0) {\n    mea_eligible = false;  \u002F\u002F fall through to unfused\n}\n```\n\n**Impact on tests**: If a test uses `total_sequence_length` not divisible by 4 (e.g., past=5 + new=6 = 11), MEA is rejected and unfused handles it. To test MEA with bias, ensure `total_sequence_length % 4 == 0`.\n\n## 4. Softcap Ordering\n\nONNX Attention opset 23\u002F24 spec ordering (per onnx\u002Fonnx#7867, which superseded\nthe now-closed onnx\u002Fonnx#7865 issue, and onnx\u002Fonnx#7913 which swapped\n`qk_matmul_output_mode` values 1 and 2 to align with the corrected pipeline):\n\n```\nscale * (Q @ K^T)        # stage 0: raw scaled QK\n    |\nsoftcap (if > 0)         # stage 1: tanh(qk \u002F softcap) * softcap\n    |\n+ attn_bias \u002F + attn_mask # stage 2: additive (mask -inf survives to stage 3)\n    |\nsoftmax                  # stage 3\n    |\n@ V\n```\n\n`qk_matmul_output_mode` integer values follow pipeline stage order:\n0 = raw scale*QK, 1 = post-softcap (pre-mask), 2 = post-mask\u002Fbias (pre-softmax),\n3 = post-softmax.\n\nCUDA implementation status (all spec-correct):\n- **MEA (CUTLASS)**: `kernel_forward.h` applies softcap inside the score-compute\n  tile loop BEFORE `attn_bias` is added.\n- **Flash**: `mha_fwd` \u002F `mha_fwd_kvcache` handle softcap natively; reject\n  explicit `attn_mask`, so ordering with float mask is moot for this path.\n- **Unfused**: `UnfusedSoftmaxKernel` does `QK -> scale -> softcap -> add bias -> softmax`\n  (all fused).\n\nCPU implementation status: `core\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention.cc::ComputeAttentionProbs\u003CT>`\napplies softcap BEFORE the mask add (post-fix; pre-fix it inverted the order\nand leaked probability through masked positions).\n\nWhy this ordering matters: a -inf in `attn_mask` must survive to softmax. If\nsoftcap were applied AFTER the mask-add, then `tanh(-inf\u002Fsoftcap) * softcap = -softcap`\n(a finite value), and softmax would assign non-zero weight to the masked\nposition — leaking poison V values into the output. The CUDA-side guard tests\nat `test_onnx_attention\u002Ftest_gqa.py:1501` and `:1761`, and the CPU-side guards\nat `TestONNXAttentionCPUSoftcapMaskOrdering` in the same file, exercise this\nproperty by combining small softcap, a -inf mask entry, and a poison V value.\n\n## 5. Grid-Stride Loops for CUDA Kernels\n\nAlways cap grid size to prevent exceeding `gridDim.x` limits, and use grid-stride loops for large workloads:\n\n```cpp\nconstexpr int64_t kMaxGridDimX = 65535;\nint threads = static_cast\u003Cint>(std::min(static_cast\u003Cint64_t>(max_threads_per_block), total));\nint64_t blocks = (total + threads - 1) \u002F threads;\nunsigned int grid_size = static_cast\u003Cunsigned int>(std::min(blocks, kMaxGridDimX));\n\nMyKernel\u003C\u003C\u003Cgrid_size, threads, 0, stream>>>(...);\n\n\u002F\u002F Inside the kernel:\nfor (int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;\n     idx \u003C total;\n     idx += static_cast\u003Cint64_t>(gridDim.x) * blockDim.x) {\n    \u002F\u002F work\n}\n```\n\n**Never** cast `int64_t` block count directly to `unsigned int` without capping — it silently truncates.\n\nAlways call `CUDA_CALL(cudaGetLastError())` after kernel launches in standalone helper functions. This is the established pattern in the file (see `ConcatPastToPresent`, `PastPresentBufferShare`).\n\n## 6. Fully-Masked Rows and Batches\n\nAll-false bool masks, an all-`-inf` `attn_mask` row, or a causal\u002Fnonpad frontier\nwith no allowed key produce NaN in CUTLASS MEA (the uniform\u002Fempty softmax degenerates:\n`s_prime=0` → `1\u002Fs_prime=inf` → `0 × inf = NaN`). Per onnx\u002Fonnx#8068 (Bug-2), a\n**fully-masked query row** — one with no key allowed by the composed causal + nonpad +\nmask constraints — must output a **zero row** (`Y = 0`), **not** mean-of-V.\n\n**This `Y = 0` behavior is now consistent on BOTH EPs** (the earlier mean(V)-vs-zero\ncross-EP divergence is RESOLVED — there is no longer an open TODO here):\n\n- **CUDA**: `ZeroFullyMaskedRowsKernel` (in `attention_mask_impl.cu`) runs after the\n  MEA\u002FCUTLASS output and zeros each fully-masked row with a **select** (not multiply,\n  so `0 @ V = 0` even when V is poisoned). It detects a fully-masked row with an exact\n  per-key predicate (within the causal\u002Fnonpad frontier AND the additive-bias slot is\n  above the mask sentinel), matching the onnx#8068 `isneginf`-of-row-max reference. A\n  finite (even very negative) user bias is not the sentinel, so its key stays unmasked\n  and the row is left untouched.\n- **CPU**: `core\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention.cc` applies the same Bug-2 guard — after\n  softmax it zeros any row whose composed frontier admitted no unmasked key.\n\n**Additive-bias path** (bool mask converted to bias): `mask_filter_value` is capped to\n`-1e+30f` (see section 2) so CUTLASS does not overflow to NaN; a row that is nonetheless\nfully masked is then zeroed by the per-row guard above.\n\n**Whole-batch empty (`seqlens_k[b] == 0`)**: the structural case where an entire batch\nhas zero valid keys is additionally handled by `ZeroOutputForFullyMaskedBatches`, which\nzeros that batch's output. (The per-row guard covers the finer-grained case where only\nsome query rows are fully masked.)\n\n**`qk_matmul_output_mode` (mode 3 \u002F post-softmax debug output)**: for a fully-masked row\nthe mode-3 snapshot is **mandated to be `0`** (zero row), consistent with `Y = 0`, per the\nonnx#8068 SIG decision (this superseded the earlier \"unspecified\" proposal). The CPU\npost-softmax snapshot is taken **after** the row-zeroing guard — matching the onnx\nreference and the v23\u002Fv24 function bodies, where the guard runs before the mode-3\ncapture — so the debug tensor reflects the same zero row as the output. Note this\nmode-3=0 behavior is served by the **CPU** path: CUDA `qk_matmul_output_mode` beyond\n`kNone`\u002F`kQK` (i.e. `kPostSoftCap`\u002F`kPostMaskBias`\u002F`kPostSoftMax`) returns\n`NOT_IMPLEMENTED` (`attention.cc`), so an agent must not assume CUDA produces mode-3=0.\n\n## 7. Test Runner Targeting\n\nUse `ScopedEnvironmentVariables` to force specific CUDA runners:\n\n```cpp\n\u002F\u002F Force MEA (disable Flash)\nScopedEnvironmentVariables scoped_env({\n    {\"ORT_DISABLE_FLASH_ATTENTION\", \"1\"},\n});\n\n\u002F\u002F Force Unfused (disable both Flash and MEA)\nScopedEnvironmentVariables scoped_env({\n    {\"ORT_DISABLE_FLASH_ATTENTION\", \"1\"},\n    {\"ORT_DISABLE_MEMORY_EFFICIENT_ATTENTION\", \"1\"},\n});\n```\n\n**Always verify which runner a test actually hits.** A test designed for MEA may silently fall to unfused if:\n- `total_sequence_length % 4 != 0` (bias alignment)\n- `head_size != v_head_size` (decode path)\n- fp32 dtype with GQA (LaunchUngroup fp16\u002Fbf16 only)\n- fp32 dtype on SM \u003C 80\n\nEnable verbose logging to confirm: `LOGS_DEFAULT(VERBOSE) \u003C\u003C \"ONNX Attention: using ...\"`.\n\n**`SKIP_IF_MEA_NOT_COMPILED`** is a local gtest macro (defined in\n`test\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention_op_test.cc`) that `GTEST_SKIP`s — rather than silently\npasses — when `USE_MEMORY_EFFICIENT_ATTENTION` is OFF, so an MEA-targeted test cannot\nfalse-green via the (correct) unfused fallback. Use it in any test that must prove the MEA\npath ran (see the `ort-test` skill → \"Verify which path\u002Fkernel actually executed\").\n\n## 8. Cross-EP Consistency\n\nCPU is the spec reference implementation. CUDA outputs should match CPU for all valid inputs.\n\n- CPU uses `mask_filter_value = std::numeric_limits\u003CT>::lowest()` (finite, not `-inf`)\n- CPU softmax: subtract-max-first → works correctly with extreme finite values\n- CPU zeros fully-masked query rows (onnx#8068 Bug-2 guard) — output `Y = 0`, matching\n  CUDA's `ZeroFullyMaskedRowsKernel`. (Earlier docs claimed CPU produced mean(V) here;\n  that divergence is resolved — both EPs now emit a zero row.)\n\nRun tests with `disable_cpu=false` to always validate against CPU. The C++ test framework (`RunTest4D`) supports `disable_cpu`, `disable_cuda`, `disable_dml` flags.\n\n## 9. File Locations\n\n### ONNX Domain (this op's code)\n\n| File | Purpose |\n|------|---------|\n| `core\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention.cc` | ONNX Attention CUDA dispatch: Flash\u002FMEA\u002FUnfused cascade, `ConvertAttnMaskToBias`, parameter setup |\n| `core\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention_mask_impl.cu` | ONNX-specific mask\u002Fbias CUDA kernels: bool→bias, nonpad→seqlens_k, ZeroOutput, bias composition |\n| `core\u002Fproviders\u002Fcuda\u002Fllm\u002Fattention_mask_impl.h` | Declarations for ONNX mask\u002Fbias kernels |\n| `core\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention.cc` | CPU reference implementation (ONNX domain) |\n| `core\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention_helper.h` | ONNX parameter validation and shape computation |\n| `test\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention_op_test.cc` | C++ tests for the **ONNX-domain** `Attention` op — suite `AttentionTest.*`, runs in `onnxruntime_provider_test` (all EPs). NOT to be confused with the contrib `test\u002Fcontrib_ops\u002Fattention_op_test.cc` (`ContribOpAttentionTest.*`); see `ort-test` skill. |\n| `test\u002Fpython\u002Ftransformers\u002Ftest_onnx_attention\u002Ftest_mha.py` | Python parity tests |\n| `test\u002Fpython\u002Ftransformers\u002Ftest_onnx_attention\u002Fcommon.py` | Python test utilities and reference `attention_ref()` |\n\n### Shared Infrastructure (used by both ONNX and contrib ops)\n\n| File | Purpose |\n|------|---------|\n| `contrib_ops\u002Fcuda\u002Fbert\u002Funfused_attention.cu` | Unified unfused attention: QK GEMM (FP32), fused softmax kernel (scale+softcap+bias+causal), V GEMM. Handles MHA and GQA. |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Funfused_attention.h` | `UnfusedAttentionParams`, `LaunchUnfusedAttention`, workspace size |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fattention_impl.cu` | Legacy unfused `QkvToContext` (contrib MHA only). Also `ApplySoftcap`, `ConcatPastToPresent` |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fattention_softmax.h` | CUDA softmax kernels (`ComputeSoftmax`, `ComputeSoftmaxWithRawMask`) — used by legacy contrib path |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fcutlass_fmha\u002F` | CUTLASS FMHA (Memory Efficient Attention) kernels |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fflash_attention\u002F` | Flash Attention kernels |\n\n### Contrib Domain (separate ops, NOT covered by this skill)\n\n| File | Purpose |\n|------|---------|\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fmultihead_attention.cu` | Contrib `MultiHeadAttention` — own dispatch, uses `contrib::AttentionParameters` directly |\n| `contrib_ops\u002Fcuda\u002Fbert\u002Fgroup_query_attention.cu` | Contrib `GroupQueryAttention` — has XQA kernel, past-present buffer sharing |\n\n## 10. Parameter Bridge (ONNX → Contrib)\n\nThe ONNX Attention op uses `attention_helper::AttentionParameters` (in `core\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention_parameters.h`). The unified unfused kernel (`LaunchUnfusedAttention`) uses its own `UnfusedAttentionParams` struct populated directly from ONNX parameters in `RunUnfusedAttention`.\n\nThe contrib `QkvToContext` function (used by contrib MHA, NOT by ONNX Attention) uses `contrib::AttentionParameters`. ONNX Attention does **not** bridge to `contrib::AttentionParameters` — it routes through the unified unfused kernel instead.\n\n## 11. Causal Alignment\n\nThe ONNX spec defines two causal alignment modes based on where query positions sit in the full attention matrix:\n\n- **Upper-left** (a.k.a. *top-left*): `q_i` attends to `kv[0..i]`. Query positions start at 0 in the full matrix.\n- **Bottom-right** (a.k.a. *lower-right*): `q_i` attends to `kv[0 .. kv_len - q_len + i]` — i.e. keys `j` with `j \u003C= i + offset`, where `offset = kv_len - q_len` (clamped `>= 0`). The causal diagonal is anchored at the end of the key axis. This is the term onnx\u002Fonnx#8068 uses; kernel flags spell it `CausalFromBottomRight`.\n\n**ONNX spec rule**: causal alignment depends on how the KV context is supplied.\n\n- **Internal cache \u002F no cache** (`past_key`, or plain self-attention): `is_causal=1`\n  is upper-left in the full matrix. When `past_key` provides context,\n  `past_sequence_length` shifts the query start position forward — the resulting\n  `[S_q × total_kv]` sub-matrix is effectively bottom-right.\n- **External \u002F static cache** (`nonpad_kv_seqlen`, no `past_key`, opset 24): per\n  onnx\u002Fonnx#8068, `is_causal=1` uses **bottom-right** (offset-aware) alignment —\n  query in-block index `i` attends key `j` iff `j \u003C= i + offset[b]`, where\n  `offset[b] = nonpad_kv_seqlen[b] - q_sequence_length` (clamped to `>= 0`).\n\n### Per-kernel behavior\n\n| Kernel | Alignment | Mechanism |\n|--------|-----------|-----------|\n| **Flash** | Bottom-right only | `is_causal` flag → `seqlen_k - seqlen_q` offset in kernel. No upper-left option. |\n| **MEA (CUTLASS)** | Both | `causal_from_top_left` flag in `MemoryEfficientAttentionParams`. `true` → `CausalFromTopLeft` (offset=0). `false` → `CausalFromBottomRight` (offset = num_keys - num_queries). |\n| **Unfused** | Both | `past_kv_length` param. `0` → upper-left. `total_kv - S_q` → bottom-right. |\n\n### Dispatch logic in attention.cc\n\n```cpp\n\u002F\u002F Pure cross-attention with NO external cache (S_q != S_kv, no past, no nonpad):\n\u002F\u002F this is the upper-left case Flash cannot express.\nbool causal_cross_no_past = parameters.is_causal &&\n    parameters.q_sequence_length != parameters.total_sequence_length &&\n    parameters.past_sequence_length == 0;\n\n\u002F\u002F Flash: eligible UNLESS (causal_cross_no_past && nonpad_kv_seqlen == nullptr).\n\u002F\u002F   - No external cache  -> upper-left required -> skip Flash (no upper-left support).\n\u002F\u002F   - External cache (nonpad_kv_seqlen != nullptr) -> required frontier IS bottom-right\n\u002F\u002F     (onnx#8068), so Flash IS eligible and produces it natively via seqlens_k.\n\u002F\u002F MEA: external cache -> causal_from_top_left = false (bottom-right, offset = num_keys -\n\u002F\u002F   num_queries == nonpad_kv_seqlen[b] - q_len per batch); otherwise causal_from_top_left\n\u002F\u002F   = (past_sequence_length == 0).\n\u002F\u002F Unfused: always correct via past_kv_length (0 -> upper-left; total_kv - S_q -> bottom-right).\n```\n\n### When S_q == S_kv\n\nUpper-left and bottom-right produce **identical** results when `S_q == S_kv` (the offset is 0 either way). The alignment distinction only matters for cross-attention shapes (`S_q != S_kv`).\n\n### TensorScatter decode (opset 24 external KV cache)\n\nTensorScatter manages KV cache externally — `past_key` is nullptr but K\u002FV already\ncontain the full sequence, with `nonpad_kv_seqlen[b]` giving each batch's valid\n(non-padded) key count. Per onnx\u002Fonnx#8068, `is_causal=1` with an external\u002Fstatic KV\ncache (no `past_key`) uses **bottom-right** (offset-aware) alignment: query in-block\nindex `i` attends key `j` iff `j \u003C= i + offset[b]`, where\n`offset[b] = nonpad_kv_seqlen[b] - q_sequence_length` (clamped to `>= 0`). For decode\n(`q_sequence_length == 1`) the single query row therefore attends all\n`nonpad_kv_seqlen[b]` valid keys — the meaningful, spec-correct result (not the\ndegenerate \"q[0] sees only kv[0]\" of upper-left).\n\n**Correct pattern**: `is_causal=1` with TensorScatter + `nonpad_kv_seqlen` (no `past_key`)\nis **valid and supported** for both decode and continued-prefill — it yields bottom-right\ncausal attention bounded by the per-batch valid-key count. (`is_causal=0` is also valid\nwhere a model wants no causal masking.) The earlier `is_causal=1` NOT_IMPLEMENTED reject\nwas **removed** in the onnx#8068 alignment work; the only still-invalid combination is\n`nonpad_kv_seqlen` together with `past_key` (mutually exclusive internal-vs-external\ncache, enforced at validation in `attention_helper.h`).\n\n## 12. Signed Offsets in CUTLASS FMHA (uint wrap hazard)\n\nThis is a specific instance of the general **signed-vs-unsigned wrap** bug class — see\n`AGENTS.md` → \"Signed vs unsigned on negative-capable differences\" for the principle. Below\nare the **attention-specific** fix sites in `cutlass_fmha\u002Fkernel_forward.h`. See §11 for what\nthe offset *means* (bottom-right alignment); this section is purely the signed-arithmetic\nhazard.\n\nAny FMHA offset computed as a difference of counts — canonically\n`causal_diagonal_offset = num_keys - num_queries` (`CausalFromBottomRight`) — is\n**negative** whenever `num_keys \u003C num_queries` (cross-attention \u002F KV-trimmed \u002F\n`nonpad_kv_seqlen[b] \u003C q_len`, onnx#8068 \u002F ORT #28904). It **must** be stored and\ncompared as `int32_t`; a `uint32_t` wraps the negative value to ~4.29e9 (`0xFFFFFFFE`),\nthe causal-mask guard `min(iter_key_start + kKeysPerBlock, num_keys) >= query_start + offset`\nbecomes permanently false, the per-element causal mask is **silently skipped**, and boundary\nquery rows over-attend one extra key.\n\n### Fix sites in `cutlass_fmha\u002Fkernel_forward.h` (symbols are stable; lines as of cc34d0b914)\n\n| Symbol \u002F guard | Line | What it must do |\n|---|---|---|\n| `int32_t causal_diagonal_offset` (field decl) | ~206 | Stay **`int32_t`** so the negative offset is preserved (rationale comment ~202-205). |\n| `causal_diagonal_offset = num_keys - num_queries;` | ~354 | Set point for `CausalFromBottomRight`; may be negative (comment ~353). |\n| `int32_t(query_start + causal_diagonal_offset + kQueriesPerBlock)` | ~366 | First (AttentionKernel) `num_keys` clamp. The inner sum **does** wrap to `0xFFFFFFFE`-style values in unsigned arithmetic when the offset is negative, but casting the **whole sum** to `int32_t` recovers the correct value by two's-complement modular arithmetic, and the result is consumed **arithmetically** (as a `fast_min` operand), so the wrap is harmless. Contrast the ~924 guard, where the value feeds a **relational** comparison — there the unsigned wrap flips the comparison result, so the operand `query_start` must be cast to `int32_t` **before** the compare. |\n| \"Mask out last if causal\" guard: `static_cast\u003Cint32_t>(query_start) + p.causal_diagonal_offset` | ~924-926 | `query_start` is `uint32_t` (~707) — cast it to `int32_t` so the comparison is signed (rationale ~919-923). |\n| Sliding-window guard (\"L957\"): `static_cast\u003Cint32_t>(query_start) + p.causal_diagonal_offset ...` | ~962-963 | Same cast hardening (rationale ~956-961). |\n\n### Rules when editing `kernel_forward.h` (or any FMHA kernel)\n\n- Keep `causal_diagonal_offset` **`int32_t`**.\n- `query_start` in the iteration kernels is **`uint32_t`** — `static_cast\u003Cint32_t>(query_start)`\n  before adding the offset in ANY relational guard.\n- The same hazard is **dormant but real** at the `window_size > 0` guard: harden it the\n  same way even though opset-24 Attention currently pins `window=-1` (a future\n  sliding-window \u002F KV-trim caller could combine `window_size>0` with a negative offset).\n- Tests that exercise this need a **negative** offset: `num_keys \u003C num_queries`. Force the\n  MEA path **portably** with `ORT_DISABLE_FLASH_ATTENTION=1` + a small `head_size` (e.g. 64)\n  — **not** `head_size=512`, whose MEA launch is arch-fragile on small-smem GPUs (#28388,\n  see §1). The regression tests live in `test\u002Fproviders\u002Fcpu\u002Fllm\u002Fattention_op_test.cc`\n  (`Attention_Causal_NonPadKVSeqLen_MEA_*`), guarded by `SKIP_IF_MEA_NOT_COMPILED`.\n",{"name":5,"description":7},"main","4edd78a847b9d7755f32d6c99aa60cab2addd39b",".github\u002Fskills\u002Fcuda-attention-kernel-patterns",4449,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fonnxruntime","https:\u002F\u002Fonnxruntime.ai","https:\u002F\u002Fgithub.com\u002Fmicrosoft","https:\u002F\u002Fopensource.microsoft.com","Open source projects and samples from Microsoft","2026-11-15 02:23:16",{"source":9,"skillName":5,"commands":68,"prompt":78,"zipAvailable":79},[69,72,75],{"tool":70,"command":71},"npx","npx skills add microsoft\u002Fonnxruntime --skill cuda-attention-kernel-patterns",{"tool":73,"command":74},"bunx","bunx skills add microsoft\u002Fonnxruntime --skill cuda-attention-kernel-patterns",{"tool":76,"command":77},"pnpm","pnpm dlx skills add microsoft\u002Fonnxruntime --skill cuda-attention-kernel-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fonnxruntime\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fcuda-attention-kernel-patterns\u002FSKILL.md",true,[],[82,116,150,182,209,228],{"skillNo":83,"name":84,"nameZh":85,"description":86,"descriptionZh":87,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":88,"categories":89,"keywords":96,"publishedAt":52},"01M69AJ65WPPT5DS4JA8YWN37B","workspace-estimation-shared-header","工作空间估计共享头文件","Use when editing a boundary-safe shared header meant to be included by both in-tree and shared-provider\u002Fplugin-bridge code (e.g. include\u002Fonnxruntime\u002Fcore\u002Fframework\u002Fworkspace_requirement.h, or any future header supporting OrtKernelWorkspaceEstimateFunc \u002F DeclareWorkspaceRequirements per issue #29775's Phase-A workspace-estimation roadmap), or when a workspace-estimation math helper needs to be callable from a future plugin EP DLL. Covers a Node forward-declaration ODR trap and the math-helper vs. graph-parsing-wrapper reuse boundary discovered while implementing PR #29811 (MatMulNBits pilot).","在编辑边界安全的共享头文件时使用，该头文件须同时被树内代码和共享提供者\u002F插件桥接代码包含（例如 include\u002Fonnxruntime\u002Fcore\u002Fframework\u002Fworkspace_requirement.h，或任何未来支持 OrtKernelWorkspaceEstimateFunc \u002F DeclareWorkspaceRequirements 的头文件，参见 issue #29775 的 Phase-A 工作空间估计路线图），或者当工作空间估计数学辅助函数需要从未来的插件 EP DLL 中调用时。涵盖 Node 前向声明的 ODR 陷阱，以及在实现 PR #29811（MatMulNBits 试点）时发现的数学辅助函数与图解析包装器之间的重用边界。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fonnxruntime\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fworkspace-estimation-shared-header\u002FSKILL.md",[90,93],{"categoryNo":91,"categoryName":92,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师",{"categoryNo":94,"categoryName":95,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BRSRXQPYT60FQ3976GDV4Q","C++ 开发",[97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,36],"workspace estimation shared header","workspace","estimation","shared","safe","pr","code","framework","graph","parsing","node","math","bridge","roadmap","Wrapper","issue","tree","implementing","phase",{"skillNo":117,"name":118,"nameZh":119,"description":120,"descriptionZh":121,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":122,"categories":123,"keywords":128,"publishedAt":52},"01M69AJ3F3NXDS7QP76KZ9EX5H","webgpu-local-testing","ONNX Runtime WebGPU 本地测试","Build and run ONNX Runtime WebGPU provider tests on Linux WITHOUT a real GPU, using a software Vulkan adapter (Mesa lavapipe). Use when you need to exercise WebGPU EP kernels off-Mac — the Linux webgpu CI leg is build-only, so software Vulkan is how you actually run WebGPU correctness tests locally. SCOPE - lavapipe only validates host-side enforce\u002Fshape bugs and MatMul-free kernels; any graph containing MatMul (including the expanded-Attention node tests) crashes lavapipe and runs ONLY on macOS-arm64 Metal, which is the source of truth for those. Covers install (dnf on Azure Linux), the --use_webgpu build flag, the onnxruntime_provider_test target, VK_ICD_FILENAMES, and the lavapipe MatMul crash gotcha.","在没有真实 GPU 的 Linux 上构建并运行 ONNX Runtime WebGPU 提供者测试，使用软件 Vulkan 适配器（Mesa lavapipe）。当需要在非 Mac 环境下运行 WebGPU EP 内核时使用——Linux 的 webgpu CI 环节仅做构建，因此软件 Vulkan 是本地实际运行 WebGPU 正确性测试的方式。范围——lavapipe 仅能验证主机侧的 enforce\u002Fshape 缺陷以及不含 MatMul 的内核；任何包含 MatMul 的图（包括扩展的 Attention 节点测试）都会使 lavapipe 崩溃，此类测试仅在 macOS-arm64 Metal 上运行，Metal 是这些测试的权威来源。涵盖安装（在 Azure Linux 上用 dnf）、--use_webgpu 构建标志、onnxruntime_provider_test 目标、VK_ICD_FILENAMES，以及 lavapipe 的 MatMul 崩溃陷阱。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fonnxruntime\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fwebgpu-local-testing\u002FSKILL.md",[124,125],{"categoryNo":91,"categoryName":92,"taxonomyType":28,"taxonomyTypeDesc":29},{"categoryNo":126,"categoryName":127,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BSTR9G4A4GZ0VB2DFN9490","开发环境与工具链管理",[129,130,131,132,133,134,135,136,137,51,50,138,139,140,141,107,142,143,144,145,146,147,148,149,36],"testing","webgpu","webgpu local testing","local testing","local","macos","metal","vulkan","linux","run","ci","exercise","how","install","only","free","host","scope","you","vk","which",{"skillNo":151,"name":152,"nameZh":153,"description":154,"descriptionZh":155,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":156,"categories":157,"keywords":164,"publishedAt":52},"01M69AJ1ASRSCJ90HDWN05TW82","python-kwargs-setattr-security","Python setattr 安全审查","When reviewing or fixing Python code that uses setattr() with user-controlled kwargs to configure C++ extension objects (SessionOptions, RunOptions, etc.) in ONNX Runtime. Use this to apply the allowlist pattern that prevents arbitrary file writes and other attacks via reflected property access.","在审查或修复 ONNX Runtime 中使用用户可控的 kwargs 通过 setattr() 配置 C++ 扩展对象（SessionOptions、RunOptions 等）的 Python 代码时使用。用于应用白名单模式，防止通过反射属性访问进行任意文件写入和其他攻击。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fonnxruntime\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fpython-kwargs-setattr-security\u002FSKILL.md",[158,161],{"categoryNo":159,"categoryName":160,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BR4MYFKGCC4WCWVJ50KJ2C","安全工程师",{"categoryNo":162,"categoryName":163,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BSJ8FPTACYEEYRWQRNFXKY","安全检测工程",[165,166,167,50,103,168,169,170,171,172,173,174,175,176,177,178,179,180,181,36],"python","security","python kwargs setattr security","file","access","configure","use","objects","pattern","c++","runtime","extension","via","with","attacks","python code","apply",{"skillNo":183,"name":184,"nameZh":185,"description":186,"descriptionZh":187,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":188,"categories":189,"keywords":196,"publishedAt":52},"01M69AHZ0M0Q90TP0KYMZ10HEP","ort-transformers-gpu-pytest","ONNX Runtime Transformers GPU 测试","Run the ONNX Runtime transformers Python tests (onnxruntime\u002Ftest\u002Fpython\u002Ftransformers) against a GPU wheel, and confirm real cuDNN\u002Fflash SDPA dispatch. Use when a transformers pytest fails with ModuleNotFoundError onnxruntime.capi, when torch's bundled CUDA\u002FcuDNN libs shadow the ORT-built ones (wrong-version dispatch or load errors), or when you must PROVE a test exercised the cuDNN SDPA decode tier instead of silently skipping\u002Ffalling back to MATH.","针对 GPU wheel 运行 ONNX Runtime transformers Python 测试（onnxruntime\u002Ftest\u002Fpython\u002Ftransformers），并确认真实的 cuDNN\u002Fflash SDPA 调度。当 transformers pytest 因 ModuleNotFoundError onnxruntime.capi 失败、torch 自带的 CUDA\u002FcuDNN 库覆盖了 ORT 构建的库（导致错误版本调度或加载错误），或必须证明测试确实执行了 cuDNN SDPA 解码层而非静默跳过或回退到 MATH 时使用。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fonnxruntime\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fort-transformers-gpu-pytest\u002FSKILL.md",[190,193],{"categoryNo":191,"categoryName":192,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQGD5WG86P4AQ5GPSSKBFR","测试工程师",{"categoryNo":194,"categoryName":195,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQJH394GT47X57A9Q8G7HX","测试与质量保障",[197,198,199,200,165,51,50,138,201,108,171,202,175,203,204,147,205,206,207,208,36],"ort transformers gpu pytest","gpu","Transformers","pytest","flash","back","tests","SDPA","errors","load","prove","decode",{"skillNo":210,"name":211,"nameZh":212,"description":213,"descriptionZh":214,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":215,"categories":216,"keywords":219,"publishedAt":52},"01M69AHW3EFVHBHB2S7103YA21","ort-test","ONNX Runtime 测试执行与调试","Run ONNX Runtime tests. Use this skill when asked to run tests, debug test failures, or find and execute specific test cases in ONNX Runtime.","运行 ONNX Runtime 测试。当被要求运行测试、调试测试失败，或在 ONNX Runtime 中查找并执行特定测试用例时使用此技能。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fonnxruntime\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fort-test\u002FSKILL.md",[217,218],{"categoryNo":191,"categoryName":192,"taxonomyType":28,"taxonomyTypeDesc":29},{"categoryNo":194,"categoryName":195,"taxonomyType":23,"taxonomyTypeDesc":24},[51,220,221,222,223,50,224,138,225,226,171,175,203,227,36],"ort test","run tests","debug","debug test","debug test failures","find","execute","test cases",{"skillNo":229,"name":230,"nameZh":231,"description":232,"descriptionZh":233,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":234,"categories":235,"keywords":242,"publishedAt":52},"01M69AHSKXBSERP5NGAJB5E6XD","ort-release-notes","ONNX Runtime 发布说明撰写","Draft ONNX Runtime release notes using preset configurations for full ORT or scoped component releases. Use when generating highlights with PR links, compiling human contributor acknowledgments from compile_contributors.py output, and applying preset path filtering.","使用预设配置为完整 ORT 或限定范围的组件发布起草 ONNX Runtime 发布说明。适用于生成带 PR 链接的亮点摘要、根据 compile_contributors.py 的输出整理人工贡献者致谢名单，以及应用预设的路径过滤。","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fonnxruntime\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fort-release-notes\u002FSKILL.md",[236,239],{"categoryNo":237,"categoryName":238,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQNXPY1AV6BSR5VKHDMWRH","部署与发布管理",{"categoryNo":240,"categoryName":241,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BVB0FJ0RR8KXYVFTKEA3XX","技术文档工程师",[243,244,245,246,247,248,50,102,249,250,251,252,253,254,175,255,256,40,257,258,36],"notes","ort release notes","release notes","release","component","preset","compile","compiling","contributors","releases","human","full","links","path","scoped","contributor"]