[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M799NHH6NP7Z1RK77KGXAN6S":3,"skill-same:01M799NHH6NP7Z1RK77KGXAN6S":50},{"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":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M799NHH6NP7Z1RK77KGXAN6S","passnet-pattern-fusion",null,"Author PassNet pass files: write patterns that actually MATCH the FX graph, pick fusion regions (which ops to absorb into one Triton kernel), and structure multi-pass submissions with the mandatory shared-dispatch architecture. Use when creating or fixing pattern()\u002Freplacement_args()\u002Freplacement_func() files, when a pass \"failed to match\", or when deciding how to fuse multiple kernels\u002Fops.","VectorSpaceLab\u002FAREX-Skill","VectorSpaceLab","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F180637102?v=4","01M7538C5WPSJGWF7KHR4EFZ9F","01M7538C6R2GFP53NPXTCZNBRT",351,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FVectorSpaceLab\u002FAREX-Skill\u002Fblob\u002Fmain\u002Fskills\u002Ftask-oriented\u002FPassNet\u002Fskills\u002Fpassnet-pattern-fusion\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: passnet-pattern-fusion\ndescription: >\n  Author PassNet pass files: write patterns that actually MATCH the FX graph, pick fusion\n  regions (which ops to absorb into one Triton kernel), and structure multi-pass\n  submissions with the mandatory shared-dispatch architecture. Use when creating or fixing\n  pattern()\u002Freplacement_args()\u002Freplacement_func() files, when a pass \"failed to match\",\n  or when deciding how to fuse multiple kernels\u002Fops.\n---\n\nA pass file teaches the compiler: \"this subgraph → my Triton kernel\". Getting the PATTERN\nright is binary (match or 0.1); getting the FUSION REGION right decides the speedup.\nKernel implementation details live in `references\u002Fkernel-templates.md`; numeric-fidelity\nrecipes in passnet-triton-opt.\n\n## 1. Pass file contract\n\n```python\nimport torch                      # 'import triton' etc. as needed\ndef pattern(a, b, ...):           # subgraph to match — torch IR, mirrors model.py\n    ...\n    return out                    # EXACTLY ONE returned value (tuple-of-1 ok)\ndef replacement_args(a, b, ...):  # pure arg shuffle, FX-traced — no math\u002F.shape here!\n    return (a, b, \"route_name\")   # constants (route strings\u002Fscalars) may be appended\ndef replacement_func():           # returns the SAME module-level function every call\n    return dispatch_wrapper\n```\nPlus `pass_dir\u002Fsorted_output_pass_rule_names.json`: `[\"PassA\", \"PassB\"]` — file stems,\npriority order, every pass you want loaded MUST be listed.\n\n## 2. The 10 hard rules (violating any ⇒ no match \u002F crash \u002F dropped pass)\n\n1. **ONE output.** A pattern returning ≥2 values crashes the variant (harness asserts).\n   If two intermediates are observable outside the region, write two passes that each end\n   at one of them — never one pattern returning both.\n2. **Mirror `model.py`'s exact call forms.** The target graph keeps the source form; your\n   pattern is traced with normalization (see matchability table below). Same op spelled\n   differently = no match (`torch.relu` ≠ `torch.nn.functional.relu`; `x.transpose(...)`\n   (method) ≠ `torch.transpose(x, ...)`).\n3. **Literals must be exactly equal**: eps `1e-05` ≠ `1e-04`, dims, shape lists, scale\n   constants, `device(type='cuda')` objects in factory calls. Shape literals differing\n   across variants ⇒ that node can't be in a shared pattern (write per-shape passes or\n   exclude the node).\n4. **Containment**: every node inside the pattern except the returned one must be consumed\n   ONLY inside the pattern. If a producer feeds both your target consumer and any outside\n   or returned value, do not hide that producer inside a larger pattern. End the region at\n   the consumer\u002Ftail output or write separate one-output passes. If `model.py` returns an\n   intermediate or feeds it to a node outside your region, end the region there (it becomes\n   the pattern's single output) or exclude it. When an external producer has multiple\n   observable consumers, prefer a one-output consumer-side floor pass or split regions\n   over pulling that producer into a fused region.\n   This is the single-output contract in practice: a producer whose value is externally\n   visible or shared across a fanout cannot disappear inside your pass unless the one value\n   returned by the pattern preserves every outside observation. Do not \"simplify\" by\n   recomputing only the consumer you care about while hiding the shared producer; that makes\n   the graph semantically incomplete or non-containment-safe.\n5. **No `tmp = None`** statements, no prints, no asserts inside `pattern`. Pure alias\n   lines in model.py (`tmp_0 = in_0`) create NO graph node either — skip them and use the\n   original name's value flow.\n6. **`replacement_args` is FX-traced**: only reorder\u002Fdrop arguments and append literal\n   constants. No arithmetic, no `.shape`, no conditionals on tensors.\n7. **`replacement_func()` must be stable** (module-level function, `f() is f()`), and with\n   2+ pass files ALL must return the SAME object via the shared-dispatch module (§4).\n8. **No RNG ops** (`torch.rand*`, dropout `training=True`) inside patterns; eval-mode\n   dropout (`training=False`) is identity and safe to absorb.\n9. **AST restrictions** (file-wide): never import `torch.nn(\u002Ffunctional)`, `torch.ops`,\n   `torch.autograd`, never alias them; in pattern bodies use full dotted\n   `torch.nn.functional.xxx(...)`. Outside `pattern`\u002F`replacement_args`, only the\n   whitelisted `torch.empty\u002Fzeros\u002Fones\u002Ffull[_like]\u002Fas_tensor` calls.\n10. **Wrapper-runtime restrictions** (poison dispatch during warmup): inside the kernel\n    wrapper, only allocator ops + metadata (`.shape\u002F.stride()\u002F.numel()\u002F.dim()\u002F.device\u002F\n    .dtype\u002F.data_ptr()`) + `.to()` + Triton launches. NO `.contiguous()`, no tensor math.\n\n## 3. Matchability — what a pattern node can bind to\n\nFor a normal callable `def pattern(...)`, the pattern is traced with `ForceArgsTracer`; the\ntarget (dynamo) graph is not. Per node:\n\n| node kind in model.py | pattern is normalized? | matchable when... | pattern should write... |\n|---|---|---|---|\n| method call `x.view(...)`, `x.mean(dim=-2, keepdim=True)`, `x.to(dtype=...)`, `x.softmax(dim=-1)` | NO | always | mirror EXACTLY (incl. kwargs spelling) |\n| C-bound function: `torch.conv2d`, `torch.matmul`, `torch.cat`, `torch.sigmoid`, `torch.arange`, `torch.sum`, `F.linear`, `F.gelu`, `operator.+ - * \u002F` | NO (no inspect signature) | always | mirror EXACTLY (incl. kwargs spelling) |\n| Python-def `F.*`: `relu`, `silu`, `softmax`, `dropout`, `layer_norm`, `batch_norm`, `embedding`, `interpolate`, `adaptive_avg_pool2d`, `pad`, `normalize`, `max_pool2d`... | YES → full positional, defaults filled | ONLY if model.py call is full-positional with ALL params spelled out | the same call (any style — it normalizes) |\n\nExamples from real graphs:\n- `torch.nn.functional.batch_norm(x, m, v, w, b, False, 0.1, 1e-05)` → matchable ✓\n- `torch.nn.functional.dropout(x, 0.1, False, False)` → matchable ✓ (and it's identity!)\n- `torch.nn.functional.relu(x, inplace = False)` → **kwargs on a Python-def op: NOT matchable** ✗\n- `torch.nn.functional.softmax(x, 2, _stacklevel = 5)` → ✗ (and `_stacklevel` precedes\n  `dtype` in the signature — normalization can't reproduce it)\n- `x.softmax(dim=-1)`, `x.mean(dim = -2, keepdim = True)` → method form: matchable ✓\n- `torch.cat([a, b], dim = 2)` → C-bound with kwargs: matchable (mirror the kwargs) ✓\n- `torch.nn.functional.gelu(x)` \u002F `F.gelu(x, approximate='none')` → C-bound: matchable ✓\n\nTreat kwargs-form Python-level activations and functional calls as suspect boundaries\nuntil `check_pattern.py` proves they match. For small or low-value regions, if they block\nmatching, start the region after that node or end just before it instead of spending\nevaluations on near-miss patterns.\n\n**Manual FX escape hatch for valuable kwargs regions.** The harness accepts `pattern` as a\n`torch.fx.GraphModule`. In that case `_replace_pattern` uses `pattern.graph` directly and\ndoes NOT run `ForceArgsTracer`, so exact kwargs-form Python functional nodes can match.\nUse this only when a high-value single-output region is blocked by callable-pattern\nnormalization and a real pre-flight matcher confirms the manual graph matches.\n\nBuild the graph inside a function literally named `pattern` (that function body is\nAST-exempt), then replace `pattern` with the returned `GraphModule` and set\n`__signature__` to the placeholders in order:\n\n```python\nimport inspect\nimport operator\nimport torch\n\ndef pattern():\n    graph = torch.fx.Graph()\n    x = graph.placeholder(\"x\")\n    y = graph.placeholder(\"y\")\n    act = graph.call_function(\n        torch.nn.functional.relu, args=(x,), kwargs={\"inplace\": True}\n    )\n    out = graph.call_function(operator.add, args=(act, y), kwargs={})\n    graph.output(out)\n    gm = torch.fx.GraphModule({}, graph, \"ExactKwargPattern\")\n    gm.__signature__ = inspect.Signature([\n        inspect.Parameter(\"x\", inspect.Parameter.POSITIONAL_OR_KEYWORD),\n        inspect.Parameter(\"y\", inspect.Parameter.POSITIONAL_OR_KEYWORD),\n    ])\n    return gm\n\npattern = pattern()\n```\n\nThe manual graph must still obey every other rule: one output, containment, exact targets\nand literals, matching `replacement_args` parameters, and Triton-only runtime computation.\nDo not use it as a speculative default; it is a repair for proven callable-pattern\nnormalization misses.\n\nManual FX does not make side effects free. Treat `inplace=True` functional calls as\nside-effectful even when the graph matches: only absorb them if the replacement mutates the\ninput exactly as eager would under repeated benchmark calls. If that is awkward or uncertain,\nleave the in-place node in eager and fuse the downstream side-effect-free region.\n\nDo NOT trust memory on which ops are C-bound — VERIFY with the pre-flight checker\n(`passnet-feedback\u002Fscripts\u002Fcheck_pattern.py`) before every GPU eval; it traces your\npattern, runs the real `SubgraphMatcher` against the real dynamo graph of every variant,\nand prints near-miss diffs when a pattern doesn't match.\n\n## 4. Multi-pass architecture (mandatory for ≥2 pass files)\n\n`output_pass_replacement_func_limit: 1` keeps only ONE distinct replacement function —\npasses returning a different object are SILENTLY dropped (watch `Loaded N passes` in the\nlog). Structure:\n\n`pass_dir\u002F_shared_kernels.py` (helper module, NOT listed in the json):\n```python\nimport torch\nimport triton\nimport triton.language as tl\n\n@triton.jit\ndef _fused_a_kernel(...): ...\n@triton.jit\ndef _fused_b_kernel(...): ...\n\ndef _run_a(x, w):\n    out = torch.empty_like(x)\n    ...launch _fused_a_kernel...\n    return out\n\ndef _run_b(x):\n    ...\n    return out\n\n@torch.fx.wrap\ndef dispatch_wrapper(*args):\n    route = args[-1]\n    if route == \"fuse_a\":\n        return _run_a(args[0], args[1])\n    if route == \"fuse_b\":\n        return _run_b(args[0])\n    raise ValueError(f\"unknown route {route}\")\n```\n\neach `pass_dir\u002FFuseA.py`:\n```python\nimport torch\nfrom pass_dir._shared_kernels import dispatch_wrapper\n\ndef pattern(x, w):\n    ...\n    return out\n\ndef replacement_args(x, w):\n    return (x, w, \"fuse_a\")\n\ndef replacement_func():\n    return dispatch_wrapper\n```\n\n- Works because the sample root is on `sys.path` while passes load; the shared module is\n  imported once → one function object → nothing is dropped.\n- Keep `_shared_kernels.py` AST-clean too (Triton + whitelisted allocators only).\n- A single-pass submission may simply define its wrapper in the pass file — but starting\n  with the shared layout costs nothing and survives growth.\n- Order in the json = application order. Earlier passes consume nodes; a later pattern\n  overlapping an earlier match will no longer find its nodes. Order independent patterns\n  freely; order overlapping ones from largest to smallest region.\n\n## 5. Choosing fusion regions\n\n1. From the analyzer output, mark every node matchable\u002Funmatchable for a normal callable\n   pattern, and separately mark high-value kwargs-form Python functional nodes that may be\n   recoverable with a manual FX `GraphModule` pattern.\n2. Greedily grow regions over callable-matchable nodes along dataflow; STOP at: an\n   unrecovered unmatchable node, RNG, a node whose output is consumed outside the region\n   (unless you end the region exactly there), a conv\u002Fbig-matmul you've decided to keep in aten.\n   **Keeping a heavy conv\u002Fmatmul in aten and fusing its tail is the DEFAULT and usually right.**\n   The clearest case where the conv itself becomes the region ANCHOR instead of a wall: a\n   **non-overlapping conv** — `stride == kernel_size`, `kernel_size > 1`, `padding == 0` — which\n   is exactly a dense patch matmul (§ kernel-templates §13). Anchoring on a 1×1 conv (already a\n   cuBLAS-optimal pointwise GEMM), a depthwise\u002Fgrouped conv, or a general matmul usually loses —\n   default to fusing their tails and leaving the op in aten (let a completed eval overrule this\n   if parameters look off-regime). Either way the op is C-bound and matches when you mirror its\n   exact positional call form; never treat \"it's a big cuDNN op\" as \"unmatchable.\"\n   If the only blocker is callable-pattern normalization of kwargs-form Python functional\n   calls and the wider region has real upside, try a manual FX pattern and require\n   `check_pattern.py` proof before evaluation.\n   For fanout, draw the boundary at the first value that has multiple external consumers.\n   If each consumer is independently valuable, write separate one-output passes using the\n   shared-dispatch architecture; if the consumers are only cheap layout\u002Fview work, treat\n   them as floor\u002Fdownside-cap candidates rather than performance targets.\n   When a shared or returned producer feeds a substantial downstream consumer, consider a\n   consumer-side region that leaves that producer outside the pattern and treats it as an\n   input. Do not reject the whole sample for global fanout if a local backward slice from the\n   chosen output still has exactly one output and absorbs enough compute to amortize a\n   launch.\n   Prefer a single-output region that absorbs several elementwise, affine, activation,\n   residual, or normalization consumers fed by the same broadcast\u002Flayout producer when\n   containment is legal. Repeated round evidence shows this family is more likely to pay the\n   fixed launch\u002Fwrapper cost than isolated reductions or tiny tails.\n   For concat-to-normalization-affine prefixes, containment can still be legal even when a\n   downstream activation is unmatchable or in-place: return the normalized or affine prefix\n   tensor as the one crossing value and leave the boundary consumer in eager. Do not pull an\n   in-place activation into the pattern just to make the region look complete.\n   When repeated duplicate compute exists, anchor the replacement on values with real users.\n   Userless\u002Fdead duplicate nodes can structurally match but fail replacement because the\n   matched return has no observable consumer. If the profitable opportunity is dead-work\n   elimination, treat it as a graph-rewrite edge case and prove it with the real matcher and\n   smoke test before spending an evaluation.\n3. Each region ⇒ one pass ⇒ ideally ONE Triton kernel launch. Two kernels for one region\n   only when a reduction's result feeds elementwise work over a DIFFERENT axis size\n   (e.g. softmax over rows then matmul) — usually better: split into two passes.\n4. Region inputs = tensors crossing into it (pattern parameters); region output = the one\n   tensor crossing out.\n5. Sanity: replacing N aten ops saves roughly Σ(their eager µs); your kernel costs\n   ~19 µs launch + memory traffic. If the sum is \u003C ~50 µs the region only makes sense as\n   the floor pass \u002F part of something bigger.\n6. Layout ops at region EDGES are usually better left outside (they're ~free in eager).\n   Layout ops INSIDE a region (between two compute ops) are absorbed for free via index\n   arithmetic. Special case worth taking even \"alone\": `view\u002Funsqueeze\u002Fexpand → binary op`\n   chains that WRITE a large output — aten's broadcast-elementwise kernels are often\n   1.5–2.5× off the bandwidth roofline, so a shape-specialized Triton kernel wins well\n   beyond the erased python overhead (measured 2.3× on a 67M-element broadcast-sub).\n   Don't guess: `analyze_graph.py --bench` gives each node's real eager µs; estimate your\n   kernel as `bytes_moved \u002F 1.4 TB\u002Fs` and compare.\n   Do not force eager metadata-only layout\u002Fview\u002Freshape work to materialize just to make a\n   larger pattern. If the pattern output is a returned or externally observed view that eager\n   can keep cheap, materializing it in a wrapper may erase the benefit of absorbing nearby\n   elementwise work; treat that as a downside cap unless a completed eval proves otherwise.\n\n## 6. Kernel wrapper conventions (poison-proof)\n\n```python\ndef _run_fused(x, w, b):\n    B, N = x.shape                       # metadata: allowed\n    out = torch.empty((B, N), dtype=x.dtype, device=x.device)\n    grid = (triton.cdiv(B * N, 1024),)\n    _kernel[grid](x, w, b, out, B * N, N,\n                  x.stride(0), x.stride(1),   # pass strides — NEVER .contiguous()\n                  BLOCK=1024)\n    return out\n```\n- Output dtype MUST equal what eager produces (usually the input dtype; watch explicit\n  `.to(torch.float32)` nodes in the region).\n- If the pattern output is consumed by `.view(...)` outside the region, your output's\n  contiguity must allow that view — return a fresh contiguous tensor of the eager\n  output's shape (the normal case).\n- Handle every variant's shapes\u002Fdtypes with ONE wrapper: derive sizes from `.shape`,\n  never hardcode, unless the pattern itself is shape-literal-specific.\n- Scalars you need (eps, slopes, dims) that appear as pattern literals: hardcode them in\n  the kernel for that pass (they're fixed by the match) or pass via `replacement_args`\n  constants.\n\nSee `references\u002Fkernel-templates.md` for ready-to-adapt Triton templates: elementwise\nchain (stride-aware), row reduction (softmax\u002Flayer_norm\u002Fmean\u002FL2-norm), BN-inference\naffine, bias+activation epilogue, cat+elementwise, embedding gather, matmul+epilogue\n(`tl.dot`), 2-pass split reductions.\n\n## 7. Debug: \"Pass X failed to match\"\n\n1. Run `check_pattern.py` — it prints the dynamo node list vs your traced pattern nodes.\n2. Compare node-by-node: op kind (`call_function` vs `call_method`), target identity,\n   arg\u002Fkwarg shapes of the WRITTEN forms, literals.\n3. Most frequent causes, in order: kwargs-form Python-def F.* op included in a normal\n   callable pattern (drop the node for a cheap region, or switch to an exact manual FX\n   pattern for a valuable one); literal mismatch across variants; intermediate consumed\n   outside (containment); userless\u002Fdead nodes selected as the match output; wrong\n   method-vs-function form; `_stacklevel`-style hidden kwargs; pattern includes a\n   `tmp = None`-induced phantom; two returned values. If a producer has outside consumers,\n   exclude that producer or split at the consumer output before retrying.\n4. `[PassMgrBackend] Diagnostic ... best-attempt` lines in eval logs name the first\n   mismatching node pair — read them.\n\n## 8. Round-planning containment checklist\n\nBefore handing a region to kernel tuning, answer these with the real graph in mind:\n\n- Does the proposed pattern return exactly one value?\n- Are all nodes hidden inside the pattern consumed only inside the pattern, except that\n  single returned value?\n- Does any producer inside the region feed another returned value, an outside consumer, or\n  a later observable fanout branch? If yes, exclude it or split into one-output passes.\n- Is the region mainly layout\u002Fview\u002Freshape\u002Fsplit fanout work? If yes, mark it as a\n  downside-cap\u002Ffloor candidate unless it bridges compute or avoids a real materialization.\n- Does the proposed region force a returned view or metadata-only layout value to become an\n  allocated output? If yes, prefer a consumer-side elementwise\u002Faffine region or a narrow\n  floor, and require completed-evaluation proof before keeping the wider materializing pass.\n- If multiple passes are needed, do they all return the same shared dispatch wrapper?\n\nTentative guidance from repeated round behavior: when a larger-looking region is blocked\nonly by the single-output\u002Fexternal-fanout contract, it is usually better to stop with the\nbest correct floor than to add tiny independent kernels that increase launch overhead.\n","A pass file teaches the compiler: \"this subgraph → my Triton kernel\". Getting the PATTERN\nright is binary (match or 0.1); getting the FUSION REGION right decides the speedup.\nKernel implementation details live in `references\u002Fkernel-templates.md`; numeric-fidelity\nrecipes in passnet-triton-opt.\n\n## 1. Pass file contract\n\n```python\nimport torch                      # 'import triton' etc. as needed\ndef pattern(a, b, ...):           # subgraph to match — torch IR, mirrors model.py\n    ...\n    return out                    # EXACTLY ONE returned value (tuple-of-1 ok)\ndef replacement_args(a, b, ...):  # pure arg shuffle, FX-traced — no math\u002F.shape here!\n    return (a, b, \"route_name\")   # constants (route strings\u002Fscalars) may be appended\ndef replacement_func():           # returns the SAME module-level function every call\n    return dispatch_wrapper\n```\nPlus `pass_dir\u002Fsorted_output_pass_rule_names.json`: `[\"PassA\", \"PassB\"]` — file stems,\npriority order, every pass you want loaded MUST be listed.\n\n## 2. The 10 hard rules (violating any ⇒ no match \u002F crash \u002F dropped pass)\n\n1. **ONE output.** A pattern returning ≥2 values crashes the variant (harness asserts).\n   If two intermediates are observable outside the region, write two passes that each end\n   at one of them — never one pattern returning both.\n2. **Mirror `model.py`'s exact call forms.** The target graph keeps the source form; your\n   pattern is traced with normalization (see matchability table below). Same op spelled\n   differently = no match (`torch.relu` ≠ `torch.nn.functional.relu`; `x.transpose(...)`\n   (method) ≠ `torch.transpose(x, ...)`).\n3. **Literals must be exactly equal**: eps `1e-05` ≠ `1e-04`, dims, shape lists, scale\n   constants, `device(type='cuda')` objects in factory calls. Shape literals differing\n   across variants ⇒ that node can't be in a shared pattern (write per-shape passes or\n   exclude the node).\n4. **Containment**: every node inside the pattern except the returned one must be consumed\n   ONLY inside the pattern. If a producer feeds both your target consumer and any outside\n   or returned value, do not hide that producer inside a larger pattern. End the region at\n   the consumer\u002Ftail output or write separate one-output passes. If `model.py` returns an\n   intermediate or feeds it to a node outside your region, end the region there (it becomes\n   the pattern's single output) or exclude it. When an external producer has multiple\n   observable consumers, prefer a one-output consumer-side floor pass or split regions\n   over pulling that producer into a fused region.\n   This is the single-output contract in practice: a producer whose value is externally\n   visible or shared across a fanout cannot disappear inside your pass unless the one value\n   returned by the pattern preserves every outside observation. Do not \"simplify\" by\n   recomputing only the consumer you care about while hiding the shared producer; that makes\n   the graph semantically incomplete or non-containment-safe.\n5. **No `tmp = None`** statements, no prints, no asserts inside `pattern`. Pure alias\n   lines in model.py (`tmp_0 = in_0`) create NO graph node either — skip them and use the\n   original name's value flow.\n6. **`replacement_args` is FX-traced**: only reorder\u002Fdrop arguments and append literal\n   constants. No arithmetic, no `.shape`, no conditionals on tensors.\n7. **`replacement_func()` must be stable** (module-level function, `f() is f()`), and with\n   2+ pass files ALL must return the SAME object via the shared-dispatch module (§4).\n8. **No RNG ops** (`torch.rand*`, dropout `training=True`) inside patterns; eval-mode\n   dropout (`training=False`) is identity and safe to absorb.\n9. **AST restrictions** (file-wide): never import `torch.nn(\u002Ffunctional)`, `torch.ops`,\n   `torch.autograd`, never alias them; in pattern bodies use full dotted\n   `torch.nn.functional.xxx(...)`. Outside `pattern`\u002F`replacement_args`, only the\n   whitelisted `torch.empty\u002Fzeros\u002Fones\u002Ffull[_like]\u002Fas_tensor` calls.\n10. **Wrapper-runtime restrictions** (poison dispatch during warmup): inside the kernel\n    wrapper, only allocator ops + metadata (`.shape\u002F.stride()\u002F.numel()\u002F.dim()\u002F.device\u002F\n    .dtype\u002F.data_ptr()`) + `.to()` + Triton launches. NO `.contiguous()`, no tensor math.\n\n## 3. Matchability — what a pattern node can bind to\n\nFor a normal callable `def pattern(...)`, the pattern is traced with `ForceArgsTracer`; the\ntarget (dynamo) graph is not. Per node:\n\n| node kind in model.py | pattern is normalized? | matchable when... | pattern should write... |\n|---|---|---|---|\n| method call `x.view(...)`, `x.mean(dim=-2, keepdim=True)`, `x.to(dtype=...)`, `x.softmax(dim=-1)` | NO | always | mirror EXACTLY (incl. kwargs spelling) |\n| C-bound function: `torch.conv2d`, `torch.matmul`, `torch.cat`, `torch.sigmoid`, `torch.arange`, `torch.sum`, `F.linear`, `F.gelu`, `operator.+ - * \u002F` | NO (no inspect signature) | always | mirror EXACTLY (incl. kwargs spelling) |\n| Python-def `F.*`: `relu`, `silu`, `softmax`, `dropout`, `layer_norm`, `batch_norm`, `embedding`, `interpolate`, `adaptive_avg_pool2d`, `pad`, `normalize`, `max_pool2d`... | YES → full positional, defaults filled | ONLY if model.py call is full-positional with ALL params spelled out | the same call (any style — it normalizes) |\n\nExamples from real graphs:\n- `torch.nn.functional.batch_norm(x, m, v, w, b, False, 0.1, 1e-05)` → matchable ✓\n- `torch.nn.functional.dropout(x, 0.1, False, False)` → matchable ✓ (and it's identity!)\n- `torch.nn.functional.relu(x, inplace = False)` → **kwargs on a Python-def op: NOT matchable** ✗\n- `torch.nn.functional.softmax(x, 2, _stacklevel = 5)` → ✗ (and `_stacklevel` precedes\n  `dtype` in the signature — normalization can't reproduce it)\n- `x.softmax(dim=-1)`, `x.mean(dim = -2, keepdim = True)` → method form: matchable ✓\n- `torch.cat([a, b], dim = 2)` → C-bound with kwargs: matchable (mirror the kwargs) ✓\n- `torch.nn.functional.gelu(x)` \u002F `F.gelu(x, approximate='none')` → C-bound: matchable ✓\n\nTreat kwargs-form Python-level activations and functional calls as suspect boundaries\nuntil `check_pattern.py` proves they match. For small or low-value regions, if they block\nmatching, start the region after that node or end just before it instead of spending\nevaluations on near-miss patterns.\n\n**Manual FX escape hatch for valuable kwargs regions.** The harness accepts `pattern` as a\n`torch.fx.GraphModule`. In that case `_replace_pattern` uses `pattern.graph` directly and\ndoes NOT run `ForceArgsTracer`, so exact kwargs-form Python functional nodes can match.\nUse this only when a high-value single-output region is blocked by callable-pattern\nnormalization and a real pre-flight matcher confirms the manual graph matches.\n\nBuild the graph inside a function literally named `pattern` (that function body is\nAST-exempt), then replace `pattern` with the returned `GraphModule` and set\n`__signature__` to the placeholders in order:\n\n```python\nimport inspect\nimport operator\nimport torch\n\ndef pattern():\n    graph = torch.fx.Graph()\n    x = graph.placeholder(\"x\")\n    y = graph.placeholder(\"y\")\n    act = graph.call_function(\n        torch.nn.functional.relu, args=(x,), kwargs={\"inplace\": True}\n    )\n    out = graph.call_function(operator.add, args=(act, y), kwargs={})\n    graph.output(out)\n    gm = torch.fx.GraphModule({}, graph, \"ExactKwargPattern\")\n    gm.__signature__ = inspect.Signature([\n        inspect.Parameter(\"x\", inspect.Parameter.POSITIONAL_OR_KEYWORD),\n        inspect.Parameter(\"y\", inspect.Parameter.POSITIONAL_OR_KEYWORD),\n    ])\n    return gm\n\npattern = pattern()\n```\n\nThe manual graph must still obey every other rule: one output, containment, exact targets\nand literals, matching `replacement_args` parameters, and Triton-only runtime computation.\nDo not use it as a speculative default; it is a repair for proven callable-pattern\nnormalization misses.\n\nManual FX does not make side effects free. Treat `inplace=True` functional calls as\nside-effectful even when the graph matches: only absorb them if the replacement mutates the\ninput exactly as eager would under repeated benchmark calls. If that is awkward or uncertain,\nleave the in-place node in eager and fuse the downstream side-effect-free region.\n\nDo NOT trust memory on which ops are C-bound — VERIFY with the pre-flight checker\n(`passnet-feedback\u002Fscripts\u002Fcheck_pattern.py`) before every GPU eval; it traces your\npattern, runs the real `SubgraphMatcher` against the real dynamo graph of every variant,\nand prints near-miss diffs when a pattern doesn't match.\n\n## 4. Multi-pass architecture (mandatory for ≥2 pass files)\n\n`output_pass_replacement_func_limit: 1` keeps only ONE distinct replacement function —\npasses returning a different object are SILENTLY dropped (watch `Loaded N passes` in the\nlog). Structure:\n\n`pass_dir\u002F_shared_kernels.py` (helper module, NOT listed in the json):\n```python\nimport torch\nimport triton\nimport triton.language as tl\n\n@triton.jit\ndef _fused_a_kernel(...): ...\n@triton.jit\ndef _fused_b_kernel(...): ...\n\ndef _run_a(x, w):\n    out = torch.empty_like(x)\n    ...launch _fused_a_kernel...\n    return out\n\ndef _run_b(x):\n    ...\n    return out\n\n@torch.fx.wrap\ndef dispatch_wrapper(*args):\n    route = args[-1]\n    if route == \"fuse_a\":\n        return _run_a(args[0], args[1])\n    if route == \"fuse_b\":\n        return _run_b(args[0])\n    raise ValueError(f\"unknown route {route}\")\n```\n\neach `pass_dir\u002FFuseA.py`:\n```python\nimport torch\nfrom pass_dir._shared_kernels import dispatch_wrapper\n\ndef pattern(x, w):\n    ...\n    return out\n\ndef replacement_args(x, w):\n    return (x, w, \"fuse_a\")\n\ndef replacement_func():\n    return dispatch_wrapper\n```\n\n- Works because the sample root is on `sys.path` while passes load; the shared module is\n  imported once → one function object → nothing is dropped.\n- Keep `_shared_kernels.py` AST-clean too (Triton + whitelisted allocators only).\n- A single-pass submission may simply define its wrapper in the pass file — but starting\n  with the shared layout costs nothing and survives growth.\n- Order in the json = application order. Earlier passes consume nodes; a later pattern\n  overlapping an earlier match will no longer find its nodes. Order independent patterns\n  freely; order overlapping ones from largest to smallest region.\n\n## 5. Choosing fusion regions\n\n1. From the analyzer output, mark every node matchable\u002Funmatchable for a normal callable\n   pattern, and separately mark high-value kwargs-form Python functional nodes that may be\n   recoverable with a manual FX `GraphModule` pattern.\n2. Greedily grow regions over callable-matchable nodes along dataflow; STOP at: an\n   unrecovered unmatchable node, RNG, a node whose output is consumed outside the region\n   (unless you end the region exactly there), a conv\u002Fbig-matmul you've decided to keep in aten.\n   **Keeping a heavy conv\u002Fmatmul in aten and fusing its tail is the DEFAULT and usually right.**\n   The clearest case where the conv itself becomes the region ANCHOR instead of a wall: a\n   **non-overlapping conv** — `stride == kernel_size`, `kernel_size > 1`, `padding == 0` — which\n   is exactly a dense patch matmul (§ kernel-templates §13). Anchoring on a 1×1 conv (already a\n   cuBLAS-optimal pointwise GEMM), a depthwise\u002Fgrouped conv, or a general matmul usually loses —\n   default to fusing their tails and leaving the op in aten (let a completed eval overrule this\n   if parameters look off-regime). Either way the op is C-bound and matches when you mirror its\n   exact positional call form; never treat \"it's a big cuDNN op\" as \"unmatchable.\"\n   If the only blocker is callable-pattern normalization of kwargs-form Python functional\n   calls and the wider region has real upside, try a manual FX pattern and require\n   `check_pattern.py` proof before evaluation.\n   For fanout, draw the boundary at the first value that has multiple external consumers.\n   If each consumer is independently valuable, write separate one-output passes using the\n   shared-dispatch architecture; if the consumers are only cheap layout\u002Fview work, treat\n   them as floor\u002Fdownside-cap candidates rather than performance targets.\n   When a shared or returned producer feeds a substantial downstream consumer, consider a\n   consumer-side region that leaves that producer outside the pattern and treats it as an\n   input. Do not reject the whole sample for global fanout if a local backward slice from the\n   chosen output still has exactly one output and absorbs enough compute to amortize a\n   launch.\n   Prefer a single-output region that absorbs several elementwise, affine, activation,\n   residual, or normalization consumers fed by the same broadcast\u002Flayout producer when\n   containment is legal. Repeated round evidence shows this family is more likely to pay the\n   fixed launch\u002Fwrapper cost than isolated reductions or tiny tails.\n   For concat-to-normalization-affine prefixes, containment can still be legal even when a\n   downstream activation is unmatchable or in-place: return the normalized or affine prefix\n   tensor as the one crossing value and leave the boundary consumer in eager. Do not pull an\n   in-place activation into the pattern just to make the region look complete.\n   When repeated duplicate compute exists, anchor the replacement on values with real users.\n   Userless\u002Fdead duplicate nodes can structurally match but fail replacement because the\n   matched return has no observable consumer. If the profitable opportunity is dead-work\n   elimination, treat it as a graph-rewrite edge case and prove it with the real matcher and\n   smoke test before spending an evaluation.\n3. Each region ⇒ one pass ⇒ ideally ONE Triton kernel launch. Two kernels for one region\n   only when a reduction's result feeds elementwise work over a DIFFERENT axis size\n   (e.g. softmax over rows then matmul) — usually better: split into two passes.\n4. Region inputs = tensors crossing into it (pattern parameters); region output = the one\n   tensor crossing out.\n5. Sanity: replacing N aten ops saves roughly Σ(their eager µs); your kernel costs\n   ~19 µs launch + memory traffic. If the sum is \u003C ~50 µs the region only makes sense as\n   the floor pass \u002F part of something bigger.\n6. Layout ops at region EDGES are usually better left outside (they're ~free in eager).\n   Layout ops INSIDE a region (between two compute ops) are absorbed for free via index\n   arithmetic. Special case worth taking even \"alone\": `view\u002Funsqueeze\u002Fexpand → binary op`\n   chains that WRITE a large output — aten's broadcast-elementwise kernels are often\n   1.5–2.5× off the bandwidth roofline, so a shape-specialized Triton kernel wins well\n   beyond the erased python overhead (measured 2.3× on a 67M-element broadcast-sub).\n   Don't guess: `analyze_graph.py --bench` gives each node's real eager µs; estimate your\n   kernel as `bytes_moved \u002F 1.4 TB\u002Fs` and compare.\n   Do not force eager metadata-only layout\u002Fview\u002Freshape work to materialize just to make a\n   larger pattern. If the pattern output is a returned or externally observed view that eager\n   can keep cheap, materializing it in a wrapper may erase the benefit of absorbing nearby\n   elementwise work; treat that as a downside cap unless a completed eval proves otherwise.\n\n## 6. Kernel wrapper conventions (poison-proof)\n\n```python\ndef _run_fused(x, w, b):\n    B, N = x.shape                       # metadata: allowed\n    out = torch.empty((B, N), dtype=x.dtype, device=x.device)\n    grid = (triton.cdiv(B * N, 1024),)\n    _kernel[grid](x, w, b, out, B * N, N,\n                  x.stride(0), x.stride(1),   # pass strides — NEVER .contiguous()\n                  BLOCK=1024)\n    return out\n```\n- Output dtype MUST equal what eager produces (usually the input dtype; watch explicit\n  `.to(torch.float32)` nodes in the region).\n- If the pattern output is consumed by `.view(...)` outside the region, your output's\n  contiguity must allow that view — return a fresh contiguous tensor of the eager\n  output's shape (the normal case).\n- Handle every variant's shapes\u002Fdtypes with ONE wrapper: derive sizes from `.shape`,\n  never hardcode, unless the pattern itself is shape-literal-specific.\n- Scalars you need (eps, slopes, dims) that appear as pattern literals: hardcode them in\n  the kernel for that pass (they're fixed by the match) or pass via `replacement_args`\n  constants.\n\nSee `references\u002Fkernel-templates.md` for ready-to-adapt Triton templates: elementwise\nchain (stride-aware), row reduction (softmax\u002Flayer_norm\u002Fmean\u002FL2-norm), BN-inference\naffine, bias+activation epilogue, cat+elementwise, embedding gather, matmul+epilogue\n(`tl.dot`), 2-pass split reductions.\n\n## 7. Debug: \"Pass X failed to match\"\n\n1. Run `check_pattern.py` — it prints the dynamo node list vs your traced pattern nodes.\n2. Compare node-by-node: op kind (`call_function` vs `call_method`), target identity,\n   arg\u002Fkwarg shapes of the WRITTEN forms, literals.\n3. Most frequent causes, in order: kwargs-form Python-def F.* op included in a normal\n   callable pattern (drop the node for a cheap region, or switch to an exact manual FX\n   pattern for a valuable one); literal mismatch across variants; intermediate consumed\n   outside (containment); userless\u002Fdead nodes selected as the match output; wrong\n   method-vs-function form; `_stacklevel`-style hidden kwargs; pattern includes a\n   `tmp = None`-induced phantom; two returned values. If a producer has outside consumers,\n   exclude that producer or split at the consumer output before retrying.\n4. `[PassMgrBackend] Diagnostic ... best-attempt` lines in eval logs name the first\n   mismatching node pair — read them.\n\n## 8. Round-planning containment checklist\n\nBefore handing a region to kernel tuning, answer these with the real graph in mind:\n\n- Does the proposed pattern return exactly one value?\n- Are all nodes hidden inside the pattern consumed only inside the pattern, except that\n  single returned value?\n- Does any producer inside the region feed another returned value, an outside consumer, or\n  a later observable fanout branch? If yes, exclude it or split into one-output passes.\n- Is the region mainly layout\u002Fview\u002Freshape\u002Fsplit fanout work? If yes, mark it as a\n  downside-cap\u002Ffloor candidate unless it bridges compute or avoids a real materialization.\n- Does the proposed region force a returned view or metadata-only layout value to become an\n  allocated output? If yes, prefer a consumer-side elementwise\u002Faffine region or a narrow\n  floor, and require completed-evaluation proof before keeping the wider materializing pass.\n- If multiple passes are needed, do they all return the same shared dispatch wrapper?\n\nTentative guidance from repeated round behavior: when a larger-looking region is blocked\nonly by the single-output\u002Fexternal-fanout contract, it is usually better to stop with the\nbest correct floor than to add tiny independent kernels that increase launch overhead.\n",{"name":5,"description":7},"main","ac3fe1afa80fb9a09775ecfb2b6cc3ba850a2db6","skills\u002Ftask-oriented\u002FPassNet\u002Fskills\u002Fpassnet-pattern-fusion",27,"https:\u002F\u002Fgithub.com\u002FVectorSpaceLab\u002FAREX-Skill","https:\u002F\u002Fgithub.com\u002FVectorSpaceLab","2026-09-03 10:25:21",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add VectorSpaceLab\u002FAREX-Skill --skill passnet-pattern-fusion",{"tool":36,"command":37},"bunx","bunx skills add VectorSpaceLab\u002FAREX-Skill --skill passnet-pattern-fusion",{"tool":39,"command":40},"pnpm","pnpm dlx skills add VectorSpaceLab\u002FAREX-Skill --skill passnet-pattern-fusion","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FVectorSpaceLab\u002FAREX-Skill\u002Fblob\u002Fmain\u002Fskills\u002Ftask-oriented\u002FPassNet\u002Fskills\u002Fpassnet-pattern-fusion\u002FSKILL.md",true,[44],{"path":45,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":48,"sourceHtmlUrl":49},"references\u002Fkernel-templates.md","REFERENCE","参考文档",15767,"https:\u002F\u002Fgithub.com\u002FVectorSpaceLab\u002FAREX-Skill\u002Fblob\u002Fmain\u002Fskills\u002Ftask-oriented\u002FPassNet\u002Fskills\u002Fpassnet-pattern-fusion\u002Freferences\u002Fkernel-templates.md",[51,58,65,72,79,86],{"skillNo":52,"name":53,"nameZh":6,"description":54,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":18},"01M799NYSH1R3RVAHSM2D88Y84","passnet-triton-opt","Make a single PassNet Triton kernel fast AND numerically faithful: performance model (when a replacement can win at all), block\u002Fgrid\u002Fwarp tuning, autotune policy, launch overhead, and per-op numeric recipes to pass the dtype baseline tolerances. Use when a pass matches and is correct but speedup below expected, or when correctness fails by small numeric margins.","https:\u002F\u002Fgithub.com\u002FVectorSpaceLab\u002FAREX-Skill\u002Fblob\u002Fmain\u002Fskills\u002Ftask-oriented\u002FPassNet\u002Fskills\u002Fpassnet-triton-opt\u002FSKILL.md",[],[],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":18},"01M799NS5APEC0N1FZ7XZVW6BN","passnet-solve","END-TO-END playbook for solving one PassNet sample: analyze the computation graphs, decide the optimization strategy (what to fuse, what to replace, what to leave alone), drive the iteration loop, and maximize the sample score. This is the ENTRY skill — invoke it first for any PassNet optimization task; it tells you when to use passnet-pattern-fusion, passnet-triton-opt and passnet-feedback.","https:\u002F\u002Fgithub.com\u002FVectorSpaceLab\u002FAREX-Skill\u002Fblob\u002Fmain\u002Fskills\u002Ftask-oriented\u002FPassNet\u002Fskills\u002Fpassnet-solve\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":18},"01M799NNY9BKSM21V5R7QVTBJX","passnet-skill","PassNet GPU kernel optimization via compiler passes. Design and implement Triton-based optimization passes, create pass files under .\u002Fpass_dir\u002F, self-evaluate with pass_evaluator, and iterate to maximize GPU speedup.","https:\u002F\u002Fgithub.com\u002FVectorSpaceLab\u002FAREX-Skill\u002Fblob\u002Fmain\u002Fskills\u002Ftask-oriented\u002FPassNet\u002Fskills\u002Fpassnet-skill\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":18},"01M799ND2J4WNC2PGAZ0A06NDF","passnet-orchestrate","Round\u002Fbatch planning and decision support for PassNet graph optimization. Use for multi-sample triage, worker allocation, eval-budget policy, and post-eval keep\u002Frevert decisions. For solving one concrete sample end to end, use passnet-solve as the entry skill; consult this skill only when you need broader planning or a specific decision gate.","https:\u002F\u002Fgithub.com\u002FVectorSpaceLab\u002FAREX-Skill\u002Fblob\u002Fmain\u002Fskills\u002Ftask-oriented\u002FPassNet\u002Fskills\u002Fpassnet-orchestrate\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M799N8SBTMY02ZDG2AZF5ZWE","passnet-feedback","Fast, deterministic feedback for PassNet work: pre-flight pattern\u002Fmatch verification WITHOUT burning a GPU evaluation, per-node bottleneck analysis of a sample's graphs, and eval-log parsing into per-variant status + estimated score + failure classification. Use BEFORE every GPU evaluation (check_pattern), at the START of a sample (analyze_graph), and AFTER every evaluation (parse_eval_log).","https:\u002F\u002Fgithub.com\u002FVectorSpaceLab\u002FAREX-Skill\u002Fblob\u002Fmain\u002Fskills\u002Ftask-oriented\u002FPassNet\u002Fskills\u002Fpassnet-feedback\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":18},"01M799N5J50300PMTGY5HVJN9R","prompt_template_rendering","Render PromptSource-style Jinja prompt templates into natural-language input\u002Ftarget pairs with answer choices, deterministic choices, skip handling, and structured diagnostics.","https:\u002F\u002Fgithub.com\u002FVectorSpaceLab\u002FAREX-Skill\u002Fblob\u002Fmain\u002Fskills\u002Ftask-oriented\u002FPaperBench\u002Fskills\u002Fwhat-will-my-model-forget\u002Fskill\u002Fp3_promptsource\u002Fprompt_template_rendering\u002FSKILL.md",[],[]]