選項
首頁首頁 Skill 數據科學與機器學習 nemo-mbridge-resiliency

nemo-mbridge-resiliency

NVIDIA/skills NVIDIA/skills

為 Megatron Bridge 訓練工作設定容錯、落後節點偵測、搶佔、進程內重啟,以及狀態機重跑功能。

...展開全部
0
更新時間 2026-09-25

韌性

穩定版文件:@docs/training/resiliency.md、@docs/training/checkpointing.md 卡片:@skills/nemo-mbridge-resiliency/card.yaml

啟用

容錯能力(僅限 Slurm)

選項 1:NeMo Run 外掛程式(建議)

from megatron.bridge.recipes.run_plugins import FaultTolerancePlugin
import nemo_run as run

task = run.Script(...)
run_plugins = [
    FaultTolerancePlugin(
        enable_ft_package=True,
        calc_ft_timeouts=True,
        num_in_job_restarts=3,
        num_job_retries_on_failure=2,
        initial_rank_heartbeat_timeout=1800,
        rank_heartbeat_timeout=300,
    )
]
run.run(task, plugins=run_plugins, executor=executor)
外掛程式參數 預設值 說明
num_in_job_restarts 3 同一工作內的最大重啟次數
num_job_retries_on_failure 2 發生失敗時最多可啟動的新工作數
初始排名心跳超時 1800 首次心跳超時 (秒)
rank_heartbeat_timeout 300 後續心跳超時 (秒)

選項 2:直接設定 + ft_launcher

from megatron.bridge.training.config import FaultToleranceConfig

cfg.ft = FaultToleranceConfig(
    enable_ft_package=True,
    calc_ft_timeouts=True,
    simulate_fault=False,
    simulated_fault_type="random",
)

使用ft_launcher(而非torchrun)啟動:

export GROUP_RANK=0  # 非 Slurm 環境下必填
ft_launcher \
    --rdzv_backend=c10d --rdzv_endpoint=${MASTER_ADDR}:${MASTER_PORT} \
    --nnodes=${NUM_NODES} --nproc-per-node=${NUM_GPUS_PER_NODE} \
    --ft-rank_section_timeouts=setup:600,step:180,checkpointing:420 \
    --ft-rank_out_of_section_timeout=300 \
    your_training_script.py
配置參數 預設值 說明
enable_ft_package False 啟用容錯功能
calc_ft_timeouts False 自動計算最佳超時值
simulate_fault False 啟用故障模擬以進行測試
模擬故障類型 "隨機" "rank_hung"、"rank_killed" 或"random"
模擬故障等級 無 要觸發故障的特定排名(若為 None 則為隨機)
模擬故障基本延遲 0 模擬故障前的基礎延遲時間

基於區段的超時監控會獨立涵蓋設定、訓練步驟、檢查點 以及超出區段的時間。當calc_ft_timeouts=True 時,超時資訊會儲存至ft_state.json 以供後續執行使用。

NVRx 落後節點偵測

from megatron.bridge.training.config import NVRxStragglerDetectionConfig

cfg.nvrx_straggler = NVRxStragglerDetectionConfig(
    enabled=True,
    report_time_interval=300.0,
    calc_relative_gpu_perf=True,
    calc_individual_gpu_perf=True,
    num_gpu_perf_scores_to_print=5,
    gpu_relative_perf_threshold=0.7,
    gpu_個別效能閾值=0.7,
    若偵測到則停止=False,
    啟用記錄=True,
)
參數 預設值 說明
啟用 False 啟用落後節點偵測
報告時間間隔 300.0 落後節點檢查之間的秒數間隔
calc_relative_gpu_perf True 相互比較各排名
calc_individual_gpu_perf True 追蹤各排名隨時間推移的效能衰退情況
gpu_relative_perf_threshold 0.7 相對效能的閾值(0-1)
gpu_個別_效能_閾值 0.7 個別效能閾值(0-1)
若偵測到則停止 False 若偵測到落後節點則終止訓練
需列印的 GPU 表現分數數量 5 要列印的最佳/最差分數數量
分析間隔 1 偵測器的分析間隔時間

預先佔用

外掛程式 (Slurm)

