Debian Codegraph @

examples/torch_native_parallelism/utils.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 """
16 Common utilities for torch-native-parallelism examples.
17 """
18
19 import time
20 from contextlib import nullcontext
21
22 import torch
23 from datasets import Dataset, load_dataset
24 from transformers import AutoModelForCausalLM, AutoTokenizer
25
26 from accelerate import Accelerator
27
28
29 def get_dataset(tokenizer: AutoTokenizer, seq_len: int, accelerator: Accelerator | None = None) -> Dataset:
30 """
31 Load and prepare TinyStories dataset.
32
33 Args:
34 accelerator (Accelerator): Accelerate accelerator instance
35 tokenizer (AutoTokenizer): Hugging Face tokenizer
36 seq_len (int): Sequence length for the dataset
37
38 Returns:
39 Dataset: Packed dataset
40 """
41 processing_ctx = accelerator.main_process_first if accelerator else nullcontext
42 raw_dataset = load_dataset("roneneldan/TinyStories", split="train[:50%]")
43
44 def tokenize_function(examples):
45 tokenized_batch = tokenizer(
46 examples["text"],
47 padding=False,
48 truncation=True,
49 max_length=seq_len,
50 return_tensors=None,
51 )
52 tokenized_batch["labels"] = tokenized_batch["input_ids"].copy()
53 return tokenized_batch
54
55 with processing_ctx():
56 tokenized_dataset = raw_dataset.map(tokenize_function, batched=True, remove_columns=["text"])
57
58 def create_packed_sequences(examples):
59 all_tokens = []
60 for input_ids in examples["input_ids"]:
61 all_tokens.extend(input_ids)
62
63 num_sequences = len(all_tokens) // (seq_len + 1)
64 packed_input_ids = []
65 packed_labels = []
66 packed_position_ids = []
67
68 for i in range(num_sequences):
69 start_idx = i * (seq_len + 1)
70 end_idx = start_idx + (seq_len + 1)
71 full_sequence = all_tokens[start_idx:end_idx]
72 packed_input_ids.append(full_sequence[:-1])
73 packed_labels.append(full_sequence[1:])
74 packed_position_ids.append(torch.arange(0, seq_len))
75
76 return {
77 "input_ids": packed_input_ids,
78 "shift_labels": packed_labels,
79 "position_ids": packed_position_ids,
80 "labels": packed_labels,
81 }
82
83 with processing_ctx():
84 packed_dataset = tokenized_dataset.map(
85 create_packed_sequences,
86 batched=True,
87 remove_columns=tokenized_dataset.column_names,
88 batch_size=1000,
89 )
90
91 return packed_dataset.shuffle(seed=42)
92
93
94 def get_model_flops_per_token(model: AutoModelForCausalLM, seq_len: int) -> float:
95 """
96 Get the number of flops per token for the model.
97
98 Args:
99 model (AutoModelForCausalLM): Model to get the flops for
100 seq_len (int): Sequence length
101 """
102 cfg = model.config
103 head_dim = cfg.hidden_size // cfg.num_attention_heads
104
105 # MLP: 3 matmuls
106 mlp_flops = 18 * cfg.hidden_size * cfg.intermediate_size
107
108 # Attn (w/o dotproduct)
109 attn_flops = 12 * head_dim * (cfg.num_attention_heads + cfg.num_key_value_heads)
110
111 # attn (dotproduct) - this scales quadratically with sequence length
112 attn_dotproduct_flops = 12 * cfg.num_attention_heads * head_dim * seq_len
113
114 # we also ignore embeddings and layernorms, etc
115 return (mlp_flops + attn_flops + attn_dotproduct_flops) * cfg.num_hidden_layers
116
117
118 def create_collate_fn():
119 """Create a collate function for batching."""
120
121 def collate_fn(batch):
122 input_ids = torch.tensor([item["input_ids"] for item in batch], dtype=torch.long)
123 shift_labels = torch.tensor([item["shift_labels"] for item in batch], dtype=torch.long)
124 return {"input_ids": input_ids, "shift_labels": shift_labels, "labels": shift_labels}
125
126 return collate_fn
127
128
129 class PerformanceTracker:
130 """Track training performance metrics."""
131
132 def __init__(self, warmup_steps: int = 10):
133 self.warmup_steps = warmup_steps
134 self.reset()
135
136 def reset(self):
137 """Reset all tracking variables."""
138 self.start_time = None
139 self.num_tokens = 0
140 self.is_in_warmup = True
141 self.step_count = 0
142
143 def step(self, batch_tokens: int, model_flops_per_token: float | None = None) -> dict:
144 """
145 Update performance tracking with a new step.
146
147 Args:
148 batch_tokens (int): Number of tokens in current batch
149
150 Returns:
151 dict: Performance metrics if past warmup, empty dict otherwise
152 """
153 self.step_count += 1
154
155 if self.step_count == self.warmup_steps:
156 self.start_time = time.perf_counter()
157 self.num_tokens = 0
158 self.is_in_warmup = False
159 return {"warmup_completed": True}
160
161 if not self.is_in_warmup and self.start_time is not None:
162 dct = {}
163 self.num_tokens += batch_tokens
164 total_time = time.perf_counter() - self.start_time
165 steps_from_warmup = self.step_count - self.warmup_steps
166
167 if total_time > 0 and steps_from_warmup > 0:
168 memory_stats = gpu_memory_usage_all()
169 dct = {
170 "tokens_per_second": self.num_tokens / total_time,
171 "steps_per_second": steps_from_warmup / total_time,
172 "total_tokens": self.num_tokens,
173 "total_time": total_time,
174 **memory_stats,
175 }
176
177 if model_flops_per_token is not None:
178 flops = model_flops_per_token * self.num_tokens
179 dct["tflops_per_device"] = flops / (total_time * 1e12)
180
181 return dct
182
183 return {}
184
185 def get_print_message(self, metrics: dict, with_memory: bool = False) -> str:
186 print_msg = f" | Average steps/s: {metrics['steps_per_second']:.2f} | Average tokens/s: {metrics['tokens_per_second']:.2f} | Average TFLOPS: {metrics['tflops_per_device']:.2f}\n"
187 if with_memory:
188 print_msg += (
189 f"\tMemory (GB): active={metrics['peak_memory_active']:.1f}, "
190 f"alloc={metrics['peak_memory_alloc']:.1f}, "
191 f"reserved={metrics['peak_memory_reserved']:.1f}"
192 )
193 return print_msg
194
195
196 def setup_tokenizer(model_id: str) -> AutoTokenizer:
197 """Setup tokenizer with proper padding token."""
198 tokenizer = AutoTokenizer.from_pretrained(model_id)
199 if tokenizer.pad_token is None:
200 tokenizer.pad_token = tokenizer.eos_token
201 return tokenizer
202
203
204 def gpu_memory_usage_all(device=0):
205 device_type = torch.accelerator.current_accelerator().type
206 device = torch.device(f"{device_type}:{device}")
207 torch_device_module = getattr(torch, device_type, torch.cuda)
208 _BYTES_IN_GIB = 1024**3
209 peak_memory_active = torch_device_module.memory_stats().get("active_bytes.all.peak", 0) / _BYTES_IN_GIB
210 peak_memory_alloc = torch_device_module.max_memory_allocated(device) / _BYTES_IN_GIB
211 peak_memory_reserved = torch_device_module.max_memory_reserved(device) / _BYTES_IN_GIB
212 memory_stats = {
213 "peak_memory_active": peak_memory_active,
214 "peak_memory_alloc": peak_memory_alloc,
215 "peak_memory_reserved": peak_memory_reserved,
216 }
217 torch_device_module.reset_peak_memory_stats(device)
218
219 return memory_stats