[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CSKS73DBDN3W7VVW5PQ4MX":3,"skill-same:01M7CSKS73DBDN3W7VVW5PQ4MX":72},{"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":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":30,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7CSKS73DBDN3W7VVW5PQ4MX","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.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Skills-技能包\u002FYYC3-Skills-技能包-skills\u002Fskills\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## 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- `scripts\u002Fperformance\u002Fconfigs\u002Fdeepseek\u002Fdeepseek_workload_base_configs.py`\n- `scripts\u002Fperformance\u002Fconfigs\u002Fqwen\u002Fqwen3_workload_base_configs.py`\n- `scripts\u002Fperformance\u002Fconfigs\u002Fgpt_oss\u002Fgpt_oss_workload_base_configs.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\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\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## 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- `scripts\u002Fperformance\u002Fconfigs\u002Fdeepseek\u002Fdeepseek_workload_base_configs.py`\n- `scripts\u002Fperformance\u002Fconfigs\u002Fqwen\u002Fqwen3_workload_base_configs.py`\n- `scripts\u002Fperformance\u002Fconfigs\u002Fgpt_oss\u002Fgpt_oss_workload_base_configs.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\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\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","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Skills-技能包\u002FYYC3-Skills-技能包-skills\u002Fskills\u002Fnemo-mbridge-perf-cuda-graphs",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill nemo-mbridge-perf-cuda-graphs",{"tool":40,"command":41},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill nemo-mbridge-perf-cuda-graphs",{"tool":43,"command":44},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill nemo-mbridge-perf-cuda-graphs","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Skills-技能包\u002FYYC3-Skills-技能包-skills\u002Fskills\u002Fnemo-mbridge-perf-cuda-graphs\u002FSKILL.md",true,[48,54,58,62,66],{"path":49,"resourceType":50,"resourceTypeDesc":51,"sizeBytes":52,"sourceHtmlUrl":53},"BENCHMARK.md","REFERENCE","参考文档",4315,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Skills-技能包\u002FYYC3-Skills-技能包-skills\u002Fskills\u002Fnemo-mbridge-perf-cuda-graphs\u002FBENCHMARK.md",{"path":55,"resourceType":50,"resourceTypeDesc":51,"sizeBytes":56,"sourceHtmlUrl":57},"card.yaml",13852,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Skills-技能包\u002FYYC3-Skills-技能包-skills\u002Fskills\u002Fnemo-mbridge-perf-cuda-graphs\u002Fcard.yaml",{"path":59,"resourceType":50,"resourceTypeDesc":51,"sizeBytes":60,"sourceHtmlUrl":61},"evals\u002Fevals.json",1400,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Skills-技能包\u002FYYC3-Skills-技能包-skills\u002Fskills\u002Fnemo-mbridge-perf-cuda-graphs\u002Fevals\u002Fevals.json",{"path":63,"resourceType":50,"resourceTypeDesc":51,"sizeBytes":64,"sourceHtmlUrl":65},"skill-card.md",3826,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Skills-技能包\u002FYYC3-Skills-技能包-skills\u002Fskills\u002Fnemo-mbridge-perf-cuda-graphs\u002Fskill-card.md",{"path":67,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":70,"sourceHtmlUrl":71},"skill.oms.sig","OTHER","其他",4821,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Skills-技能包\u002FYYC3-Skills-技能包-skills\u002Fskills\u002Fnemo-mbridge-perf-cuda-graphs\u002Fskill.oms.sig",[73,81,88,95,102,109],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":77,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":77,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":77,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":77,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":77,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\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":77,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]