Debian Codegraph @

examples/alst_ulysses_sequence_parallelism/sp-alst.py

raw
1 # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import torch
16 from deepspeed.runtime.utils import move_to_device
17 from transformers import AutoModelForCausalLM, AutoTokenizer
18
19 from accelerate import Accelerator
20 from accelerate.utils import ParallelismConfig, set_seed
21 from accelerate.utils.dataclasses import DeepSpeedSequenceParallelConfig
22
23
24 set_seed(42)
25
26 model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
27 # to run the example faster switch to the random model
28 # model_name = "hf-internal-testing/tiny-random-LlamaForCausalLM"
29
30 micro_batch_size = 1
31
32 parallelism_config = ParallelismConfig(
33 sp_backend="deepspeed",
34 sp_size=4,
35 sp_handler=DeepSpeedSequenceParallelConfig(
36 sp_seq_length=256,
37 sp_seq_length_is_variable=True,
38 sp_attn_implementation="sdpa",
39 ),
40 )
41
42 accelerator = Accelerator(
43 parallelism_config=parallelism_config,
44 # log_with="wandb", # enable to log into wandb
45 )
46 accelerator.init_trackers(
47 project_name="ulysses-accelerate",
48 config={},
49 init_kwargs={"wandb": dict(entity="yak", name="deepspeed")},
50 )
51
52 tokenizer = AutoTokenizer.from_pretrained(model_name)
53 model = AutoModelForCausalLM.from_pretrained(model_name)
54
55 # 2 quick rough datasets to demonstrate the workings
56 if 1: # real dataset
57 from datasets import load_dataset
58
59 ds = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft[:12]")
60
61 # this is a quick example, it should be made more efficient to be used in real application
62 def convert(ex):
63 texts = tokenizer.apply_chat_template(conversation=ex["messages"], tokenize=False)
64 tokenized_dict = tokenizer(texts, max_length=256, padding=True, truncation=True)
65 return tokenized_dict
66
67 ds = ds.map(convert, batched=False, remove_columns=["prompt", "prompt_id", "messages"])
68
69 def collate_fn(batch):
70 input_ids = torch.tensor(batch[0]["input_ids"]).unsqueeze(0)
71 attention_mask = torch.tensor(batch[0]["attention_mask"]).unsqueeze(0)
72 position_ids = torch.arange(input_ids.shape[1]).unsqueeze(0)
73 return dict(
74 input_ids=input_ids,
75 position_ids=position_ids,
76 labels=input_ids,
77 attention_mask=attention_mask,
78 )
79
80 dl = torch.utils.data.DataLoader(
81 ds, batch_size=micro_batch_size, collate_fn=collate_fn, drop_last=True, shuffle=False
82 )
83
84 else: # fake dataset
85 samples = 16
86 seqlen = 256
87 input_ids = torch.arange(1, seqlen * samples + 1).view(-1, seqlen) + 100
88 position_ids = torch.arange(seqlen * samples).view(-1, seqlen)
89
90 ds = torch.utils.data.TensorDataset(input_ids, position_ids)
91
92 def collate_fn(batch):
93 input_ids, position_ids = batch[0]
94 return dict(
95 input_ids=input_ids.unsqueeze(0),
96 position_ids=position_ids.unsqueeze(0),
97 labels=input_ids.unsqueeze(0),
98 )
99
100 dl = torch.utils.data.DataLoader(ds, batch_size=micro_batch_size, collate_fn=collate_fn)
101
102 optimizer = torch.optim.Adam(model.parameters(), lr=1e-5)
103
104 rank = torch.distributed.get_rank()
105
106 if rank == 0:
107 print(f"DL orig: {len(dl)} samples")
108
109 model, optimizer, dl = accelerator.prepare(model, optimizer, dl)
110
111 if rank == 0:
112 print(f"DL w/ adapter: {len(dl)} samples")
113
114 sp_size = parallelism_config.sp_size if parallelism_config else 1
115 if sp_size > 1:
116 sp_group = accelerator.torch_device_mesh["sp"].get_group()
117 sp_world_size = parallelism_config.sp_size
118
119 unwrapped_model = accelerator.unwrap_model(model)
120
121 # Normal training loop
122 for iter, batch in enumerate(dl):
123 optimizer.zero_grad()
124
125 if rank == 0:
126 print(f"batch {iter}: seqlen: {len(batch['input_ids'][0])}")
127 batch = move_to_device(batch, model.device)
128
129 # The model automatically receives shift_labels via **kwargs and uses it for loss computation.
130 # Both standard transformer models and Liger-patched models handle this correctly.
131 outputs = model(**batch)
132 loss = outputs.loss
133
134 if sp_size > 1:
135 # differentiable weighted per-shard-loss aggregation across ranks
136 losses_per_rank = torch.distributed.nn.functional.all_gather(loss, group=sp_group)
137 # special dealing with SFT that has prompt tokens that aren't used in loss computation
138 good_tokens = (batch["shift_labels"] != -100).view(-1).sum()
139 good_tokens_per_rank = torch.distributed.nn.functional.all_gather(good_tokens, group=sp_group)
140 total_loss = sum(losses_per_rank[rank] * good_tokens_per_rank[rank] for rank in range(sp_world_size))
141 total_good_tokens = sum(good_tokens_per_rank)
142 loss = total_loss / max(total_good_tokens, 1)
143
144 if rank == 0:
145 accelerator.print(f"{iter}: {loss=}")
146 accelerator.log(dict(train_loss=loss, step=iter))
147
148 accelerator.backward(loss)
149 optimizer.step()
150
151 accelerator.end_training()