Skip to content

[SDC] Integrate deterministic replay into Trainer - #4334

Merged
xmfan merged 1 commit into
mainfrom
xmfan/stack/45
Aug 31, 2026
Merged

xmfan merged 1 commit into
mainfrom
xmfan/stack/45

Conversation

@xmfan

@xmfan xmfan commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


[SDC] Integrate deterministic replay into Trainer

Add opt-in deterministic replay for detecting silent data corruption during
training.

The Trainer builds an SDCReplayer when config.sdc_replay is set and holds it
as self.sdc_replayer (config.sdc_replay is None by default, which disables
replay). For each optimizer step, the step's first forward/backward call --
one gradient-accumulation group, which under pipeline parallelism is one
complete pipeline schedule -- is routed through sdc_replayer.run_fwd_bwd,
which replay-checks it when scheduled. Later accumulation groups exercise
the same compute and communication paths and run unchecked. A mismatch
raises SDCReplayMismatch on every rank before gradient clipping, optimizer,
scheduler, or checkpoint updates can observe corrupted state.

The replayer is built from config with narrow runtime inputs (modules,
device, and a ScalarStateAccessor for ntokens_seen, which the replayed
forward/backward mutates; self.step is incremented outside the replay
boundary and needs no capture); it does not receive the Trainer. train_step
enters the replay boundary right after optimizers.zero_grad, satisfying the
replayer's empty-entry-gradients contract. All replay
scheduling state lives inside the replayer; the check schedule is
process-local, not checkpointed, and restarts after checkpoint loading via
reset_schedule.

GraphTrainer shares the same replay boundary by inheriting Trainer.

The feature is disabled by default and has no CLI surface (sdc_replay is
suppressed from tyro parsing); enable it programmatically:

from torchtitan.observability.sdc_replayer import SDCReplayer

config.debug.deterministic = True
config.sdc_replay = SDCReplayer.Config(
    num_steps=1,    # optimizer steps checked after each (re)start; -1 checks every step
    num_replays=1,  # re-executions compared against the reference
)

Replay requires debug.deterministic=True and
debug.deterministic_warn_only=False. Eager execution, torch.compile, CUDA
graphs, symmetric-memory FSDP, distributed GEMM, async TP, DeepEP v2,
HybridEP, and MinimalAsyncEP use the same replay boundary. CUDA graphs
require num_replays=1; this is validated purely from config (independent of
runtime CUDA graph availability) because additional replays would require
CUDA-graph-aware restoration of graph-owned gradient and optional-buffer
storage.

After config overrides are applied, Trainer re-runs the full
Config.post_init (raise-only) instead of individual validators.

Document the feature under torchtitan/observability/ and add CPU and GPU
coverage including an intentionally corrupted distributed gradient. The
sdc_replay_mismatch integration test sets use_real_pg=True because
cross-rank mismatch propagation (all_reduce and all_gather_object) needs
real collectives.

  • pytest -q tests/unit_tests/cpu/test_trainer.py
    tests/unit_tests/cpu/observability/test_sdc_replayer.py
    tests/unit_tests/cpu/test_invalid_loss.py
    tests/unit_tests/cpu/test_config_manager.py
  • tests/integration_tests/features.py::sdc_replay_cudagraph
  • torchtitan/experiments/graph_trainer/tests/integration_tests.py::sdc_replay
  • tests/integration_tests/h100.py::deepseek_v3_fsdp+cp+tp+minimal_async_ep+sdc_replay
  • tests/integration_tests/features.py::sdc_replay_mismatch
  • git diff --check
  • pre-commit run --all-files

xmfan added a commit that referenced this pull request Aug 26, 2026
## Summary

Add opt-in deterministic replay for detecting silent data corruption during training.

For selected optimizer steps, Trainer snapshots the relevant state, runs a reference forward/backward unit, restores the snapshot, and runs the configured number of candidate executions. A mismatch raises `SDCReplayMismatch` on every rank before gradient clipping, optimizer, scheduler, or checkpoint updates can observe corrupted state.

Only the first gradient-accumulation unit of each checked optimizer step is replayed. Under pipeline parallelism, that unit is one complete pipeline schedule including all pipeline microbatches. The attempt-local replay schedule is deliberately process-local and restarts after checkpoint loading.