from megatron.bridge.recipes.run_plugins import PreemptionPlugin

plugins = [
    PreemptionPlugin(
        preempt_time=60,
        enable_exit_handler=True,
        enable_exit_handler_for_data_loader=False,
    )
]
外掛程式參數 預設值 說明
preempt_time 60 在工作達到限制前發出訊號的前秒數
enable_exit_handler True 在訓練期間啟用訊號處理程序
enable_exit_handler_for_data_loader False 針對資料載入器工作節點啟用

直接設定

import signal
cfg.train.exit_signal_handler = True
cfg.train.exit_signal = signal.SIGTERM
cfg.train.exit_signal_handler_for_dataloader = False

重新執行狀態機(實驗性)

from megatron.bridge.training.config import RerunStateMachineConfig

cfg.rerun_state_machine = RerunStateMachineConfig(
    rerun_mode="validate_results",
    check_for_nan_in_loss=True,
    check_for_spiky_loss=False,
    spiky_loss_factor=10.0,
)
參數 預設值 說明
rerun_mode "已停用" "已停用","驗證結果","報告確定性統計資料"
檢查損失中的 NaN True 檢查損失中是否存在 NaN
檢查損失值是否出現尖峰 False 檢查損失值是否出現意外龐大值
spiky_loss_factor 10.0 若損失值大於「因子」乘以「最大觀察值」,則標記為異常(針對大型模型應提高此值)

退出代碼:16 = 繼續執行以消除歧義,17 = 驗證失敗。

進程中重啟(實驗性)

from megatron.bridge.training.config import InProcessRestartConfig

cfg.inprocess_restart = InProcessRestartConfig(
    enabled=True,
    granularity="node",
    soft_timeout=60.0,
    hard_timeout=90.0,
)
參數 預設值 說明
enabled False 啟用進程內重啟
active_world_size 無 執行工作負載的層級(其餘為預熱備用)
粒度 「節點」 「節點」或「排名」重啟粒度
最大迭代次數 無 最大重啟次數(None 表示無限制)
soft_timeout 60.0 偵測 GIL 釋放後的卡死狀況(秒)
硬時限 90.0 強制終止卡住的 rank(秒)
心跳間隔 30.0 心跳間隔(秒)
心跳超時 60.0 心跳遺失超時 (秒)
barrier_timeout 120.0 分散式屏障超時 (秒)
completion_timeout 120.0 完成屏障超時 (秒)
empty_cuda_cache True 重新啟動時清除 CUDA 快取
最大排位錯誤數 無 終止前允許發生的最大排位錯誤次數
監控程序日誌目錄 無 監控日誌目錄

必需的環境變數:

export TORCH_CPP_LOG_LEVEL=error
export TORCH_NCCL_RETHROW_CUDA_ERRORS=0
export NCCL_NVLS_ENABLE=0

PyTorch NCCL 監控器超時設定必須大於hard_timeout。NeMo-Run 的 Slurm 執行器不被支援;請直接使用srun --kill-on-bad-exit=0 啟動。

非同步檢查點儲存

cfg.checkpoint.async_save = True
cfg.checkpoint.ckpt_format = "torch_dist"

本機檢查點儲存 (NVRx)

cfg.checkpoint.non_persistent_local_ckpt_dir = "/local/scratch/ckpt"
cfg.checkpoint.non_persistent_local_ckpt_algo = "fully_parallel"

程式碼錨點

容錯機制

  • 設定檔:src/megatron/bridge/training/config.py—FaultToleranceConfig
  • 執行時:src/megatron/bridge/training/fault_tolerance.py
  • 外掛程式:src/megatron/bridge/recipes/run_plugins.py—FaultTolerancePlugin
  • 效能外掛程式:scripts/performance/nemo-mbridge-resiliency_plugins.py
  • 測試:tests/unit_tests/training/test_fault_tolerance.py
  • 範例:examples/training_features/nemo-mbridge-resiliency/fault_tolerance/

落後節點偵測

  • 設定檔:src/megatron/bridge/training/config.py—NVRxStragglerDetectionConfig
  • 執行時:src/megatron/bridge/training/nvrx_straggler.py
  • 訓練迴圈:src/megatron/bridge/training/train.py—check_nvrx_straggler_detection
  • 測試:tests/unit_tests/training/test_nvrx_straggler.py、tests/functional_tests/training/test_nvrx_straggler.py
  • 範例:examples/training_features/nemo-mbridge-resiliency/straggler_detection/

