Skip to content

[SDC] Add deterministic replay engine - #4333

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

xmfan merged 1 commit into
mainfrom
xmfan/stack/44

Conversation

@xmfan

@xmfan xmfan commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


[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.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 26, 2026

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.

folder recently refactored -- need to put in either cpu/ or gpu/

Comment thread torchtitan/distributed/sdc_replay.py Outdated
num_replays: int = 1
"""Number of candidate executions compared with the reference execution."""

def validate(self) -> 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.

just do __post_init__

Comment thread torchtitan/distributed/sdc_replay.py Outdated
class SDCReplay:
"""Coordinates state restoration, repeated execution, and comparison."""

Config = SDCReplayConfig

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.

Can just define it here as SDCReplay.Config (take Trainer.Config as an example)

Comment thread torchtitan/distributed/sdc_replay.py Outdated
"""Enable deterministic forward/backward replay for SDC detection."""

num_steps: int = 1
"""Number of attempt-local optimizer steps to check; -1 checks every step."""

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.

"attempt-local" sounds confusing, could you expand a bit?

Comment thread torchtitan/distributed/sdc_replay.py Outdated
num_steps: int = 1
"""Number of attempt-local optimizer steps to check; -1 checks every step."""

num_replays: int = 1

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.

As someone who doesn't know exactly when and what span SDC is replaying, the two fields are hard difficult for me to understand.

  • would appreciate more education
  • is this the only way of doing SDC replay?

Comment thread torchtitan/distributed/sdc_replay.py Outdated
"""Number of attempt-local optimizer steps to check; -1 checks every step."""

num_replays: int = 1
"""Number of candidate executions compared with the reference execution."""

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 "candidate execution" unit?

Comment thread torchtitan/distributed/sdc_replay.py Outdated
return None


class 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.

Suggested change
class SDCReplay:
class SDCReplayer:

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.

not very distributed to me, maybe should put under observability/

@xmfan
xmfan force-pushed the xmfan/stack/44 branch 2 times, most recently from 9dfc9b2 to 7640988 Compare August 27, 2026 21:40

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 rename to sdc_replayer.py to be consistent with structured_logger and tensor_logger (wip) in this folder

Comment thread torchtitan/observability/sdc_replay.py Outdated


@dataclass(frozen=True, slots=True)
class ReplaySignature:

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 this be

Suggested change
class ReplaySignature:
class _ReplaySignature:

if it's only used within this file; similar comment to other dataclasses

Comment thread torchtitan/observability/sdc_replay.py Outdated

@dataclass(kw_only=True, slots=True)
class Config(Configurable.Config):
enabled: bool = False

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.

I'd prefer not having this field, and rely on sdc_replayer being None or not to trigger it.

There's some historical reason to use enabled style args (e.g. CLI), but we are moving away.

Comment on lines +201 to +210
gradients = tuple(
_GradientSnapshot(
parameter=parameter,
original=parameter.grad,
value=(
None if parameter.grad is None else _clone_tensor(parameter.grad)
),
)
for parameter in parameters
)

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.

If we are only playing the first step of grad accumulation, why we'd need to capture this?

@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 do need to capture the param.grad to reset the state to before the reference capture. If we don't do the clone, we could branch again on CG zero_grad(set_to_none=self.config.training.disable_cuda_graphs), grads can be None or zero tensor. I like the decoupling copying buys you, but it does come at a copy kernel cost.

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.

changed my mind, perf is important if we want to have sdc run periodically and grads are large. The common case should be either None grads or zero grads, so let's bake it in. I added docstrings to SDCReplayer, but did not add any checks that would introduce more kernels.

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.

Then that means we couldn't replay other than the first grad accum step, which is fine for now.

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.

stack-info: PR: #4333, branch: xmfan/stack/44
@xmfan
xmfan marked this pull request as ready for review August 28, 2026 22:52
@xmfan
xmfan requested review from fegin, wconstab and wwwjn as code owners August 28, 2026 22:52
@xmfan
xmfan merged commit 9b1303c into main Aug 31, 2026
24 of 25 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.

2 participants