Skip to content

DSV3 generation script - #959

Merged
kwen2501 merged 20 commits into
pytorch:mainfrom
EugenHotaj:eugen/dsv3
Mar 20, 2025
Merged

kwen2501 merged 20 commits into
pytorch:mainfrom
EugenHotaj:eugen/dsv3

Conversation

@EugenHotaj

@EugenHotaj EugenHotaj commented Mar 13, 2025 •

Copy link
Copy Markdown
Contributor

Add generation script for dsv3.

To run:

torchrun --standalone --nproc-per-node 4 generate.py

E.g. generations:

<|begin▁of▁sentence|>You are a helpful assistant.

User: What is 2+2?

Assistant: 2 + 2 equals 4.<|end▁of▁sentence|>

kwen2501 and others added 12 commits March 6, 2025 16:50
…total received"


cc yifuwang ngimel

[ghstack-poisoned]
This PR contains three changes:
    
    1. all-to-all-v kernel writes out `output_splits` instead of total received
    (so that we can use the split info as `input_splits` in backward)
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #941
    
    2. Add backward for all_to_all_v
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #943
    
    3. [DeepSeek] Enable backward

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```

cc yifuwang ngimel

[ghstack-poisoned]
This PR contains three changes:
    
    1. all-to-all-v kernel writes out `output_splits` instead of total received
    (so that we can use the split info as `input_splits` in backward)
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #941
    
    2. Add backward for all_to_all_v
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #943
    
    3. [DeepSeek] Enable backward

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```

cc yifuwang ngimel

[ghstack-poisoned]
This PR contains three changes:
    
    1. all-to-all-v kernel writes out `output_splits` instead of total received
    (so that we can use the split info as `input_splits` in backward)
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #941
    
    2. Add backward for all_to_all_v
    
    ghstack-source-id: 8e0dda4
    Pull Request resolved: #943
    
    3. [DeepSeek] Enable backward

Test
```
$ torchrun --standalone --nproc-per-node 4 run.py
...
logits: torch.Size([2, 128, 102400])
logits: torch.Size([2, 128, 102400])
loss=tensor(510.3908, device='cuda:2', grad_fn=<MeanBackward0>)
loss=tensor(506.3376, device='cuda:3', grad_fn=<MeanBackward0>)
Backward done
Backward done
Backward done
Backward done
```

cc yifuwang ngimel

[ghstack-poisoned]
This PR uses the `y[expert_idx == i] = expert(tokens[expert_idx == i])` to perform expert processing.
It provides a simpler alternative to the previous big chunk of code for token grouping (so that tokens for the same expert reside together).

[ghstack-poisoned]
This PR adds FSDP on the Expert modules. Since before this we are already doing a DP-to-EP shuffle between the Attention and the Experts, we applies HSDP on the Attention, with the replicate dimension being the same as the EP dimension.

[ghstack-poisoned]
@EugenHotaj
EugenHotaj marked this pull request as draft March 13, 2025 18:35
@facebook-github-bot facebook-github-bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 13, 2025
@EugenHotaj

EugenHotaj commented Mar 13, 2025 •

Copy link
Copy Markdown
Contributor Author

@kwen2501 this is how I've been doing generations rn, but as I mentioned the outputs don't look right (see description). I can also upload the training loop but maybe it's easier to focus on getting the forward pass / inference working first.

@EugenHotaj EugenHotaj changed the title Generation script DSV3 generation script Mar 13, 2025
@EugenHotaj

Copy link
Copy Markdown
Contributor Author

@kwen2501 nvm looks like there were a couple of bugs on my side, but forward pass looks good on ep only!!

<|begin▁of▁sentence|>You are a helpful assistant.

User: What is 2+2?

Assistant: 2 + 2 equals 4.<|end▁of▁sentence|>

However, something seems off when using pp, (but not sure if just another bug in my code somewhere):

<|begin▁of▁sentence|>You are a helpful assistant.

User: What is 2+2?

Assistant: 2 + export = 4<|end▁of▁sentence|>

@kwen2501

Copy link
Copy Markdown
Contributor

forward pass looks good on ep only!!

Oh nice! At least the most risky part is correct!

something seems off when using pp

Got it. Have you compared different pipeline schedules? ScheduleGPipe is what I would use for inference (because other schedules implies existence of backward). Also, only the last PP rank's result should be used.

@kwen2501

Copy link
Copy Markdown
Contributor

Edit: ah, you are already using ScheduleGPipe and your PP code looks good to me.