進程內重啟

  • 設定檔:src/megatron/bridge/training/config.py—InProcessRestartConfig
  • 執行時:src/megatron/bridge/training/inprocess_restart.py
  • 入口點:src/megatron/bridge/training/pretrain.py—maybe_wrap_for_inprocess_restart
  • 測試:tests/unit_tests/training/test_inprocess_restart.py、tests/functional_tests/training/test_inprocess_restart.py

預先終止

  • 外掛程式:src/megatron/bridge/recipes/run_plugins.py—PreemptionPlugin
  • 訊號處理常式:src/megatron/bridge/training/utils/sig_utils.py
  • 測試:tests/unit_tests/recipes/test_run_plugins.py

重新執行狀態機

  • 設定檔:src/megatron/bridge/training/config.py—RerunStateMachineConfig
  • 初始化:src/megatron/bridge/training/initialize.py—init_rerun_state

檢查點

  • 非同步儲存:src/megatron/bridge/training/checkpointing.py—schedule_async_save
  • 本機檢查點:src/megatron/bridge/training/checkpointing.py—LocalCheckpointManager
  • 測試:tests/functional_tests/training/test_local_checkpointing.py

注意事項

  1. 使用 ft_launcher 而非 torchrun:直接使用FaultToleranceConfig需要 ft_launcher。若使用torchrun,將默默停用 FT。若非 Slurm 環境, 請設定GROUP_RANK=0。

  2. 非同步儲存需使用 torch_dist:async_save=True僅適用於 ckpt_format="torch_dist"。其他格式會無預警失敗或拋出錯誤。

  3. IPR + NeMo-Run:進程內重啟與 NeMo-Run 或 Slurm 預先奪取外掛程式不相容。需使用特定版本的 PyTorch/NCCL 及環境變數。

  4. NVRx 與傳統落後節點偵測器:目前存在兩種偵測器。請使用 NVRx (nvrx_straggler);請勿同時啟用兩者。

  5. stop_if_detected 預設值:NVRx 預設會記錄日誌,但不會 停止訓練。若要自動終止,請將stop_if_detected 設為 True。

  6. NCCL 監控機制 vs hard_timeout:對於 IPR,NCCL 監控機制的超時設定必須 大於hard_timeout,否則 PyTorch 會在恢復前終止程序。

  7. 重跑狀態機處於 alpha 階段:請使用check_for_nan_in_loss=True進行 NaN 偵測,但目前尚不應依賴完整重跑工作流程。

驗證

容錯

./examples/training_features/nemo-mbridge-resiliency/fault_tolerance/run_fault_tolerance.sh
./examples/training_features/nemo-mbridge-resiliency/fault_tolerance/run_fault_tolerance.sh --simulate-fault

請查找[FaultTolerance]/[RankMonitorServer]日誌中包含 timeouts 區段的記錄。模擬的故障應會觸發從檢查點重新啟動。

落後節點偵測

uv run python -m torch.distributed.run --nproc_per_node=2 \
    examples/training_features/nemo-mbridge-resiliency/straggler_detection/straggler_detection_example.py

請查看包含各排名分數的GPU 相對效能與GPU 個別效能報告 。

非同步檢查點

請在日誌中查找「Scheduling async checkpoint save」的記錄。在檢查點檔案寫入期間, 訓練迭代應能持續進行。

進程內重啟

pytest tests/functional_tests/training/test_inprocess_restart.py -v

需使用相容的 PyTorch/NCCL 版本。

在 GitHub 上查看
---
name: nemo-mbridge-resiliency
description: Configure fault tolerance, straggler detection, preemption, in-process restart, and re-run state machine for Megatron Bridge training jobs.
license: Apache-2.0
---

# Resiliency

Stable docs: @docs/training/resiliency.md, @docs/training/checkpointing.md
Card: @skills/nemo-mbridge-resiliency/card.yaml

## Enablement

### Fault tolerance (Slurm only)

