[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M787ZFCPHAMFDS7TA87WRRQ4":3,"skill-same:01M787ZFCPHAMFDS7TA87WRRQ4":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":14,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M787ZFCPHAMFDS7TA87WRRQ4","nemo-mbridge-perf-cuda-graphs",null,"Validate and use CUDA graph capture in Megatron Bridge, including local full-iteration graphs and Transformer Engine scoped graphs for attention, MLP, and MoE modules.","Solizardking\u002Ftrain2earn","Solizardking","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F108096810?v=4","01M786KDB10AYV042N0F9BD5B5","Clawd","01M786KDC5C3NPE4W44C5641EZ",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fpublic\u002Fapi\u002Fskills\u002Fnvidia\u002Fnemo-mbridge-perf-cuda-graphs\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: nemo-mbridge-perf-cuda-graphs\ndescription: Validate and use CUDA graph capture in Megatron Bridge, including local full-iteration graphs and Transformer Engine scoped graphs for attention, MLP, and MoE modules.\nlicense: Apache-2.0\nwhen_to_use: Reducing host-driver overhead via CUDA graphs, or tracing a crash or regression to a CUDA graph config change; 'cuda_graph_impl', 'full iteration graph', 'TE scoped graph', 'graphed callables', 'CUDA graph capture'.\n---\n\n# CUDA Graphs\n\nStable documentation: @docs\u002Ftraining\u002Fcuda-graphs.md\nCard: @skills\u002Fnemo-mbridge-perf-cuda-graphs\u002Fcard.yaml\n\n\u003C!-- NVSkills CI refresh: 2026-06-15. No instruction changes. -->\n\n## What It Is\n\nCUDA graphs capture GPU operations once and replay them with minimal\nhost-driver overhead. Bridge supports two implementations:\n\n| `cuda_graph_impl` | Mechanism | Scope support |\n|---|---|---|\n| `\"local\"` | MCore `FullCudaGraphWrapper` wrapping entire fwd+bwd | `full_iteration` |\n| `\"transformer_engine\"` | TE `make_graphed_callables()` per layer | `attn`, `mlp`, `moe`, `moe_router`, `moe_preprocess`, `mamba` |\n\n## Quick Decision\n\nStart with TE-scoped graphs for most training workloads, then verify replay\ntiming against eager on the same dispatcher, layout, and container:\n\n- dense models: `attn`, then optionally `mlp`\n- dropless MoE: `attn moe_router moe_preprocess`\n- VLMs: the same dropless-MoE scope, but only after the real-data path is stable\n\nUse `local` + `full_iteration` only when you specifically want full-iteration\ncapture and can satisfy the tighter constraints.\n\nFor recompute-heavy workloads:\n\n- TE-scoped graphs pair naturally with selective recompute\n- full recompute usually pushes you toward `local` full-iteration graphs or away\n  from graphs entirely\n\nRelated docs:\n\n- @docs\u002Ftraining\u002Fcuda-graphs.md\n- @docs\u002Ftraining\u002Factivation-recomputation.md\n\n## Enablement\n\n### Local full-iteration graph\n\n```python\ncfg.model.cuda_graph_impl = \"local\"\ncfg.model.cuda_graph_scope = [\"full_iteration\"]\ncfg.model.cuda_graph_warmup_steps = 3\ncfg.model.use_te_rng_tracker = True\ncfg.rng.te_rng_tracker = True\ncfg.rerun_state_machine.check_for_nan_in_loss = False\ncfg.ddp.check_for_nan_in_grad = False\n```\n\n### TE scoped graph (dense model)\n\n```python\ncfg.model.cuda_graph_impl = \"transformer_engine\"\ncfg.model.cuda_graph_scope = [\"attn\"]           # or [\"attn\", \"mlp\"]\ncfg.model.cuda_graph_warmup_steps = 3\ncfg.model.use_te_rng_tracker = True\ncfg.rng.te_rng_tracker = True\n```\n\n### TE scoped graph (MoE model)\n\n```python\ncfg.model.cuda_graph_impl = \"transformer_engine\"\ncfg.model.cuda_graph_scope = [\"attn\", \"moe_router\", \"moe_preprocess\"]\ncfg.model.cuda_graph_warmup_steps = 3\ncfg.model.use_te_rng_tracker = True\ncfg.rng.te_rng_tracker = True\n```\n\n### Performance harness CLI\n\n```bash\nuv run python scripts\u002Fperformance\u002Frun_script.py \\\n  -m qwen \\\n  -mr qwen3_30b_a3b \\\n  --task pretrain \\\n  -g h100 \\\n  -c bf16 \\\n  -ng 16 \\\n  --cuda_graph_impl transformer_engine \\\n  --cuda_graph_scope attn,moe_router,moe_preprocess \\\n  ...\n```\n\nValid CLI values live in `scripts\u002Fperformance\u002Fargument_parser.py`:\n- `VALID_CUDA_GRAPH_IMPLS`: `[\"none\", \"local\", \"transformer_engine\"]`\n- `VALID_CUDA_GRAPH_SCOPES`: `[\"full_iteration\", \"attn\", \"mlp\", \"moe\", \"moe_router\", \"moe_preprocess\", \"mamba\"]`\n\nThe performance harness uses a comma-separated `--cuda_graph_scope` value and\nauto-enables `model.use_te_rng_tracker` plus `rng.te_rng_tracker` when\n`--cuda_graph_impl` is not `none`.\n\n### Required constraints\n\n- `use_te_rng_tracker = True` (enforced in `gpt_provider.py`)\n- `full_iteration` scope only with `cuda_graph_impl = \"local\"`\n- `full_iteration` scope requires `check_for_nan_in_loss = False`\n- Do not combine `moe` scope and `moe_router` scope\n- Tensor shapes must be static (fixed seq_length, fixed micro_batch_size)\n- MoE token-dropless routing limits graphable scope to dense modules\n- With `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`, set\n  `NCCL_GRAPH_REGISTER=0` (MCore enforces for local impl on arch \u003C sm_100;\n  TE impl asserts unconditionally)\n- CPU offloading is incompatible with CUDA graphs\n- `moe_preprocess` scope requires `moe_router` scope to also be set\n\n### Practical bring-up order\n\n1. Stabilize the eager run first.\n2. Fix sequence length and micro-batch size.\n3. Enable the narrowest useful graph scope.\n4. Confirm replay is active and memory is still acceptable.\n5. Compare eager against graph replay iterations after warmup and capture; do\n   not include the capture step in steady-state timing.\n6. Only then widen scope or combine with overlap features.\n\n## Code Anchors\n\n### Bridge config and validation\n\n```1524:1531:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Fconfig.py\n        # CUDA graph scope validation: check_for_nan_in_loss must be disabled with full_iteration graph\n        if self.model.cuda_graph_impl == \"local\" and CudaGraphScope.full_iteration in self.model.cuda_graph_scope:\n            assert not self.rerun_state_machine.check_for_nan_in_loss, (\n                \"check_for_nan_in_loss must be disabled when using full_iteration CUDA graph. \"\n                \"Set rerun_state_machine.check_for_nan_in_loss=False.\"\n            )\n        if self.model.cuda_graph_impl == \"none\":\n            self.model.cuda_graph_scope = []\n```\n\n### TE RNG tracker requirement\n\n```213:216:src\u002Fmegatron\u002Fbridge\u002Fmodels\u002Fgpt_provider.py\n        if self.cuda_graph_impl != \"none\":\n            assert getattr(self, \"use_te_rng_tracker\", False), (\n                \"Transformer engine's RNG tracker is required for cudagraphs, it can be \"\n                \"enabled with use_te_rng_tracker=True'.\"\n```\n\n### Graph creation and capture in training loop\n\n```231:255:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Ftrain.py\n    # Capture CUDA Graphs.\n    cuda_graph_helper = None\n    if model_config.cuda_graph_impl == \"transformer_engine\":\n        cuda_graph_helper = TECudaGraphHelper(...)\n    # ...\n    if config.model.cuda_graph_impl == \"local\" and CudaGraphScope.full_iteration in config.model.cuda_graph_scope:\n        forward_backward_func = FullCudaGraphWrapper(\n            forward_backward_func, cuda_graph_warmup_steps=config.model.cuda_graph_warmup_steps\n        )\n```\n\n### TE graph capture after warmup\n\n```338:350:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Ftrain.py\n        # Capture CUDA Graphs after warmup.\n        if (\n            model_config.cuda_graph_impl == \"transformer_engine\"\n            and cuda_graph_helper is not None\n            and not cuda_graph_helper.graphs_created()\n            and global_state.train_state.step - start_iteration == model_config.cuda_graph_warmup_steps\n        ):\n            if model_config.cuda_graph_warmup_steps > 0 and should_toggle_forward_pre_hook:\n                disable_forward_pre_hook(model, param_sync=False)\n            cuda_graph_helper.create_cudagraphs()\n            if model_config.cuda_graph_warmup_steps > 0 and should_toggle_forward_pre_hook:\n                enable_forward_pre_hook(model)\n                cuda_graph_helper.cuda_graph_set_manual_hooks()\n```\n\n### RNG initialization\n\n```199:206:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Finitialize.py\n        _set_random_seed(\n            rng_config.seed,\n            rng_config.data_parallel_random_init,\n            rng_config.te_rng_tracker,\n            rng_config.inference_rng_tracker,\n            use_cudagraphable_rng=(model_config.cuda_graph_impl != \"none\"),\n            pg_collection=pg_collection,\n        )\n```\n\n### Delayed wgrad + CUDA graph interaction\n\n```522:555:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Fcomm_overlap.py\n            cuda_graph_scope = getattr(model_cfg, \"cuda_graph_scope\", []) or []\n            # ... scope parsing ...\n            if wgrad_in_graph_scope:\n                assert is_te_min_version(\"2.12.0\"), ...\n                assert model_cfg.gradient_accumulation_fusion, ...\n                if attn_scope_enabled:\n                    assert not model_cfg.add_bias_linear and not model_cfg.add_qkv_bias, ...\n```\n\n### Perf harness override helper\n\n```102:124:scripts\u002Fperformance\u002Futils\u002Foverrides.py\ndef _set_cuda_graph_overrides(\n    recipe, cuda_graph_impl=None, cuda_graph_scope=None\n):\n    # Sets impl, scope, and auto-enables te_rng_tracker\n```\n\n### Graph cleanup\n\n```1414:1441:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Ftrain.py\ndef _delete_cuda_graphs(cuda_graph_helper):\n    # Deletes FullCudaGraphWrapper and TE graph objects to free NCCL buffers\n```\n\n### MCore classes (in 3rdparty\u002FMegatron-LM)\n\n- `CudaGraphManager`: `megatron\u002Fcore\u002Ftransformer\u002Fcuda_graphs.py`\n- `TECudaGraphHelper`: `megatron\u002Fcore\u002Ftransformer\u002Fcuda_graphs.py`\n- `FullCudaGraphWrapper`: `megatron\u002Fcore\u002Ffull_cuda_graph.py`\n- `CudaGraphScope` enum: `megatron\u002Fcore\u002Ftransformer\u002Fenums.py`\n\n### Positive recipe anchors\n\n- `src\u002Fmegatron\u002Fbridge\u002Fperf_recipes\u002Fdeepseek\u002Fgb300\u002Fdeepseek_v3.py`\n- `src\u002Fmegatron\u002Fbridge\u002Fperf_recipes\u002Fqwen\u002Fgb300\u002Fqwen3_moe.py`\n- `src\u002Fmegatron\u002Fbridge\u002Fperf_recipes\u002Fgpt_oss\u002Fgb300\u002Fgpt_oss.py`\n\n### Tests\n\n| File | Coverage |\n|---|---|\n| `tests\u002Funit_tests\u002Ftraining\u002Ftest_config.py` | `full_iteration` NaN-check constraint |\n| `tests\u002Funit_tests\u002Ftraining\u002Ftest_comm_overlap.py` | `delay_wgrad` + CUDA graph interaction |\n| `tests\u002Funit_tests\u002Fmodels\u002Ftest_gpt_full_te_layer_autocast_spec.py` | TE autocast with CUDA graphs |\n| `tests\u002Ffunctional_tests\u002Ftest_groups\u002Frecipes\u002Ftest_llama_recipes_pretrain_cuda_graphs.py` | End-to-end local and TE graph smoke tests |\n| `tests\u002Funit_tests\u002Frecipes\u002Fkimi\u002Ftest_kimi_k2.py` | TE + CUDA graph recipe config |\n| `tests\u002Funit_tests\u002Frecipes\u002Fgpt\u002Ftest_gpt3_175b.py` | TE + CUDA graph recipe config |\n| `tests\u002Funit_tests\u002Frecipes\u002Fqwen_vl\u002Ftest_qwen25_vl_recipes.py` | VLM CUDA graph settings |\n\n## Pitfalls\n\n1. **TE RNG tracker is mandatory**: Setting `cuda_graph_impl` without\n   `use_te_rng_tracker=True` and `rng.te_rng_tracker=True` will assert\n   in the provider.\n\n2. **`full_iteration` requires NaN checks disabled**: The entire fwd+bwd is\n   captured, so loss-NaN checking cannot inspect intermediate values.\n\n3. **MoE scope restrictions**: `moe` scope and `moe_router` scope are\n   mutually exclusive. Token-dropless MoE can only graph `moe_router` and\n   `moe_preprocess`, not the full expert dispatch.\n\n4. **Memory overhead**: CUDA graphs pin all intermediate buffers for the\n   graph's lifetime (no memory reuse). TE scoped graphs add a few GB;\n   full-iteration graphs can increase peak memory by 1.5–2×. `PP > 1`\n   compounds overhead since each stage holds its own graph.\n\n5. **Delayed wgrad interaction**: When `delay_wgrad_compute=True` and\n   attention or MoE router is in `cuda_graph_scope`, additional constraints\n   apply: TE >= 2.12.0, `gradient_accumulation_fusion=True`, and no\n   attention bias.\n\n6. **Variable-length sequences break graphs**: Sequence lengths must be\n   constant across steps. Use padded packed sequences if packing is needed.\n\n7. **Graph cleanup is required**: CUDA graph objects hold NCCL buffer\n   references. Bridge handles this in `_delete_cuda_graphs()` at the end\n   of training, but early exits must call it explicitly.\n\n8. **Older GPU architectures**: On GPUs with compute capability \u003C 10.0\n   (pre-Blackwell), set `NCCL_GRAPH_REGISTER=0` when using\n   `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`. Enforced in MCore\n   `CudaGraphManager` (cuda_graphs.py:1428) and `TECudaGraphHelper`\n   (cuda_graphs.py:1697). The TE impl asserts unconditionally regardless\n   of arch.\n\n9. **CPU offloading incompatible**: CUDA graphs cannot be used with CPU\n   offloading. Enforced in MCore `transformer_config.py:1907`.\n\n10. **MoE recompute + moe_router scope**: MoE recompute is not supported\n    with `moe_router` CUDA graph scope when using `cuda_graph_impl =\n    \"transformer_engine\"`. Enforced in MCore `transformer_config.py:1977`.\n\n11. **Layer-level recompute requires `full_iteration` scope**: Using\n    `recompute_granularity=\"full\"` with `recompute_num_layers` (recompute N\n    whole transformer layers) is incompatible with TE-scoped graphs. MCore\n    calls this \"full\" granularity even though you're selecting how many\n    layers — the name refers to recomputing the full layer, not full model.\n    Any TE-scoped scope (`attn`, `mlp`, `moe_router`, etc.) will assert:\n    `AssertionError: full recompute is only supported with full iteration CUDA graph.`\n    This commonly hits FP8 configs that default to TE-scoped graphs (e.g.\n    `LLAMA3_70B_SFT_CONFIG_H100_FP8_CS_V1` uses `cuda_graph_impl=\n    \"transformer_engine\"`, `cuda_graph_scope=\"mlp\"`). Fix: use submodule\n    recompute (`recompute_granularity=\"selective\"` + `recompute_modules`),\n    disable CUDA graphs, or switch to `local` + `full_iteration`. Enforced\n    in MCore `transformer_config.py:2001-2005`. See also\n    @skills\u002Fnemo-mbridge-perf-activation-recompute\u002FSKILL.md.\n\n12. **Benchmark numbers are workload-specific**: graph wins are usually real\n    when host overhead is visible, but the exact gain depends on batch shape,\n    PP depth, recompute, dispatcher backend, and whether the eager baseline was\n    already optimized.\n\n13. **A successful capture is not a speedup guarantee**: On 2026-05-18,\n    Qwen3 30B A3B H100 BF16 pretrain with the all-to-all dispatcher captured\n    TE-scoped `attn,moe_router,moe_preprocess` graphs successfully (`48`\n    graphable layers, about `6.9 s` capture time on rank 0), but replay\n    iterations 5-8 averaged `42.00 s` versus `41.36 s` for eager. Treat\n    scoped graphs as a bring-up candidate and validate on the target stack.\n\n## Verification\n\n### Unit tests\n\n```bash\nuv run python -m pytest \\\n  tests\u002Funit_tests\u002Ftraining\u002Ftest_config.py -k \"cuda_graph\" \\\n  tests\u002Funit_tests\u002Ftraining\u002Ftest_comm_overlap.py -k \"cuda_graph\" \\\n  tests\u002Funit_tests\u002Fmodels\u002Ftest_gpt_full_te_layer_autocast_spec.py -k \"cuda_graph\" -q\n```\n\n### Functional smoke test (requires GPU)\n\n```bash\nuv run python -m pytest \\\n  tests\u002Ffunctional_tests\u002Ftest_groups\u002Frecipes\u002Ftest_llama_recipes_pretrain_cuda_graphs.py -q\n```\n\n### Success criteria\n\n- Unit tests pass, covering config validation for both `local` and\n  `transformer_engine` implementations.\n- Functional test completes training steps with both CUDA graph\n  implementations.\n- No NCCL errors or illegal memory access in logs.\n","# CUDA Graphs\n\nStable documentation: @docs\u002Ftraining\u002Fcuda-graphs.md\nCard: @skills\u002Fnemo-mbridge-perf-cuda-graphs\u002Fcard.yaml\n\n\u003C!-- NVSkills CI refresh: 2026-06-15. No instruction changes. -->\n\n## What It Is\n\nCUDA graphs capture GPU operations once and replay them with minimal\nhost-driver overhead. Bridge supports two implementations:\n\n| `cuda_graph_impl` | Mechanism | Scope support |\n|---|---|---|\n| `\"local\"` | MCore `FullCudaGraphWrapper` wrapping entire fwd+bwd | `full_iteration` |\n| `\"transformer_engine\"` | TE `make_graphed_callables()` per layer | `attn`, `mlp`, `moe`, `moe_router`, `moe_preprocess`, `mamba` |\n\n## Quick Decision\n\nStart with TE-scoped graphs for most training workloads, then verify replay\ntiming against eager on the same dispatcher, layout, and container:\n\n- dense models: `attn`, then optionally `mlp`\n- dropless MoE: `attn moe_router moe_preprocess`\n- VLMs: the same dropless-MoE scope, but only after the real-data path is stable\n\nUse `local` + `full_iteration` only when you specifically want full-iteration\ncapture and can satisfy the tighter constraints.\n\nFor recompute-heavy workloads:\n\n- TE-scoped graphs pair naturally with selective recompute\n- full recompute usually pushes you toward `local` full-iteration graphs or away\n  from graphs entirely\n\nRelated docs:\n\n- @docs\u002Ftraining\u002Fcuda-graphs.md\n- @docs\u002Ftraining\u002Factivation-recomputation.md\n\n## Enablement\n\n### Local full-iteration graph\n\n```python\ncfg.model.cuda_graph_impl = \"local\"\ncfg.model.cuda_graph_scope = [\"full_iteration\"]\ncfg.model.cuda_graph_warmup_steps = 3\ncfg.model.use_te_rng_tracker = True\ncfg.rng.te_rng_tracker = True\ncfg.rerun_state_machine.check_for_nan_in_loss = False\ncfg.ddp.check_for_nan_in_grad = False\n```\n\n### TE scoped graph (dense model)\n\n```python\ncfg.model.cuda_graph_impl = \"transformer_engine\"\ncfg.model.cuda_graph_scope = [\"attn\"]           # or [\"attn\", \"mlp\"]\ncfg.model.cuda_graph_warmup_steps = 3\ncfg.model.use_te_rng_tracker = True\ncfg.rng.te_rng_tracker = True\n```\n\n### TE scoped graph (MoE model)\n\n```python\ncfg.model.cuda_graph_impl = \"transformer_engine\"\ncfg.model.cuda_graph_scope = [\"attn\", \"moe_router\", \"moe_preprocess\"]\ncfg.model.cuda_graph_warmup_steps = 3\ncfg.model.use_te_rng_tracker = True\ncfg.rng.te_rng_tracker = True\n```\n\n### Performance harness CLI\n\n```bash\nuv run python scripts\u002Fperformance\u002Frun_script.py \\\n  -m qwen \\\n  -mr qwen3_30b_a3b \\\n  --task pretrain \\\n  -g h100 \\\n  -c bf16 \\\n  -ng 16 \\\n  --cuda_graph_impl transformer_engine \\\n  --cuda_graph_scope attn,moe_router,moe_preprocess \\\n  ...\n```\n\nValid CLI values live in `scripts\u002Fperformance\u002Fargument_parser.py`:\n- `VALID_CUDA_GRAPH_IMPLS`: `[\"none\", \"local\", \"transformer_engine\"]`\n- `VALID_CUDA_GRAPH_SCOPES`: `[\"full_iteration\", \"attn\", \"mlp\", \"moe\", \"moe_router\", \"moe_preprocess\", \"mamba\"]`\n\nThe performance harness uses a comma-separated `--cuda_graph_scope` value and\nauto-enables `model.use_te_rng_tracker` plus `rng.te_rng_tracker` when\n`--cuda_graph_impl` is not `none`.\n\n### Required constraints\n\n- `use_te_rng_tracker = True` (enforced in `gpt_provider.py`)\n- `full_iteration` scope only with `cuda_graph_impl = \"local\"`\n- `full_iteration` scope requires `check_for_nan_in_loss = False`\n- Do not combine `moe` scope and `moe_router` scope\n- Tensor shapes must be static (fixed seq_length, fixed micro_batch_size)\n- MoE token-dropless routing limits graphable scope to dense modules\n- With `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`, set\n  `NCCL_GRAPH_REGISTER=0` (MCore enforces for local impl on arch \u003C sm_100;\n  TE impl asserts unconditionally)\n- CPU offloading is incompatible with CUDA graphs\n- `moe_preprocess` scope requires `moe_router` scope to also be set\n\n### Practical bring-up order\n\n1. Stabilize the eager run first.\n2. Fix sequence length and micro-batch size.\n3. Enable the narrowest useful graph scope.\n4. Confirm replay is active and memory is still acceptable.\n5. Compare eager against graph replay iterations after warmup and capture; do\n   not include the capture step in steady-state timing.\n6. Only then widen scope or combine with overlap features.\n\n## Code Anchors\n\n### Bridge config and validation\n\n```1524:1531:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Fconfig.py\n        # CUDA graph scope validation: check_for_nan_in_loss must be disabled with full_iteration graph\n        if self.model.cuda_graph_impl == \"local\" and CudaGraphScope.full_iteration in self.model.cuda_graph_scope:\n            assert not self.rerun_state_machine.check_for_nan_in_loss, (\n                \"check_for_nan_in_loss must be disabled when using full_iteration CUDA graph. \"\n                \"Set rerun_state_machine.check_for_nan_in_loss=False.\"\n            )\n        if self.model.cuda_graph_impl == \"none\":\n            self.model.cuda_graph_scope = []\n```\n\n### TE RNG tracker requirement\n\n```213:216:src\u002Fmegatron\u002Fbridge\u002Fmodels\u002Fgpt_provider.py\n        if self.cuda_graph_impl != \"none\":\n            assert getattr(self, \"use_te_rng_tracker\", False), (\n                \"Transformer engine's RNG tracker is required for cudagraphs, it can be \"\n                \"enabled with use_te_rng_tracker=True'.\"\n```\n\n### Graph creation and capture in training loop\n\n```231:255:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Ftrain.py\n    # Capture CUDA Graphs.\n    cuda_graph_helper = None\n    if model_config.cuda_graph_impl == \"transformer_engine\":\n        cuda_graph_helper = TECudaGraphHelper(...)\n    # ...\n    if config.model.cuda_graph_impl == \"local\" and CudaGraphScope.full_iteration in config.model.cuda_graph_scope:\n        forward_backward_func = FullCudaGraphWrapper(\n            forward_backward_func, cuda_graph_warmup_steps=config.model.cuda_graph_warmup_steps\n        )\n```\n\n### TE graph capture after warmup\n\n```338:350:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Ftrain.py\n        # Capture CUDA Graphs after warmup.\n        if (\n            model_config.cuda_graph_impl == \"transformer_engine\"\n            and cuda_graph_helper is not None\n            and not cuda_graph_helper.graphs_created()\n            and global_state.train_state.step - start_iteration == model_config.cuda_graph_warmup_steps\n        ):\n            if model_config.cuda_graph_warmup_steps > 0 and should_toggle_forward_pre_hook:\n                disable_forward_pre_hook(model, param_sync=False)\n            cuda_graph_helper.create_cudagraphs()\n            if model_config.cuda_graph_warmup_steps > 0 and should_toggle_forward_pre_hook:\n                enable_forward_pre_hook(model)\n                cuda_graph_helper.cuda_graph_set_manual_hooks()\n```\n\n### RNG initialization\n\n```199:206:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Finitialize.py\n        _set_random_seed(\n            rng_config.seed,\n            rng_config.data_parallel_random_init,\n            rng_config.te_rng_tracker,\n            rng_config.inference_rng_tracker,\n            use_cudagraphable_rng=(model_config.cuda_graph_impl != \"none\"),\n            pg_collection=pg_collection,\n        )\n```\n\n### Delayed wgrad + CUDA graph interaction\n\n```522:555:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Fcomm_overlap.py\n            cuda_graph_scope = getattr(model_cfg, \"cuda_graph_scope\", []) or []\n            # ... scope parsing ...\n            if wgrad_in_graph_scope:\n                assert is_te_min_version(\"2.12.0\"), ...\n                assert model_cfg.gradient_accumulation_fusion, ...\n                if attn_scope_enabled:\n                    assert not model_cfg.add_bias_linear and not model_cfg.add_qkv_bias, ...\n```\n\n### Perf harness override helper\n\n```102:124:scripts\u002Fperformance\u002Futils\u002Foverrides.py\ndef _set_cuda_graph_overrides(\n    recipe, cuda_graph_impl=None, cuda_graph_scope=None\n):\n    # Sets impl, scope, and auto-enables te_rng_tracker\n```\n\n### Graph cleanup\n\n```1414:1441:src\u002Fmegatron\u002Fbridge\u002Ftraining\u002Ftrain.py\ndef _delete_cuda_graphs(cuda_graph_helper):\n    # Deletes FullCudaGraphWrapper and TE graph objects to free NCCL buffers\n```\n\n### MCore classes (in 3rdparty\u002FMegatron-LM)\n\n- `CudaGraphManager`: `megatron\u002Fcore\u002Ftransformer\u002Fcuda_graphs.py`\n- `TECudaGraphHelper`: `megatron\u002Fcore\u002Ftransformer\u002Fcuda_graphs.py`\n- `FullCudaGraphWrapper`: `megatron\u002Fcore\u002Ffull_cuda_graph.py`\n- `CudaGraphScope` enum: `megatron\u002Fcore\u002Ftransformer\u002Fenums.py`\n\n### Positive recipe anchors\n\n- `src\u002Fmegatron\u002Fbridge\u002Fperf_recipes\u002Fdeepseek\u002Fgb300\u002Fdeepseek_v3.py`\n- `src\u002Fmegatron\u002Fbridge\u002Fperf_recipes\u002Fqwen\u002Fgb300\u002Fqwen3_moe.py`\n- `src\u002Fmegatron\u002Fbridge\u002Fperf_recipes\u002Fgpt_oss\u002Fgb300\u002Fgpt_oss.py`\n\n### Tests\n\n| File | Coverage |\n|---|---|\n| `tests\u002Funit_tests\u002Ftraining\u002Ftest_config.py` | `full_iteration` NaN-check constraint |\n| `tests\u002Funit_tests\u002Ftraining\u002Ftest_comm_overlap.py` | `delay_wgrad` + CUDA graph interaction |\n| `tests\u002Funit_tests\u002Fmodels\u002Ftest_gpt_full_te_layer_autocast_spec.py` | TE autocast with CUDA graphs |\n| `tests\u002Ffunctional_tests\u002Ftest_groups\u002Frecipes\u002Ftest_llama_recipes_pretrain_cuda_graphs.py` | End-to-end local and TE graph smoke tests |\n| `tests\u002Funit_tests\u002Frecipes\u002Fkimi\u002Ftest_kimi_k2.py` | TE + CUDA graph recipe config |\n| `tests\u002Funit_tests\u002Frecipes\u002Fgpt\u002Ftest_gpt3_175b.py` | TE + CUDA graph recipe config |\n| `tests\u002Funit_tests\u002Frecipes\u002Fqwen_vl\u002Ftest_qwen25_vl_recipes.py` | VLM CUDA graph settings |\n\n## Pitfalls\n\n1. **TE RNG tracker is mandatory**: Setting `cuda_graph_impl` without\n   `use_te_rng_tracker=True` and `rng.te_rng_tracker=True` will assert\n   in the provider.\n\n2. **`full_iteration` requires NaN checks disabled**: The entire fwd+bwd is\n   captured, so loss-NaN checking cannot inspect intermediate values.\n\n3. **MoE scope restrictions**: `moe` scope and `moe_router` scope are\n   mutually exclusive. Token-dropless MoE can only graph `moe_router` and\n   `moe_preprocess`, not the full expert dispatch.\n\n4. **Memory overhead**: CUDA graphs pin all intermediate buffers for the\n   graph's lifetime (no memory reuse). TE scoped graphs add a few GB;\n   full-iteration graphs can increase peak memory by 1.5–2×. `PP > 1`\n   compounds overhead since each stage holds its own graph.\n\n5. **Delayed wgrad interaction**: When `delay_wgrad_compute=True` and\n   attention or MoE router is in `cuda_graph_scope`, additional constraints\n   apply: TE >= 2.12.0, `gradient_accumulation_fusion=True`, and no\n   attention bias.\n\n6. **Variable-length sequences break graphs**: Sequence lengths must be\n   constant across steps. Use padded packed sequences if packing is needed.\n\n7. **Graph cleanup is required**: CUDA graph objects hold NCCL buffer\n   references. Bridge handles this in `_delete_cuda_graphs()` at the end\n   of training, but early exits must call it explicitly.\n\n8. **Older GPU architectures**: On GPUs with compute capability \u003C 10.0\n   (pre-Blackwell), set `NCCL_GRAPH_REGISTER=0` when using\n   `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`. Enforced in MCore\n   `CudaGraphManager` (cuda_graphs.py:1428) and `TECudaGraphHelper`\n   (cuda_graphs.py:1697). The TE impl asserts unconditionally regardless\n   of arch.\n\n9. **CPU offloading incompatible**: CUDA graphs cannot be used with CPU\n   offloading. Enforced in MCore `transformer_config.py:1907`.\n\n10. **MoE recompute + moe_router scope**: MoE recompute is not supported\n    with `moe_router` CUDA graph scope when using `cuda_graph_impl =\n    \"transformer_engine\"`. Enforced in MCore `transformer_config.py:1977`.\n\n11. **Layer-level recompute requires `full_iteration` scope**: Using\n    `recompute_granularity=\"full\"` with `recompute_num_layers` (recompute N\n    whole transformer layers) is incompatible with TE-scoped graphs. MCore\n    calls this \"full\" granularity even though you're selecting how many\n    layers — the name refers to recomputing the full layer, not full model.\n    Any TE-scoped scope (`attn`, `mlp`, `moe_router`, etc.) will assert:\n    `AssertionError: full recompute is only supported with full iteration CUDA graph.`\n    This commonly hits FP8 configs that default to TE-scoped graphs (e.g.\n    `LLAMA3_70B_SFT_CONFIG_H100_FP8_CS_V1` uses `cuda_graph_impl=\n    \"transformer_engine\"`, `cuda_graph_scope=\"mlp\"`). Fix: use submodule\n    recompute (`recompute_granularity=\"selective\"` + `recompute_modules`),\n    disable CUDA graphs, or switch to `local` + `full_iteration`. Enforced\n    in MCore `transformer_config.py:2001-2005`. See also\n    @skills\u002Fnemo-mbridge-perf-activation-recompute\u002FSKILL.md.\n\n12. **Benchmark numbers are workload-specific**: graph wins are usually real\n    when host overhead is visible, but the exact gain depends on batch shape,\n    PP depth, recompute, dispatcher backend, and whether the eager baseline was\n    already optimized.\n\n13. **A successful capture is not a speedup guarantee**: On 2026-05-18,\n    Qwen3 30B A3B H100 BF16 pretrain with the all-to-all dispatcher captured\n    TE-scoped `attn,moe_router,moe_preprocess` graphs successfully (`48`\n    graphable layers, about `6.9 s` capture time on rank 0), but replay\n    iterations 5-8 averaged `42.00 s` versus `41.36 s` for eager. Treat\n    scoped graphs as a bring-up candidate and validate on the target stack.\n\n## Verification\n\n### Unit tests\n\n```bash\nuv run python -m pytest \\\n  tests\u002Funit_tests\u002Ftraining\u002Ftest_config.py -k \"cuda_graph\" \\\n  tests\u002Funit_tests\u002Ftraining\u002Ftest_comm_overlap.py -k \"cuda_graph\" \\\n  tests\u002Funit_tests\u002Fmodels\u002Ftest_gpt_full_te_layer_autocast_spec.py -k \"cuda_graph\" -q\n```\n\n### Functional smoke test (requires GPU)\n\n```bash\nuv run python -m pytest \\\n  tests\u002Ffunctional_tests\u002Ftest_groups\u002Frecipes\u002Ftest_llama_recipes_pretrain_cuda_graphs.py -q\n```\n\n### Success criteria\n\n- Unit tests pass, covering config validation for both `local` and\n  `transformer_engine` implementations.\n- Functional test completes training steps with both CUDA graph\n  implementations.\n- No NCCL errors or illegal memory access in logs.\n",{"name":5,"license":15,"description":7,"when_to_use":24},"Reducing host-driver overhead via CUDA graphs, or tracing a crash or regression to a CUDA graph config change; 'cuda_graph_impl', 'full iteration graph', 'TE scoped graph', 'graphed callables', 'CUDA graph capture'.","main","86cc27ffd16af6cb85948f1155578e6f3f61cc4c","skillhub\u002Fpublic\u002Fapi\u002Fskills\u002Fnvidia\u002Fnemo-mbridge-perf-cuda-graphs","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn","https:\u002F\u002Fgithub.com\u002FSolizardking","https:\u002F\u002Fmusebook.trade","Got a mile high and never came down","2026-10-08 11:52:53",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add Solizardking\u002Ftrain2earn --skill nemo-mbridge-perf-cuda-graphs",{"tool":39,"command":40},"bunx","bunx skills add Solizardking\u002Ftrain2earn --skill nemo-mbridge-perf-cuda-graphs",{"tool":42,"command":43},"pnpm","pnpm dlx skills add Solizardking\u002Ftrain2earn --skill nemo-mbridge-perf-cuda-graphs","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fpublic\u002Fapi\u002Fskills\u002Fnvidia\u002Fnemo-mbridge-perf-cuda-graphs\u002FSKILL.md",true,[47,53,57,61,65],{"path":48,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":52},"BENCHMARK.md","REFERENCE","参考文档",3982,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fpublic\u002Fapi\u002Fskills\u002Fnvidia\u002Fnemo-mbridge-perf-cuda-graphs\u002FBENCHMARK.md",{"path":54,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":55,"sourceHtmlUrl":56},"card.yaml",13862,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fpublic\u002Fapi\u002Fskills\u002Fnvidia\u002Fnemo-mbridge-perf-cuda-graphs\u002Fcard.yaml",{"path":58,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":59,"sourceHtmlUrl":60},"metadata.json",404,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fpublic\u002Fapi\u002Fskills\u002Fnvidia\u002Fnemo-mbridge-perf-cuda-graphs\u002Fmetadata.json",{"path":62,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":63,"sourceHtmlUrl":64},"skill-card.md",4165,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fpublic\u002Fapi\u002Fskills\u002Fnvidia\u002Fnemo-mbridge-perf-cuda-graphs\u002Fskill-card.md",{"path":66,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":67,"sourceHtmlUrl":68},"verification.json",1554,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fpublic\u002Fapi\u002Fskills\u002Fnvidia\u002Fnemo-mbridge-perf-cuda-graphs\u002Fverification.json",[70,78,86,94,101,109],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":74,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M78B94RSCAKMH1QS79VE6DG9","testing","For testing with Light Protocol programs and clients on localnet, devnet, and mainnet validation.","MIT","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fskills\u002Ftesting\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":74,"licenseFileUrl":82,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M78B81BKY8RX12HETPG8YKWK","qedgen","Formally verify programs by writing Lean 4 proofs. Trigger this skill whenever the user wants to formally verify code, generate Lean 4 proofs, prove properties about algorithms or smart contracts, verify invariants, convert program logic into formal specifications, or anything involving Lean 4 and formal verification. Also trigger when the user mentions \"qedgen\", \"lean proof\", \"formal proof\", \"verify my code\", \"prove correctness\", \"formal verification\", or wants mathematical guarantees about their implementation.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fskills\u002Fsolana-formal-verification\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fskills\u002Fsolana-formal-verification\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":74,"licenseFileUrl":90,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M78B7Q7C5K54E01DN83A60KG","solana-dev","Use when user asks to \"build a Solana dapp\", \"write an Anchor program\", \"create a token\", \"debug Solana errors\", \"set up wallet connection\", \"test my Solana program\", \"deploy to devnet\", or \"explain Solana concepts\" (rent, accounts, PDAs, CPIs, etc.). Also use for quick on-chain lookups via public RPC + curl — \"what's the balance of \u003Cwallet>\", \"look up transaction \u003Csig>\", \"token balance for \u003Caccount>\", \"check this address on mainnet\u002Fdevnet\". End-to-end Solana development playbook covering wallet connection, Anchor\u002FPinocchio programs, Codama client generation, LiteSVM\u002FMollusk\u002FSurfpool testing, security checklists, and JSON-RPC curl lookups against public clusters. Integrates with the Solana MCP server for live documentation search. Prefers framework-kit (@solana\u002Fclient + @solana\u002Freact-hooks) for UI, wallet-standard-first connection (incl. ConnectorKit), @solana\u002Fkit for client\u002FRPC code, and @solana\u002Fweb3-compat for legacy boundaries.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fskills\u002Fsolana-dev\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fskills\u002Fsolana-dev\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":74,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":19},"01M78B7HXD6N6GWKSVRQ8F6Q31","solana-common-errors","Diagnose and fix common Solana development errors — GLIBC mismatches, Anchor version conflicts, cargo build-sbf \u002F platform-tools failures, LiteSVM issues, edition2024 crate pins, RPC airdrops, and Anchor 0.29→0.32 migrations. Use when builds fail, Anchor CLI won't install, or CI breaks on Debian\u002FUbuntu.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fskills\u002Fsolana-common-errors\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":105,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":19},"01M78B6T7YSYWQ0N4DP40QDXEZ","skill-creator","Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fskills\u002Fskill-creator\u002Flicense.txt","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fskills\u002Fskill-creator\u002FSKILL.md",[],[],{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":74,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":19},"01M78B1VFT9X5AND7AE1HZPZGF","phantom-wallet-mcp","Execute wallet operations through the Phantom MCP server. Use when the user wants to interact with their Phantom wallet directly — get addresses, transfer SOL or SPL tokens, buy\u002Fswap tokens, sign transactions, and sign messages across Solana, Ethereum, Bitcoin, and Sui. Requires the @phantom\u002Fmcp-server to be configured as an MCP server.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Ftrain2earn\u002Fblob\u002Fmain\u002Fskillhub\u002Fskills\u002Fphantom-wallet-mcp\u002FSKILL.md",[],[]]