Debian Codegraph @

tests/deepspeed/test_deepspeed_gradient_accumulation.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 inspect
16 import json
17 from pathlib import Path
18
19 import torch
20 from torch.utils.data import DataLoader
21 from transformers import AutoModel
22 from transformers.trainer_utils import set_seed
23
24 from accelerate.accelerator import Accelerator
25 from accelerate.test_utils.testing import AccelerateTestCase, require_deepspeed
26 from accelerate.test_utils.training import RegressionDataset
27 from accelerate.utils import patch_environment
28 from accelerate.utils.dataclasses import DeepSpeedPlugin
29
30
31 set_seed(42)
32
33 GPT2_TINY = "hf-internal-testing/tiny-random-gpt2"
34 ZERO2 = "zero2"
35 ZERO3 = "zero3"
36 FP16 = "fp16"
37
38
39 @require_deepspeed
40 class DeepSpeedGradientAccumulationTest(AccelerateTestCase):
41 def setUp(self):
42 super().setUp()
43
44 self._test_file_path = inspect.getfile(self.__class__)
45 path = Path(self._test_file_path).resolve()
46 self.test_file_dir_str = str(path.parents[0])
47
48 self.ds_config_file = dict(
49 zero2=f"{self.test_file_dir_str}/ds_config_zero2.json",
50 zero3=f"{self.test_file_dir_str}/ds_config_zero3.json",
51 )
52
53 # Load config files
54 with open(self.ds_config_file[ZERO2], encoding="utf-8") as f:
55 config_zero2 = json.load(f)
56 with open(self.ds_config_file[ZERO3], encoding="utf-8") as f:
57 config_zero3 = json.load(f)
58 config_zero3["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] = False
59
60 self.ds_config_dict = dict(zero2=config_zero2, zero3=config_zero3)
61
62 self.dist_env = dict(
63 ACCELERATE_USE_DEEPSPEED="true",
64 MASTER_ADDR="localhost",
65 MASTER_PORT="10999",
66 RANK="0",
67 LOCAL_RANK="0",
68 WORLD_SIZE="1",
69 )
70
71 def test_gradient_accumulation_boundary_integration(self):
72 """Test that gradient accumulation boundaries are automatically handled by DeepSpeed integration."""
73 gradient_accumulation_steps = 4
74
75 deepspeed_plugin = DeepSpeedPlugin(
76 gradient_accumulation_steps=gradient_accumulation_steps,
77 gradient_clipping=1.0,
78 zero_stage=2,
79 offload_optimizer_device="cpu",
80 offload_param_device="cpu",
81 zero3_save_16bit_model=False,
82 zero3_init_flag=False,
83 )
84
85 with patch_environment(**self.dist_env):
86 accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin)
87
88 # Setup simple training components
89 train_set = RegressionDataset(length=80)
90 train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True)
91 model = AutoModel.from_pretrained(GPT2_TINY)
92 optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
93
94 model, optimizer, train_dataloader = accelerator.prepare(model, optimizer, train_dataloader)
95
96 model.train()
97
98 # Test gradient accumulation with accumulate context manager
99 batch_data = next(iter(train_dataloader))
100 # Create proper input format for GPT2 model (RegressionDataset returns {"x": scalar, "y": scalar})
101 # We need to create dummy input_ids for the GPT2 model
102 batch_size = batch_data["x"].shape[0] if isinstance(batch_data["x"], torch.Tensor) else 1
103
104 # Create dummy input_ids for GPT2 model and move to same device as model
105 device = next(model.parameters()).device
106 input_ids = torch.randint(0, 1000, (batch_size, 10), device=device) # batch_size x sequence_length
107 inputs = {"input_ids": input_ids}
108
109 # Track sync_gradients values to verify correct gradient accumulation behavior
110 sync_values = []
111
112 # Simulate gradient accumulation steps
113 for micro_step in range(gradient_accumulation_steps):
114 with accelerator.accumulate(model):
115 sync_values.append(accelerator.sync_gradients)
116 outputs = model(**inputs)
117 # Use the last hidden state and create a simple loss
118 prediction = outputs.last_hidden_state.mean()
119 loss = prediction.sum() # Simple scalar loss
120
121 # This should automatically handle gradient accumulation boundaries
122 accelerator.backward(loss)
123
124 if accelerator.sync_gradients:
125 optimizer.step()
126 optimizer.zero_grad()
127
128 # Verify gradient accumulation pattern was correct
129 # Should be False for first 3 steps, True for the last step
130 expected_sync = [False, False, False, True]
131 self.assertEqual(sync_values, expected_sync)
132
133 # Reset step counter for accelerator
134 accelerator.step = 0
135
136 def test_clip_grad_norm_returns_deepspeed_grad_norm(self):
137 """Test that clip_grad_norm_ works with DeepSpeed and returns gradient norm when available."""
138 deepspeed_plugin = DeepSpeedPlugin(
139 gradient_accumulation_steps=1,
140 gradient_clipping=1.0,
141 zero_stage=2,
142 offload_optimizer_device="cpu",
143 offload_param_device="cpu",
144 zero3_save_16bit_model=False,
145 zero3_init_flag=False,
146 )
147
148 with patch_environment(**self.dist_env):
149 accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin)
150
151 # Setup simple model
152 model = AutoModel.from_pretrained(GPT2_TINY)
153 optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
154
155 # Create a simple dataloader for prepare to work
156 train_set = RegressionDataset(length=16)
157 train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True)
158
159 model, optimizer, train_dataloader = accelerator.prepare(model, optimizer, train_dataloader)
160
161 # Perform a forward and backward pass to generate gradients
162 batch_data = next(iter(train_dataloader))
163 batch_size = len(batch_data["x"]) if isinstance(batch_data["x"], torch.Tensor) else 1
164
165 # Create dummy input_ids for GPT2 model and move to same device as model
166 device = next(model.parameters()).device
167 input_ids = torch.randint(0, 1000, (batch_size, 10), device=device)
168 inputs = {"input_ids": input_ids}
169
170 # Forward pass
171 outputs = model(**inputs)
172 prediction = outputs.last_hidden_state.mean()
173 loss = prediction.sum()
174
175 # Backward pass to generate gradients
176 accelerator.backward(loss)
177
178 # Test that gradient clipping works and returns a value
179 grad_norm = accelerator.clip_grad_norm_(model.parameters(), max_norm=1.0)
180 # After backward pass, we should get a valid gradient norm (either from DeepSpeed or fallback)
181 self.assertIsInstance(grad_norm, (int, float, type(None)))
182 if grad_norm is not None:
183 self.assertGreaterEqual(grad_norm, 0.0)
184
185 def test_accelerator_backward_passes_sync_gradients(self):
186 """Test that Accelerator.backward() passes sync_gradients to DeepSpeed wrapper."""
187 deepspeed_plugin = DeepSpeedPlugin(
188 gradient_accumulation_steps=2,
189 gradient_clipping=1.0,
190 zero_stage=2,
191 offload_optimizer_device="cpu",
192 offload_param_device="cpu",
193 zero3_save_16bit_model=False,
194 zero3_init_flag=False,
195 )
196
197 with patch_environment(**self.dist_env):
198 accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin)
199
200 # Setup simple model and data
201 model = AutoModel.from_pretrained(GPT2_TINY)
202 optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
203 train_set = RegressionDataset(length=16)
204 train_dataloader = DataLoader(train_set, batch_size=8, shuffle=True)
205
206 model, optimizer, train_dataloader = accelerator.prepare(model, optimizer, train_dataloader)
207
208 # Track sync_gradients values during backward calls
209 sync_values = []
210
211 # Test two gradient accumulation steps
212 batch_data = next(iter(train_dataloader))
213 # Create proper input format for GPT2 model
214 batch_size = len(batch_data["x"]) if isinstance(batch_data["x"], torch.Tensor) else 1
215
216 # Create dummy input_ids for GPT2 model and move to same device as model
217 device = next(model.parameters()).device
218 input_ids = torch.randint(0, 1000, (batch_size, 10), device=device)
219 inputs = {"input_ids": input_ids}
220
221 # First step - should have sync_gradients=False
222 with accelerator.accumulate(model):
223 sync_values.append(accelerator.sync_gradients)
224 outputs = model(**inputs)
225 prediction = outputs.last_hidden_state.mean()
226 loss = prediction # Simple loss
227 accelerator.backward(loss)
228
229 # Second step - should have sync_gradients=True
230 with accelerator.accumulate(model):
231 sync_values.append(accelerator.sync_gradients)
232 outputs = model(**inputs)
233 prediction = outputs.last_hidden_state.mean()
234 loss = prediction # Simple loss
235 accelerator.backward(loss)
236
237 # Verify sync_gradients pattern was correct
238 self.assertEqual(len(sync_values), 2)
239 self.assertFalse(sync_values[0]) # First step: not syncing
240 self.assertTrue(sync_values[1]) # Second step: syncing