#### Option 1: NeMo Run plugin (recommended)

```python
from megatron.bridge.recipes.run_plugins import FaultTolerancePlugin
import nemo_run as run

task = run.Script(...)
run_plugins = [
    FaultTolerancePlugin(
        enable_ft_package=True,
        calc_ft_timeouts=True,
        num_in_job_restarts=3,
        num_job_retries_on_failure=2,
        initial_rank_heartbeat_timeout=1800,
        rank_heartbeat_timeout=300,
    )
]
run.run(task, plugins=run_plugins, executor=executor)
```

| Plugin parameter | Default | Description |
|---|---|---|
| `num_in_job_restarts` | 3 | Max restarts within same job |
| `num_job_retries_on_failure` | 2 | Max new job launches on failure |
| `initial_rank_heartbeat_timeout` | 1800 | First heartbeat timeout (seconds) |
| `rank_heartbeat_timeout` | 300 | Subsequent heartbeat timeout (seconds) |

#### Option 2: Direct config + ft_launcher

```python
from megatron.bridge.training.config import FaultToleranceConfig

cfg.ft = FaultToleranceConfig(
    enable_ft_package=True,
    calc_ft_timeouts=True,
    simulate_fault=False,
    simulated_fault_type="random",
)
```

Launch with `ft_launcher` (not `torchrun`):

```bash
export GROUP_RANK=0  # required for non-Slurm
ft_launcher \
    --rdzv_backend=c10d --rdzv_endpoint=${MASTER_ADDR}:${MASTER_PORT} \
    --nnodes=${NUM_NODES} --nproc-per-node=${NUM_GPUS_PER_NODE} \
    --ft-rank_section_timeouts=setup:600,step:180,checkpointing:420 \
    --ft-rank_out_of_section_timeout=300 \
    your_training_script.py
```

| Config parameter | Default | Description |
|---|---|---|
| `enable_ft_package` | False | Enable fault tolerance |
| `calc_ft_timeouts` | False | Auto-compute optimal timeouts |
| `simulate_fault` | False | Enable fault simulation for testing |
| `simulated_fault_type` | `"random"` | `"rank_hung"`, `"rank_killed"`, or `"random"` |
| `simulated_fault_rank` | None | Specific rank to fault (random if None) |
| `simulated_fault_base_delay` | 0 | Base delay before simulating fault |

Section-based timeout monitoring covers setup, training steps, checkpointing,
and out-of-section time independently. Timeouts are saved to `ft_state.json`
for subsequent runs when `calc_ft_timeouts=True`.

### NVRx straggler detection

```python
from megatron.bridge.training.config import NVRxStragglerDetectionConfig

cfg.nvrx_straggler = NVRxStragglerDetectionConfig(
    enabled=True,
    report_time_interval=300.0,
    calc_relative_gpu_perf=True,
    calc_individual_gpu_perf=True,
    num_gpu_perf_scores_to_print=5,
    gpu_relative_perf_threshold=0.7,
    gpu_individual_perf_threshold=0.7,
    stop_if_detected=False,
    enable_logging=True,
)
```

| Parameter | Default | Description |
|---|---|---|
| `enabled` | False | Enable straggler detection |
| `report_time_interval` | 300.0 | Seconds between straggler checks |
| `calc_relative_gpu_perf` | True | Compare ranks against each other |
| `calc_individual_gpu_perf` | True | Track per-rank degradation over time |
| `gpu_relative_perf_threshold` | 0.7 | Threshold for relative performance (0-1) |
| `gpu_individual_perf_threshold` | 0.7 | Threshold for individual performance (0-1) |
| `stop_if_detected` | False | Terminate training on straggler |
| `num_gpu_perf_scores_to_print` | 5 | Number of best/worst scores to print |
| `profiling_interval` | 1 | Profiling interval for detector |

### Preemption

#### Plugin (Slurm)

```python
from megatron.bridge.recipes.run_plugins import PreemptionPlugin

plugins = [
    PreemptionPlugin(
        preempt_time=60,
        enable_exit_handler=True,
        enable_exit_handler_for_data_loader=False,
    )
]
```

