-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Deepspeed Ulysses/ALST integration #3817
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+943
−35
Merged
Changes from 11 commits
Commits
Show all changes
53 commits
Select commit
Hold shift + click to select a range
439fa7e
Feat: initial impl
S1ro1 e238f7b
improve
sfc-gh-sbekman 876fa2d
s/flavour/backend/
sfc-gh-sbekman b016317
style + ver
sfc-gh-sbekman a63d094
better check
sfc-gh-sbekman 73d3dbc
check
sfc-gh-sbekman 8b4a4f4
docs + example
sfc-gh-sbekman 76288a8
add tests
sfc-gh-sbekman 209eab7
add tests
sfc-gh-sbekman c013677
cleanup
sfc-gh-sbekman 685453c
cleanup
sfc-gh-sbekman a396904
Apply suggestions from code review
stas00 fb80e02
add experimental notice
sfc-gh-sbekman 21a4a2d
style
sfc-gh-sbekman 05b6ac1
Merge branch 'alst-integration' of https://github.com/stas00/accelera…
sfc-gh-sbekman 60f7493
new deepspeed version
sfc-gh-sbekman 453fb55
additional checks + tests
sfc-gh-sbekman 8677f23
more docs
sfc-gh-sbekman 8ee9b03
more docs
sfc-gh-sbekman 2e577d3
working now
sfc-gh-sbekman 5c51897
style
sfc-gh-sbekman 8317241
update docs
sfc-gh-sbekman 94f558b
more robust config parsing
sfc-gh-sbekman a2388cd
fix
sfc-gh-sbekman e6e243f
Apply suggestions from code review
stas00 2330dcd
check backend, integrate ulysses API improvement
sfc-gh-sbekman 9dbcf91
style
sfc-gh-sbekman e79034f
fix default to match the doc
sfc-gh-sbekman 61873c6
Apply suggestions from code review
stas00 756bd9f
fix
sfc-gh-sbekman 56df621
deepspeed=0.18.2 is out
sfc-gh-sbekman 380747c
Apply suggestions from code review
stas00 38c84fa
s/cp/sp
sfc-gh-sbekman 5c2f34e
fixes
sfc-gh-sbekman 190494b
Apply suggestions from code review
stas00 285e24f
Update src/accelerate/parallelism_config.py
stas00 a7d2e5d
suggestion
sfc-gh-sbekman d4ee156
Update docs/source/concept_guides/sequence_parallelism.md
stas00 99b321a
Update sequence_parallelism.md
stas00 b769fc8
fix
sfc-gh-sbekman 04b4dc3
fix
sfc-gh-sbekman a4005e7
fix
sfc-gh-sbekman 10978a0
Apply suggestion from @kashif
kashif 4115257
Apply suggestion from @kashif
kashif 891c702
Apply suggestion from @kashif
kashif 71f61d6
Apply suggestion from @kashif
kashif 1d5bc22
Apply suggestion from @kashif
kashif 7282db8
Apply suggestion from @kashif
kashif 84638eb
Apply suggestion from @kashif
kashif d0d8860
Apply suggestion from @kashif
kashif 1e19b82
Apply suggestion from @kashif
kashif 5d099cf
Apply suggestion from @kashif
kashif c3b2ce7
Apply suggestion from @kashif
kashif File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| # Deepspeed's ALST/Ulysses sequence parallelism | ||
|
|
||
| This is an example of the use of Ulysses Sequence Parallelism, which uses attention head parallelism and which is part of the Arctic Long Sequence Training project at [ArcticTraining](https://github.com/snowflakedb/ArcticTraining). [This paper](https://arxiv.org/abs/2506.13996) goes into the details of this protocol. | ||
stas00 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| For nuances of usage please refer to the main HF Accelerate tutorial on [Context Parallelism](https://huggingface.co/docs/accelerate/en/concept_guides/context_parallelism). | ||
|
|
||
| You need to use at least `2` gpus to enable ALST/Ulysses sequence parallelism. | ||
|
|
||
| To run the example with `4` gpus: | ||
|
|
||
| ```bash | ||
| bash ./cp-alst.sh | ||
| ``` | ||
|
|
||
| Change `4` to the desired sequence parallelism degree in these 2 files: | ||
| ``` | ||
| cp-alst.accelerate-config.yml:num_processes: 4 | ||
| cp-alst.py: cp_size=4, | ||
| ``` | ||
12 changes: 12 additions & 0 deletions
12
examples/alst_ulysses_sequence_parallelism/cp-alst.accelerate-config.yml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| compute_environment: LOCAL_MACHINE | ||
| deepspeed_config: | ||
| deepspeed_config_file: cp-alst.ds-config.json | ||
| zero3_init_flag: false | ||
| distributed_type: DEEPSPEED | ||
| machine_rank: 0 | ||
| main_training_function: main | ||
| num_machines: 1 | ||
| num_processes: 4 | ||
| rdzv_backend: static | ||
| same_network: true | ||
| use_cpu: false |
12 changes: 12 additions & 0 deletions
12
examples/alst_ulysses_sequence_parallelism/cp-alst.ds-config.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| { | ||
| "bf16": { | ||
| "enabled": true | ||
| }, | ||
| "zero_optimization": { | ||
| "stage": 3 | ||
| }, | ||
| "gradient_accumulation_steps": 1, | ||
| "train_batch_size": "auto", | ||
| "train_micro_batch_size_per_gpu": "auto", | ||
| "seq_parallel_communication_data_type": "bf16" | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| # Copyright 2025 The HuggingFace Inc. team. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import torch | ||
| from deepspeed.runtime.utils import move_to_device | ||
| from transformers import AutoModelForCausalLM, AutoTokenizer | ||
|
|
||
| from accelerate import Accelerator | ||
| from accelerate.utils import ParallelismConfig, set_seed | ||
| from accelerate.utils.dataclasses import DeepSpeedContextParallelConfig | ||
|
|
||
|
|
||
| set_seed(42) | ||
|
|
||
| model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" | ||
| # to run the example faster switch to the random model | ||
| # model_name = "hf-internal-testing/tiny-random-LlamaForCausalLM" | ||
|
|
||
| micro_batch_size = 1 | ||
|
|
||
| parallelism_config = ParallelismConfig( | ||
| backend="deepspeed", | ||
| cp_size=4, | ||
| # dp_shard_size=1, # set if dp is wanted as well | ||
| cp_handler=DeepSpeedContextParallelConfig( | ||
| seq_length=256, | ||
| seq_length_is_variable=True, | ||
| attn_implementation="sdpa", | ||
stas00 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ), | ||
| ) | ||
|
|
||
| accelerator = Accelerator( | ||
| parallelism_config=parallelism_config, | ||
| # log_with="wandb", # enable to log into wandb | ||
| ) | ||
| accelerator.init_trackers( | ||
| project_name="ulysses-accelerate", | ||
| config={}, | ||
| init_kwargs={"wandb": dict(entity="yak", name="deepspeed")}, | ||
| ) | ||
|
|
||
| tokenizer = AutoTokenizer.from_pretrained(model_name) | ||
| model = AutoModelForCausalLM.from_pretrained(model_name) | ||
|
|
||
| # 2 quick rough datasets to demonstrate the workings | ||
| if 1: # real dataset | ||
| from datasets import load_dataset | ||
|
|
||
| ds = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft[:12]") | ||
|
|
||
| # this is a quick example, it should be made more efficient to be used in real application | ||
| def convert(ex): | ||
| texts = tokenizer.apply_chat_template(conversation=ex["messages"], tokenize=False) | ||
| tokenized_dict = tokenizer(texts, max_length=256, padding=True, truncation=True) | ||
| return tokenized_dict | ||
| ds = ds.map(convert, batched=False, remove_columns=["prompt", "prompt_id", "messages"]) | ||
|
|
||
| def collate_fn(batch): | ||
| input_ids = torch.tensor(batch[0]["input_ids"]).unsqueeze(0) | ||
| attention_mask = torch.tensor(batch[0]["attention_mask"]).unsqueeze(0) | ||
| position_ids = torch.arange(input_ids.shape[1]).unsqueeze(0) | ||
| return dict( | ||
| input_ids=input_ids, | ||
| position_ids=position_ids, | ||
| labels=input_ids, | ||
| attention_mask=attention_mask, | ||
| ) | ||
|
|
||
| dl = torch.utils.data.DataLoader( | ||
| ds, batch_size=micro_batch_size, collate_fn=collate_fn, drop_last=True, shuffle=False | ||
| ) | ||
|
|
||
| else: # fake dataset | ||
| samples = 16 | ||
| seqlen = 256 | ||
| input_ids = torch.arange(1, seqlen * samples + 1).view(-1, seqlen) + 100 | ||
| position_ids = torch.arange(seqlen * samples).view(-1, seqlen) | ||
|
|
||
| ds = torch.utils.data.TensorDataset(input_ids, position_ids) | ||
|
|
||
| def collate_fn(batch): | ||
| input_ids, position_ids = batch[0] | ||
| return dict( | ||
| input_ids=input_ids.unsqueeze(0), | ||
| position_ids=position_ids.unsqueeze(0), | ||
| labels=input_ids.unsqueeze(0), | ||
| ) | ||
|
|
||
| dl = torch.utils.data.DataLoader(ds, batch_size=micro_batch_size, collate_fn=collate_fn) | ||
|
|
||
| optimizer = torch.optim.Adam(model.parameters(), lr=1e-5) | ||
|
|
||
| rank = torch.distributed.get_rank() | ||
|
|
||
| if rank == 0: | ||
| print(f"DL orig: {len(dl)} samples") | ||
|
|
||
| model, optimizer, dl = accelerator.prepare(model, optimizer, dl) | ||
|
|
||
| if rank == 0: | ||
| print(f"DL w/ adapter: {len(dl)} samples") | ||
|
|
||
| cp_size = parallelism_config.cp_size if parallelism_config else 1 | ||
| if cp_size > 1: | ||
| sp_group = accelerator.torch_device_mesh["cp"].get_group() | ||
| sp_world_size = parallelism_config.cp_size | ||
|
|
||
| unwrapped_model = accelerator.unwrap_model(model) | ||
|
|
||
| # Normal training loop | ||
| for iter, batch in enumerate(dl): | ||
| optimizer.zero_grad() | ||
|
|
||
| if rank == 0: | ||
| print(f"batch {iter}: seqlen: {len(batch['input_ids'][0])}") | ||
| batch = move_to_device(batch, model.device) | ||
| outputs = model(**batch) | ||
|
|
||
| shift_labels = batch["shift_labels"] | ||
| loss = unwrapped_model.loss_function( | ||
| logits=outputs.logits, | ||
| labels=None, | ||
| shift_labels=shift_labels, | ||
| vocab_size=unwrapped_model.config.vocab_size, | ||
| ) | ||
|
|
||
| if cp_size > 1: | ||
| # differentiable weighted per-shard-loss aggregation across ranks | ||
| losses_per_rank = torch.distributed.nn.functional.all_gather(loss, group=sp_group) | ||
| # special dealing with SFT that has prompt tokens that aren't used in loss computation | ||
| good_tokens = (shift_labels != -100).view(-1).sum() | ||
| good_tokens_per_rank = torch.distributed.nn.functional.all_gather(good_tokens, group=sp_group) | ||
| total_loss = sum(losses_per_rank[rank] * good_tokens_per_rank[rank] for rank in range(sp_world_size)) | ||
| total_good_tokens = sum(good_tokens_per_rank) | ||
| loss = total_loss / max(total_good_tokens, 1) | ||
|
|
||
| if rank == 0: | ||
| accelerator.print(f"{iter}: {loss=}") | ||
| accelerator.log(dict(train_loss=loss, step=iter)) | ||
|
|
||
| accelerator.backward(loss) | ||
| optimizer.step() | ||
|
|
||
| accelerator.end_training() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| export MASTER_ADDR=localhost | ||
| export MASTER_PORT=9998 | ||
| python -u -m accelerate.commands.launch \ | ||
| --rdzv_conf "rdzv_backend=c10d,rdzv_endpoint=$MASTER_ADDR:$MASTER_PORT" \ | ||
| --main_process_ip $MASTER_ADDR \ | ||
| --main_process_port $MASTER_PORT \ | ||
| --config_file cp-alst.accelerate-config.yml \ | ||
| cp-alst.py |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.