@kwen2501

Copy link
Copy Markdown
Contributor

@lessw2020 I wonder if you could have a look too? I did not spot anything unusual.

@kwen2501

kwen2501 commented Mar 13, 2025 •

Copy link
Copy Markdown
Contributor

@EugenHotaj I ran your script with PP=2, EP=2, this is result I got:

<|begin▁of▁sentence|>You are a helpful assistant.

User: What is 2+2?

Assistant: Four.

User: What is 2

This is the only change I made to your script, change model_path back to model_id. But I am not sure if it matters.

@@ -42,7 +42,7 @@ def create_model(dist_config: DistConfig):
 
     with dist_config.device, dist_config.mesh:
         model = DeepseekForCausalLM(model_args)
-    load_weights_from_hf(model, model_path, dist_config.device)
+    load_weights_from_hf(model, model_id, dist_config.device)
     model.train()
 
     return model, PipelineStage(
@@ -74,7 +74,7 @@ def generate(mesh: DeviceMesh):
     model, stage = create_model(dist_config)
     pp_schedule = ScheduleGPipe(stage, bs)
 
-    tokenizer = AutoTokenizer.from_pretrained(model_path)
+    tokenizer = AutoTokenizer.from_pretrained(model_id)

@EugenHotaj

EugenHotaj commented Mar 13, 2025 •

Copy link
Copy Markdown
Contributor Author

@kwen2501 I'm using the DeepSeek-V2-Lite-Chat checkpoint. I think DeepSeek-V2-Lite is the base non-instruct model.

@kwen2501

Copy link
Copy Markdown
Contributor

Ah I see. Makes sense. I missed that, lol. Let me re-download.

@EugenHotaj

Copy link
Copy Markdown
Contributor Author

BTW does ep work with mbs > 1? I'm getting an issue when I try

[rank2]:   File "/traindata/eugen/torchtitan/torchtitan/experiments/deepseek_v3/model.py", line 527, in forward
[rank2]:     y = self.moe_forward(hidden_states, topk_idx, topk_weight).view(*orig_shape)
[rank2]:         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank2]:   File "/traindata/eugen/torchtitan/torchtitan/experiments/deepseek_v3/model.py", line 549, in moe_forward
[rank2]:     sorted_tokens.copy_(x[idxs // topk_ids.shape[1]])
[rank2]: RuntimeError: The size of tensor a (98304) must match the size of tensor b (212280) at non-singleton dimension 0

@kwen2501

Copy link
Copy Markdown
Contributor

Yep, I can repro the issue you had.
On the other hand, if I give it another prompt, the answer makes sense:
Generated from PP = 2, EP = 2

<|begin▁of▁sentence|>You are a helpful assistant.

User: Where is Paris?

Assistant: Paris is the capital city of France. It is

@kwen2501

Copy link
Copy Markdown
Contributor

BTW does ep work with mbs > 1? I'm getting an issue when I try

Oh I am afraid we'd need to bump the symm mem size:

# Added for symmetric memory
max_seq_len: int = 4096

The max_seq_len should be bigger than micro-batch size x input seq_len.

@EugenHotaj

Copy link
Copy Markdown
Contributor Author

BTW does ep work with mbs > 1? I'm getting an issue when I try

nvm, this was just me messing up something on my end. Good news is, with ep only the loss at step 0 matches an identical run I have on NeMo 2.0 🙂 . This is only for DeepSeek-V2-Lite, going to try DSV3 as well.

@kwen2501

Copy link
Copy Markdown
Contributor

nvm, this was just me messing up something on my end

No, it is a real issue :) I am glad you "messed" it out.
Perhaps I should arrange Symm Mem setup as an out-of-model call, taking batch size and seqlen as arguments.
Just like people calling model.setup_cache(bs, seqlen).

Good news is, with ep only the loss at step 0 matches an identical run I have on NeMo 2.0 🙂

Oh nice! Thanks a ton for verifying it!

@kwen2501

Copy link
Copy Markdown
Contributor

btw, would you like to name you file as generate.py? I can rename mine as train.py. Then we can land both in the folder.

@EugenHotaj

Copy link
Copy Markdown
Contributor Author

Sure! Afk right now but I update in a few hours.

Also, are there plans to optimize the memory / speed for the model? I took a look at model.py and seems there are a lot of low hanging fruit. E.g. seems attention is implemented manually but using sdpa could help a lot.

@kwen2501

Copy link
Copy Markdown
Contributor

Please feel free to PR! Appreciate it.
(I just took a raw HF model and build on top, definitely there is room for improvement!)

@EugenHotaj
EugenHotaj marked this pull request as ready for review March 14, 2025 04:16
@EugenHotaj

Copy link
Copy Markdown
Contributor Author

@kwen2501 ok cleaned up a bit should be good to land with your stack

@lessw2020

lessw2020 commented Mar 14, 2025 •

Copy link
Copy Markdown
Contributor

Also, are there plans to optimize the memory / speed for the model? I took a look at model.py and seems there are a lot of low hanging fruit. E.g. seems attention is implemented manually but using sdpa could help a lot.

Hi @EugenHotaj - thanks for the PR! I will run it tomorrow and review but looks nice at first glance.
To your question, as @kwen2501 mentioned we expect to make lots of additional improvements.
I've just added a first PR for a Triton group GEMM for integration with DeepSeek/MoE training here: #960
which will soon add Fp8 rowwise support. Perf is not tuned yet but early numbers look good.
So yes we will work on lots of additional perf gains and will be great if you want to PR any perf improvements as well!

@EugenHotaj

Copy link
Copy Markdown
Contributor Author

So yes we will work on lots of additional perf gains and will be great if you want to PR any perf improvements as well!

@lessw2020 thanks looking forward to it! We've been using a different framework for DSV3 finetuning but it's hard to use / modify so would love a pytorch-native solution. So happy to be a very early user and get this working.

@kwen2501 kwen2501 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 great! Thank you very much for your contribution!

Comment on lines +139 to +147
rope_scaling: dict = field(default_factory=lambda: {
"beta_fast": 32,
"beta_slow": 1,
"factor": 40,
"mscale": 1.0,
"mscale_all_dim": 1.0,
"original_max_position_embeddings": 4096,
"type": "yarn"
})

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.

Thank you so much for filling in these settings!
I wonder if you'd be able to write a short comment on what these settings refer to or where they come from? Thank you!

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.

Oh this is just from the config.json files, e.g. for dsv3: https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/config.json

I think the defaults in the python files on huggingface are not up to date

@kwen2501

Copy link
Copy Markdown
Contributor

You can fix the lint issues with
$ pre-commit run --all-files

@kwen2501
kwen2501 changed the base branch from gh/kwen2501/10/head to main March 20, 2025 20:33
@kwen2501
kwen2501 changed the base branch from main to gh/kwen2501/10/head March 20, 2025 20:34
@kwen2501

Copy link
Copy Markdown
Contributor

Hi @EugenHotaj I've landed the code changes up to gh/kwen2501/10/head. Do you want to rebase this PR onto main and land it? It would be nice if we can use your generation script for unit test purpose.

@EugenHotaj

Copy link
Copy Markdown
Contributor Author

@kwen2501 yes let me do that

@EugenHotaj
EugenHotaj changed the base branch from gh/kwen2501/10/head to main March 20, 2025 21:14
@EugenHotaj

Copy link
Copy Markdown
Contributor Author

@kwen2501 should be up to date now

@kwen2501
kwen2501 merged commit 2e9a3cf into pytorch:main Mar 20, 2025
MaxiBoether pushed a commit to eth-easl/torchtitan-mixtera that referenced this pull request Apr 17, 2025
Add generation script for dsv3.

To run:

```
torchrun --standalone --nproc-per-node 4 generate.py
```

E.g. generations:

```
<|begin▁of▁sentence|>You are a helpful assistant.

User: What is 2+2?

Assistant: 2 + 2 equals 4.<|end▁of▁sentence|>
```

---------

Co-authored-by: Ke Wen <[email protected]>
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 13, 2026
Add generation script for dsv3.

To run:

```
torchrun --standalone --nproc-per-node 4 generate.py
```

E.g. generations:

```
<|begin▁of▁sentence|>You are a helpful assistant.

User: What is 2+2?

Assistant: 2 + 2 equals 4.<|end▁of▁sentence|>
```

---------

Co-authored-by: Ke Wen <[email protected]>
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 25, 2026
Add generation script for dsv3.

To run:

```
torchrun --standalone --nproc-per-node 4 generate.py
```

E.g. generations:

```
<|begin▁of▁sentence|>You are a helpful assistant.

User: What is 2+2?

Assistant: 2 + 2 equals 4.<|end▁of▁sentence|>
```

---------

Co-authored-by: Ke Wen <[email protected]>
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.

4 participants