| Plugin parameter | Default | Description |
|---|---|---|
| `preempt_time` | 60 | Seconds before job limit to send signal |
| `enable_exit_handler` | True | Enable signal handler in training |
| `enable_exit_handler_for_data_loader` | False | Enable for dataloader workers |

#### Direct config

```python
import signal
cfg.train.exit_signal_handler = True
cfg.train.exit_signal = signal.SIGTERM
cfg.train.exit_signal_handler_for_dataloader = False
```

### Re-run state machine (experimental)

```python
from megatron.bridge.training.config import RerunStateMachineConfig

cfg.rerun_state_machine = RerunStateMachineConfig(
    rerun_mode="validate_results",
    check_for_nan_in_loss=True,
    check_for_spiky_loss=False,
    spiky_loss_factor=10.0,
)
```

| Parameter | Default | Description |
|---|---|---|
| `rerun_mode` | `"disabled"` | `"disabled"`, `"validate_results"`, `"report_determinism_stats"` |
| `check_for_nan_in_loss` | True | Check for NaN in loss |
| `check_for_spiky_loss` | False | Check for unexpectedly large loss |
| `spiky_loss_factor` | 10.0 | Loss flagged if > factor * max observed (increase for large models) |

Exit codes: 16 = resume to disambiguate, 17 = failed validation.

### In-process restart (experimental)

```python
from megatron.bridge.training.config import InProcessRestartConfig

cfg.inprocess_restart = InProcessRestartConfig(
    enabled=True,
    granularity="node",
    soft_timeout=60.0,
    hard_timeout=90.0,
)
```

| Parameter | Default | Description |
|---|---|---|
| `enabled` | False | Enable in-process restart |
| `active_world_size` | None | Ranks executing workload (rest are warm reserves) |
| `granularity` | `"node"` | `"node"` or `"rank"` restart granularity |
| `max_iterations` | None | Max restart attempts (None = unlimited) |
| `soft_timeout` | 60.0 | Detect GIL-released hangs (seconds) |
| `hard_timeout` | 90.0 | Force-terminate hung ranks (seconds) |
| `heartbeat_interval` | 30.0 | Heartbeat interval (seconds) |
| `heartbeat_timeout` | 60.0 | Missing heartbeat timeout (seconds) |
| `barrier_timeout` | 120.0 | Distributed barrier timeout (seconds) |
| `completion_timeout` | 120.0 | Completion barrier timeout (seconds) |
| `empty_cuda_cache` | True | Clear CUDA cache during restart |
| `max_rank_faults` | None | Max rank faults before terminating |
| `monitor_process_logdir` | None | Directory for monitor logs |

Required environment variables:

```bash
export TORCH_CPP_LOG_LEVEL=error
export TORCH_NCCL_RETHROW_CUDA_ERRORS=0
export NCCL_NVLS_ENABLE=0
```

The PyTorch NCCL watchdog timeout must exceed `hard_timeout`. NeMo-Run's
Slurm Executor is not supported; launch directly with `srun --kill-on-bad-exit=0`.

### Async checkpoint save

```python
cfg.checkpoint.async_save = True
cfg.checkpoint.ckpt_format = "torch_dist"
```

### Local checkpointing (NVRx)

```python
cfg.checkpoint.non_persistent_local_ckpt_dir = "/local/scratch/ckpt"
cfg.checkpoint.non_persistent_local_ckpt_algo = "fully_parallel"
```

## Code Anchors

### Fault tolerance
- Config: `src/megatron/bridge/training/config.py` — `FaultToleranceConfig`
- Runtime: `src/megatron/bridge/training/fault_tolerance.py`
- Plugin: `src/megatron/bridge/recipes/run_plugins.py` — `FaultTolerancePlugin`
- Perf plugin: `scripts/performance/nemo-mbridge-resiliency_plugins.py`
- Tests: `tests/unit_tests/training/test_fault_tolerance.py`
- Example: `examples/training_features/nemo-mbridge-resiliency/fault_tolerance/`

### Straggler detection
- Config: `src/megatron/bridge/training/config.py` — `NVRxStragglerDetectionConfig`
- Runtime: `src/megatron/bridge/training/nvrx_straggler.py`
- Train loop: `src/megatron/bridge/training/train.py` — `check_nvrx_straggler_detection`
- Tests: `tests/unit_tests/training/test_nvrx_straggler.py`, `tests/functional_tests/training/test_nvrx_straggler.py`
- Example: `examples/training_features/nemo-mbridge-resiliency/straggler_detection/`