Integrate the common replay boundary with the core Trainer, Flux, GraphTrainer, and TorchFT while preserving their existing forward/backward implementations. Flux additionally includes its text encoders and autoencoder in replay state when present.

## Configuration

The feature is disabled by default and can be enabled through Python configuration or the CLI:

```bash
--debug.deterministic
--sdc-replay.enabled
--sdc-replay.num-steps 1
--sdc-replay.num-replays 1
```

`num_steps` defaults to `1`; `-1` checks every locally attempted optimizer step. `num_replays` defaults to `1` and counts candidate executions compared with the reference. Replay requires `debug.deterministic=True` and `debug.deterministic_warn_only=False`.

Eager execution, `torch.compile`, CUDA graphs, symmetric-memory FSDP, distributed GEMM, async TP, DeepEP v2, HybridEP, and MinimalAsyncEP use the same replay boundary. CUDA graphs currently require `num_replays=1` because additional candidates would require CUDA-graph-aware restoration of graph-owned gradient and optional-buffer storage.

Document the feature and its current hashing limitation, expose the configuration through the CLI, and add CPU and GPU coverage including an intentionally corrupted distributed gradient.

## Testing

- `pytest -q tests/unit_tests/cpu/test_trainer.py tests/unit_tests/test_sdc_replay.py tests/unit_tests/cpu/test_invalid_loss.py tests/unit_tests/cpu/test_config_manager.py`
  - 73 passed
- `tests/integration_tests/features.py::sdc_replay_cudagraph`
  - Passed on 1 GPU
- `torchtitan/experiments/graph_trainer/tests/integration_tests.py::sdc_replay`
  - Passed on 1 GPU
- `tests/integration_tests/h100.py::deepseek_v3_fsdp+cp+tp+minimal_async_ep+sdc_replay`
  - Passed for 10 steps on 8 H100 GPUs with identical losses and gradient norms across ranks
- `tests/integration_tests/features.py::sdc_replay_mismatch`
  - Detected the injected rank-0 gradient mismatch on both ranks before the optimizer step
- `git diff --check`
- `pre-commit run --all-files`

stack-info: PR: #4334, branch: xmfan/stack/45
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 26, 2026
Comment thread docs/silent_data_corruption.md Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please put under observability/

configs=[recipes.deepseek_v3_debugmodel_sdc_replay_mismatch],
test_descr="SDC replay detects a distributed gradient mismatch",
test_name="sdc_replay_mismatch",
ngpu=2,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wwwjn should / how should we use this field after the CI refactor? I think the idea is that here we need one real pg test for sdc replay. Do you think this is needed?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ngpu set the world_size. For a single OverrideDefinitions test, it will be run as 1 GPU fake pg test when PR is created / synced, use ngpu to decided the worldsize it mimics. And the same test will also be run on 8GPU real PG when the PR is merged.

If SDC is only runnable on real_pg, you should set use_real_pg=True

Comment on lines +171 to +173
"sdc_replay.enabled",
"sdc_replay.num_replays",
"sdc_replay.num_steps",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we're moving away from CLI args. For SDC let's suppress tyro parsing so that this file is not changed

