Debian Codegraph @

tests/test_fp8.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 import json
17 import os
18 import tempfile
19 import textwrap
20 import unittest
21 from pathlib import Path
22
23 import torch
24
25 from accelerate import Accelerator
26 from accelerate.state import AcceleratorState
27 from accelerate.test_utils import (
28 get_launch_command,
29 require_cuda_or_hpu,
30 require_huggingface_suite,
31 require_multi_device,
32 require_torchao,
33 require_transformer_engine,
34 require_transformer_engine_mxfp8,
35 run_first,
36 )
37 from accelerate.test_utils.testing import require_deepspeed, run_command
38 from accelerate.utils import (
39 AORecipeKwargs,
40 TERecipeKwargs,
41 has_ao_layers,
42 has_transformer_engine_layers,
43 )
44
45
46 def can_convert_te_model(from_config=False):
47 if not from_config:
48 accelerator_kwargs = {"mixed_precision": "fp8", "kwargs_handlers": [TERecipeKwargs()]}
49 else:
50 accelerator_kwargs = {}
51
52 accelerator = Accelerator(**accelerator_kwargs)
53 assert accelerator.fp8_enabled, "FP8 is not enabled"
54
55 dataloader = torch.utils.data.DataLoader(torch.randn(10, 32), batch_size=2)
56 model = torch.nn.Sequential(torch.nn.Linear(32, 32), torch.nn.LayerNorm(32, bias=False), torch.nn.Linear(32, 16))
57 optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
58 scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.1)
59
60 model, optimizer, dataloader, scheduler = accelerator.prepare(model, optimizer, dataloader, scheduler)
61 assert has_transformer_engine_layers(model)
62
63
64 def maintain_proper_deepspeed_config(expected_version):
65 assert AcceleratorState().deepspeed_plugin.zero_stage == expected_version, (
66 f"Expected zero stage {expected_version} but got {AcceleratorState().deepspeed_plugin.zero_stage}"
67 )
68
69
70 def can_convert_ao_model(from_config=False):
71 from transformers import AutoModelForSequenceClassification
72
73 if not from_config:
74 accelerator_kwargs = {"mixed_precision": "fp8", "kwargs_handlers": [AORecipeKwargs()]}
75 else:
76 accelerator_kwargs = {}
77
78 accelerator = Accelerator(**accelerator_kwargs)
79 dataloader = torch.utils.data.DataLoader(torch.randn(10, 32), batch_size=2)
80 model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased")
81 optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
82 scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.1)
83
84 model, optimizer, dataloader, scheduler = accelerator.prepare(model, optimizer, dataloader, scheduler)
85 assert has_ao_layers(model)
86
87
88 @run_first
89 @require_transformer_engine
90 @require_cuda_or_hpu
91 class TestTransformerEngine(unittest.TestCase):
92 def test_can_prepare_model_single_gpu(self):
93 command = get_launch_command(num_processes=1, monitor_interval=0.1)
94 command += ["-m", "tests.test_fp8", "--test_te"]
95 run_command(command)
96
97 def test_can_prepare_model_single_gpu_from_config(self):
98 with tempfile.TemporaryDirectory() as dir_name:
99 config_file = Path(dir_name) / "config.yaml"
100 config_file.write_text(
101 textwrap.dedent(
102 """
103 distributed_type: "NO"
104 num_processes: 1
105 mixed_precision: fp8
106 fp8_config:
107 backend: TE
108 """
109 )
110 )
111 command = get_launch_command(config_file=str(config_file), monitor_interval=0.1)
112 command += ["-m", "tests.test_fp8", "--test_te", "--from_config"]
113 run_command(command)
114
115 @require_transformer_engine_mxfp8
116 def test_can_prepare_model_with_mxfp8_block_scaling(self):
117 with tempfile.TemporaryDirectory() as dir_name:
118 config_file = Path(dir_name) / "config.yaml"
119 config_file.write_text(
120 textwrap.dedent(
121 """
122 distributed_type: "NO"
123 num_processes: 1
124 mixed_precision: fp8
125 fp8_config:
126 backend: TE
127 use_mxfp8_block_scaling: true
128 """
129 )
130 )
131 command = get_launch_command(config_file=str(config_file), monitor_interval=0.1)
132 command += ["-m", "tests.test_fp8", "--test_te", "--from_config"]
133 run_command(command)
134
135 @require_multi_device
136 def test_can_prepare_model_multi_gpu(self):
137 command = get_launch_command(num_processes=2, monitor_interval=0.1)
138 command += ["-m", "tests.test_fp8", "--test_te"]
139 run_command(command)
140
141 @require_deepspeed
142 @require_multi_device
143 def test_can_prepare_model_multigpu_deepspeed(self):
144 for zero_stage in [1, 2, 3]:
145 os.environ["ZERO_STAGE"] = str(zero_stage)
146 ds_config = {
147 "bf16": {"enabled": True},
148 "zero_optimization": {
149 "stage": zero_stage,
150 "allgather_partitions": True,
151 "allgather_bucket_size": 2e8,
152 "overlap_comm": True,
153 "reduce_scatter": True,
154 "reduce_bucket_size": 2e8,
155 "contiguous_gradients": True,
156 },
157 "gradient_accumulation_steps": 1,
158 "gradient_clipping": "auto",
159 "steps_per_print": 2000,
160 "train_batch_size": "auto",
161 "train_micro_batch_size_per_gpu": "auto",
162 "wall_clock_breakdown": False,
163 }
164
165 ds_config = json.dumps(ds_config)
166
167 command = get_launch_command(
168 num_processes=2, monitor_interval=0.1, use_deepspeed=True, deepspeed_config_file=ds_config
169 )
170 command += ["-m", "tests.test_fp8", "--test_te"]
171 run_command(command)
172
173 @require_deepspeed
174 @require_multi_device
175 def test_can_prepare_model_multigpu_deepspeed_from_config(self):
176 os.environ["ZERO_STAGE"] = str(1)
177 with tempfile.TemporaryDirectory() as dir_name:
178 config_file = Path(dir_name) / "config.yaml"
179 config_file.write_text(
180 textwrap.dedent(
181 """
182 distributed_type: "DEEPSPEED"
183 deepspeed_config:
184 gradient_clipping: 1.0
185 gradient_accumulation_steps: 1
186 offload_optimizer_device: none
187 offload_param_device: none
188 zero3_init_flag: false
189 zero_stage: 1
190 deepspeed_multinode_launcher: standard
191 num_processes: 2
192 mixed_precision: fp8
193 fp8_config:
194 backend: TE
195 """
196 )
197 )
198 command = get_launch_command(config_file=str(config_file), monitor_interval=0.1)
199 command += ["-m", "tests.test_fp8", "--test_te", "--from_config"]
200 run_command(command)
201
202
203 @require_torchao
204 @require_huggingface_suite
205 class TestTorchAO(unittest.TestCase):
206 def test_can_prepare_model_single_accelerator(self):
207 command = get_launch_command(num_processes=1, monitor_interval=0.1)
208 command += ["-m", "tests.test_fp8", "--test_ao"]
209 run_command(command)
210
211 def test_can_prepare_model_single_gpu_from_config(self):
212 with tempfile.TemporaryDirectory() as dir_name:
213 config_file = Path(dir_name) / "config.yaml"
214 config_file.write_text(
215 textwrap.dedent(
216 """
217 distributed_type: "NO"
218 num_processes: 1
219 mixed_precision: fp8
220 fp8_config:
221 backend: AO
222 """
223 )
224 )
225 command = get_launch_command(config_file=str(config_file), monitor_interval=0.1)
226 command += ["-m", "tests.test_fp8", "--test_ao", "--from_config"]
227 run_command(command)
228
229 def test_can_prepare_model_single_gpu_from_config_with_additional_params(self):
230 with tempfile.TemporaryDirectory() as dir_name:
231 config_file = Path(dir_name) / "config.yaml"
232 config_file.write_text(
233 textwrap.dedent(
234 """
235 distributed_type: "NO"
236 num_processes: 1
237 mixed_precision: fp8
238 fp8_config:
239 backend: AO
240 pad_inner_dim: true
241 enable_fsdp_float8_all_gather: false
242 """
243 )
244 )
245 command = get_launch_command(config_file=str(config_file), monitor_interval=0.1)
246 command += ["-m", "tests.test_fp8", "--test_ao", "--from_config"]
247 run_command(command)
248
249 @require_multi_device
250 def test_can_prepare_model_multi_accelerator(self):
251 command = get_launch_command(num_processes=2, monitor_interval=0.1)
252 command += ["-m", "tests.test_fp8", "--test_ao"]
253 run_command(command)
254
255 @require_deepspeed
256 @require_multi_device
257 def test_can_prepare_model_multi_accelerator_deepspeed(self):
258 for zero_stage in [1, 2, 3]:
259 os.environ["ZERO_STAGE"] = str(zero_stage)
260 ds_config = {
261 "bf16": {"enabled": True},
262 "zero_optimization": {
263 "stage": zero_stage,
264 "allgather_partitions": True,
265 "allgather_bucket_size": 2e8,
266 "overlap_comm": True,
267 "reduce_scatter": True,
268 "reduce_bucket_size": 2e8,
269 "contiguous_gradients": True,
270 },
271 "gradient_accumulation_steps": 1,
272 "gradient_clipping": "auto",
273 "steps_per_print": 2000,
274 "train_batch_size": "auto",
275 "train_micro_batch_size_per_gpu": "auto",
276 "wall_clock_breakdown": False,
277 }
278
279 ds_config = json.dumps(ds_config)
280
281 command = get_launch_command(
282 num_processes=2, monitor_interval=0.1, use_deepspeed=True, deepspeed_config_file=ds_config
283 )
284 command += ["-m", "tests.test_fp8", "--test_ao"]
285 run_command(command)
286
287
288 if __name__ == "__main__":
289 # TE suite
290 parser = argparse.ArgumentParser()
291 parser.add_argument("--test_te", action="store_true", default=False)
292 parser.add_argument("--test_ao", action="store_true", default=False)
293 parser.add_argument("--from_config", action="store_true", default=False)
294 args = parser.parse_args()
295
296 if not args.test_te and not args.test_ao:
297 raise ValueError("Must specify at least one of --test_te or --test_ao")
298
299 if args.test_te:
300 can_convert_te_model(args.from_config)
301 if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true":
302 maintain_proper_deepspeed_config(int(os.environ.get("ZERO_STAGE")))
303
304 # AO suite
305 if args.test_ao:
306 can_convert_ao_model(args.from_config)