### In-process restart
- Config: `src/megatron/bridge/training/config.py` — `InProcessRestartConfig`
- Runtime: `src/megatron/bridge/training/inprocess_restart.py`
- Entry point: `src/megatron/bridge/training/pretrain.py` — `maybe_wrap_for_inprocess_restart`
- Tests: `tests/unit_tests/training/test_inprocess_restart.py`, `tests/functional_tests/training/test_inprocess_restart.py`

### Preemption
- Plugin: `src/megatron/bridge/recipes/run_plugins.py` — `PreemptionPlugin`
- Signal handler: `src/megatron/bridge/training/utils/sig_utils.py`
- Tests: `tests/unit_tests/recipes/test_run_plugins.py`

### Re-run state machine
- Config: `src/megatron/bridge/training/config.py` — `RerunStateMachineConfig`
- Init: `src/megatron/bridge/training/initialize.py` — `init_rerun_state`

### Checkpointing
- Async save: `src/megatron/bridge/training/checkpointing.py` — `schedule_async_save`
- Local ckpt: `src/megatron/bridge/training/checkpointing.py` — `LocalCheckpointManager`
- Tests: `tests/functional_tests/training/test_local_checkpointing.py`

## Pitfalls

1. **ft_launcher, not torchrun**: Direct `FaultToleranceConfig` requires
   `ft_launcher`. Using `torchrun` silently disables FT. For non-Slurm,
   set `GROUP_RANK=0`.

2. **Async save requires torch_dist**: `async_save=True` only works with
   `ckpt_format="torch_dist"`. Other formats silently fail or error.

3. **IPR + NeMo-Run**: In-process restart is not compatible with NeMo-Run
   or Slurm preemption plugins. Requires specific PyTorch/NCCL versions
   and env vars.

4. **NVRx vs legacy straggler**: Two detectors exist. Use NVRx
   (`nvrx_straggler`); do not enable both.

5. **stop_if_detected default**: NVRx logs but does not stop training by
   default. Set `stop_if_detected=True` for automatic termination.

6. **NCCL watchdog vs hard_timeout**: For IPR, NCCL watchdog timeout must
   exceed `hard_timeout` or PyTorch kills the process before recovery.

7. **Rerun state machine is alpha**: Use `check_for_nan_in_loss=True` for
   NaN detection, but don't rely on full rerun workflows yet.

## Verification

### Fault tolerance
```bash
./examples/training_features/nemo-mbridge-resiliency/fault_tolerance/run_fault_tolerance.sh
./examples/training_features/nemo-mbridge-resiliency/fault_tolerance/run_fault_tolerance.sh --simulate-fault
```
Look for `[FaultTolerance]` / `[RankMonitorServer]` log lines with section
timeouts. Simulated fault should trigger restart from checkpoint.

### Straggler detection
```bash
uv run python -m torch.distributed.run --nproc_per_node=2 \
    examples/training_features/nemo-mbridge-resiliency/straggler_detection/straggler_detection_example.py
```
Look for `GPU relative performance` and `GPU individual performance` reports
with per-rank scores.

### Async checkpoint
Look for `Scheduling async checkpoint save` in logs. Training iterations
should continue while checkpoint files are being written.

### In-process restart
```bash
pytest tests/functional_tests/training/test_inprocess_restart.py -v
```
Requires compatible PyTorch/NCCL versions.

安裝 nemo-mbridge-resiliency

請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。

下載 ZIP

複製儲存庫並將技能檔案複製到您的專案中。

git clone https://github.com/NVIDIA/skills/tree/main/skills/nemo-mbridge-resiliency # Copy SKILL.md to your .claude/skills/ directory

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/ Claude 會自動偵測並使用該技能
儲存庫 NVIDIA/skills

相關技能

web-search
更新時間 2026-06-29
webapp-testing
更新時間 2026-06-29
lark-base
更新時間 2026-07-05
agentmail
更新時間 2026-06-29
OR