Skip to content

Pull in upstream - #3

Merged
saforem2 merged 5 commits into
saforem2:mainfrom
pytorch:main
Oct 9, 2025
Merged

saforem2 merged 5 commits into
saforem2:mainfrom
pytorch:main

Conversation

@saforem2

@saforem2 saforem2 commented Oct 9, 2025 •

Copy link
Copy Markdown
Owner

Copilot Summary

This pull request introduces several important enhancements and fixes to checkpointing, profiling, and model configuration, with a focus on supporting quantized HuggingFace checkpoints, advanced RoPE scaling for Llama4 models, and improved distributed training consistency.

Checkpointing and Quantized Checkpoint Support:

  • Added support for loading HuggingFace safetensors format with quantized state dict keys by introducing the initial_load_in_hf_quantized option in the Checkpoint config and updating the checkpoint loading logic to handle quantized checkpoints. This includes new assertions and parameter propagation throughout the checkpoint loading pipeline. [1] [2] [3] [4] [5] [6] [7]

Profiling Configuration Enhancements:

  • Added profiler_active and profiler_warmup options to the profiling configuration, allowing finer control over torch profiler scheduling and warmup steps.

Llama4 Model RoPE Scaling Improvements:

  • Introduced the RoPEScalingArgs dataclass and integrated it into the Llama4 model configuration and frequency computation logic. This enables advanced scaling of rotary positional embeddings, supporting longer context lengths and flexible frequency scaling. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

Distributed Training and Gradient Reduction Consistency:

  • Implemented a _ScaledPartial placement class and updated the FSDP/simple_fsdp logic to allow custom scaling of gradient reduction (via reduction_divide_factor). This ensures correct gradient averaging when using expert parallelism and aligns with the data parallel mesh. [1] [2] [3] [4] [5]

Determinism and Reproducibility:

  • Ensured that flex_attention is compiled without max-autotune in set_determinism to guarantee reproducibility in distributed runs.

Other Notable Changes:

  • Adjusted the DeepSeek V3 model configuration for testing by reducing the number of layers from 61 to 4.
  • Minor import cleanups and dependency adjustments.

These changes collectively improve model flexibility, reproducibility, and distributed training correctness, while expanding support for advanced checkpointing and model scaling techniques.

Summary by Sourcery

Add quantized HuggingFace checkpoint support, advanced RoPE scaling for Llama models, and custom gradient reduction scaling for distributed training, alongside profiling enhancements and reproducibility fixes

New Features:

  • Enable loading of quantized HuggingFace safetensors via initial_load_in_hf_quantized and QuantizedHuggingFaceStorageReader
  • Introduce RoPEScalingArgs and apply advanced rotary positional embedding scaling in Llama3 and Llama4
  • Support custom reduction_divide_factor in simple_fsdp using a new _ScaledPartial placement for correct gradient averaging

Enhancements:

  • Add profiler_active and profiler_warmup options to configure torch.profiler scheduling
  • Ensure FlexAttention is compiled without max-autotune for deterministic distributed runs

Chores:

  • Reduce DeepSeek V3 model layers from 61 to 4 for testing
  • Apply minor import cleanups and formatting adjustments

wwwjn and others added 5 commits October 8, 2025 10:19
## Benchmarking
<meta charset="utf-8"><b style="font-weight:normal;"
id="docs-internal-guid-852d634c-7fff-a3ae-72e8-d17e64bb4b2c"><div
dir="ltr" style="margin-left:0pt;" align="center">
Step | time | log
-- | -- | --
to_hf() | 0.1103s | [trainer0\|0]:[titan] 2025-10-03 17:07:45,697 - root
- INFO - Completed to_hf conversion, generated 189 keys, duration:
0.1103s
Split local GroupedExperts DTensor to individual experts’ weight | 0.008
s per layer per matrix (total 58 MoE Layers * 3 weight matrices per
layer) | [trainer0\|0]:[titan] 2025-10-03 17:07:45,697 - root - INFO -
Completed _get_local_experts_weights for layer 6, abstract_key:
model.layers.{}.mlp.experts.{}.up_proj.weight, duration: 0.0082s
dcp.load()Threads count=4 | 193.20s | [trainer0\|0]:[titan] 2025-10-03
17:10:58,899 - root - INFO - dcp.load with HuggingFaceStorageReader
completed in 193.20 seconds
from_hf() | 0.48s | [trainer0\|0]:[titan] 2025-10-03 17:10:59,378 - root
- INFO - Completed from_hf conversion, processed 189 keys, duration:
0.4787s
Concatenate individual experts weight into GroupedExperts weight | 0.01s
per layer per matrix (total 58 MoE Layers * 3 weight matrices) |
[trainer0\|0]:[titan] 2025-10-03 17:10:59,120 - root - INFO - Completed
_concatenate_expert_weights_dtensor for layer 5, abstract_key:
layers.{}.moe.experts.w2, duration: 0.0142s
Total | 193.87s | [trainer0\|0]:[titan] 2025-10-03 17:10:59,458 - root -
INFO - Finished loading the checkpoint in 193.87 seconds.