Comment thread torchtitan/trainer.py Outdated
)
if (
not self.training.disable_cuda_graphs
and is_cudagraph_available()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should error out without this condition?

Comment thread torchtitan/trainer.py Outdated
Comment on lines +225 to +227
"SDC replay with CUDA graphs requires "
"sdc_replay.num_replays=1. Set --sdc-replay.num-replays 1 "
"or --training.disable_cuda_graphs."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please make this message CLI free

Comment thread torchtitan/models/flux/trainer.py Outdated
Comment on lines +286 to +290
def _get_sdc_replay_modules(self) -> Iterable[torch.nn.Module]:
modules = [*self.model_parts, self.t5_encoder, self.clip_encoder]
if self.autoencoder is not None:
modules.append(self.autoencoder)
return modules

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's not worry about flux for now

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's also not worry about ft

Comment thread torchtitan/trainer.py Outdated

def _get_sdc_replay(self) -> SDCReplay:
if self._sdc_replay is None:
self._sdc_replay = SDCReplay(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should build from config

Comment thread torchtitan/trainer.py Outdated
# additional training states
step: int
ntokens_seen: int
sdc_attempt_step: int

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

too vague .. do you mean step_after_checkpoint_load

Comment thread torchtitan/trainer.py Outdated
self.ntokens_seen = 0
# Initialize process-local SDC replay state. This state is not checkpointed.
self.sdc_attempt_step = 0
self._sdc_replay_unit_index = 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is a "unit" and what's the "index" of a unit

@xmfan
xmfan changed the base branch from xmfan/stack/44 to main August 27, 2026 21:36
@xmfan
xmfan changed the base branch from main to xmfan/stack/44 August 27, 2026 21:36
@xmfan
xmfan changed the base branch from xmfan/stack/44 to main August 27, 2026 21:40
xmfan added a commit that referenced this pull request Aug 27, 2026
Add opt-in deterministic replay for detecting silent data corruption during
training.

The Trainer builds an SDCReplayer from config when the feature is enabled and
holds it as self.sdc_replayer (None when disabled). For each optimizer step,
the step's first forward/backward -- one full gradient-accumulation group,
or one complete pipeline schedule under pipeline parallelism -- is routed
through sdc_replayer.run_fwd_bwd, which replay-checks it when scheduled. A
mismatch raises SDCReplayMismatch on every rank before gradient clipping,
optimizer, scheduler, or checkpoint updates can observe corrupted state.

The replayer is built from config with narrow runtime inputs (modules,
device, and a ScalarStateAccessor for ntokens_seen, which the replayed
forward/backward mutates); it does not receive the Trainer. All replay
scheduling state lives inside the replayer; the check schedule is
process-local, not checkpointed, and restarts after checkpoint loading via
reset_schedule.

GraphTrainer shares the same replay boundary by inheriting Trainer.

The feature is disabled by default and has no CLI surface (sdc_replay is
suppressed from tyro parsing); enable it programmatically:

```python
config.debug.deterministic = True
config.sdc_replay.enabled = True
config.sdc_replay.num_steps = 1    # optimizer steps checked after each (re)start; -1 checks every step
config.sdc_replay.num_replays = 1  # re-executions compared against the reference
```

Replay requires debug.deterministic=True and
debug.deterministic_warn_only=False. Eager execution, torch.compile, CUDA
graphs, symmetric-memory FSDP, distributed GEMM, async TP, DeepEP v2,
HybridEP, and MinimalAsyncEP use the same replay boundary. CUDA graphs
require num_replays=1; this is validated purely from config (independent of
runtime CUDA graph availability) because additional replays would require
CUDA-graph-aware restoration of graph-owned gradient and optional-buffer
storage.

After config overrides are applied, Trainer re-runs the full
Config.__post_init__ (raise-only) instead of individual validators.

Document the feature under docs/observability/ and add CPU and GPU coverage
including an intentionally corrupted distributed gradient.

- pytest -q tests/unit_tests/cpu/test_trainer.py
  tests/unit_tests/cpu/observability/test_sdc_replay.py
  tests/unit_tests/cpu/test_invalid_loss.py
  tests/unit_tests/cpu/test_config_manager.py
- tests/integration_tests/features.py::sdc_replay_cudagraph
- torchtitan/experiments/graph_trainer/tests/integration_tests.py::sdc_replay
- tests/integration_tests/h100.py::deepseek_v3_fsdp+cp+tp+minimal_async_ep+sdc_replay
- tests/integration_tests/features.py::sdc_replay_mismatch
- git diff --check
- pre-commit run --all-files

stack-info: PR: #4334, branch: xmfan/stack/45
@xmfan
xmfan changed the base branch from main to xmfan/stack/44 August 27, 2026 21:40

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks very nice!

Only feel a bit mysterious on why we're limited to replay the first step of grad accumulation.

Comment thread torchtitan/trainer.py
modules=self.model_parts,
device=self.device,
scalar_state={
"ntokens_seen": ScalarStateAccessor(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about "step"? I guess the idea is it's not error-prone?

@xmfan xmfan Aug 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sry for the confusion, so right now this exists because the fwd_bwd that is being replayed does self.ntokens_seen += tokens each iteration. SDC needs to reset the state in between capture and replay, but since self.ntokens_seen is not part of the model's nn.module state (as buffer registration), it's hard to reset it properly from outside. This is essentially a reset() mechanism, implemented via manual registration of the mutation.

ntokens_seen is for logging purposes only, so i understand why we don't want it in model code. but if we do add it to the module's buffers, SDC could handle it together with the module.buffers reset.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry to clarify: let's put this under torchtitan/observability/silent_data_corruption.md, as we plan to move all docs to local folders

## What is replayed

Only the first forward/backward of a checked optimizer step is replayed: one
full gradient-accumulation group or, with pipeline parallelism, one complete

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

slightly inaccurate -- gradient accum can be used with or without PP, so even with PP it's replaying a full gradient accumulation step


## What is replayed

Only the first forward/backward of a checked optimizer step is replayed: one

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where's this limitation from -- why can't we replay multiple grad accum steps

@xmfan xmfan Aug 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can add it as an option, it's just more expensive to rerun

@xmfan
xmfan changed the base branch from xmfan/stack/44 to main August 28, 2026 21:42
xmfan added a commit that referenced this pull request Aug 28, 2026
Add opt-in deterministic replay for detecting silent data corruption during
training.

The Trainer builds an SDCReplayer when config.sdc_replay is set and holds it
as self.sdc_replayer (config.sdc_replay is None by default, which disables
replay). For each optimizer step, the step's first forward/backward call --
one gradient-accumulation group, which under pipeline parallelism is one
complete pipeline schedule -- is routed through sdc_replayer.run_fwd_bwd,
which replay-checks it when scheduled. Later accumulation groups exercise
the same compute and communication paths and run unchecked. A mismatch
raises SDCReplayMismatch on every rank before gradient clipping, optimizer,
scheduler, or checkpoint updates can observe corrupted state.

The replayer is built from config with narrow runtime inputs (modules,
device, reset_gradients bound to the same optimizers.zero_grad call
train_step performs before the replay boundary, and a ScalarStateAccessor
for ntokens_seen, which the replayed forward/backward mutates; self.step is
incremented outside the replay boundary and needs no capture); it does not
receive the Trainer. All replay
scheduling state lives inside the replayer; the check schedule is
process-local, not checkpointed, and restarts after checkpoint loading via
reset_schedule.

GraphTrainer shares the same replay boundary by inheriting Trainer.

The feature is disabled by default and has no CLI surface (sdc_replay is
suppressed from tyro parsing); enable it programmatically:

```python
from torchtitan.observability.sdc_replayer import SDCReplayer

config.debug.deterministic = True
config.sdc_replay = SDCReplayer.Config(
    num_steps=1,    # optimizer steps checked after each (re)start; -1 checks every step
    num_replays=1,  # re-executions compared against the reference
)
```

Replay requires debug.deterministic=True and
debug.deterministic_warn_only=False. Eager execution, torch.compile, CUDA
graphs, symmetric-memory FSDP, distributed GEMM, async TP, DeepEP v2,
HybridEP, and MinimalAsyncEP use the same replay boundary. CUDA graphs
require num_replays=1; this is validated purely from config (independent of
runtime CUDA graph availability) because additional replays would require
CUDA-graph-aware restoration of graph-owned gradient and optional-buffer
storage.

After config overrides are applied, Trainer re-runs the full
Config.__post_init__ (raise-only) instead of individual validators.

Document the feature under torchtitan/observability/ and add CPU and GPU
coverage including an intentionally corrupted distributed gradient. The
sdc_replay_mismatch integration test sets use_real_pg=True because
cross-rank mismatch propagation (all_reduce and all_gather_object) needs
real collectives.

- pytest -q tests/unit_tests/cpu/test_trainer.py
  tests/unit_tests/cpu/observability/test_sdc_replayer.py
  tests/unit_tests/cpu/test_invalid_loss.py
  tests/unit_tests/cpu/test_config_manager.py
- tests/integration_tests/features.py::sdc_replay_cudagraph
- torchtitan/experiments/graph_trainer/tests/integration_tests.py::sdc_replay
- tests/integration_tests/h100.py::deepseek_v3_fsdp+cp+tp+minimal_async_ep+sdc_replay
- tests/integration_tests/features.py::sdc_replay_mismatch
- git diff --check
- pre-commit run --all-files

stack-info: PR: #4334, branch: xmfan/stack/45
@xmfan
xmfan changed the base branch from main to xmfan/stack/44 August 28, 2026 21:42
@xmfan
xmfan changed the base branch from xmfan/stack/44 to main August 28, 2026 22:50
xmfan added a commit that referenced this pull request Aug 28, 2026
Add opt-in deterministic replay for detecting silent data corruption during
training.

The Trainer builds an SDCReplayer when config.sdc_replay is set and holds it
as self.sdc_replayer (config.sdc_replay is None by default, which disables
replay). For each optimizer step, the step's first forward/backward call --
one gradient-accumulation group, which under pipeline parallelism is one
complete pipeline schedule -- is routed through sdc_replayer.run_fwd_bwd,
which replay-checks it when scheduled. Later accumulation groups exercise
the same compute and communication paths and run unchecked. A mismatch
raises SDCReplayMismatch on every rank before gradient clipping, optimizer,
scheduler, or checkpoint updates can observe corrupted state.

The replayer is built from config with narrow runtime inputs (modules,
device, and a ScalarStateAccessor for ntokens_seen, which the replayed
forward/backward mutates; self.step is incremented outside the replay
boundary and needs no capture); it does not receive the Trainer. train_step
enters the replay boundary right after optimizers.zero_grad, satisfying the
replayer's empty-entry-gradients contract. All replay
scheduling state lives inside the replayer; the check schedule is
process-local, not checkpointed, and restarts after checkpoint loading via
reset_schedule.

GraphTrainer shares the same replay boundary by inheriting Trainer.

The feature is disabled by default and has no CLI surface (sdc_replay is
suppressed from tyro parsing); enable it programmatically:

```python
from torchtitan.observability.sdc_replayer import SDCReplayer

config.debug.deterministic = True
config.sdc_replay = SDCReplayer.Config(
    num_steps=1,    # optimizer steps checked after each (re)start; -1 checks every step
    num_replays=1,  # re-executions compared against the reference
)
```

Replay requires debug.deterministic=True and
debug.deterministic_warn_only=False. Eager execution, torch.compile, CUDA
graphs, symmetric-memory FSDP, distributed GEMM, async TP, DeepEP v2,
HybridEP, and MinimalAsyncEP use the same replay boundary. CUDA graphs
require num_replays=1; this is validated purely from config (independent of
runtime CUDA graph availability) because additional replays would require
CUDA-graph-aware restoration of graph-owned gradient and optional-buffer
storage.

After config overrides are applied, Trainer re-runs the full
Config.__post_init__ (raise-only) instead of individual validators.

Document the feature under torchtitan/observability/ and add CPU and GPU
coverage including an intentionally corrupted distributed gradient. The
sdc_replay_mismatch integration test sets use_real_pg=True because
cross-rank mismatch propagation (all_reduce and all_gather_object) needs
real collectives.

- pytest -q tests/unit_tests/cpu/test_trainer.py
  tests/unit_tests/cpu/observability/test_sdc_replayer.py
  tests/unit_tests/cpu/test_invalid_loss.py
  tests/unit_tests/cpu/test_config_manager.py
- tests/integration_tests/features.py::sdc_replay_cudagraph
- torchtitan/experiments/graph_trainer/tests/integration_tests.py::sdc_replay
- tests/integration_tests/h100.py::deepseek_v3_fsdp+cp+tp+minimal_async_ep+sdc_replay
- tests/integration_tests/features.py::sdc_replay_mismatch
- git diff --check
- pre-commit run --all-files

stack-info: PR: #4334, branch: xmfan/stack/45
@xmfan
xmfan changed the base branch from main to xmfan/stack/44 August 28, 2026 22:50
@xmfan
xmfan marked this pull request as ready for review August 28, 2026 22:52
Comment thread torchtitan/trainer.py Outdated
# NOTE: sdc_replay is suppressed from tyro CLI parsing; enable it
# programmatically in a config/recipe by assigning a config
# (config.sdc_replay = SDCReplayer.Config()). None disables replay.
sdc_replay: Annotated[SDCReplayer.Config | None, tyro.conf.Suppress] = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
sdc_replay: Annotated[SDCReplayer.Config | None, tyro.conf.Suppress] = None
sdc_replayer: Annotated[SDCReplayer.Config | None, tyro.conf.Suppress] = None

xmfan added a commit that referenced this pull request Aug 31, 2026
Stacked PRs:
 * #4334
 * __->__#4333


--- --- ---

### [SDC] Add deterministic replay engine


Add a model-agnostic deterministic replay engine for detecting silent
data
corruption across repeated forward/backward executions.

For each checked optimizer step, SDCReplayer:

1. captures the semantic baseline state;
2. executes the step's first forward/backward and records a reference
   signature;
3. restores the baseline before every replay;
4. compares each replay with the reference across all ranks; and
5. discards the reference and intermediate executions so only the final
   matching execution remains committed.

The checked forward/backward is one gradient-accumulation group, which
under
pipeline parallelism is one complete pipeline schedule; when a step has
multiple accumulation groups only the first is checked, a cost choice
rather
than an engine limitation since the engine replays any forward/backward
callable.

The captured state includes Python, CPU, and accelerator RNG state,
registered module buffers, and caller-owned scalars passed through
ScalarStateAccessor (e.g. a token counter the forward/backward mutates).
Gradient values are never snapshotted: run_fwd_bwd requires entry
gradients
to be empty (None or zeros, the post-zero_grad state), and restore
rebuilds
that entry state directly from per-parameter None markers and tensor
identities -- parameters that entered without a gradient return to None,
and entry gradient tensors are zeroed in place. This avoids
gradient-sized
clone and copy kernels on checked steps while keeping gradient storage
addresses stable for CUDA graphs, without coupling the engine to any
caller-provided reset. Replay signatures cover
the loss, gradients, buffers, RNG advancement, and scalar state, with
DTensors compared and restored through their local shards.

SDCReplayer follows the Configurable pattern with a nested Config
validated
in __post_init__, and lives in torchtitan/observability/sdc_replayer.py
next
to the other observability components. The Config carries no enabled
flag:
callers express "disabled" by not constructing a replayer.
Module-internal
signature and snapshot types are underscore-private; the public surface
is
SDCReplayer, ScalarStateAccessor, and SDCReplayMismatch. The replayer
owns
its check schedule: run_fwd_bwd counts the optimizer steps it has seen
(steps_since_reset) and checks the first num_steps of them;
reset_schedule
restarts the count (e.g. after a checkpoint load). A mismatch raises
SDCReplayMismatch on every rank, reporting the global step, the step's
position in the current check schedule (local_step), the replay number,
the
originating rank, and the first divergent signature entry.

Tensor digests remain on-device and are compared as one batch. The
matching
path performs one host synchronization after the distributed mismatch
reduction; detailed per-entry comparison runs only after a mismatch. The
implementation uses the existing XOR-based torch.hash_tensor mode; that
checksum is order-insensitive, so permutations and some repeated-value
corruptions can collide. Unregistered execution scratch state is
intentionally outside the replay contract when each invocation
overwrites it
before reading it.

- pytest -q tests/unit_tests/cpu/observability/test_sdc_replayer.py
  - 18 passed

Coverage includes state restoration, final-execution commit semantics,
compiled execution, DTensor state, replay scheduling and re-arming,
batched
digest comparison, and local and remote mismatch reporting.
@xmfan
xmfan changed the base branch from xmfan/stack/44 to main August 31, 2026 18:20
xmfan added a commit that referenced this pull request Aug 31, 2026
Add opt-in deterministic replay for detecting silent data corruption during
training.

The Trainer builds an SDCReplayer when config.sdc_replay is set and holds it
as self.sdc_replayer (config.sdc_replay is None by default, which disables
replay). For each optimizer step, the step's first forward/backward call --
one gradient-accumulation group, which under pipeline parallelism is one
complete pipeline schedule -- is routed through sdc_replayer.run_fwd_bwd,
which replay-checks it when scheduled. Later accumulation groups exercise
the same compute and communication paths and run unchecked. A mismatch
raises SDCReplayMismatch on every rank before gradient clipping, optimizer,
scheduler, or checkpoint updates can observe corrupted state.

The replayer is built from config with narrow runtime inputs (modules,
device, and a ScalarStateAccessor for ntokens_seen, which the replayed
forward/backward mutates; self.step is incremented outside the replay
boundary and needs no capture); it does not receive the Trainer. train_step
enters the replay boundary right after optimizers.zero_grad, satisfying the
replayer's empty-entry-gradients contract. All replay
scheduling state lives inside the replayer; the check schedule is
process-local, not checkpointed, and restarts after checkpoint loading via
reset_schedule.

GraphTrainer shares the same replay boundary by inheriting Trainer.

The feature is disabled by default and has no CLI surface (sdc_replay is
suppressed from tyro parsing); enable it programmatically:

```python
from torchtitan.observability.sdc_replayer import SDCReplayer

config.debug.deterministic = True
config.sdc_replay = SDCReplayer.Config(
    num_steps=1,    # optimizer steps checked after each (re)start; -1 checks every step
    num_replays=1,  # re-executions compared against the reference
)
```

Replay requires debug.deterministic=True and
debug.deterministic_warn_only=False. Eager execution, torch.compile, CUDA
graphs, symmetric-memory FSDP, distributed GEMM, async TP, DeepEP v2,
HybridEP, and MinimalAsyncEP use the same replay boundary. CUDA graphs
require num_replays=1; this is validated purely from config (independent of
runtime CUDA graph availability) because additional replays would require
CUDA-graph-aware restoration of graph-owned gradient and optional-buffer
storage.

After config overrides are applied, Trainer re-runs the full
Config.__post_init__ (raise-only) instead of individual validators.

Document the feature under torchtitan/observability/ and add CPU and GPU
coverage including an intentionally corrupted distributed gradient. The
sdc_replay_mismatch integration test sets use_real_pg=True because
cross-rank mismatch propagation (all_reduce and all_gather_object) needs
real collectives.

- pytest -q tests/unit_tests/cpu/test_trainer.py
  tests/unit_tests/cpu/observability/test_sdc_replayer.py
  tests/unit_tests/cpu/test_invalid_loss.py
  tests/unit_tests/cpu/test_config_manager.py
- tests/integration_tests/features.py::sdc_replay_cudagraph
- torchtitan/experiments/graph_trainer/tests/integration_tests.py::sdc_replay
- tests/integration_tests/h100.py::deepseek_v3_fsdp+cp+tp+minimal_async_ep+sdc_replay
- tests/integration_tests/features.py::sdc_replay_mismatch
- git diff --check
- pre-commit run --all-files

stack-info: PR: #4334, branch: xmfan/stack/45
xmfan added a commit that referenced this pull request Aug 31, 2026
Add opt-in deterministic replay for detecting silent data corruption during
training.

The Trainer builds an SDCReplayer when config.sdc_replay is set and holds it
as self.sdc_replayer (config.sdc_replay is None by default, which disables
replay). For each optimizer step, the step's first forward/backward call --
one gradient-accumulation group, which under pipeline parallelism is one
complete pipeline schedule -- is routed through sdc_replayer.run_fwd_bwd,
which replay-checks it when scheduled. Later accumulation groups exercise
the same compute and communication paths and run unchecked. A mismatch
raises SDCReplayMismatch on every rank before gradient clipping, optimizer,
scheduler, or checkpoint updates can observe corrupted state.

The replayer is built from config with narrow runtime inputs (modules,
device, and a ScalarStateAccessor for ntokens_seen, which the replayed
forward/backward mutates; self.step is incremented outside the replay
boundary and needs no capture); it does not receive the Trainer. train_step
enters the replay boundary right after optimizers.zero_grad, satisfying the
replayer's empty-entry-gradients contract. All replay
scheduling state lives inside the replayer; the check schedule is
process-local, not checkpointed, and restarts after checkpoint loading via
reset_schedule.

GraphTrainer shares the same replay boundary by inheriting Trainer.

The feature is disabled by default and has no CLI surface (sdc_replay is
suppressed from tyro parsing); enable it programmatically:

```python
from torchtitan.observability.sdc_replayer import SDCReplayer

config.debug.deterministic = True
config.sdc_replay = SDCReplayer.Config(
    num_steps=1,    # optimizer steps checked after each (re)start; -1 checks every step
    num_replays=1,  # re-executions compared against the reference
)
```

Replay requires debug.deterministic=True and
debug.deterministic_warn_only=False. Eager execution, torch.compile, CUDA
graphs, symmetric-memory FSDP, distributed GEMM, async TP, DeepEP v2,
HybridEP, and MinimalAsyncEP use the same replay boundary. CUDA graphs
require num_replays=1; this is validated purely from config (independent of
runtime CUDA graph availability) because additional replays would require
CUDA-graph-aware restoration of graph-owned gradient and optional-buffer
storage.

After config overrides are applied, Trainer re-runs the full
Config.__post_init__ (raise-only) instead of individual validators.

Document the feature under torchtitan/observability/ and add CPU and GPU
coverage including an intentionally corrupted distributed gradient. The
sdc_replay_mismatch integration test sets use_real_pg=True because
cross-rank mismatch propagation (all_reduce and all_gather_object) needs
real collectives.

- pytest -q tests/unit_tests/cpu/test_trainer.py
  tests/unit_tests/cpu/observability/test_sdc_replayer.py
  tests/unit_tests/cpu/test_invalid_loss.py
  tests/unit_tests/cpu/test_config_manager.py
- tests/integration_tests/features.py::sdc_replay_cudagraph
- torchtitan/experiments/graph_trainer/tests/integration_tests.py::sdc_replay
- tests/integration_tests/h100.py::deepseek_v3_fsdp+cp+tp+minimal_async_ep+sdc_replay
- tests/integration_tests/features.py::sdc_replay_mismatch
- git diff --check
- pre-commit run --all-files

stack-info: PR: #4334, branch: xmfan/stack/45
Add opt-in deterministic replay for detecting silent data corruption during
training.

The Trainer builds an SDCReplayer when config.sdc_replay is set and holds it
as self.sdc_replayer (config.sdc_replay is None by default, which disables
replay). For each optimizer step, the step's first forward/backward call --
one gradient-accumulation group, which under pipeline parallelism is one
complete pipeline schedule -- is routed through sdc_replayer.run_fwd_bwd,
which replay-checks it when scheduled. Later accumulation groups exercise
the same compute and communication paths and run unchecked. A mismatch
raises SDCReplayMismatch on every rank before gradient clipping, optimizer,
scheduler, or checkpoint updates can observe corrupted state.

The replayer is built from config with narrow runtime inputs (modules,
device, and a ScalarStateAccessor for ntokens_seen, which the replayed
forward/backward mutates; self.step is incremented outside the replay
boundary and needs no capture); it does not receive the Trainer. train_step
enters the replay boundary right after optimizers.zero_grad, satisfying the
replayer's empty-entry-gradients contract. All replay
scheduling state lives inside the replayer; the check schedule is
process-local, not checkpointed, and restarts after checkpoint loading via
reset_schedule.

GraphTrainer shares the same replay boundary by inheriting Trainer.

The feature is disabled by default and has no CLI surface (sdc_replay is
suppressed from tyro parsing); enable it programmatically:

```python
from torchtitan.observability.sdc_replayer import SDCReplayer

config.debug.deterministic = True
config.sdc_replay = SDCReplayer.Config(
    num_steps=1,    # optimizer steps checked after each (re)start; -1 checks every step
    num_replays=1,  # re-executions compared against the reference
)
```

Replay requires debug.deterministic=True and
debug.deterministic_warn_only=False. Eager execution, torch.compile, CUDA
graphs, symmetric-memory FSDP, distributed GEMM, async TP, DeepEP v2,
HybridEP, and MinimalAsyncEP use the same replay boundary. CUDA graphs
require num_replays=1; this is validated purely from config (independent of
runtime CUDA graph availability) because additional replays would require
CUDA-graph-aware restoration of graph-owned gradient and optional-buffer
storage.

After config overrides are applied, Trainer re-runs the full
Config.__post_init__ (raise-only) instead of individual validators.

Document the feature under torchtitan/observability/ and add CPU and GPU
coverage including an intentionally corrupted distributed gradient. The
sdc_replay_mismatch integration test sets use_real_pg=True because
cross-rank mismatch propagation (all_reduce and all_gather_object) needs
real collectives.

- pytest -q tests/unit_tests/cpu/test_trainer.py
  tests/unit_tests/cpu/observability/test_sdc_replayer.py
  tests/unit_tests/cpu/test_invalid_loss.py
  tests/unit_tests/cpu/test_config_manager.py
- tests/integration_tests/features.py::sdc_replay_cudagraph
- torchtitan/experiments/graph_trainer/tests/integration_tests.py::sdc_replay
- tests/integration_tests/h100.py::deepseek_v3_fsdp+cp+tp+minimal_async_ep+sdc_replay
- tests/integration_tests/features.py::sdc_replay_mismatch
- git diff --check
- pre-commit run --all-files

stack-info: PR: #4334, branch: xmfan/stack/45
@xmfan
xmfan merged commit 4ab7596 into main Aug 31, 2026
19 of 20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants