Debian Codegraph @

tests/tp/fsdp2_tp_preparation.py

raw
1 # Copyright 2022 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 os
16 from datetime import timedelta
17
18 import torch
19 from datasets import load_dataset
20 from torch.utils.data import DataLoader
21 from transformers import AutoModelForCausalLM, AutoTokenizer
22
23 from accelerate import Accelerator, InitProcessGroupKwargs
24 from accelerate.parallelism_config import ParallelismConfig
25 from accelerate.utils import FullyShardedDataParallelPlugin
26
27
28 class LmHeadWrapper(torch.nn.Module):
29 def __init__(self, lm_head):
30 super().__init__()
31 self.lm_head = lm_head
32
33 def forward(self, x):
34 return self.lm_head(x)
35
36
37 def build_simple_dataloader(tokenizer, seq_len=64, batch_size=2):
38 """Build a simple dataloader for reproduction."""
39 # Load small dataset
40 raw = load_dataset("wikitext", "wikitext-2-raw-v1", split="train[:1%]")
41 raw = raw.filter(lambda x: len(tokenizer(x["text"])["input_ids"]) > 0)
42 raw = raw.select(range(min(100, len(raw)))) # Use only 100 samples
43
44 def tok_fn(examples):
45 return tokenizer(examples["text"], truncation=True, max_length=seq_len)
46
47 ds = raw.map(tok_fn, batched=True, remove_columns=["text"])
48 ds.set_format(type="torch", columns=["input_ids"])
49
50 def collate(batch):
51 ids = [b["input_ids"] for b in batch]
52 labels = [x.clone() for x in ids]
53 pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id
54 x = torch.nn.utils.rnn.pad_sequence(ids, batch_first=True, padding_value=pad_id)
55 y = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=-100)
56 return {"input_ids": x, "labels": y}
57
58 return DataLoader(ds, batch_size=batch_size, shuffle=False, collate_fn=collate)
59
60
61 def main():
62 # Configuration
63 MODEL_NAME = "Qwen/Qwen3-0.6B"
64 BATCH_SIZE = 2
65 SEQ_LEN = 64
66 world_size = int(os.environ.get("WORLD_SIZE", "1"))
67 TP = min(2, world_size)
68 DP = max(1, world_size // TP)
69
70 # Setup Accelerator with FSDP2
71 init_kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=1800))
72 pc = ParallelismConfig(dp_shard_size=DP, tp_size=TP)
73
74 fsdp_plugin = FullyShardedDataParallelPlugin(
75 fsdp_version=2,
76 reshard_after_forward=True,
77 auto_wrap_policy="transformer_based_wrap",
78 state_dict_type="SHARDED_STATE_DICT",
79 activation_checkpointing=False,
80 cpu_ram_efficient_loading=True,
81 )
82
83 accelerator = Accelerator(kwargs_handlers=[init_kwargs], parallelism_config=pc, fsdp_plugin=fsdp_plugin)
84
85 rank = accelerator.process_index
86 print(f"[Rank {rank}] Initializing...")
87
88 # Load model with TP if needed
89 model_kwargs = {"tp_size": TP, "tp_plan": "auto", "device_mesh": accelerator.torch_device_mesh} if TP > 1 else {}
90
91 model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, use_cache=False, **model_kwargs)
92
93 model.lm_head = LmHeadWrapper(model.lm_head)
94
95 tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
96 optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
97
98 print(f"[Rank {rank}] Building dataloader...")
99 loader = build_simple_dataloader(tokenizer, seq_len=SEQ_LEN, batch_size=BATCH_SIZE)
100
101 print(f"[Rank {rank}] Preparing with accelerator...")
102 # ERROR OCCURS HERE AT LINE 110 in original script
103 model, optimizer, loader = accelerator.prepare(model, optimizer, loader)
104
105 print(f"[Rank {rank}] Preparation successful!")
106
107
108 if __name__ == "__main__":
109 main()