</div></b>

## End-to-End verification for 671B model
Parallelsim: FSDP=32, PP=8, 1F1B, EP=32

<img width="393" height="421" alt="Screenshot 2025-10-06 at 8 32 37 PM"
src="https://github.com/user-attachments/assets/6d8dab00-a188-4c57-8348-02bae1d21d03"
/>
<img width="393" height="421" alt="Screenshot 2025-10-06 at 8 32 54 PM"
src="https://github.com/user-attachments/assets/a730f71b-3dc8-45e0-8d3e-b21080884f8d"
/>
With max-autotune, FlexAttention is not deterministic even if
torch.use_deterministic_algorithms is True. When deterministic mode is
set, we should also remove the usage of `max-autotune`.
Summary:
allow users to specify the profiler schedule

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with
[ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/1809).
* #1811
* #1810
* #1812
* __->__ #1809

Co-authored-by: Tushar Jain <[email protected]>
this PR is a followup of SimpleFSDP+EP
[PR](#1529). Here, we add a
`gradient_divide_factor` following FSDP2 to ensure modules wrapped by
(FSDP+EP) has the correct gradient reduction value.

- The original FSDP2 implementation is in this
[PR](#1551).
- The `gradient_divide_factor` logic is
[here](https://github.com/pytorch/pytorch/blob/main/torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py#L688)

We have two ways of handling `gradient_divide_factor` in
`reduce_scatter`:

1. The first one is to use `ReduceOp.PREMUL_SUM` to handle the
`gradient_divide_factor`. However, DTensor's `_reduce_shard_value` only
accepts `reduce_op` as a str input
([here](https://github.com/pytorch/pytorch/blob/8f705d019a64b1ca882e043b3eb98559273a9e59/torch/distributed/tensor/placement_types.py#L177-L210)).

To make` _reduce_shard_value` work correctly with ReduceOp.PREMUL_SUM,
we need to update the DTensor `_reduce_shard_tensor` and
`torch.distributed._functional_collectives.reduce_scatter_tensor` so
that it can pass the factor associated with ReduceOp.PREMUL_SUM as an
input.



2. Another way is to simulate `ReduceOp.PREMUL_SUM` with `ReduceOp.SUM`.
The logic is in this [Diff](https://www.internalfb.com/diff/D76546536).
It does a `div_` over gradient before performing `ReduceOp.SUM`.

Currently I'm following 2 since it is requires less change to
`_functional_collectives`.


After enabling `reduction_divide_factor`, we will see FSDP(=2) + EP (=4)
have identical loss:

<img width="1194" height="780" alt="Screenshot 2025-10-08 at 5 27 24 PM"
src="https://github.com/user-attachments/assets/aaf83109-8db8-4051-973d-c7b6950513de"
/>
Llama 3.1 models use scaled RoPE by default, and Llama 4 17B x 16E uses
scaled RoPE while 17B x 128E does not.

1. Verified forward parity between Titan Llama 3.1 8B and HuggingFace
Llama 3.1 8B. The KL divergence of outputs from the same sample inputs
is small.
![llama 3 8b forward parity
small](https://github.com/user-attachments/assets/891df89b-006f-4ed0-a68a-36e939d2169b)

For comparison, before adding scaled RoPE support, the forward parity
check on the Llama 3.1 8B model incurred a slightly larger KL divergence
on sample inputs.
![llama 3 8b forward parity without scaled
rope](https://github.com/user-attachments/assets/9a68357a-34d4-497f-977f-27cc548d8f62)

2. Verified training of Llama 3.1 8B with tensor parallel degree = 4.
![llama 3-1 8b training
tp=4](https://github.com/user-attachments/assets/a8b1ab10-0da0-4d02-afbb-a775716beaa3)

3. Verified training of Llama 4 debug model with scaled RoPE.
![llama 4 debug model
training](https://github.com/user-attachments/assets/1fbf8939-31a5-475f-987c-d5bcf6d2376b)
@sourcery-ai

sourcery-ai Bot commented Oct 9, 2025 •

Copy link
Copy Markdown

Reviewer's Guide

This PR integrates quantized HuggingFace checkpoint loading, refines profiling scheduling options, adds advanced RoPE scaling in Llama3/4, implements custom gradient reduction scaling for FSDP, and enhances determinism for flex_attention, alongside minor model and import cleanups.

Class diagram for RoPEScalingArgs and TransformerModelArgs in Llama3/Llama4

classDiagram
    class RoPEScalingArgs {
        +float scaling_factor
        +float low_freq_factor
        +float high_freq_factor
        +int original_max_position_embeddings
    }
    class TransformerModelArgs {
        +int dim
        +int n_layers
        +int n_heads
        +int vocab_size
        +float norm_eps
        +float rope_theta
        +RoPEScalingArgs rope_scaling_args
        +int max_seq_len
        ...
    }
    TransformerModelArgs --> RoPEScalingArgs : uses
Loading

Class diagram for DeepSeekV3StateDictAdapter and HuggingFaceStorageReader

classDiagram
    class DeepSeekV3StateDictAdapter {
        +get_hf_storage_reader(path: str, from_quantized: bool): HuggingFaceStorageReader
        +to_hf(state_dict: dict): dict
        +from_hf(hf_state_dict: dict): dict
    }
    class HuggingFaceStorageReader {
        +path: str
    }
    class QuantizedHuggingFaceStorageReader {
        +path: str
        +target_dtype: torch.dtype
        +block_size: int
        +thread_count: int
    }
    DeepSeekV3StateDictAdapter --> HuggingFaceStorageReader : returns
    DeepSeekV3StateDictAdapter --> QuantizedHuggingFaceStorageReader : returns (if quantized)
Loading

File-Level Changes

Change Details Files
Support for loading quantized HF safetensors checkpoints
  • Add initial_load_in_hf_quantized flag to Checkpoint config
  • Propagate from_quantized through checkpoint loading and dcp_load
  • Define abstract get_hf_storage_reader in StateDictAdapter
  • Override reader in DeepSeekV3 adapter to use QuantizedHuggingFaceStorageReader
  • Remove manual dequantization and scale-insertion methods
torchtitan/config/job_config.py
torchtitan/components/checkpoint.py
torchtitan/protocols/state_dict_adapter.py
torchtitan/models/deepseek_v3/model/state_dict_adapter.py
Enhanced profiling schedule parameters
  • Add profiler_warmup and profiler_active options to Profiling config
  • Use new warmup and active values in torch profiler schedule
  • Update profiling tool logic to derive wait from warmup and active
torchtitan/config/job_config.py
torchtitan/tools/profiling.py
Advanced RoPE scaling arguments integrated in Llama4 models
  • Introduce RoPEScalingArgs dataclass in llama4 args
  • Extend precompute_freqs_cis to accept and apply scaling_args
  • Pass rope_scaling_args in model’s _precompute_freqs_cis
  • Set default rope_scaling_args in Llama4 experiment configs
torchtitan/experiments/llama4/model/args.py
torchtitan/experiments/llama4/model/model.py
torchtitan/experiments/llama4/__init__.py
Advanced RoPE scaling arguments integrated in Llama3 models
  • Add RoPEScalingArgs dataclass in llama3 args
  • Modify precompute_freqs_cis signature and logic for scaling
  • Include rope_scaling_args in precompute calls
torchtitan/models/llama3/model/args.py
torchtitan/models/llama3/model/model.py
Custom gradient reduction scaling in FSDP/Partial placements
  • Create _ScaledPartial subclass allowing reduction_divide_factor
  • Use _ScaledPartial for grad_placements in simple_fsdp
  • Propagate reduction_divide_factor through data_parallel and DeepSeekV3 parallelize
torchtitan/experiments/simple_fsdp/simple_fsdp.py
torchtitan/experiments/simple_fsdp/deepseek_v3/parallelize.py
Ensure reproducibility by compiling flex_attention deterministically
  • Import flex_attention and recompile in set_determinism without max-autotune
torchtitan/distributed/utils.py
Miscellaneous model and import adjustments
  • Reduce DeepSeek V3 layer count from 61 to 4 for testing
  • Clean up stale quantization import and remove quantization.py
  • Fix toml boolean formatting in DeepSeekV3 train config
torchtitan/models/deepseek_v3/__init__.py
torchtitan/models/deepseek_v3/model/quantization.py
torchtitan/models/deepseek_v3/train_configs/deepseek_v3_671b.toml

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@saforem2
saforem2 merged commit 871f15c into saforem2:main Oct 9, 2025

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes - here's some feedback:

  • Avoid using list multiplication for grad_placements as it reuses the same _ScaledPartial instance across dimensions—use a list comprehension to create a fresh object per axis.
  • You’ve duplicated RoPEScalingArgs in both llama3 and llama4 modules with slight default differences—consider extracting it to a shared location to reduce code duplication and drift.
  • In your RoPE scaling interpolation logic, capture the original frequency tensor before you apply scaling so that the linear blend uses the correct unmodified baseline frequencies for smoothing.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Avoid using list multiplication for grad_placements as it reuses the same _ScaledPartial instance across dimensions—use a list comprehension to create a fresh object per axis.
- You’ve duplicated RoPEScalingArgs in both llama3 and llama4 modules with slight default differences—consider extracting it to a shared location to reduce code duplication and drift.
- In your RoPE scaling interpolation logic, capture the original frequency tensor before you apply scaling so that the linear blend uses the correct unmodified baseline frequencies for smoothing.

## Individual Comments

### Comment 1
<location> `torchtitan/models/llama3/model/model.py:21-25` </location>
<code_context>


-def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0) -> torch.Tensor:
+def precompute_freqs_cis(
+    dim: int,
+    end: int,
</code_context>

<issue_to_address>
**issue (bug_risk):** Default argument instantiation may lead to unexpected shared state.

Mutable default arguments can result in shared state across function calls. Use None as the default and instantiate RoPEScalingArgs within the function to avoid this issue.
</issue_to_address>

### Comment 2
<location> `torchtitan/experiments/simple_fsdp/simple_fsdp.py:52-61` </location>
<code_context>
     reduce_dtype: Optional[torch.dtype] = None


+class _ScaledPartial(Partial):
+    # A subclass of Partial placement that allows user to perform reduction with a custom
+    # factor (reduction_divide_factor) other than the default world size.
+    def __init__(
+        self,
+        reduction_divide_factor: float,
+    ):
+        self.reduction_divide_factor = reduction_divide_factor
+        super().__init__(reduce_op="sum")
+
+    def _reduce_value(
+        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
+    ) -> torch.Tensor:
+        # for all_reduce in DDP
+        tensor.div_(self.reduction_divide_factor)
+        reduced = super()._reduce_value(tensor, mesh, mesh_dim)
+        return reduced
+
</code_context>

<issue_to_address>
**suggestion:** Custom reduction logic may cause numerical instability for non-integer divide factors.

Rounding errors may occur if reduction_divide_factor is not an integer or not equal to the world size. Please validate or document the acceptable values for this parameter.
</issue_to_address>

### Comment 3
<location> `torchtitan/experiments/simple_fsdp/simple_fsdp.py:233` </location>
<code_context>
         self.mode = mode
         self.compute_placements = [Replicate()] * self.device_mesh.ndim
-        self.grad_placements = [Partial(reduce_op="avg")] * self.device_mesh.ndim
+        self.grad_placements = [
+            _ScaledPartial(
+                reduction_divide_factor=reduction_divide_factor,
</code_context>

<issue_to_address>
**issue (complexity):** Consider replacing the _ScaledPartial subclass with a factory function and using list comprehensions to create fresh Partial instances for each mesh dimension.

```suggestion
# 1) Avoid list-multiplication, which shares a single Placement instance across all dims.
#    Use list‐comprehensions to get fresh instances and eliminate subtle shared‐state bugs.
# 2) You can drop the `_ScaledPartial` subclass entirely by patching a `Partial` instance
#    via a small factory, instead of duplicating two override methods in a subclass.

# Replace your `_ScaledPartial` with this factory at top‐level:
def make_scaled_partial(divide_factor: float) -> Partial:
    p = Partial(reduce_op="sum")
    orig_reduce = p._reduce_value
    orig_reduce_shard = p._reduce_shard_value

    def _reduce_value(tensor, mesh, mesh_dim):
        tensor.div_(divide_factor)
        return orig_reduce(tensor, mesh, mesh_dim)

    def _reduce_shard_value(tensor, mesh, mesh_dim, shard_spec):
        tensor.div_(divide_factor)
        return orig_reduce_shard(tensor, mesh, mesh_dim, shard_spec)

    p._reduce_value = _reduce_value
    p._reduce_shard_value = _reduce_shard_value
    return p

# Then in your ReplicateComputation.__init__:
if reduction_divide_factor is not None:
    self.grad_placements = [
        make_scaled_partial(reduction_divide_factor)
        for _ in range(self.device_mesh.ndim)
    ]
else:
    self.grad_placements = [
        Partial(reduce_op="avg")
        for _ in range(self.device_mesh.ndim)
    ]
```

This
- removes the extra subclass,
- guarantees a fresh `Partial` per mesh‐dim,
- and keeps the same reduction‐and‐divide behavior.
</issue_to_address>

### Comment 4
<location> `torchtitan/experiments/simple_fsdp/simple_fsdp.py:67-68` </location>
<code_context>
    def _reduce_value(
        self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
    ) -> torch.Tensor:
        # for all_reduce in DDP
        tensor.div_(self.reduction_divide_factor)
        reduced = super()._reduce_value(tensor, mesh, mesh_dim)
        return reduced

</code_context>

<issue_to_address>
**suggestion (code-quality):** Inline variable that is immediately returned ([`inline-immediately-returned-variable`](https://docs.sourcery.ai/Reference/Default-Rules/refactorings/inline-immediately-returned-variable/))

```suggestion
        return super()._reduce_value(tensor, mesh, mesh_dim)
```
</issue_to_address>

### Comment 5
<location> `torchtitan/experiments/simple_fsdp/simple_fsdp.py:79-80` </location>
<code_context>
    def _reduce_shard_value(
        self,
        tensor: torch.Tensor,
        mesh: DeviceMesh,
        mesh_dim: int,
        shard_spec: Placement,
    ) -> torch.Tensor:
        # for reduce_scatter in FSDP
        tensor.div_(self.reduction_divide_factor)
        reduced = super()._reduce_shard_value(tensor, mesh, mesh_dim, shard_spec)
        return reduced

</code_context>

<issue_to_address>
**suggestion (code-quality):** Inline variable that is immediately returned ([`inline-immediately-returned-variable`](https://docs.sourcery.ai/Reference/Default-Rules/refactorings/inline-immediately-returned-variable/))

```suggestion
        return super()._reduce_shard_value(tensor, mesh, mesh_dim, shard_spec)
```
</issue_to_address>

### Comment 6
<location> `torchtitan/models/deepseek_v3/model/state_dict_adapter.py:80` </location>
<code_context>
    def get_hf_storage_reader(
        self, path: str, from_quantized: bool = False
    ) -> HuggingFaceStorageReader:
        """
        Override default get_hf_storage_reader function to return QuantizedHFStorageReader.
        """
        if from_quantized:
            from torch.distributed.checkpoint.quantized_hf_storage import (
                QuantizedHuggingFaceStorageReader,
            )

            # NOTE: Now we use Quantized HF storage reader to read DeepSeek-V3 671B model.
            # If loading checkpoints without quantization, use HuggingFaceStorageReader instead
            BLOCK_SIZE = 128
            return QuantizedHuggingFaceStorageReader(
                path=path,
                target_dtype=torch.float32,
                block_size=BLOCK_SIZE,
                thread_count=4,
            )
        else:
            return HuggingFaceStorageReader(path)

</code_context>

<issue_to_address>
**issue (code-quality):** We've found these issues:

- Swap if/else branches ([`swap-if-else-branches`](https://docs.sourcery.ai/Reference/Default-Rules/refactorings/swap-if-else-branches/))
- Remove unnecessary else after guard condition ([`remove-unnecessary-else`](https://docs.sourcery.ai/Reference/Default-Rules/refactorings/remove-unnecessary-else/))
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +21 to +25
def precompute_freqs_cis(
dim: int,
end: int,
theta: float = 10000.0,
scaling_args: RoPEScalingArgs = RoPEScalingArgs(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (bug_risk): Default argument instantiation may lead to unexpected shared state.

Mutable default arguments can result in shared state across function calls. Use None as the default and instantiate RoPEScalingArgs within the function to avoid this issue.

Comment on lines +52 to +61
class _ScaledPartial(Partial):
# A subclass of Partial placement that allows user to perform reduction with a custom
# factor (reduction_divide_factor) other than the default world size.
def __init__(
self,
reduction_divide_factor: float,
):
self.reduction_divide_factor = reduction_divide_factor
super().__init__(reduce_op="sum")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: Custom reduction logic may cause numerical instability for non-integer divide factors.

Rounding errors may occur if reduction_divide_factor is not an integer or not equal to the world size. Please validate or document the acceptable values for this parameter.

self.mode = mode
self.compute_placements = [Replicate()] * self.device_mesh.ndim
self.grad_placements = [Partial(reduce_op="avg")] * self.device_mesh.ndim
self.grad_placements = [

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (complexity): Consider replacing the _ScaledPartial subclass with a factory function and using list comprehensions to create fresh Partial instances for each mesh dimension.

Suggested change
self.grad_placements = [
# 1) Avoid list-multiplication, which shares a single Placement instance across all dims.
# Use list‐comprehensions to get fresh instances and eliminate subtle shared‐state bugs.
# 2) You can drop the `_ScaledPartial` subclass entirely by patching a `Partial` instance
# via a small factory, instead of duplicating two override methods in a subclass.
# Replace your `_ScaledPartial` with this factory at top‐level:
def make_scaled_partial(divide_factor: float) -> Partial:
p = Partial(reduce_op="sum")
orig_reduce = p._reduce_value
orig_reduce_shard = p._reduce_shard_value
def _reduce_value(tensor, mesh, mesh_dim):
tensor.div_(divide_factor)
return orig_reduce(tensor, mesh, mesh_dim)
def _reduce_shard_value(tensor, mesh, mesh_dim, shard_spec):
tensor.div_(divide_factor)
return orig_reduce_shard(tensor, mesh, mesh_dim, shard_spec)
p._reduce_value = _reduce_value
p._reduce_shard_value = _reduce_shard_value
return p
# Then in your ReplicateComputation.__init__:
if reduction_divide_factor is not None:
self.grad_placements = [
make_scaled_partial(reduction_divide_factor)
for _ in range(self.device_mesh.ndim)
]
else:
self.grad_placements = [
Partial(reduce_op="avg")
for _ in range(self.device_mesh.ndim)
]

This

  • removes the extra subclass,
  • guarantees a fresh Partial per mesh‐dim,
  • and keeps the same reduction‐and‐divide behavior.

Comment on lines +67 to +68
reduced = super()._reduce_value(tensor, mesh, mesh_dim)
return reduced

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
reduced = super()._reduce_value(tensor, mesh, mesh_dim)
return reduced
return super()._reduce_value(tensor, mesh, mesh_dim)

Comment on lines +79 to +80
reduced = super()._reduce_shard_value(tensor, mesh, mesh_dim, shard_spec)
return reduced

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
reduced = super()._reduce_shard_value(tensor, mesh, mesh_dim, shard_spec)
return reduced
return super()._reduce_shard_value(tensor, mesh, mesh_dim, shard_spec)

Dequantize the weights from float8 to float32.
Override default get_hf_storage_reader function to return QuantizedHFStorageReader.
"""
if from_quantized:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (code-quality): We've found these issues:

saforem2 added a commit that referenced this pull request Jun 10, 2026
…-v2.sh

Iterations 1-3 of the backfill scripts (8533153, 8533448, 8533449,
8533560, 8533561) all failed because I was building a custom invocation
of convert_and_eval.sh that hit a series of issues:

1. Missing --repo-root (DCP-exists check fires unconditionally)
2. Wrong --label (HF dir layout: agpt-MODEL-v2-LABEL)
3. lm_eval CLI not found in .venv (.venv is the torch 2.13 training
   venv; lm_eval lives in venvs/aurora/tt-lm-eval overlay on the
   frameworks/2025.3.1 module)

Instead of fixing #3 in convert_and_eval.sh (which would require
porting the monkey-patch + venv switch + HF-backend-not-vllm fix),
rewrite both oneoff scripts as thin wrappers that delegate to the
already-working eval-{2b,20b}-v2.sh canonical scripts via STEPS/
CKPT_NAME/LABEL/TASKS env overrides. Those scripts:

- module load frameworks/2025.3.1
- source venvs/aurora/tt-lm-eval/bin/activate
- monkey-patch transformers.modeling_utils.caching_allocator_warmup
- run lm_eval.evaluator.simple_evaluate via Python (not CLI)
- use model="hf" (vllm doesn't work on XPU)
- skip-if-results-exist (which is why results.json was moved aside)

Net result: oneoff scripts are now ~3 lines of env vars instead of a
hand-built invocation that bypassed all the platform setup.
@saforem2 saforem2 mentioned this pull request Jun 11, 2026
saforem2 added a commit to nscottnichols/torchtitan that referenced this pull request Jun 11, 2026
Two distributed-hang risks fixed by making both per-rank decisions
agree globally across the EP mesh:

(1) `_can_use_equal_a2a_splits` returned a local-only min!=max bool.
    Different ranks could decide differently (rank A's splits
    uniform -> False -> takes explicit-splits a2a path; rank B's
    splits uneven -> True -> takes equal-padding a2a path with
    None/None). The two ranks then hand `all_to_all_single`
    different argument shapes -> hang.

    Fix: new `_can_use_equal_a2a_splits_global` helper does an
    all_reduce(MAX) of the local bool across `ep_mesh`. Any rank
    voting "True" forces all peers to also pad, keeping branch
    decisions in lockstep.

(2) `TT_MOE_NORMAL_EQUAL_A2A_PADDING` env var was read on every
    `dispatch()` call via `_normal_equal_a2a_padding_enabled()` /
    `_normal_equal_a2a_padding_policy()`. PBS env propagation across
    Sunspot/Aurora hosts isn't uniformly guaranteed (per-host
    .bashrc differences, partial `-v` broadcast), so rank 0 could
    see "force" while rank 7 saw "" - and the two would take
    different branches.

    Fix: read the env var ONCE at `wire_meshes()` time and
    all_reduce(MAX) across `ep_mesh` into
    `self._normal_equal_a2a_policy`. Encode policy as
    int (off=0, adaptive=1, force=2) so the strongest policy wins
    - this biases toward enabling the optimization when any rank
    asked for it (consistent with the failure mode where a user
    only exports the env var on rank 0's host). Telemetry flag
    cached similarly into `self._normal_equal_a2a_telemetry`.

    The dispatch hot path now references the cached attributes
    directly; no per-step env-var read.

Both reductions are tiny (1 int over ep_mesh.size() ranks) and
happen at construction time (the env-var one) or once per dispatch
(the splits one). The latter could be folded into the existing
`_global_equal_a2a_split_size` collective in a follow-up if perf
matters, but the simple separate all_reduce keeps the code clear.

Addresses review findings saforem2#3 + saforem2#5 on saforem2#14.
saforem2 added a commit that referenced this pull request Jun 12, 2026
Tight-clip test 8539593 (max_norm=0.1) NaN'd at step 4 instead of
step 6 — earlier than baseline. Three possible causes:
1. clip-norm legitimately changes weights enough to shift the
   overflow trajectory
2. RNG state shifts (FSDP scheduling, dataloader) → different
   forward inputs
3. FP chaos (nan-poisoning during clip_grad_norm)

The deterministic pair removes #2 and #3:
- n32-det.sh: baseline + --debug.seed=42 --debug.deterministic
  (max_norm=1.0 default)
- n32-det-tight-clip.sh: same + --training.max-norm=0.1

With matched seed + deterministic, the two runs are bit-identical
through whatever number of steps until clip diverges them. If clip
changes nothing meaningful, they'll both NaN at the same step.

Per CLAUDE.md: --debug.deterministic only (NEVER
--debug.deterministic_warn_only).
saforem2 added a commit that referenced this pull request Jul 27, 2026
Appendix A (80B NaN): the full run ladder (8574385/8661293 identical NaN ->
optimizer-independent; 8537349 fp32-params clean; 8671046 per-block-fp32res
clean@4N but 8671243 NaN@dp=192; 8673658 full-depth-fp32res NaN@dp=192). Narrows
the overflow to bf16 sublayer compute (attn scores / FFN), not the residual ->
cheap untried fixes = QK-Norm + attention softcap (both in-tree, unused by 80B).

Appendix B (SFT 384-rank fault): deterministic GPU NotPresent-Write at step 1-2
via oneCCL; failing jobs 12470336/338/339 (+12468348/371/398); VERIFIED 2N-clean
repro _diag_bigmix_2n_len1024.sh (12470343, 24 ranks); rank-221-across-nodes,
OOV-ruled-out, base-independent. Onset near the same ~186-192 dp boundary as the
80B wall. Wired asks #1/#3 to the appendices.
saforem2 added a commit that referenced this pull request Aug 17, 2026
Recommendation #5 from the concurrent-job-ckpt-collision writeup. Episode 2 was
found 18 days late by hand-counting files; this detector would have caught it
the same day.

The discriminator is INDEX ALIGNMENT, not just an mtime gap. A collided dir has
two mtime clusters where the split falls exactly on a shard index -- a 192-rank
job wrote shards 0-191 over the top of a 3072-rank job's, hours apart and at a
different file size. Straggler ranks also produce a gap (three dirs in the same
tree gapped 108-121s and are benign), but their late files are a handful
scattered anywhere, not a contiguous prefix. So a non-aligned split is reported
as stragglers and only an aligned one is called MIXED.

Also covers recommendation #3 (shard count differing from the tree's mode is a
scale change and should never be silent), plus out-of-order mtimes and
empty/metadata-less dirs.

Read-only, and deliberately so: reclaiming 906 GB of orphan shards is a human
decision, and each mixed dir may still hold a coherent checkpoint for its step.
Exits 1 on any MIXED dir so it can gate a resume.
saforem2 added a commit that referenced this pull request Aug 25, 2026
…tract

Gate 7558682 aborted in config.build(), one rename past the last one:

    TypeError: BlendCorpusDataLoader.Config.__init__() got an unexpected
               keyword argument 'repeat'

core's Validator.__init__ runs
`replace(config.dataloader, repeat=config.steps != -1)` unconditionally
(components/validate.py:132), and dataclasses.replace raises on an
unknown field -- so the validator simply cannot be built on this path.
`repeat` is upstream's spelling of our `infinite`; added as a field with
a __post_init__ that reconciles the two, since the rest of the loader
reads `infinite` and a silent divergence would hand the validator an
endless dataloader.

Also fixed the same class of break one level down, before it could
surface as gate #5: __init__ REQUIRED seq_len + local_batch_size, but
core's own Validator.validate() calls dl_config.build() with only
max_context_length + num_tokens_per_batch (validate.py:235). ezpz
overrides _get_validation_dataloader and sends the old pair, which is
the only reason that path had not fired yet. All four names now bind,
with tokens -> sequences conversion at the boundary.

This is the FOURTH pytorch#4121 casualty on the blendcorpus path, and they
share a shape: each fires only where the 2N sync smokes did not look
(#3 and #4 both need --validator.enable, which the smokes had off). So
the tests here assert the CONTRACT -- the names core reaches for -- on
CPU with no GPU, no corpus, and no cluster. 14 tests; both real gate
failures are covered as explicit negative controls.
saforem2 added a commit that referenced this pull request Sep 16, 2026
The native-DDP preflight could never run. Two independent defects, both
on the same call path, both from f5f6ee6:

1. trainer.py passed 6 of the 9 required keyword-only args. Missing:
   fault_tolerance_enabled, create_seed_checkpoint,
   optimizer_has_param_groups -- none of which have defaults. Any run
   with enable_data_parallel_native_ddp=true died with TypeError at
   trainer construction, before anything else was reached.

   All three are available at the callsite and now passed:
   config.fault_tolerance.enable, config.checkpoint.create_seed_checkpoint,
   and whether config.optimizer declares param_groups.

2. Even fixed, the validator read three fields that do not exist here:
   parallelism.enable_fsdp_async_all_reduce,
   pipeline_parallel_fsdp_overlap and pipeline_parallel_fsdp_overlap_policy.
   Those are on the upstream Aurora MoE branch's CORE ParallelismConfig;
   ours is EzpzParallelismConfig, which deliberately ports only the five
   fields our code reads, and core torchtitan never had them. Reading
   them on a slotted dataclass raised AttributeError, and they sit two
   gates before the final check, so they were always reached.

   Now read via getattr with the upstream default. Keeping the checks
   rather than deleting them means the rejection still fires if those
   fields are ever added; deleting would silently accept a combination
   the author explicitly rejected.

Verified by calling the validator against REAL objects -- a real
ParallelDims built from its own dataclass fields, a real TrainingConfig,
and a real EzpzParallelismConfig with the flag on. It now runs every
gate and returns a policy ValueError ("native DDP currently requires
standard CrossEntropyLoss") instead of TypeError or AttributeError.
That is the validator working.

Both found by /code-review on my own PR (#17), findings 1 and 2 of 15.
I shipped f5f6ee6 saying the hooks were wired and 73824cf saying the
flags made the path live. Neither was true, and no test I wrote would
have caught it -- they all exercise the expert backends instead.

Still open from that review: #3 (wrap_native_ddp runs on a meta-device
model before to_empty), #4 (a helper imports _NativeDDPPipelineStage from
core, where I moved it out of), and #15 (scale_native_ddp_loss defined
but never called, leaving gradients dp_degree x off).
saforem2 added a commit that referenced this pull request Sep 17, 2026
…(review #3, #4, #15)

Three remaining findings from /code-review on #17. With b2deeb2 this
closes all five blockers on the native-DDP path.

#3 -- wrap_native_ddp ran on a META-DEVICE model.

The model is built under torch.device("meta") and moved to the real
device by to_empty(). The wrap sat BEFORE that, so DDP read
next(model.parameters()).device, got device(type='meta') with .index
None, computed device_ids=[None], and built reduction buckets over meta
storage. to_empty() then reallocated every parameter, invalidating the
bucket views DDP had just built with gradient_as_bucket_view=True.

Moved after to_empty/init_states and before model.train(). Order is now
to_empty -> init_states -> wrap -> train.

#4 -- wrap_native_ddp_pipeline_stage imported _NativeDDPPipelineStage
from torchtitan.distributed.pipeline_parallel, where it does not exist.

ab24c5c moved that class into native_ddp.py as part of the dependency
inversion -- it is defined at line 853 of the same file that was
importing it from core. ImportError for any PP + native-DDP run, and the
isinstance check three lines later could never have matched. Only
unreached because the function has no callers. Import dropped; the
class resolves from module scope.

#15 -- scale_native_ddp_loss was defined and never called, leaving
gradients dp_degree x too small. This is the one that would have
TRAINED, not crashed.

Core's forward_backward_step states it: "The returned loss here is local
SUM loss / global_valid_tokens". global_valid_tokens is a cross-DP sum
(dist_sum over batch_mesh), so gradients are already globally normalized
before backward. DDP's reducer then divides by process_group.size()
again. FSDP hits the same thing and solves it with
disable_fsdp_gradient_division (agpt/parallelize.py); DDP exposes no
equivalent switch, so the compensation has to happen on the loss -- which
is precisely what scale_native_ddp_loss exists for.

Wired at self.loss_fn construction, which ezpz owns, so it lands before
every consumer without touching core's forward_backward_step. Guarded on
the flag and on dp_degree > 1.

Verified: gradient ratio exactly 4.0 at dp=4 and 8.0 at dp=8, loss VALUE
unchanged in both (so reported loss stays comparable across paths), and
dp=1 refuses rather than silently no-opping.

Not yet run end-to-end with the flag enabled on hardware. These fixes are
reasoned from the code plus unit-level verification of the scaling math;
the path still needs a real run before anyone should trust it, and that
is the next step rather than a claim this commit makes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants