Debian Codegraph @

benchmarks/fsdp2/utils.py

raw
1 # Copyright 2025 The HuggingFace 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 argparse
16 from types import MethodType
17 from typing import Union
18
19 import torch
20 from datasets import load_dataset
21 from measure_utils import MemoryTracker
22 from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard
23 from torch.optim import AdamW
24 from torch.utils.data import DataLoader
25 from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, DataCollatorForLanguageModeling
26 from transformers.models.qwen2.modeling_qwen2 import Qwen2DecoderLayer
27
28 from accelerate import Accelerator, FullyShardedDataParallelPlugin
29 from accelerate.state import AcceleratorState, is_initialized
30 from accelerate.utils import convert_outputs_to_fp32, set_seed
31
32
33 SEED = 421
34
35
36 def get_named_parameters(model: torch.nn.Module, drop_refs: bool = False) -> dict[str, Union[torch.Tensor, int]]:
37 """
38 This function returns a dictionary mapping the parameter names to their data pointers or
39 the original parameters if `drop_refs` is `False`.
40 It is used to get the original parameter names before `fully_shard` is applied.
41
42 We only return the data pointers, so we drop the references to the original parameters
43 and `fully_shard` will then trigger a new allocation for the sharded ones.
44
45 Args:
46 model (`torch.nn.Module`): Model instance to get the named parameters from
47 drop_refs (`bool`, *optional*, defaults to `False`): Whether to drop the references to the original parameters
48
49 Returns:
50 `dict[str, Union[torch.Tensor, int]]`: Dictionary mapping the parameter names to their data pointers or the original parameters if `drop_refs` is `False`
51 """
52 named_parameters = {}
53 for n, p in model.named_parameters():
54 # We only preserve the data pointers to have the unique 1:1 mapping between the original and the sharded parameters
55 named_parameters[n] = p.data_ptr() if drop_refs else p
56 return named_parameters
57
58
59 def replace_optimizer_params(optimizer: torch.optim.Optimizer):
60 """
61 This function is called before using `fully_shard` on the model. It replaces the parameters of the optimizer with
62 empty tensors, so `fully_shard` can trigger a new allocation for the sharded ones. After this, we swap the parameters
63 `data_ptr` to the original one, so we can reuse that later to map the sharded parameters to the original ones.
64 This function modifies the optimizer in-place.
65
66 Args:
67 optimizer (torch.optim.Optimizer): Optimizer instance which contains the original model parameters
68 """
69
70 for param_group in optimizer.param_groups:
71 for i, p in enumerate(param_group["params"]):
72 # We drop a reference to the original param here, so that _move_states_to_device triggers a reallocation
73 # This is required or else the `fully_shard` -> `_move_states_to_device` uses the original memory address
74 # for the sharded parameters, and we get a weird/undefined behavior.
75 param_group["params"][i] = torch.empty_like(p)
76
77 # We save the original data_ptr, so we can swap back the parameters later
78 param_group["params"][i].data_ptr = p.data_ptr()
79
80
81 def swap_back_optimizer_params(
82 model: torch.nn.Module, optimizer: torch.optim.Optimizer, old_named_parameter_pointers: dict[str, int]
83 ):
84 """
85 This function is the counterpart of `replace_optimizer_params`. It is called after `fully_shard` being applied to
86 the model. It swaps the parameters of the optimizer to their sharded counterparts.
87 It is done using the `data_ptr` mapping prepared in `replace_optimizer_params` and `get_named_parameters`.
88
89 Args:
90 model (`torch.nn.Module`): Model instance to get the new named parameters from
91 optimizer (`torch.optim.Optimizer`): Optimizer instance to swap the parameters of
92 old_named_parameter_pointers (`dict[str, int]`): Dictionary mapping the original parameter names: data_ptrs to the new ones
93 """
94 # We get the new named parameters after `fully_shard` being applied
95 # We don't drop the references as we need the sharded parameters now
96 new_named_parameters = get_named_parameters(model, drop_refs=False)
97
98 # We create a mapping from the original data_ptr to the new sharded param corresponding to it
99 mapping = {p: new_named_parameters[n] for n, p in old_named_parameter_pointers.items()}
100
101 for param_group in optimizer.param_groups:
102 # We swap the parameters of the optimizer to the new sharded ones
103 param_group["params"] = [mapping[p.data_ptr] for p in param_group["params"]]
104
105
106 def parse_args():
107 parser = argparse.ArgumentParser()
108 parser.add_argument(
109 "--output_dir",
110 type=str,
111 help="Directory to save the benchmarking results.",
112 )
113 parser.add_argument(
114 "--save_memory_snapshot",
115 action="store_true",
116 default=False,
117 help="If True, `torch.cuda.memory._dump_snapshot` will be used to additionally save the memory trace.",
118 )
119 ######################
120 # Training arguments #
121 ######################
122 parser.add_argument(
123 "--batch_size",
124 type=int,
125 default=2,
126 help="Batch size for the training loop.",
127 )
128 parser.add_argument(
129 "--block_size",
130 type=int,
131 default=128,
132 help="The maximum sequence length to use with the model.",
133 )
134 parser.add_argument(
135 "--dataset_fraction",
136 type=float,
137 default=1.0,
138 help="Fraction of the dataset to use.",
139 )
140 return parser.parse_args()
141
142
143 def prepare_dataloader(tokenizer, args, accelerator: Accelerator) -> DataLoader:
144 dataset = load_dataset("tiny_shakespeare", split="train", trust_remote_code=True)
145
146 def tokenize_function(example):
147 return tokenizer(
148 example["text"],
149 )
150
151 dataset = dataset.map(
152 tokenize_function,
153 batched=True,
154 remove_columns=["text"],
155 )
156
157 block_size = min(tokenizer.model_max_length, args.block_size)
158
159 def group_texts(examples):
160 concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
161 total_length = len(concatenated_examples[list(examples.keys())[0]])
162
163 total_length = (total_length // block_size) * block_size
164
165 result = {
166 k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
167 for k, t in concatenated_examples.items()
168 }
169
170 result["labels"] = result["input_ids"].copy()
171 return result
172
173 dataset = dataset.map(group_texts, batched=True)
174 dataset = dataset.select(range(int(len(dataset) * args.dataset_fraction)))
175
176 def collate_fn(examples):
177 return DataCollatorForLanguageModeling(
178 tokenizer=tokenizer,
179 mlm=False,
180 )(examples)
181
182 dataloader = DataLoader(
183 dataset,
184 batch_size=args.batch_size,
185 collate_fn=collate_fn,
186 )
187 dataloader = accelerator.prepare(dataloader)
188 return dataloader
189
190
191 def get_model(model_name: str):
192 # We require model to be loaded in fp32, otherwise benchmarks don't match as accelerate does upcasting of parameters to fp32
193 config = AutoConfig.from_pretrained(model_name, trust_remote_code=True, torch_dtype=torch.float32)
194 model = AutoModelForCausalLM.from_config(config)
195 return model
196
197
198 def get_tokenizer(model_name: str):
199 tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
200 tokenizer.pad_token = tokenizer.eos_token
201 return tokenizer
202
203
204 def prepare_torch(
205 args, config: dict, post_shard_optimizer: bool = False, apply_optimizer_fix: bool = False
206 ) -> tuple[torch.nn.Module, torch.optim.Optimizer, torch.utils.data.DataLoader, Accelerator]:
207 mp_policy = MixedPrecisionPolicy(
208 param_dtype=torch.bfloat16,
209 reduce_dtype=torch.bfloat16,
210 output_dtype=torch.bfloat16,
211 )
212
213 accelerator = Accelerator(mixed_precision="bf16")
214 set_seed(SEED)
215 is_fixed = "fixed" if apply_optimizer_fix else "not_fixed"
216 is_post_shard = "optimizer_after_fsdp" if post_shard_optimizer else "optimizer_before_fsdp"
217 run_name = f"torch_{is_post_shard}" if post_shard_optimizer else f"torch_{is_post_shard}_{is_fixed}"
218
219 tokenizer = get_tokenizer(config["model_name"])
220 train_dataloader = prepare_dataloader(tokenizer, args, accelerator)
221
222 memory_tracker = MemoryTracker(accelerator.device, args.output_dir, run_name, args.save_memory_snapshot)
223 memory_tracker.start()
224
225 model = get_model(config["model_name"])
226 optimizer = None
227
228 if not post_shard_optimizer:
229 optimizer = AdamW(model.parameters(), lr=config["learning_rate"])
230
231 if apply_optimizer_fix:
232 # We drop the references to the original parameters, so that `fully_shard` can trigger a new allocation
233 # Then we get the `module_name: data_ptr` mapping, so we can swap back the parameters later
234 old_named_parameters = get_named_parameters(model, drop_refs=True)
235
236 # We replace the parameters of the optimizer with empty tensors, so that `fully_shard` can trigger a new allocation
237 # We also change the `data_ptr` of the parameters to the original ones, so we can swap back the parameters later
238 replace_optimizer_params(optimizer)
239
240 for module in model.modules():
241 if isinstance(module, Qwen2DecoderLayer):
242 fully_shard(module, mp_policy=mp_policy)
243 fully_shard(model, mp_policy=mp_policy)
244
245 # We do this to imitate how accelerate forces outputs to be in fp32 via `convert_outputs_to_fp32`
246 autocast_context = torch.autocast(device_type=accelerator.state.device.type, dtype=torch.bfloat16)
247 model_forward_func = model.forward.__func__
248 new_forward = autocast_context(model_forward_func)
249 model.forward = MethodType(new_forward, model)
250 model.forward = MethodType(convert_outputs_to_fp32(model.forward.__func__), model)
251
252 if post_shard_optimizer:
253 optimizer = AdamW(model.parameters(), lr=config["learning_rate"])
254
255 if not post_shard_optimizer and apply_optimizer_fix:
256 # We swap back the parameters of the optimizer to the original ones
257 swap_back_optimizer_params(model, optimizer, old_named_parameters)
258
259 return model, optimizer, train_dataloader, accelerator, memory_tracker
260
261
262 def prepare_accelerate(
263 args, config: dict
264 ) -> tuple[torch.nn.Module, torch.optim.Optimizer, torch.utils.data.DataLoader, Accelerator]:
265 if is_initialized():
266 AcceleratorState()._reset_state(True)
267
268 fsdp_plugin = FullyShardedDataParallelPlugin(
269 fsdp_version=2,
270 auto_wrap_policy="transformer_based_wrap",
271 transformer_cls_names_to_wrap=["Qwen2DecoderLayer"],
272 )
273 accelerator = Accelerator(
274 fsdp_plugin=fsdp_plugin,
275 mixed_precision="bf16",
276 )
277 set_seed(SEED)
278
279 tokenizer = get_tokenizer(config["model_name"])
280 train_dataloader = prepare_dataloader(tokenizer, args, accelerator)
281
282 memory_tracker = MemoryTracker(accelerator.device, args.output_dir, "accelerate", args.save_memory_snapshot)
283 memory_tracker.start()
284
285 model = get_model(config["model_name"])
286 optimizer = AdamW(model.parameters(), lr=config["learning_rate"])
287
288 model, optimizer = accelerator.prepare(model, optimizer)
289
290 return model, optimizer, train_dataloader, accelerator, memory_tracker