AdithyaSK HF Staff commited on
Commit
51300e3
·
verified ·
1 Parent(s): 4c243b2

Stage Harbor release files 99501-100000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-f1fb6bb8619d/environment/source/tests/test_state_checkpointing.py +444 -0
  2. tasks/tasksmith-f1fb6bb8619d/environment/source/tests/test_tpu.py +34 -0
  3. tasks/tasksmith-f1fb6bb8619d/environment/source/tests/test_tracking.py +946 -0
  4. tasks/tasksmith-f1fb6bb8619d/environment/source/tests/test_utils.py +681 -0
  5. tasks/tasksmith-f1fb6bb8619d/environment/source/tests/tp/fsdp2_tp_preparation.py +107 -0
  6. tasks/tasksmith-f1fb6bb8619d/environment/source/tests/tp/fsdp2_tp_preparation_config.yaml +18 -0
  7. tasks/tasksmith-f1fb6bb8619d/environment/source/tests/tp/test_tp.py +79 -0
  8. tasks/tasksmith-f1fb6bb8619d/environment/source/tests/xla_spawn.py +94 -0
  9. tasks/tasksmith-f1fb6bb8619d/environment/source/utils/log_reports.py +177 -0
  10. tasks/tasksmith-f1fb6bb8619d/environment/source/utils/stale.py +69 -0
  11. tasks/tasksmith-f1fb6bb8619d/instruction.md +15 -0
  12. tasks/tasksmith-f1fb6bb8619d/solution/reference/src/accelerate/data_loader.py +1469 -0
  13. tasks/tasksmith-f1fb6bb8619d/solution/solve.sh +3 -0
  14. tasks/tasksmith-f1fb6bb8619d/task.toml +102 -0
  15. tasks/tasksmith-f1fb6bb8619d/tests/Dockerfile +9 -0
  16. tasks/tasksmith-f1fb6bb8619d/tests/contract.json +1 -0
  17. tasks/tasksmith-f1fb6bb8619d/tests/grade.py +112 -0
  18. tasks/tasksmith-f1fb6bb8619d/tests/source/.devcontainer/devcontainer.json +29 -0
  19. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml +63 -0
  20. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/PULL_REQUEST_TEMPLATE.md +47 -0
  21. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/dependabot.yml +11 -0
  22. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/build-docker-images-release.yml +110 -0
  23. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/build_and_run_tests.yml +50 -0
  24. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/build_docker_images.yml +116 -0
  25. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/build_documentation.yml +18 -0
  26. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/build_pr_documentation.yml +17 -0
  27. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/fp8_runner.yml +37 -0
  28. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/gaudi3_scheduled.yml +87 -0
  29. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/integration_tests.yml +58 -0
  30. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/nightly.yml +245 -0
  31. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/pr_style_bot.yml +20 -0
  32. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/quality.yml +24 -0
  33. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/run_merge_tests.yml +188 -0
  34. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/self_hosted_integration_tests.yml +127 -0
  35. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/stale.yml +33 -0
  36. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/test.yml +71 -0
  37. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/test_imports.yml +55 -0
  38. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/trufflehog.yml +15 -0
  39. tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/upload_pr_documentation.yml +20 -0
  40. tasks/tasksmith-f1fb6bb8619d/tests/source/.gitignore +144 -0
  41. tasks/tasksmith-f1fb6bb8619d/tests/source/.pre-commit-config.yaml +13 -0
  42. tasks/tasksmith-f1fb6bb8619d/tests/source/CODE_OF_CONDUCT.md +129 -0
  43. tasks/tasksmith-f1fb6bb8619d/tests/source/CONTRIBUTING.md +249 -0
  44. tasks/tasksmith-f1fb6bb8619d/tests/source/Dockerfile +7 -0
  45. tasks/tasksmith-f1fb6bb8619d/tests/source/LICENSE +201 -0
  46. tasks/tasksmith-f1fb6bb8619d/tests/source/Makefile +98 -0
  47. tasks/tasksmith-f1fb6bb8619d/tests/source/README.md +277 -0
  48. tasks/tasksmith-f1fb6bb8619d/tests/source/benchmarks/README.md +5 -0
  49. tasks/tasksmith-f1fb6bb8619d/tests/source/benchmarks/big_model_inference/README.md +46 -0
  50. tasks/tasksmith-f1fb6bb8619d/tests/source/benchmarks/big_model_inference/big_model_inference.py +143 -0
tasks/tasksmith-f1fb6bb8619d/environment/source/tests/test_state_checkpointing.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 logging
17
+ import os
18
+ import random
19
+ import shutil
20
+ import tempfile
21
+ import uuid
22
+ from contextlib import contextmanager
23
+
24
+ import pytest
25
+ import torch
26
+ from parameterized import parameterized_class
27
+ from torch import nn
28
+ from torch.utils.data import DataLoader, TensorDataset
29
+
30
+ from accelerate import Accelerator
31
+ from accelerate.test_utils import (
32
+ DEFAULT_LAUNCH_COMMAND,
33
+ execute_subprocess_async,
34
+ require_non_cpu,
35
+ require_non_torch_xla,
36
+ run_first,
37
+ )
38
+ from accelerate.test_utils.testing import AccelerateTestCase
39
+ from accelerate.utils import DistributedType, ProjectConfiguration, patch_environment, set_seed
40
+
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+
45
+ def dummy_dataloaders(a=2, b=3, batch_size=16, n_train_batches: int = 10, n_valid_batches: int = 2):
46
+ "Generates a tuple of dummy DataLoaders to test with"
47
+
48
+ def get_dataset(n_batches):
49
+ x = torch.randn(batch_size * n_batches, 1)
50
+ return TensorDataset(x, a * x + b + 0.1 * torch.randn(batch_size * n_batches, 1))
51
+
52
+ train_dataset = get_dataset(n_train_batches)
53
+ valid_dataset = get_dataset(n_valid_batches)
54
+ train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4)
55
+ valid_dataloader = DataLoader(valid_dataset, shuffle=False, batch_size=batch_size, num_workers=4)
56
+ return (train_dataloader, valid_dataloader)
57
+
58
+
59
+ def train(num_epochs, model, dataloader, optimizer, accelerator, scheduler=None):
60
+ "Trains for `num_epochs`"
61
+ rands = []
62
+ for epoch in range(num_epochs):
63
+ # Train quickly
64
+ model.train()
65
+ for batch in dataloader:
66
+ x, y = batch
67
+ outputs = model(x)
68
+ loss = torch.nn.functional.mse_loss(outputs, y)
69
+ accelerator.backward(loss)
70
+ optimizer.step()
71
+ optimizer.zero_grad()
72
+ rands.append(random.random()) # Introduce some randomness
73
+ if scheduler is not None:
74
+ scheduler.step()
75
+ return rands
76
+
77
+
78
+ class DummyModel(nn.Module):
79
+ "Simple model to do y=mx+b"
80
+
81
+ def __init__(self):
82
+ super().__init__()
83
+ self.a = nn.Parameter(torch.randn(1))
84
+ self.b = nn.Parameter(torch.randn(1))
85
+
86
+ def forward(self, x):
87
+ return x * self.a + self.b
88
+
89
+
90
+ def parameterized_custom_name_func(func, param_num, param):
91
+ # customize the test name generator function as we want both params to appear in the sub-test
92
+ # name, as by default it shows only the first param
93
+ param_based_name = "use_safetensors" if param["use_safetensors"] is True else "use_pytorch"
94
+ return f"{func.__name__}_{param_based_name}"
95
+
96
+
97
+ @parameterized_class(("use_safetensors",), [[True], [False]], class_name_func=parameterized_custom_name_func)
98
+ class CheckpointTest(AccelerateTestCase):
99
+ def check_adam_state(self, state1, state2, distributed_type):
100
+ # For DistributedType.XLA, the `accelerator.save_state` function calls `xm._maybe_convert_to_cpu` before saving.
101
+ # As a result, all tuple values are converted to lists. Therefore, we need to convert them back here.
102
+ # Remove this code once Torch XLA fixes this issue.
103
+ if distributed_type == DistributedType.XLA:
104
+ state1["param_groups"][0]["betas"] = tuple(state1["param_groups"][0]["betas"])
105
+ state2["param_groups"][0]["betas"] = tuple(state2["param_groups"][0]["betas"])
106
+ assert state1 == state2
107
+
108
+ def test_with_save_limit(self):
109
+ with tempfile.TemporaryDirectory() as tmpdir:
110
+ set_seed(42)
111
+ model = DummyModel()
112
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
113
+ train_dataloader, valid_dataloader = dummy_dataloaders()
114
+ project_config = ProjectConfiguration(total_limit=1, project_dir=tmpdir, automatic_checkpoint_naming=True)
115
+ # Train baseline
116
+ accelerator = Accelerator(project_config=project_config)
117
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
118
+ model, optimizer, train_dataloader, valid_dataloader
119
+ )
120
+ # Save initial
121
+ accelerator.save_state(safe_serialization=self.use_safetensors)
122
+
123
+ # Save second state
124
+ accelerator.save_state(safe_serialization=self.use_safetensors)
125
+ assert len(os.listdir(accelerator.project_dir)) == 1
126
+
127
+ def test_can_resume_training_with_folder(self):
128
+ with tempfile.TemporaryDirectory() as tmpdir:
129
+ set_seed(42)
130
+ model = DummyModel()
131
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
132
+ train_dataloader, valid_dataloader = dummy_dataloaders()
133
+ # Train baseline
134
+ accelerator = Accelerator()
135
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
136
+ model, optimizer, train_dataloader, valid_dataloader
137
+ )
138
+ # Save initial
139
+ initial = os.path.join(tmpdir, "initial")
140
+ accelerator.save_state(initial, safe_serialization=self.use_safetensors)
141
+ (a, b) = model.a.item(), model.b.item()
142
+ opt_state = optimizer.state_dict()
143
+ ground_truth_rands = train(3, model, train_dataloader, optimizer, accelerator)
144
+ (a1, b1) = model.a.item(), model.b.item()
145
+ opt_state1 = optimizer.state_dict()
146
+
147
+ # Train partially
148
+ set_seed(42)
149
+ model = DummyModel()
150
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
151
+ train_dataloader, valid_dataloader = dummy_dataloaders()
152
+ accelerator = Accelerator()
153
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
154
+ model, optimizer, train_dataloader, valid_dataloader
155
+ )
156
+ accelerator.load_state(initial)
157
+ (a2, b2) = model.a.item(), model.b.item()
158
+ opt_state2 = optimizer.state_dict()
159
+ self.assertEqual(a, a2)
160
+ self.assertEqual(b, b2)
161
+ assert a == a2
162
+ assert b == b2
163
+ self.check_adam_state(opt_state, opt_state2, accelerator.distributed_type)
164
+
165
+ test_rands = train(2, model, train_dataloader, optimizer, accelerator)
166
+ # Save everything
167
+ checkpoint = os.path.join(tmpdir, "checkpoint")
168
+ accelerator.save_state(checkpoint, safe_serialization=self.use_safetensors)
169
+
170
+ # Load everything back in and make sure all states work
171
+ accelerator.load_state(checkpoint)
172
+ test_rands += train(1, model, train_dataloader, optimizer, accelerator)
173
+ (a3, b3) = model.a.item(), model.b.item()
174
+ opt_state3 = optimizer.state_dict()
175
+ assert a1 == a3
176
+ assert b1 == b3
177
+ self.check_adam_state(opt_state1, opt_state3, accelerator.distributed_type)
178
+ assert ground_truth_rands == test_rands
179
+
180
+ def test_can_resume_training(self):
181
+ with tempfile.TemporaryDirectory() as tmpdir:
182
+ set_seed(42)
183
+ model = DummyModel()
184
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
185
+ train_dataloader, valid_dataloader = dummy_dataloaders()
186
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True)
187
+
188
+ # Train baseline
189
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
190
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
191
+ model, optimizer, train_dataloader, valid_dataloader
192
+ )
193
+ # Save initial
194
+ accelerator.save_state(safe_serialization=self.use_safetensors)
195
+ (a, b) = model.a.item(), model.b.item()
196
+ opt_state = optimizer.state_dict()
197
+ ground_truth_rands = train(3, model, train_dataloader, optimizer, accelerator)
198
+ (a1, b1) = model.a.item(), model.b.item()
199
+ opt_state1 = optimizer.state_dict()
200
+
201
+ # Train partially
202
+ set_seed(42)
203
+ model = DummyModel()
204
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
205
+ train_dataloader, valid_dataloader = dummy_dataloaders()
206
+ project_config = ProjectConfiguration(iteration=1, automatic_checkpoint_naming=True)
207
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
208
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
209
+ model, optimizer, train_dataloader, valid_dataloader
210
+ )
211
+ accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_0"))
212
+ (a2, b2) = model.a.item(), model.b.item()
213
+ opt_state2 = optimizer.state_dict()
214
+ assert a == a2
215
+ assert b == b2
216
+ self.check_adam_state(opt_state, opt_state2, accelerator.distributed_type)
217
+
218
+ test_rands = train(2, model, train_dataloader, optimizer, accelerator)
219
+ # Save everything
220
+ accelerator.save_state(safe_serialization=self.use_safetensors)
221
+
222
+ # Load everything back in and make sure all states work
223
+ accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_1"))
224
+ test_rands += train(1, model, train_dataloader, optimizer, accelerator)
225
+ (a3, b3) = model.a.item(), model.b.item()
226
+ opt_state3 = optimizer.state_dict()
227
+ assert a1 == a3
228
+ assert b1 == b3
229
+ self.check_adam_state(opt_state1, opt_state3, accelerator.distributed_type)
230
+ assert ground_truth_rands == test_rands
231
+
232
+ def test_can_resume_training_checkpoints_relative_path(self):
233
+ # See #1983
234
+ # This test is like test_can_resume_training but uses a relative path for the checkpoint and automatically
235
+ # infers the checkpoint path when loading.
236
+ @contextmanager
237
+ def temporary_relative_directory():
238
+ # This is equivalent to tempfile.TemporaryDirectory() except that it returns a relative path
239
+ rand_dir = f"test_path_{uuid.uuid4()}"
240
+ os.mkdir(rand_dir)
241
+ try:
242
+ yield rand_dir
243
+ finally:
244
+ shutil.rmtree(rand_dir)
245
+
246
+ with temporary_relative_directory() as tmpdir:
247
+ set_seed(42)
248
+ model = DummyModel()
249
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
250
+ train_dataloader, valid_dataloader = dummy_dataloaders()
251
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True)
252
+
253
+ # Train baseline
254
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
255
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
256
+ model, optimizer, train_dataloader, valid_dataloader
257
+ )
258
+ # Save initial
259
+ accelerator.save_state(safe_serialization=self.use_safetensors)
260
+ (a, b) = model.a.item(), model.b.item()
261
+ opt_state = optimizer.state_dict()
262
+ ground_truth_rands = train(3, model, train_dataloader, optimizer, accelerator)
263
+ (a1, b1) = model.a.item(), model.b.item()
264
+ opt_state1 = optimizer.state_dict()
265
+
266
+ # Train partially
267
+ set_seed(42)
268
+ model = DummyModel()
269
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
270
+ train_dataloader, valid_dataloader = dummy_dataloaders()
271
+ project_config = ProjectConfiguration(iteration=1, automatic_checkpoint_naming=True)
272
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
273
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
274
+ model, optimizer, train_dataloader, valid_dataloader
275
+ )
276
+ accelerator.load_state() # <= infer the directory automatically
277
+ (a2, b2) = model.a.item(), model.b.item()
278
+ opt_state2 = optimizer.state_dict()
279
+ assert a == a2
280
+ assert b == b2
281
+ self.check_adam_state(opt_state, opt_state2, accelerator.distributed_type)
282
+ assert opt_state == opt_state2
283
+
284
+ test_rands = train(2, model, train_dataloader, optimizer, accelerator)
285
+ # Save everything
286
+ accelerator.save_state(safe_serialization=self.use_safetensors)
287
+
288
+ # Load everything back in and make sure all states work
289
+ accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_1"))
290
+ test_rands += train(1, model, train_dataloader, optimizer, accelerator)
291
+ (a3, b3) = model.a.item(), model.b.item()
292
+ opt_state3 = optimizer.state_dict()
293
+ assert a1 == a3
294
+ assert b1 == b3
295
+ self.check_adam_state(opt_state1, opt_state3, accelerator.distributed_type)
296
+ assert ground_truth_rands == test_rands
297
+
298
+ def test_invalid_registration(self):
299
+ t = torch.tensor([1, 2, 3])
300
+ t1 = torch.tensor([2, 3, 4])
301
+ net = DummyModel()
302
+ opt = torch.optim.Adam(net.parameters())
303
+ accelerator = Accelerator()
304
+ with self.assertRaises(ValueError) as ve:
305
+ accelerator.register_for_checkpointing(t, t1, net, opt)
306
+ message = str(ve.exception)
307
+ assert "Item at index 0" in message
308
+ assert "Item at index 1" in message
309
+ assert "Item at index 2" not in message
310
+ assert "Item at index 3" not in message
311
+
312
+ def test_with_scheduler(self):
313
+ with tempfile.TemporaryDirectory() as tmpdir:
314
+ set_seed(42)
315
+ model = DummyModel()
316
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
317
+ scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
318
+ train_dataloader, valid_dataloader = dummy_dataloaders()
319
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True)
320
+ # Train baseline
321
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
322
+ model, optimizer, train_dataloader, valid_dataloader, scheduler = accelerator.prepare(
323
+ model, optimizer, train_dataloader, valid_dataloader, scheduler
324
+ )
325
+ # Save initial
326
+ accelerator.save_state(safe_serialization=self.use_safetensors)
327
+ scheduler_state = scheduler.state_dict()
328
+ train(3, model, train_dataloader, optimizer, accelerator, scheduler)
329
+ assert scheduler_state != scheduler.state_dict()
330
+
331
+ # Load everything back in and make sure all states work
332
+ accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_0"))
333
+ assert scheduler_state == scheduler.state_dict()
334
+
335
+ def test_automatic_loading(self):
336
+ with tempfile.TemporaryDirectory() as tmpdir:
337
+ set_seed(42)
338
+ model = DummyModel()
339
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
340
+ scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
341
+ train_dataloader, valid_dataloader = dummy_dataloaders()
342
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True)
343
+ # Train baseline
344
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
345
+ model, optimizer, train_dataloader, valid_dataloader, scheduler = accelerator.prepare(
346
+ model, optimizer, train_dataloader, valid_dataloader, scheduler
347
+ )
348
+ # Save initial
349
+ accelerator.save_state(safe_serialization=self.use_safetensors)
350
+ train(2, model, train_dataloader, optimizer, accelerator, scheduler)
351
+ (a2, b2) = model.a.item(), model.b.item()
352
+ # Save a first time
353
+ accelerator.save_state(safe_serialization=self.use_safetensors)
354
+ train(1, model, train_dataloader, optimizer, accelerator, scheduler)
355
+ (a3, b3) = model.a.item(), model.b.item()
356
+
357
+ # Load back in the last saved checkpoint, should point to a2, b2
358
+ accelerator.load_state()
359
+ assert a3 != model.a.item()
360
+ assert b3 != model.b.item()
361
+ assert a2 == model.a.item()
362
+ assert b2 == model.b.item()
363
+
364
+ def test_checkpoint_deletion(self):
365
+ with tempfile.TemporaryDirectory() as tmpdir:
366
+ set_seed(42)
367
+ model = DummyModel()
368
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True, total_limit=2)
369
+ # Train baseline
370
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
371
+ model = accelerator.prepare(model)
372
+ # Save 3 states:
373
+ for _ in range(11):
374
+ accelerator.save_state(safe_serialization=self.use_safetensors)
375
+ assert not os.path.exists(os.path.join(tmpdir, "checkpoints", "checkpoint_0"))
376
+ assert os.path.exists(os.path.join(tmpdir, "checkpoints", "checkpoint_9"))
377
+ assert os.path.exists(os.path.join(tmpdir, "checkpoints", "checkpoint_10"))
378
+
379
+ @run_first
380
+ @require_non_cpu
381
+ @require_non_torch_xla
382
+ def test_map_location(self):
383
+ cmd = DEFAULT_LAUNCH_COMMAND + [inspect.getfile(self.__class__)]
384
+
385
+ env_kwargs = dict(use_safe_tensors=str(self.use_safetensors), omp_num_threads="1")
386
+ with patch_environment(**env_kwargs):
387
+ execute_subprocess_async(cmd)
388
+
389
+
390
+ if __name__ == "__main__":
391
+ use_safetensors = os.environ.get("USE_SAFETENSORS", "False") == "True"
392
+ savedir = "/tmp/accelerate/state_checkpointing"
393
+ model = DummyModel()
394
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
395
+ scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
396
+ train_dataloader, valid_dataloader = dummy_dataloaders()
397
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True)
398
+ # Train baseline
399
+ accelerator = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="no")
400
+ if accelerator.process_index == 0:
401
+ if os.path.exists(savedir):
402
+ shutil.rmtree(savedir)
403
+ os.makedirs(savedir)
404
+ model, optimizer, train_dataloader, valid_dataloader, scheduler = accelerator.prepare(
405
+ model, optimizer, train_dataloader, valid_dataloader, scheduler
406
+ )
407
+ model, optimizer = accelerator.prepare(model, optimizer)
408
+ train(3, model, train_dataloader, optimizer, accelerator, scheduler)
409
+ # Check that the initial optimizer is loaded on the GPU
410
+ for group in optimizer.param_groups:
411
+ param_device = group["params"][0].device
412
+ break
413
+ assert param_device.type == accelerator.device.type
414
+ model = model.cpu()
415
+ accelerator.wait_for_everyone()
416
+ accelerator.save_state(safe_serialization=use_safetensors)
417
+ accelerator.wait_for_everyone()
418
+
419
+ # Check CPU state
420
+ accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="cpu")
421
+ for group in optimizer.param_groups:
422
+ param_device = group["params"][0].device
423
+ break
424
+ assert param_device.type == torch.device("cpu").type, (
425
+ f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"
426
+ )
427
+
428
+ # Check device state
429
+ model.to(accelerator.device)
430
+ accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="on_device")
431
+ for group in optimizer.param_groups:
432
+ param_device = group["params"][0].device
433
+ break
434
+ assert param_device.type == accelerator.device.type, (
435
+ f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"
436
+ )
437
+
438
+ # Check error
439
+ with pytest.raises(TypeError, match="Unsupported optimizer map location passed"):
440
+ accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="invalid")
441
+ accelerator.wait_for_everyone()
442
+ if accelerator.process_index == 0:
443
+ shutil.rmtree(savedir)
444
+ accelerator.wait_for_everyone()
tasks/tasksmith-f1fb6bb8619d/environment/source/tests/test_tpu.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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
+ import sys
17
+ import unittest
18
+
19
+ from accelerate.test_utils import execute_subprocess_async, path_in_accelerate_package, require_tpu
20
+
21
+
22
+ class MultiTPUTester(unittest.TestCase):
23
+ test_file_path = path_in_accelerate_package("test_utils", "scripts", "test_script.py")
24
+ test_dir = os.path.dirname(__file__)
25
+
26
+ @require_tpu
27
+ def test_tpu(self):
28
+ distributed_args = f"""
29
+ {self.test_dir}/xla_spawn.py
30
+ --num_cores 8
31
+ {self.test_file_path}
32
+ """.split()
33
+ cmd = [sys.executable] + distributed_args
34
+ execute_subprocess_async(cmd)
tasks/tasksmith-f1fb6bb8619d/environment/source/tests/test_tracking.py ADDED
@@ -0,0 +1,946 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 csv
16
+ import json
17
+ import logging
18
+ import os
19
+ import random
20
+ import re
21
+ import subprocess
22
+ import tempfile
23
+ import unittest
24
+ import zipfile
25
+ from pathlib import Path
26
+ from typing import Optional
27
+ from unittest import mock
28
+
29
+ import numpy as np
30
+ import torch
31
+ from packaging import version
32
+
33
+ # We use TF to parse the logs
34
+ from accelerate import Accelerator
35
+ from accelerate.state import PartialState
36
+ from accelerate.test_utils.testing import (
37
+ MockingTestCase,
38
+ TempDirTestCase,
39
+ require_aim,
40
+ require_clearml,
41
+ require_comet_ml,
42
+ require_dvclive,
43
+ require_matplotlib,
44
+ require_mlflow,
45
+ require_pandas,
46
+ require_swanlab,
47
+ require_tensorboard,
48
+ require_trackio,
49
+ require_wandb,
50
+ skip,
51
+ )
52
+ from accelerate.tracking import (
53
+ AimTracker,
54
+ ClearMLTracker,
55
+ CometMLTracker,
56
+ DVCLiveTracker,
57
+ GeneralTracker,
58
+ MLflowTracker,
59
+ SwanLabTracker,
60
+ TensorBoardTracker,
61
+ TrackioTracker,
62
+ WandBTracker,
63
+ )
64
+ from accelerate.utils import (
65
+ ProjectConfiguration,
66
+ is_comet_ml_available,
67
+ is_dvclive_available,
68
+ is_tensorboard_available,
69
+ )
70
+
71
+
72
+ if is_comet_ml_available():
73
+ from comet_ml import ExperimentConfig
74
+
75
+ if is_tensorboard_available():
76
+ import struct
77
+
78
+ from tensorboard.compat.proto import event_pb2
79
+
80
+ if is_dvclive_available():
81
+ from dvclive.plots.metric import Metric
82
+ from dvclive.serialize import load_yaml
83
+ from dvclive.utils import parse_metrics
84
+
85
+ logger = logging.getLogger(__name__)
86
+
87
+
88
+ @require_tensorboard
89
+ class TensorBoardTrackingTest(unittest.TestCase):
90
+ @unittest.skipIf(version.parse(np.__version__) >= version.parse("2.0"), "TB doesn't support numpy 2.0")
91
+ def test_init_trackers(self):
92
+ project_name = "test_project_with_config"
93
+ with tempfile.TemporaryDirectory() as dirpath:
94
+ accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath)
95
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
96
+ accelerator.init_trackers(project_name, config)
97
+ accelerator.end_training()
98
+ for child in Path(f"{dirpath}/{project_name}").glob("*/**"):
99
+ log = list(filter(lambda x: x.is_file(), child.iterdir()))[0]
100
+ assert str(log) != ""
101
+
102
+ def test_log(self):
103
+ project_name = "test_project_with_log"
104
+ with tempfile.TemporaryDirectory() as dirpath:
105
+ accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath)
106
+ accelerator.init_trackers(project_name)
107
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
108
+ accelerator.log(values, step=0)
109
+ accelerator.end_training()
110
+ # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
111
+ # Names are randomly generated each time
112
+ log = list(filter(lambda x: x.is_file(), Path(f"{dirpath}/{project_name}").iterdir()))[0]
113
+ assert str(log) != ""
114
+
115
+ def test_log_with_tensor(self):
116
+ project_name = "test_project_with_log"
117
+ with tempfile.TemporaryDirectory() as dirpath:
118
+ accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath)
119
+ accelerator.init_trackers(project_name)
120
+ values = {"tensor": torch.tensor(1)}
121
+ accelerator.log(values, step=0)
122
+ accelerator.end_training()
123
+ # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
124
+ # Names are randomly generated each time
125
+ log = list(filter(lambda x: x.is_file(), Path(f"{dirpath}/{project_name}").iterdir()))[0]
126
+ # Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685
127
+ with open(log, "rb") as f:
128
+ data = f.read()
129
+ found_tensor = False
130
+ while data:
131
+ header = struct.unpack("Q", data[:8])
132
+
133
+ event_str = data[12 : 12 + int(header[0])] # 8+4
134
+ data = data[12 + int(header[0]) + 4 :]
135
+ event = event_pb2.Event()
136
+
137
+ event.ParseFromString(event_str)
138
+ if event.HasField("summary"):
139
+ for value in event.summary.value:
140
+ if value.simple_value == 1.0 and value.tag == "tensor":
141
+ found_tensor = True
142
+ assert found_tensor, "Converted tensor was not found in the log file!"
143
+
144
+ def test_project_dir(self):
145
+ with self.assertRaisesRegex(ValueError, "Logging with `tensorboard` requires a `logging_dir`"):
146
+ _ = Accelerator(log_with="tensorboard")
147
+ with tempfile.TemporaryDirectory() as dirpath:
148
+ _ = Accelerator(log_with="tensorboard", project_dir=dirpath)
149
+
150
+ def test_project_dir_with_config(self):
151
+ config = ProjectConfiguration(total_limit=30)
152
+ with tempfile.TemporaryDirectory() as dirpath:
153
+ _ = Accelerator(log_with="tensorboard", project_dir=dirpath, project_config=config)
154
+
155
+
156
+ @require_wandb
157
+ @mock.patch.dict(os.environ, {"WANDB_MODE": "offline"})
158
+ class WandBTrackingTest(TempDirTestCase, MockingTestCase):
159
+ def setUp(self):
160
+ super().setUp()
161
+ # wandb let's us override where logs are stored to via the WANDB_DIR env var
162
+ self.add_mocks(mock.patch.dict(os.environ, {"WANDB_DIR": self.tmpdir}))
163
+
164
+ @staticmethod
165
+ def parse_log(log: str, section: str, record: bool = True):
166
+ """
167
+ Parses wandb log for `section` and returns a dictionary of
168
+ all items in that section. Section names are based on the
169
+ output of `wandb sync --view --verbose` and items starting
170
+ with "Record" in that result
171
+ """
172
+ # Big thanks to the W&B team for helping us parse their logs
173
+ pattern = rf"{section} ([\S\s]*?)\n\n"
174
+ if record:
175
+ pattern = rf"Record: {pattern}"
176
+ cleaned_record = re.findall(pattern, log)[0]
177
+ # A config
178
+ if section == "config" or section == "history":
179
+ cleaned_record = re.findall(r'"([a-zA-Z0-9_.,]+)', cleaned_record)
180
+ return {key: val for key, val in zip(cleaned_record[0::2], cleaned_record[1::2])}
181
+ # Everything else
182
+ else:
183
+ return dict(re.findall(r'(\w+): "([^\s]+)"', cleaned_record))
184
+
185
+ @skip
186
+ def test_wandb(self):
187
+ project_name = "test_project_with_config"
188
+ accelerator = Accelerator(log_with="wandb")
189
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
190
+ kwargs = {"wandb": {"tags": ["my_tag"]}}
191
+ accelerator.init_trackers(project_name, config, kwargs)
192
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
193
+ accelerator.log(values, step=0)
194
+ accelerator.end_training()
195
+ # The latest offline log is stored at wandb/latest-run/*.wandb
196
+ for child in Path(f"{self.tmpdir}/wandb/latest-run").glob("*"):
197
+ if child.is_file() and child.suffix == ".wandb":
198
+ cmd = ["wandb", "sync", "--view", "--verbose", str(child)]
199
+ content = subprocess.check_output(cmd, encoding="utf8", errors="ignore")
200
+ break
201
+
202
+ # Check HPS through careful parsing and cleaning
203
+ logged_items = self.parse_log(content, "config")
204
+ assert logged_items["num_iterations"] == "12"
205
+ assert logged_items["learning_rate"] == "0.01"
206
+ assert logged_items["some_boolean"] == "false"
207
+ assert logged_items["some_string"] == "some_value"
208
+ assert logged_items["some_string"] == "some_value"
209
+
210
+ # Run tags
211
+ logged_items = self.parse_log(content, "run", False)
212
+ assert logged_items["tags"] == "my_tag"
213
+
214
+ # Actual logging
215
+ logged_items = self.parse_log(content, "history")
216
+ assert logged_items["total_loss"] == "0.1"
217
+ assert logged_items["iteration"] == "1"
218
+ assert logged_items["my_text"] == "some_value"
219
+ assert logged_items["_step"] == "0"
220
+
221
+
222
+ @require_mlflow
223
+ class MLflowTrackingTest(unittest.TestCase):
224
+ def setUp(self):
225
+ import mlflow
226
+
227
+ self.tmpdir = tempfile.TemporaryDirectory()
228
+ mlflow.set_tracking_uri("file://" + self.tmpdir.name)
229
+
230
+ @require_matplotlib
231
+ def create_mock_figure(self):
232
+ """Create a mock figure for testing."""
233
+ import matplotlib.pyplot as plt
234
+
235
+ fig = plt.figure(figsize=(6, 4))
236
+ return fig
237
+
238
+ def test_log(self):
239
+ import mlflow
240
+
241
+ """Test that log calls mlflow.log_metrics with only numeric values and the correct step."""
242
+ values = {"accuracy": 0.95, "loss": 0.1, "non_numeric": "ignored"}
243
+ tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name)
244
+ accelerator = Accelerator(log_with=tracker)
245
+ accelerator.init_trackers(project_name="test_exp")
246
+ tracker.log(values, step=10)
247
+
248
+ run_id = tracker.active_run.info.run_id
249
+ accelerator.end_training()
250
+
251
+ # Retrieve the run and check the logged metrics.
252
+ run = mlflow.get_run(run_id)
253
+ metrics = run.data.metrics
254
+ self.assertEqual(metrics.get("accuracy"), 0.95)
255
+ self.assertEqual(metrics.get("loss"), 0.1)
256
+ self.assertNotIn("non_numeric", metrics)
257
+
258
+ @require_matplotlib
259
+ def test_log_figure(self):
260
+ import mlflow
261
+
262
+ """Test that log_figure calls mlflow.log_figure with the correct arguments."""
263
+ dummy_figure = self.create_mock_figure()
264
+ tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name)
265
+ accelerator = Accelerator(log_with=tracker)
266
+ accelerator.init_trackers(project_name="test_exp")
267
+ tracker.log_figure(dummy_figure, artifact_file="dummy_figure.png")
268
+
269
+ run_id = tracker.active_run.info.run_id
270
+ accelerator.end_training()
271
+
272
+ self.assertIn(
273
+ "dummy_figure.png",
274
+ [artifact.path for artifact in mlflow.artifacts.list_artifacts(run_id=run_id)],
275
+ )
276
+
277
+ def test_log_artifact(self):
278
+ import mlflow
279
+
280
+ """Test that log_artifact calls mlflow.log_artifact with the correct file path."""
281
+ dummy_file_path = os.path.join(self.tmpdir.name, "dummy.txt")
282
+ with open(dummy_file_path, "w") as f:
283
+ f.write("dummy content")
284
+ tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name)
285
+ accelerator = Accelerator(log_with=tracker)
286
+ accelerator.init_trackers(project_name="test_exp")
287
+ tracker.log_artifact(dummy_file_path, artifact_path="artifact_dir")
288
+
289
+ run_id = tracker.active_run.info.run_id
290
+ accelerator.end_training()
291
+
292
+ self.assertIn(
293
+ "artifact_dir/dummy.txt",
294
+ [
295
+ artifact.path
296
+ for artifact in mlflow.artifacts.list_artifacts(run_id=run_id, artifact_path="artifact_dir")
297
+ ],
298
+ )
299
+
300
+ def test_log_artifacts(self):
301
+ import mlflow
302
+
303
+ """Test that log_artifacts calls mlflow.log_artifacts with the correct directory."""
304
+ dummy_dir = os.path.join(self.tmpdir.name, "dummy_dir")
305
+ os.mkdir(dummy_dir)
306
+ dummy_file_path = os.path.join(dummy_dir, "dummy.txt")
307
+ with open(dummy_file_path, "w") as f:
308
+ f.write("dummy content")
309
+ tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name)
310
+ accelerator = Accelerator(log_with=tracker)
311
+ accelerator.init_trackers(project_name="test_exp")
312
+ tracker.log_artifacts(dummy_dir, artifact_path="artifact_dir")
313
+
314
+ run_id = tracker.active_run.info.run_id
315
+ accelerator.end_training()
316
+
317
+ self.assertIn(
318
+ "artifact_dir/dummy.txt",
319
+ [
320
+ artifact.path
321
+ for artifact in mlflow.artifacts.list_artifacts(run_id=run_id, artifact_path="artifact_dir")
322
+ ],
323
+ )
324
+
325
+ def test_store_init_configuration_does_not_mutate_input(self):
326
+ import mlflow
327
+
328
+ """`store_init_configuration` must not mutate the caller's dict when dropping over-long values.
329
+
330
+ The same `config` object is shared across all trackers in `Accelerator.init_trackers`, so deleting
331
+ keys in place removed them from the user's dict and from every other tracker too.
332
+ """
333
+ too_long = "x" * (mlflow.utils.validation.MAX_PARAM_VAL_LENGTH + 1)
334
+ values = {"learning_rate": 0.001, "too_long": too_long}
335
+ tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name)
336
+ accelerator = Accelerator(log_with=tracker)
337
+ accelerator.init_trackers(project_name="test_exp")
338
+ tracker.store_init_configuration(values)
339
+
340
+ run_id = tracker.active_run.info.run_id
341
+ accelerator.end_training()
342
+
343
+ # The caller's dict must be left untouched (previously `too_long` was deleted in place).
344
+ self.assertEqual(values, {"learning_rate": 0.001, "too_long": too_long})
345
+
346
+ # The over-long value is still dropped from what is actually logged to MLflow.
347
+ params = mlflow.get_run(run_id).data.params
348
+ self.assertIn("learning_rate", params)
349
+ self.assertNotIn("too_long", params)
350
+
351
+ def test_log_without_step(self):
352
+ """`MLflowTracker.log` should treat `step` as optional, matching the docstring."""
353
+ tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name)
354
+ accelerator = Accelerator(log_with=tracker)
355
+ accelerator.init_trackers(project_name="test_exp")
356
+ # Should not raise; previously raised TypeError because `step` had no default.
357
+ tracker.log({"loss": 0.1})
358
+ accelerator.end_training()
359
+
360
+ def test_log_accepts_extra_kwargs(self):
361
+ """`MLflowTracker.log` should accept extra kwargs forwarded by `Accelerator.log(log_kwargs=...)`.
362
+
363
+ Previously the signature omitted `**kwargs`, so any per-tracker kwarg (e.g. `synchronous`)
364
+ passed via `log_kwargs={"mlflow": {...}}` raised TypeError. Beyond not raising, the kwarg
365
+ must reach `mlflow.log_metrics` so it actually changes mlflow's behavior.
366
+ """
367
+ tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name)
368
+ accelerator = Accelerator(log_with=tracker)
369
+ accelerator.init_trackers(project_name="test_exp")
370
+ # `synchronous` is a real mlflow.log_metrics kwarg; the tracker must forward it.
371
+ with mock.patch("mlflow.log_metrics") as mock_log_metrics:
372
+ accelerator.log({"loss": 0.1}, step=1, log_kwargs={"mlflow": {"synchronous": True}})
373
+ accelerator.end_training()
374
+ mock_log_metrics.assert_called_once()
375
+ call_kwargs = mock_log_metrics.call_args.kwargs
376
+ assert call_kwargs.get("synchronous") is True, (
377
+ f"expected synchronous=True forwarded to mlflow.log_metrics, got kwargs={call_kwargs}"
378
+ )
379
+ assert call_kwargs.get("step") == 1, (
380
+ f"expected step=1 forwarded to mlflow.log_metrics, got kwargs={call_kwargs}"
381
+ )
382
+
383
+
384
+ @require_comet_ml
385
+ class CometMLTest(unittest.TestCase):
386
+ @staticmethod
387
+ def get_value_from_key(log_list, key: str, is_param: bool = False):
388
+ "Extracts `key` from Comet `log`"
389
+ for log in log_list:
390
+ j = json.loads(log)["payload"]
391
+ if is_param and "param" in j.keys():
392
+ if j["param"]["paramName"] == key:
393
+ return j["param"]["paramValue"]
394
+ if "log_other" in j.keys():
395
+ if j["log_other"]["key"] == key:
396
+ return j["log_other"]["val"]
397
+ if "metric" in j.keys():
398
+ if j["metric"]["metricName"] == key:
399
+ return j["metric"]["metricValue"]
400
+ if j.get("key", None) == key:
401
+ return j["value"]
402
+
403
+ def test_init_trackers(self):
404
+ with tempfile.TemporaryDirectory() as d:
405
+ tracker = CometMLTracker(
406
+ "test_project_with_config", online=False, experiment_config=ExperimentConfig(offline_directory=d)
407
+ )
408
+ accelerator = Accelerator(log_with=tracker)
409
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
410
+ accelerator.init_trackers(None, config)
411
+ accelerator.end_training()
412
+ log = os.listdir(d)[0] # Comet is nice, it's just a zip file here
413
+ # We parse the raw logs
414
+ p = os.path.join(d, log)
415
+ archive = zipfile.ZipFile(p, "r")
416
+ log = archive.open("messages.json").read().decode("utf-8")
417
+ list_of_json = log.split("\n")[:-1]
418
+ assert self.get_value_from_key(list_of_json, "num_iterations", True) == 12
419
+ assert self.get_value_from_key(list_of_json, "learning_rate", True) == 0.01
420
+ assert self.get_value_from_key(list_of_json, "some_boolean", True) is False
421
+ assert self.get_value_from_key(list_of_json, "some_string", True) == "some_value"
422
+
423
+ def test_log(self):
424
+ with tempfile.TemporaryDirectory() as d:
425
+ tracker = CometMLTracker(
426
+ "test_project_with_config", online=False, experiment_config=ExperimentConfig(offline_directory=d)
427
+ )
428
+ accelerator = Accelerator(log_with=tracker)
429
+ accelerator.init_trackers(None)
430
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
431
+ accelerator.log(values, step=0)
432
+ accelerator.end_training()
433
+ log = os.listdir(d)[0] # Comet is nice, it's just a zip file here
434
+ # We parse the raw logs
435
+ p = os.path.join(d, log)
436
+ archive = zipfile.ZipFile(p, "r")
437
+ log = archive.open("messages.json").read().decode("utf-8")
438
+ list_of_json = log.split("\n")[:-1]
439
+ assert self.get_value_from_key(list_of_json, "curr_step", True) == 0
440
+ assert self.get_value_from_key(list_of_json, "total_loss") == 0.1
441
+ assert self.get_value_from_key(list_of_json, "iteration") == 1
442
+ assert self.get_value_from_key(list_of_json, "my_text") == "some_value"
443
+
444
+
445
+ @require_clearml
446
+ class ClearMLTest(TempDirTestCase, MockingTestCase):
447
+ def setUp(self):
448
+ super().setUp()
449
+ # ClearML offline session location is stored in CLEARML_CACHE_DIR
450
+ self.add_mocks(mock.patch.dict(os.environ, {"CLEARML_CACHE_DIR": str(self.tmpdir)}))
451
+
452
+ @staticmethod
453
+ def _get_offline_dir(accelerator):
454
+ from clearml.config import get_offline_dir
455
+
456
+ return get_offline_dir(task_id=accelerator.get_tracker("clearml", unwrap=True).id)
457
+
458
+ @staticmethod
459
+ def _get_metrics(offline_dir):
460
+ metrics = []
461
+ with open(os.path.join(offline_dir, "metrics.jsonl")) as f:
462
+ json_lines = f.readlines()
463
+ for json_line in json_lines:
464
+ metrics.extend(json.loads(json_line))
465
+ return metrics
466
+
467
+ def test_init_trackers(self):
468
+ from clearml import Task
469
+ from clearml.utilities.config import text_to_config_dict
470
+
471
+ Task.set_offline(True)
472
+ accelerator = Accelerator(log_with="clearml")
473
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
474
+ accelerator.init_trackers("test_project_with_config", config)
475
+
476
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
477
+ accelerator.end_training()
478
+
479
+ with open(os.path.join(offline_dir, "task.json")) as f:
480
+ offline_session = json.load(f)
481
+ clearml_offline_config = text_to_config_dict(offline_session["configuration"]["General"]["value"])
482
+ assert config == clearml_offline_config
483
+
484
+ def test_log(self):
485
+ from clearml import Task
486
+
487
+ Task.set_offline(True)
488
+ accelerator = Accelerator(log_with="clearml")
489
+ accelerator.init_trackers("test_project_with_log")
490
+ values_with_iteration = {"should_be_under_train": 1, "eval_value": 2, "test_value": 3.1, "train_value": 4.1}
491
+ accelerator.log(values_with_iteration, step=1)
492
+ single_values = {"single_value_1": 1.1, "single_value_2": 2.2}
493
+ accelerator.log(single_values)
494
+
495
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
496
+ accelerator.end_training()
497
+
498
+ metrics = ClearMLTest._get_metrics(offline_dir)
499
+ assert (len(values_with_iteration) + len(single_values)) == len(metrics)
500
+ for metric in metrics:
501
+ if metric["metric"] == "Summary":
502
+ assert metric["variant"] in single_values
503
+ assert metric["value"] == single_values[metric["variant"]]
504
+ elif metric["metric"] == "should_be_under_train":
505
+ assert metric["variant"] == "train"
506
+ assert metric["iter"] == 1
507
+ assert metric["value"] == values_with_iteration["should_be_under_train"]
508
+ else:
509
+ values_with_iteration_key = metric["variant"] + "_" + metric["metric"]
510
+ assert values_with_iteration_key in values_with_iteration
511
+ assert metric["iter"] == 1
512
+ assert metric["value"] == values_with_iteration[values_with_iteration_key]
513
+
514
+ def test_log_images(self):
515
+ from clearml import Task
516
+
517
+ Task.set_offline(True)
518
+ accelerator = Accelerator(log_with="clearml")
519
+ accelerator.init_trackers("test_project_with_log_images")
520
+
521
+ base_image = np.eye(256, 256, dtype=np.uint8) * 255
522
+ base_image_3d = np.concatenate((np.atleast_3d(base_image), np.zeros((256, 256, 2), dtype=np.uint8)), axis=2)
523
+ images = {
524
+ "base_image": base_image,
525
+ "base_image_3d": base_image_3d,
526
+ }
527
+ accelerator.get_tracker("clearml").log_images(images, step=1)
528
+
529
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
530
+ accelerator.end_training()
531
+
532
+ images_saved = Path(os.path.join(offline_dir, "data")).rglob("*.jpeg")
533
+ assert len(list(images_saved)) == len(images)
534
+
535
+ def test_log_table(self):
536
+ from clearml import Task
537
+
538
+ Task.set_offline(True)
539
+ accelerator = Accelerator(log_with="clearml")
540
+ accelerator.init_trackers("test_project_with_log_table")
541
+
542
+ accelerator.get_tracker("clearml").log_table(
543
+ "from lists with columns", columns=["A", "B", "C"], data=[[1, 3, 5], [2, 4, 6]]
544
+ )
545
+ accelerator.get_tracker("clearml").log_table("from lists", data=[["A2", "B2", "C2"], [7, 9, 11], [8, 10, 12]])
546
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
547
+ accelerator.end_training()
548
+
549
+ metrics = ClearMLTest._get_metrics(offline_dir)
550
+ assert len(metrics) == 2
551
+ for metric in metrics:
552
+ assert metric["metric"] in ("from lists", "from lists with columns")
553
+ plot = json.loads(metric["plot_str"])
554
+ if metric["metric"] == "from lists with columns":
555
+ print(plot["data"][0])
556
+ self.assertCountEqual(plot["data"][0]["header"]["values"], ["A", "B", "C"])
557
+ self.assertCountEqual(plot["data"][0]["cells"]["values"], [[1, 2], [3, 4], [5, 6]])
558
+ else:
559
+ self.assertCountEqual(plot["data"][0]["header"]["values"], ["A2", "B2", "C2"])
560
+ self.assertCountEqual(plot["data"][0]["cells"]["values"], [[7, 8], [9, 10], [11, 12]])
561
+
562
+ @require_pandas
563
+ def test_log_table_pandas(self):
564
+ import pandas as pd
565
+ from clearml import Task
566
+
567
+ Task.set_offline(True)
568
+ accelerator = Accelerator(log_with="clearml")
569
+ accelerator.init_trackers("test_project_with_log_table_pandas")
570
+
571
+ accelerator.get_tracker("clearml").log_table(
572
+ "from df", dataframe=pd.DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}), step=1
573
+ )
574
+
575
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
576
+ accelerator.end_training()
577
+
578
+ metrics = ClearMLTest._get_metrics(offline_dir)
579
+ assert len(metrics) == 1
580
+ assert metrics[0]["metric"] == "from df"
581
+ plot = json.loads(metrics[0]["plot_str"])
582
+ self.assertCountEqual(plot["data"][0]["header"]["values"], [["A"], ["B"], ["C"]])
583
+ self.assertCountEqual(plot["data"][0]["cells"]["values"], [[1, 2], [3, 4], [5, 6]])
584
+
585
+
586
+ @require_swanlab
587
+ @mock.patch.dict(os.environ, {"SWANLAB_MODE": "local"})
588
+ class SwanLabTrackingTest(TempDirTestCase, MockingTestCase):
589
+ def setUp(self):
590
+ super().setUp()
591
+ # Setting Path where SwanLab parsed log files are saved via the SWANLAB_LOG_DIR env var
592
+ self.add_mocks(mock.patch.dict(os.environ, {"SWANLAB_LOG_DIR": self.tmpdir}))
593
+
594
+ @skip
595
+ def test_swanlab(self):
596
+ # Disable hardware monitoring to prevent errors in test mode.
597
+ import swanlab
598
+ from swanlab.log.backup import BackupHandler
599
+ from swanlab.log.backup.datastore import DataStore
600
+ from swanlab.log.backup.models import ModelsParser
601
+
602
+ swanlab.merge_settings(swanlab.Settings(hardware_monitor=False))
603
+ # Start a fake training session.
604
+ accelerator = Accelerator(log_with="swanlab")
605
+ project_name = "test_project_with_config"
606
+ experiment_name = "test"
607
+ description = "test project for swanlab"
608
+ tags = ["my_tag"]
609
+ config = {
610
+ "epochs": 10,
611
+ "learning_rate": 0.01,
612
+ "offset": 0.1,
613
+ }
614
+ kwargs = {
615
+ "swanlab": {
616
+ "experiment_name": experiment_name,
617
+ "description": description,
618
+ "tags": tags,
619
+ }
620
+ }
621
+ accelerator.init_trackers(project_name, config, kwargs)
622
+ record_metrics = []
623
+ record_scalars = []
624
+ record_images_count = 0
625
+ record_logs = []
626
+ for epoch in range(1, swanlab.config.epochs):
627
+ acc = 1 - 2**-epoch - random.random() / epoch - 0.1
628
+ loss = 2**-epoch + random.random() / epoch + 0.1
629
+ ll = swanlab.log(
630
+ {
631
+ "accuracy": acc,
632
+ "loss": loss,
633
+ "image": swanlab.Image(np.random.random((3, 3, 3))),
634
+ },
635
+ step=epoch,
636
+ )
637
+ log = f"epoch={epoch}, accuracy={acc}, loss={loss}"
638
+ print(log)
639
+ record_scalars.extend([acc, loss])
640
+ record_images_count += 1
641
+ record_logs.append(log)
642
+ record_metrics.extend([x for _, x in ll.items()])
643
+ accelerator.end_training()
644
+
645
+ # Load latest offline log
646
+ run_dir = swanlab.get_run().public.run_dir
647
+ assert os.path.exists(run_dir) is True
648
+ ds = DataStore()
649
+ ds.open_for_scan(os.path.join(run_dir.__str__(), BackupHandler.BACKUP_FILE).__str__())
650
+ with ModelsParser() as models_parser:
651
+ for record in ds:
652
+ if record is None:
653
+ continue
654
+ models_parser.parse_record(record)
655
+ header, project, experiment, logs, runtime, columns, scalars, medias, footer = models_parser.get_parsed()
656
+
657
+ # test file header
658
+ assert header.backup_type == "DEFAULT"
659
+
660
+ # test project info
661
+ assert project.name == project_name
662
+ assert project.workspace is None
663
+ assert project.public is None
664
+
665
+ # test experiment info
666
+ assert experiment.name is not None
667
+ assert experiment.description == description
668
+ assert experiment.tags == tags
669
+
670
+ # test log record
671
+ backup_logs = [log.message for log in logs]
672
+ for record_log in record_logs:
673
+ assert record_log in backup_logs, "Log not found in backup logs: " + record_log
674
+
675
+ # test runtime info
676
+ runtime_info = runtime.to_file_model(os.path.join(run_dir.__str__(), "files"))
677
+ assert runtime_info.conda is None, "Not using conda, should be None"
678
+ assert isinstance(runtime_info.requirements, str), "Requirements should be a string"
679
+ assert isinstance(runtime_info.metadata, dict), "Metadata should be a dictionary"
680
+ assert isinstance(runtime_info.config, dict), "Config should be a dictionary"
681
+ for key in runtime_info.config:
682
+ assert key in config, f"Config key {key} not found in original config"
683
+ assert runtime_info.config[key]["value"] == config[key], (
684
+ f"Config value for {key} does not match original value"
685
+ )
686
+
687
+ # test scalar
688
+ assert len(scalars) + len(medias) == len(record_metrics), "Total metrics count does not match"
689
+ backup_scalars = [
690
+ metric.metric["data"]
691
+ for metric in record_metrics
692
+ if metric.column_info.chart_type.value.column_type == "FLOAT"
693
+ ]
694
+ assert len(backup_scalars) == len(scalars), "Total scalars count does not match"
695
+ for scalar in backup_scalars:
696
+ assert scalar in record_scalars, f"Scalar {scalar} not found in original scalars"
697
+ backup_images = [
698
+ metric for metric in record_metrics if metric.column_info.chart_type.value.column_type == "IMAGE"
699
+ ]
700
+ assert len(backup_images) == record_images_count, "Total images count does not match"
701
+
702
+
703
+ class MyCustomTracker(GeneralTracker):
704
+ "Basic tracker that writes to a csv for testing"
705
+
706
+ _col_names = [
707
+ "total_loss",
708
+ "iteration",
709
+ "my_text",
710
+ "learning_rate",
711
+ "num_iterations",
712
+ "some_boolean",
713
+ "some_string",
714
+ ]
715
+
716
+ name = "my_custom_tracker"
717
+ requires_logging_directory = False
718
+
719
+ def __init__(self, dir: str, **kwargs):
720
+ super().__init__(**kwargs)
721
+ self.log_dir = dir
722
+ self.f = None
723
+ self.writer = None
724
+
725
+ def start(self):
726
+ if self.f is None:
727
+ self.f = open(os.path.join(self.log_dir, "log.csv"), "w+")
728
+ self.writer = csv.DictWriter(self.f, fieldnames=self._col_names)
729
+ self.writer.writeheader()
730
+
731
+ @property
732
+ def tracker(self):
733
+ return self.writer
734
+
735
+ def store_init_configuration(self, values: dict):
736
+ logger.info("Call init")
737
+ self.writer.writerow(values)
738
+
739
+ def log(self, values: dict, step: Optional[int] = None):
740
+ logger.info("Call log")
741
+ self.writer.writerow(values)
742
+
743
+ def finish(self):
744
+ self.f.close()
745
+
746
+
747
+ class CustomTrackerTestCase(unittest.TestCase):
748
+ def test_init_trackers(self):
749
+ with tempfile.TemporaryDirectory() as d:
750
+ tracker = MyCustomTracker(d)
751
+ accelerator = Accelerator(log_with=tracker)
752
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
753
+ accelerator.init_trackers("Some name", config)
754
+ accelerator.end_training()
755
+ with open(f"{d}/log.csv") as f:
756
+ data = csv.DictReader(f)
757
+ data = next(data)
758
+ truth = {
759
+ "total_loss": "",
760
+ "iteration": "",
761
+ "my_text": "",
762
+ "learning_rate": "0.01",
763
+ "num_iterations": "12",
764
+ "some_boolean": "False",
765
+ "some_string": "some_value",
766
+ }
767
+ assert data == truth
768
+
769
+ def test_log(self):
770
+ with tempfile.TemporaryDirectory() as d:
771
+ tracker = MyCustomTracker(d)
772
+ accelerator = Accelerator(log_with=tracker)
773
+ accelerator.init_trackers("Some name")
774
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
775
+ accelerator.log(values, step=0)
776
+ accelerator.end_training()
777
+ with open(f"{d}/log.csv") as f:
778
+ data = csv.DictReader(f)
779
+ data = next(data)
780
+ truth = {
781
+ "total_loss": "0.1",
782
+ "iteration": "1",
783
+ "my_text": "some_value",
784
+ "learning_rate": "",
785
+ "num_iterations": "",
786
+ "some_boolean": "",
787
+ "some_string": "",
788
+ }
789
+ assert data == truth
790
+
791
+ def test_init_trackers_none_kwargs(self):
792
+ with tempfile.TemporaryDirectory() as d:
793
+ tracker = MyCustomTracker(d)
794
+ accelerator = Accelerator(log_with=tracker)
795
+ # Passing init_kwargs=None must not raise AttributeError
796
+ accelerator.init_trackers("Some name", init_kwargs=None)
797
+ accelerator.end_training()
798
+
799
+ def test_log_none_kwargs(self):
800
+ with tempfile.TemporaryDirectory() as d:
801
+ tracker = MyCustomTracker(d)
802
+ accelerator = Accelerator(log_with=tracker)
803
+ accelerator.init_trackers("Some name")
804
+ values = {"total_loss": 0.1}
805
+ # Passing log_kwargs=None must not raise AttributeError
806
+ accelerator.log(values, step=0, log_kwargs=None)
807
+ accelerator.end_training()
808
+
809
+
810
+ @require_dvclive
811
+ @mock.patch("dvclive.live.get_dvc_repo", return_value=None)
812
+ class DVCLiveTrackingTest(unittest.TestCase):
813
+ def test_init_trackers(self, mock_repo):
814
+ project_name = "test_project_with_config"
815
+ with tempfile.TemporaryDirectory() as dirpath:
816
+ accelerator = Accelerator(log_with="dvclive")
817
+ config = {
818
+ "num_iterations": 12,
819
+ "learning_rate": 1e-2,
820
+ "some_boolean": False,
821
+ "some_string": "some_value",
822
+ }
823
+ init_kwargs = {"dvclive": {"dir": dirpath, "save_dvc_exp": False, "dvcyaml": None}}
824
+ accelerator.init_trackers(project_name, config, init_kwargs)
825
+ accelerator.end_training()
826
+ live = accelerator.trackers[0].live
827
+ params = load_yaml(live.params_file)
828
+ assert params == config
829
+
830
+ def test_log(self, mock_repo):
831
+ project_name = "test_project_with_log"
832
+ with tempfile.TemporaryDirectory() as dirpath:
833
+ accelerator = Accelerator(log_with="dvclive", project_dir=dirpath)
834
+ init_kwargs = {"dvclive": {"dir": dirpath, "save_dvc_exp": False, "dvcyaml": None}}
835
+ accelerator.init_trackers(project_name, init_kwargs=init_kwargs)
836
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
837
+ # Log step 0
838
+ accelerator.log(values)
839
+ # Log step 1
840
+ accelerator.log(values)
841
+ # Log step 3 (skip step 2)
842
+ accelerator.log(values, step=3)
843
+ accelerator.end_training()
844
+ live = accelerator.trackers[0].live
845
+ logs, latest = parse_metrics(live)
846
+ assert latest.pop("step") == 3
847
+ assert latest == values
848
+ scalars = os.path.join(live.plots_dir, Metric.subfolder)
849
+ for val in values:
850
+ val_path = os.path.join(scalars, f"{val}.tsv")
851
+ steps = [int(row["step"]) for row in logs[val_path]]
852
+ assert steps == [0, 1, 3]
853
+
854
+
855
+ class TrackerDeferredInitializationTest(unittest.TestCase):
856
+ """
857
+ Tests tracker's deferred initialization via `start()` method, preventing
858
+ premature `PartialState` access (and `torch.distributed` init) before
859
+ `Accelerator` has configured the distributed environment, especially with
860
+ `InitProcessGroupKwargs`.
861
+ """
862
+
863
+ @require_tensorboard
864
+ def test_tensorboard_deferred_init(self):
865
+ """Test that TensorBoard tracker initialization doesn't initialize distributed"""
866
+ with tempfile.TemporaryDirectory() as temp_dir:
867
+ PartialState._reset_state()
868
+ tracker = TensorBoardTracker(run_name="test_tb", logging_dir=temp_dir)
869
+ self.assertEqual(PartialState._shared_state, {})
870
+ _ = Accelerator(log_with=tracker)
871
+ self.assertNotEqual(PartialState._shared_state, {})
872
+
873
+ @require_wandb
874
+ def test_wandb_deferred_init(self):
875
+ """Test that WandB tracker initialization doesn't initialize distributed"""
876
+ PartialState._reset_state()
877
+ tracker = WandBTracker(run_name="test_wandb")
878
+ self.assertEqual(PartialState._shared_state, {})
879
+ _ = Accelerator(log_with=tracker)
880
+ self.assertNotEqual(PartialState._shared_state, {})
881
+
882
+ @require_trackio
883
+ def test_trackio_deferred_init(self):
884
+ """Test that trackio tracker initialization doesn't initialize distributed"""
885
+ PartialState._reset_state()
886
+ tracker = TrackioTracker(run_name="test_trackio")
887
+ self.assertEqual(PartialState._shared_state, {})
888
+ _ = Accelerator(log_with=tracker)
889
+ self.assertNotEqual(PartialState._shared_state, {})
890
+
891
+ @require_comet_ml
892
+ def test_comet_ml_deferred_init(self):
893
+ """Test that CometML tracker initialization doesn't initialize distributed"""
894
+ PartialState._reset_state()
895
+ tracker = CometMLTracker(run_name="test_comet")
896
+ self.assertEqual(PartialState._shared_state, {})
897
+ _ = Accelerator(log_with=tracker)
898
+ self.assertNotEqual(PartialState._shared_state, {})
899
+
900
+ @require_aim
901
+ def test_aim_deferred_init(self):
902
+ """Test that Aim tracker initialization doesn't initialize distributed"""
903
+ with tempfile.TemporaryDirectory() as temp_dir:
904
+ PartialState._reset_state()
905
+ tracker = AimTracker(run_name="test_aim", repo=temp_dir)
906
+ self.assertEqual(PartialState._shared_state, {})
907
+ _ = Accelerator(log_with=tracker)
908
+ self.assertNotEqual(PartialState._shared_state, {})
909
+
910
+ @require_mlflow
911
+ def test_mlflow_deferred_init(self):
912
+ """Test that MLflow tracker initialization doesn't initialize distributed"""
913
+ with tempfile.TemporaryDirectory() as temp_dir:
914
+ PartialState._reset_state()
915
+ tracker = MLflowTracker(experiment_name="test_mlflow", logging_dir=temp_dir)
916
+ self.assertEqual(PartialState._shared_state, {})
917
+ _ = Accelerator(log_with=tracker)
918
+ self.assertNotEqual(PartialState._shared_state, {})
919
+
920
+ @require_clearml
921
+ def test_clearml_deferred_init(self):
922
+ """Test that ClearML tracker initialization doesn't initialize distributed"""
923
+ PartialState._reset_state()
924
+ tracker = ClearMLTracker(run_name="test_clearml")
925
+ self.assertEqual(PartialState._shared_state, {})
926
+ _ = Accelerator(log_with=tracker)
927
+ self.assertNotEqual(PartialState._shared_state, {})
928
+
929
+ @require_dvclive
930
+ def test_dvclive_deferred_init(self):
931
+ """Test that DVCLive tracker initialization doesn't initialize distributed"""
932
+ with tempfile.TemporaryDirectory() as temp_dir:
933
+ PartialState._reset_state()
934
+ tracker = DVCLiveTracker(dir=temp_dir)
935
+ self.assertEqual(PartialState._shared_state, {})
936
+ _ = Accelerator(log_with=tracker)
937
+ self.assertNotEqual(PartialState._shared_state, {})
938
+
939
+ @require_swanlab
940
+ def test_swanlab_deferred_init(self):
941
+ """Test that SwanLab tracker initialization doesn't initialize distributed"""
942
+ PartialState._reset_state()
943
+ tracker = SwanLabTracker(run_name="test_swanlab")
944
+ self.assertEqual(PartialState._shared_state, {})
945
+ _ = Accelerator(log_with=tracker)
946
+ self.assertNotEqual(PartialState._shared_state, {})
tasks/tasksmith-f1fb6bb8619d/environment/source/tests/test_utils.py ADDED
@@ -0,0 +1,681 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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
+ import os
15
+ import pickle
16
+ import tempfile
17
+ import unittest
18
+ import warnings
19
+ from collections import UserDict, namedtuple
20
+ from typing import NamedTuple, Optional
21
+ from unittest.mock import Mock, patch
22
+
23
+ import numpy as np
24
+ import pytest
25
+ import torch
26
+ from torch import nn
27
+
28
+ from accelerate.big_modeling import cpu_offload_with_hook
29
+ from accelerate.hooks import attach_align_device_hook, remove_hook_from_module
30
+ from accelerate.state import PartialState
31
+ from accelerate.test_utils.testing import (
32
+ require_huggingface_suite,
33
+ require_non_cpu,
34
+ require_non_torch_xla,
35
+ require_torch_min_version,
36
+ require_tpu,
37
+ require_triton,
38
+ torch_device,
39
+ )
40
+ from accelerate.test_utils.training import RegressionModel
41
+ from accelerate.utils import (
42
+ CannotPadNestedTensorWarning,
43
+ check_os_kernel,
44
+ clear_environment,
45
+ concatenate,
46
+ convert_dict_to_env_variables,
47
+ convert_outputs_to_fp32,
48
+ convert_to_fp32,
49
+ extract_model_from_parallel,
50
+ find_device,
51
+ has_offloaded_params,
52
+ is_torch_xla_available,
53
+ listify,
54
+ pad_across_processes,
55
+ pad_input_tensors,
56
+ patch_environment,
57
+ purge_accelerate_environment,
58
+ recursively_apply,
59
+ save,
60
+ send_to_device,
61
+ )
62
+ from accelerate.utils.operations import is_namedtuple
63
+
64
+
65
+ if is_torch_xla_available():
66
+ import torch_xla.distributed.spmd as xs
67
+ import torch_xla.runtime as xr
68
+ from torch_xla.experimental.spmd_fully_sharded_data_parallel import SpmdFullyShardedDataParallel as FSDPv2
69
+
70
+ ExampleNamedTuple = namedtuple("ExampleNamedTuple", "a b c")
71
+
72
+
73
+ class UtilsTester(unittest.TestCase):
74
+ def setUp(self):
75
+ # logging requires initialized state
76
+ PartialState()
77
+
78
+ def test_send_to_device(self):
79
+ tensor = torch.randn(5, 2)
80
+ device = torch.device(f"{torch_device}:0")
81
+
82
+ result1 = send_to_device(tensor, device)
83
+ assert torch.equal(result1.cpu(), tensor)
84
+
85
+ result2 = send_to_device((tensor, [tensor, tensor], 1), device)
86
+ assert isinstance(result2, tuple)
87
+ assert torch.equal(result2[0].cpu(), tensor)
88
+ assert isinstance(result2[1], list)
89
+ assert torch.equal(result2[1][0].cpu(), tensor)
90
+ assert torch.equal(result2[1][1].cpu(), tensor)
91
+ assert result2[2] == 1
92
+
93
+ result2 = send_to_device({"a": tensor, "b": [tensor, tensor], "c": 1}, device)
94
+ assert isinstance(result2, dict)
95
+ assert torch.equal(result2["a"].cpu(), tensor)
96
+ assert isinstance(result2["b"], list)
97
+ assert torch.equal(result2["b"][0].cpu(), tensor)
98
+ assert torch.equal(result2["b"][1].cpu(), tensor)
99
+ assert result2["c"] == 1
100
+
101
+ result3 = send_to_device(ExampleNamedTuple(a=tensor, b=[tensor, tensor], c=1), device)
102
+ assert isinstance(result3, ExampleNamedTuple)
103
+ assert torch.equal(result3.a.cpu(), tensor)
104
+ assert isinstance(result3.b, list)
105
+ assert torch.equal(result3.b[0].cpu(), tensor)
106
+ assert torch.equal(result3.b[1].cpu(), tensor)
107
+ assert result3.c == 1
108
+
109
+ result4 = send_to_device(UserDict({"a": tensor, "b": [tensor, tensor], "c": 1}), device)
110
+ assert isinstance(result4, UserDict)
111
+ assert torch.equal(result4["a"].cpu(), tensor)
112
+ assert isinstance(result4["b"], list)
113
+ assert torch.equal(result4["b"][0].cpu(), tensor)
114
+ assert torch.equal(result4["b"][1].cpu(), tensor)
115
+ assert result4["c"] == 1
116
+
117
+ def test_honor_type(self):
118
+ with self.assertRaises(TypeError) as cm:
119
+ _ = recursively_apply(torch.tensor, (torch.tensor(1), 1), error_on_other_type=True)
120
+ assert (
121
+ str(cm.exception)
122
+ == "Unsupported types (<class 'int'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed."
123
+ )
124
+
125
+ def test_listify(self):
126
+ tensor = torch.tensor([1, 2, 3, 4, 5])
127
+ assert listify(tensor) == [1, 2, 3, 4, 5]
128
+
129
+ tensor = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
130
+ assert listify(tensor) == [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
131
+
132
+ tensor = torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]])
133
+ assert listify(tensor) == [[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]
134
+
135
+ def test_patch_environment(self):
136
+ with patch_environment(aa=1, BB=2):
137
+ assert os.environ.get("AA") == "1"
138
+ assert os.environ.get("BB") == "2"
139
+
140
+ assert "AA" not in os.environ
141
+ assert "BB" not in os.environ
142
+
143
+ def test_patch_environment_key_exists(self):
144
+ # check that patch_environment correctly restores pre-existing env vars
145
+ with patch_environment(aa=1, BB=2):
146
+ assert os.environ.get("AA") == "1"
147
+ assert os.environ.get("BB") == "2"
148
+
149
+ with patch_environment(Aa=10, bb="20", cC=30):
150
+ assert os.environ.get("AA") == "10"
151
+ assert os.environ.get("BB") == "20"
152
+ assert os.environ.get("CC") == "30"
153
+
154
+ assert os.environ.get("AA") == "1"
155
+ assert os.environ.get("BB") == "2"
156
+ assert "CC" not in os.environ
157
+
158
+ assert "AA" not in os.environ
159
+ assert "BB" not in os.environ
160
+ assert "CC" not in os.environ
161
+
162
+ def test_patch_environment_restores_on_error(self):
163
+ # we need to find an upper-case envvar
164
+ # because `patch_environment upper-cases all keys...
165
+ key, orig_value = next(kv for kv in os.environ.items() if kv[0].isupper())
166
+ new_value = f"{orig_value}_foofoofoo"
167
+ with pytest.raises(RuntimeError), patch_environment(**{key: new_value}):
168
+ assert os.environ[key] == os.getenv(key) == new_value # noqa: TID251
169
+ raise RuntimeError("Oopsy daisy!")
170
+ assert os.environ[key] == os.getenv(key) == orig_value # noqa: TID251
171
+
172
+ def test_clear_environment(self):
173
+ key, value = os.environ.copy().popitem()
174
+ with pytest.raises(RuntimeError), clear_environment():
175
+ assert key not in os.environ
176
+ assert not os.getenv(key) # test the environment is actually cleared # noqa: TID251
177
+ raise RuntimeError("Oopsy daisy!")
178
+ # Test values are restored
179
+ assert os.getenv(key) == os.environ[key] == value # noqa: TID251
180
+
181
+ def test_can_undo_convert_outputs(self):
182
+ model = RegressionModel()
183
+ model._original_forward = model.forward
184
+ model.forward = convert_outputs_to_fp32(model.forward)
185
+ model = extract_model_from_parallel(model, keep_fp32_wrapper=False)
186
+ _ = pickle.dumps(model)
187
+
188
+ @require_non_cpu
189
+ def test_can_undo_fp16_conversion(self):
190
+ model = RegressionModel()
191
+ model._original_forward = model.forward
192
+ model.forward = torch.autocast(device_type=torch_device, dtype=torch.float16)(model.forward)
193
+ model.forward = convert_outputs_to_fp32(model.forward)
194
+ model = extract_model_from_parallel(model, keep_fp32_wrapper=False)
195
+ _ = pickle.dumps(model)
196
+
197
+ @require_triton
198
+ @require_non_cpu
199
+ def test_dynamo(self):
200
+ model = RegressionModel().to(torch_device)
201
+ model._original_forward = model.forward
202
+ model.forward = torch.autocast(device_type=torch_device, dtype=torch.float16)(model.forward)
203
+ model.forward = convert_outputs_to_fp32(model.forward)
204
+ model.forward = torch.compile(model.forward, backend="inductor")
205
+ inputs = torch.randn(4, 10).to(torch_device)
206
+ _ = model(inputs)
207
+
208
+ def test_extract_model(self):
209
+ model = RegressionModel()
210
+ # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
211
+ distributed_model = torch.nn.parallel.DataParallel(model)
212
+ model_unwrapped = extract_model_from_parallel(distributed_model)
213
+
214
+ assert model == model_unwrapped
215
+
216
+ @require_tpu
217
+ @require_huggingface_suite
218
+ def test_extract_model_recursive_fsdpv2(self):
219
+ # Specifically tests for FSDPv2 extraction
220
+ # reported in https://github.com/huggingface/transformers/pull/29780
221
+ xr.use_spmd()
222
+ from transformers import AutoModelForCausalLM
223
+
224
+ model = AutoModelForCausalLM.from_pretrained("gpt2")
225
+ orig_state_dict_keys = list(model.state_dict().keys())
226
+ num_devices = xr.global_runtime_device_count()
227
+ # Set environment for FSDPv2 to be active
228
+ xs.set_global_mesh(xs.Mesh(np.array(range(num_devices)), (num_devices, 1), axis_names=("fsdp", "tensor")))
229
+
230
+ def nested_wrap(model):
231
+ layer = model.wte
232
+ wrapped_layer = FSDPv2(layer)
233
+ model.wte = wrapped_layer
234
+ return model
235
+
236
+ wrapped_model = nested_wrap(model)
237
+ unwrapped_model = extract_model_from_parallel(wrapped_model, recursive=True)
238
+ unwrapped_state_dict_keys = list(unwrapped_model.state_dict().keys())
239
+ for original_key, new_key in zip(orig_state_dict_keys, unwrapped_state_dict_keys):
240
+ assert original_key == new_key, f"Keys did not align: {original_key} != {new_key}"
241
+
242
+ def test_dynamo_extract_model_keep_torch_compile(self):
243
+ model = RegressionModel()
244
+ compiled_model = torch.compile(model)
245
+
246
+ # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
247
+ distributed_model = torch.nn.parallel.DataParallel(model)
248
+ distributed_compiled_model = torch.compile(distributed_model)
249
+ compiled_model_unwrapped = extract_model_from_parallel(distributed_compiled_model, keep_torch_compile=True)
250
+
251
+ assert compiled_model._orig_mod == compiled_model_unwrapped._orig_mod
252
+
253
+ def test_dynamo_extract_model_remove_torch_compile(self):
254
+ model = RegressionModel()
255
+ compiled_model = torch.compile(model)
256
+
257
+ # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
258
+ distributed_model = torch.nn.parallel.DataParallel(model)
259
+ distributed_compiled_model = torch.compile(distributed_model)
260
+ compiled_model_unwrapped = extract_model_from_parallel(distributed_compiled_model, keep_torch_compile=False)
261
+
262
+ assert compiled_model._orig_mod == compiled_model_unwrapped
263
+
264
+ def test_find_device(self):
265
+ assert find_device([1, "a", torch.tensor([1, 2, 3])]) == torch.device("cpu")
266
+ assert find_device({"a": 1, "b": torch.tensor([1, 2, 3])}) == torch.device("cpu")
267
+ assert find_device([1, "a"]) is None
268
+
269
+ def test_check_os_kernel_no_warning_when_release_gt_min(self):
270
+ # min version is 5.5
271
+ with patch("platform.uname", return_value=Mock(release="5.15.0-35-generic", system="Linux")):
272
+ with warnings.catch_warnings(record=True) as w:
273
+ check_os_kernel()
274
+ assert len(w) == 0
275
+
276
+ def test_check_os_kernel_no_warning_when_not_linux(self):
277
+ # system must be Linux
278
+ with patch("platform.uname", return_value=Mock(release="5.4.0-35-generic", system="Darwin")):
279
+ with warnings.catch_warnings(record=True) as w:
280
+ check_os_kernel()
281
+ assert len(w) == 0
282
+
283
+ def test_check_os_kernel_warning_when_release_lt_min(self):
284
+ # min version is 5.5
285
+ with patch("platform.uname", return_value=Mock(release="5.4.0-35-generic", system="Linux")):
286
+ with self.assertLogs() as ctx:
287
+ check_os_kernel()
288
+ assert len(ctx.records) == 1
289
+ assert ctx.records[0].levelname == "WARNING"
290
+ assert "5.4.0" in ctx.records[0].msg
291
+ assert "5.5.0" in ctx.records[0].msg
292
+
293
+ @require_non_torch_xla
294
+ def test_save_safetensor_shared_memory(self):
295
+ class Model(nn.Module):
296
+ def __init__(self):
297
+ super().__init__()
298
+ self.a = nn.Linear(100, 100)
299
+ self.b = self.a
300
+
301
+ def forward(self, x):
302
+ return self.b(self.a(x))
303
+
304
+ model = Model()
305
+ with tempfile.TemporaryDirectory() as tmp_dir:
306
+ save_path = os.path.join(tmp_dir, "model.safetensors")
307
+ with self.assertLogs(level="WARNING") as log:
308
+ save(model.state_dict(), save_path, safe_serialization=True)
309
+ assert len(log.records) == 1
310
+ assert "Removed shared tensor" in log.output[0]
311
+
312
+ @require_torch_min_version(version="1.12")
313
+ def test_pad_across_processes(self):
314
+ from torch.nested import nested_tensor
315
+
316
+ nt = nested_tensor([[1, 2, 3], [1], [1, 2]])
317
+ with self.assertWarns(CannotPadNestedTensorWarning):
318
+ nt2 = pad_across_processes(nt)
319
+ assert nt is nt2
320
+
321
+ # Basic functionality
322
+ tensor = torch.randn(4, 3, 100)
323
+ padded_tensor = pad_across_processes(tensor, dim=-1)
324
+ assert padded_tensor.shape[-1] == 100
325
+
326
+ # dim = -4 is out of bounds
327
+ padded_tensor = pad_across_processes(tensor, dim=-4)
328
+ assert padded_tensor is tensor
329
+
330
+ def test_slice_and_concatenate(self):
331
+ # First base case: 2 processes, batch size of 1
332
+ num_processes = 2
333
+ batch_size = 1
334
+ batch = torch.rand(batch_size, 4)
335
+ result = pad_input_tensors(batch, batch_size, num_processes)
336
+ # We should expect there to be 2 items now
337
+ assert result.shape == torch.Size([2, 4])
338
+
339
+ # Second base case: 2 processes, batch size of 3
340
+ num_processes = 2
341
+ batch_size = 3
342
+ batch = torch.rand(batch_size, 4)
343
+ result = pad_input_tensors(batch, batch_size, num_processes)
344
+ # We should expect there to be 4 items now
345
+ assert result.shape == torch.Size([4, 4])
346
+
347
+ # Third base case: 3 processes, batch size of 4
348
+ num_processes = 3
349
+ batch_size = 4
350
+ batch = torch.rand(batch_size, 4, 4)
351
+ result = pad_input_tensors(batch, batch_size, num_processes)
352
+ # We should expect there to be 6 items now
353
+ assert result.shape == torch.Size([6, 4, 4])
354
+
355
+ # Fourth base case: 4 processes, batch size of 3
356
+ num_processes = 4
357
+ batch_size = 3
358
+ batch = torch.rand(batch_size, 4, 4)
359
+ result = pad_input_tensors(batch, batch_size, num_processes)
360
+ # We should expect there to be 4 items now
361
+ assert result.shape == torch.Size([4, 4, 4])
362
+
363
+ # Fifth base case: 6 processes, batch size of 4
364
+ num_processes = 6
365
+ batch_size = 4
366
+ batch = torch.rand(batch_size, 4, 4)
367
+ result = pad_input_tensors(batch, batch_size, num_processes)
368
+ # We should expect there to be 6 items now
369
+ assert result.shape == torch.Size([6, 4, 4])
370
+
371
+ # Sixth base case: 6 processes, batch size of 1
372
+ num_processes = 6
373
+ batch_size = 1
374
+ batch = torch.rand(batch_size, 4, 4)
375
+ result = pad_input_tensors(batch, batch_size, num_processes)
376
+ # We should expect there to be 6 items now
377
+ assert result.shape == torch.Size([6, 4, 4])
378
+
379
+ # Seventh base case: 6 processes, batch size of 2
380
+ num_processes = 6
381
+ batch_size = 2
382
+ batch = torch.rand(batch_size, 4, 4)
383
+ result = pad_input_tensors(batch, batch_size, num_processes)
384
+ # We should expect there to be 6 items now
385
+ assert result.shape == torch.Size([6, 4, 4])
386
+
387
+ # Eighth base case: 6 processes, batch size of 61
388
+ num_processes = 6
389
+ batch_size = 61
390
+ batch = torch.rand(batch_size, 4, 4)
391
+ result = pad_input_tensors(batch, batch_size, num_processes)
392
+ # We should expect there to be 66 items now
393
+ assert result.shape == torch.Size([66, 4, 4])
394
+
395
+ def test_send_to_device_compiles(self):
396
+ compiled_send_to_device = torch.compile(send_to_device, fullgraph=True)
397
+ compiled_send_to_device(torch.zeros([1], dtype=torch.bfloat16), "cpu")
398
+
399
+ def test_convert_to_fp32(self):
400
+ compiled_convert_to_fp32 = torch.compile(convert_to_fp32, fullgraph=True)
401
+ compiled_convert_to_fp32(torch.zeros([1], dtype=torch.bfloat16))
402
+
403
+ def test_named_tuples(self):
404
+ class QuantTensorBase(NamedTuple):
405
+ value: torch.Tensor
406
+ scale: Optional[torch.Tensor]
407
+ zero_point: Optional[torch.Tensor]
408
+
409
+ class Second(QuantTensorBase):
410
+ pass
411
+
412
+ a = QuantTensorBase(torch.tensor(1.0), None, None)
413
+ b = Second(torch.tensor(1.0), None, None)
414
+
415
+ point = namedtuple("Point", ["x", "y"])
416
+ p = point(11, y=22)
417
+
418
+ self.assertTrue(is_namedtuple(a))
419
+ self.assertTrue(is_namedtuple(b))
420
+ self.assertTrue(is_namedtuple(p))
421
+ self.assertFalse(is_namedtuple((1, 2)))
422
+ self.assertFalse(is_namedtuple("hey"))
423
+ self.assertFalse(is_namedtuple(object()))
424
+
425
+ def test_convert_dict_to_env_variables(self):
426
+ env = {"ACCELERATE_DEBUG_MODE": "1", "BAD_ENV_NAME": "<mything", "OTHER_ENV": "2"}
427
+ with self.assertLogs("accelerate.utils.environment", level="WARNING"):
428
+ valid_env_items = convert_dict_to_env_variables(env)
429
+ assert valid_env_items == ["ACCELERATE_DEBUG_MODE=1\n", "OTHER_ENV=2\n"]
430
+
431
+ def test_has_offloaded_params(self):
432
+ model = RegressionModel()
433
+ assert not has_offloaded_params(model)
434
+
435
+ attach_align_device_hook(model, offload=False)
436
+ assert not has_offloaded_params(model)
437
+
438
+ remove_hook_from_module(model)
439
+ model, _ = cpu_offload_with_hook(model)
440
+ assert not has_offloaded_params(model)
441
+
442
+ remove_hook_from_module(model)
443
+ attach_align_device_hook(model, offload=True)
444
+ assert has_offloaded_params(model)
445
+
446
+ def test_concatenate(self):
447
+ tensor1 = torch.randn(2, 3)
448
+ tensor2 = torch.randn(2, 3)
449
+ result = concatenate([tensor1, tensor2])
450
+ assert result.shape == torch.Size([4, 3])
451
+ assert torch.equal(result[:2], tensor1)
452
+ assert torch.equal(result[2:], tensor2)
453
+
454
+ single_tensor = torch.randn(3, 4)
455
+ result = concatenate([single_tensor])
456
+ assert result.shape == torch.Size([3, 4])
457
+ assert torch.equal(result, single_tensor)
458
+
459
+ # NOTE: We return as-is if there's just a single batch of data, even if it's not a tensor
460
+ single_value = "test_string"
461
+ result = concatenate([single_value])
462
+ assert result == single_value
463
+
464
+ data = [
465
+ [torch.randn(2, 3), torch.randn(2, 4)],
466
+ [torch.randn(2, 3), torch.randn(2, 4)],
467
+ ]
468
+ result = concatenate(data)
469
+ assert isinstance(result, list)
470
+ assert len(result) == 2
471
+ assert result[0].shape == torch.Size([4, 3])
472
+ assert result[1].shape == torch.Size([4, 4])
473
+
474
+ data = [
475
+ (torch.randn(2, 3), torch.randn(2, 4)),
476
+ (torch.randn(2, 3), torch.randn(2, 4)),
477
+ ]
478
+ result = concatenate(data)
479
+ assert isinstance(result, tuple)
480
+ assert len(result) == 2
481
+ assert result[0].shape == torch.Size([4, 3])
482
+ assert result[1].shape == torch.Size([4, 4])
483
+
484
+ data = [
485
+ {"a": torch.randn(2, 3), "b": torch.randn(2, 4)},
486
+ {"a": torch.randn(2, 3), "b": torch.randn(2, 4)},
487
+ ]
488
+ result = concatenate(data)
489
+ assert isinstance(result, dict)
490
+ assert "a" in result and "b" in result
491
+ assert result["a"].shape == torch.Size([4, 3])
492
+ assert result["b"].shape == torch.Size([4, 4])
493
+
494
+ # NOTE: We can't merge multiple batches of non-tensor data
495
+ data = [
496
+ {"a": torch.randn(2, 3), "b": torch.randn(2, 4), "c": "test_string1"},
497
+ {"a": torch.randn(2, 3), "b": torch.randn(2, 4), "c": "test_string2"},
498
+ ]
499
+ with self.assertRaises(TypeError):
500
+ result = concatenate(data)
501
+
502
+ batch1 = torch.randn(5, 10)
503
+ batch2 = torch.randn(5, 10)
504
+ batch3 = torch.randn(5, 10)
505
+ result = concatenate([batch1, batch2, batch3])
506
+ assert result.shape == torch.Size([15, 10])
507
+ assert torch.equal(result[:5], batch1)
508
+ assert torch.equal(result[5:10], batch2)
509
+ assert torch.equal(result[10:], batch3)
510
+
511
+ # NOTE: We can't merge misaligned batches, the torch.cat will raise a RuntimeError
512
+ batch1 = torch.randn(5, 10)
513
+ batch2 = torch.randn(5, 12)
514
+ with self.assertRaises(RuntimeError):
515
+ result = concatenate([batch1, batch2])
516
+
517
+ tensor1 = torch.randn(3, 2, 4)
518
+ tensor2 = torch.randn(3, 2, 4)
519
+ result = concatenate([tensor1, tensor2], dim=1)
520
+ assert result.shape == torch.Size([3, 4, 4])
521
+
522
+ data = [
523
+ {"inputs": [torch.randn(2, 3), torch.randn(2, 4)], "labels": torch.randn(2, 1)},
524
+ {"inputs": [torch.randn(2, 3), torch.randn(2, 4)], "labels": torch.randn(2, 1)},
525
+ {"inputs": [torch.randn(2, 3), torch.randn(2, 4)], "labels": torch.randn(2, 1)},
526
+ ]
527
+ result = concatenate(data)
528
+ assert isinstance(result, dict)
529
+ assert isinstance(result["inputs"], list)
530
+ assert result["inputs"][0].shape == torch.Size([6, 3])
531
+ assert result["inputs"][1].shape == torch.Size([6, 4])
532
+ assert result["labels"].shape == torch.Size([6, 1])
533
+
534
+
535
+ def set_dummy_accelerate_env_var():
536
+ """Set an accelerate env var
537
+
538
+ This class emulates the behavior of, for instance, transformers.TrainingArguments, which is allowed to set
539
+ accelerate env vars but does not clean them up. E.g.
540
+
541
+ TrainingArguments(fp16=True, output_dir="/tmp/test")
542
+
543
+ leaves ACCELERATE_MIXED_PRECISION=fp16 as an env var.
544
+ """
545
+ os.environ["ACCELERATE_SOME_ENV_VAR"] = "true"
546
+
547
+
548
+ @purge_accelerate_environment
549
+ class MyUnittest(unittest.TestCase):
550
+ def test_purge_env_vars_unittest_1(self):
551
+ os.environ.pop("ACCELERATE_SOME_ENV_VAR", None)
552
+ set_dummy_accelerate_env_var()
553
+ assert "ACCELERATE_SOME_ENV_VAR" in os.environ
554
+
555
+ def test_purge_env_vars_unittest_2(self):
556
+ assert "ACCELERATE_SOME_ENV_VAR" not in os.environ
557
+
558
+
559
+ @unittest.skipIf(False, "dummy unittest wrapper")
560
+ @purge_accelerate_environment
561
+ @unittest.skipUnless(True, "dummy unittest wrapper")
562
+ class MyUnittestWithDecorators(unittest.TestCase):
563
+ def test_purge_env_vars_unittest_with_wrapper_1(self):
564
+ os.environ.pop("ACCELERATE_SOME_ENV_VAR", None)
565
+ set_dummy_accelerate_env_var()
566
+ assert "ACCELERATE_SOME_ENV_VAR" in os.environ
567
+
568
+ def test_purge_env_vars_unittest_with_wrapper_2(self):
569
+ assert "ACCELERATE_SOME_ENV_VAR" not in os.environ
570
+
571
+ @unittest.skipIf(False, "dummy unittest wrapper")
572
+ def test_purge_env_vars_unittest_with_wrapper_3(self):
573
+ assert "ACCELERATE_SOME_ENV_VAR" not in os.environ
574
+
575
+ @unittest.skipIf(True, "this is always skipped")
576
+ def test_purge_env_vars_unittest_with_wrapper_4(self):
577
+ # ensure that unittest markers still do their job
578
+ assert False
579
+
580
+
581
+ @purge_accelerate_environment
582
+ class _BaseCls(unittest.TestCase):
583
+ def test_purge_env_vars_unittest_with_inheritance_3(self):
584
+ assert "ACCELERATE_SOME_ENV_VAR" not in os.environ
585
+
586
+
587
+ class MyUnittestWithInheritance(_BaseCls):
588
+ def test_purge_env_vars_unittest_with_inheritance_1(self):
589
+ os.environ.pop("ACCELERATE_SOME_ENV_VAR", None)
590
+ set_dummy_accelerate_env_var()
591
+ assert "ACCELERATE_SOME_ENV_VAR" in os.environ
592
+
593
+ def test_purge_env_vars_unittest_with_inheritance_2(self):
594
+ assert "ACCELERATE_SOME_ENV_VAR" not in os.environ
595
+
596
+
597
+ @purge_accelerate_environment
598
+ class TestMyPytest:
599
+ def test_purge_env_vars_pytest_1(self):
600
+ os.environ.pop("ACCELERATE_SOME_ENV_VAR", None)
601
+ set_dummy_accelerate_env_var()
602
+ assert "ACCELERATE_SOME_ENV_VAR" in os.environ
603
+
604
+ def test_purge_env_vars_pytest_2(self):
605
+ assert "ACCELERATE_SOME_ENV_VAR" not in os.environ
606
+
607
+
608
+ @pytest.fixture
609
+ def dummy_fixture():
610
+ pass
611
+
612
+
613
+ @pytest.mark.skipif(False, reason="dummy pytest wrapper")
614
+ @pytest.mark.usefixtures("dummy_fixture")
615
+ @purge_accelerate_environment
616
+ @pytest.mark.skipif(False, reason="dummy pytest wrapper")
617
+ @pytest.mark.usefixtures("dummy_fixture")
618
+ class TestPytestWithWrapper:
619
+ def test_purge_env_vars_pytest_with_wrapper_1(self):
620
+ os.environ.pop("ACCELERATE_SOME_ENV_VAR", None)
621
+ set_dummy_accelerate_env_var()
622
+ assert "ACCELERATE_SOME_ENV_VAR" in os.environ
623
+
624
+ def test_purge_env_vars_pytest_with_wrapper_2(self):
625
+ assert "ACCELERATE_SOME_ENV_VAR" not in os.environ
626
+
627
+ @pytest.mark.skipif(False, reason="dummy pytest wrapper")
628
+ @pytest.mark.usefixtures("dummy_fixture")
629
+ def test_purge_env_vars_pytest_with_wrapper_3(self):
630
+ assert "ACCELERATE_SOME_ENV_VAR" not in os.environ
631
+
632
+ @pytest.mark.skipif(True, reason="this is always skipped")
633
+ def test_purge_env_vars_pytest_with_wrapper_4_should_be_skipped(self):
634
+ # ensure that pytest markers still do their job
635
+ assert False
636
+
637
+
638
+ @purge_accelerate_environment
639
+ class _PytestBaseCls:
640
+ def test_purge_env_vars_pytest_with_inheritance_3(self):
641
+ assert "ACCELERATE_SOME_ENV_VAR" not in os.environ
642
+
643
+
644
+ class TestPytestWithInheritance(_PytestBaseCls):
645
+ def test_purge_env_vars_pytest_with_inheritance_1(self):
646
+ os.environ.pop("ACCELERATE_SOME_ENV_VAR", None)
647
+ set_dummy_accelerate_env_var()
648
+ assert "ACCELERATE_SOME_ENV_VAR" in os.environ
649
+
650
+ def test_purge_env_vars_pytest_with_inheritance_2(self):
651
+ assert "ACCELERATE_SOME_ENV_VAR" not in os.environ
652
+
653
+
654
+ @purge_accelerate_environment
655
+ def test_purge_env_vars_standalone_1():
656
+ os.environ.pop("ACCELERATE_SOME_ENV_VAR", None)
657
+ set_dummy_accelerate_env_var()
658
+ assert "ACCELERATE_SOME_ENV_VAR" in os.environ
659
+
660
+
661
+ def test_purge_env_vars_standalone_2():
662
+ assert "ACCELERATE_SOME_ENV_VAR" not in os.environ
663
+
664
+
665
+ def test_purge_env_vars_restores_previous_values():
666
+ # Ensure that purge_accelerate_environment restores values of previous accelerate env vars and does not delete
667
+ # untouched env vars.
668
+ @purge_accelerate_environment
669
+ def dummy_func():
670
+ os.environ["ACCELERATE_SOME_ENV_VAR"] = "456"
671
+
672
+ os.environ["ACCELERATE_SOME_ENV_VAR"] = "1"
673
+ os.environ["ACCELERATE_ANOTHER_ENV_VAR"] = "2"
674
+
675
+ dummy_func()
676
+
677
+ assert os.environ["ACCELERATE_SOME_ENV_VAR"] == "1"
678
+ assert os.environ["ACCELERATE_ANOTHER_ENV_VAR"] == "2"
679
+
680
+ del os.environ["ACCELERATE_SOME_ENV_VAR"]
681
+ del os.environ["ACCELERATE_ANOTHER_ENV_VAR"]
tasks/tasksmith-f1fb6bb8619d/environment/source/tests/tp/fsdp2_tp_preparation.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from datetime import timedelta
16
+
17
+ import torch
18
+ from datasets import load_dataset
19
+ from torch.utils.data import DataLoader
20
+ from transformers import AutoModelForCausalLM, AutoTokenizer
21
+
22
+ from accelerate import Accelerator, InitProcessGroupKwargs
23
+ from accelerate.parallelism_config import ParallelismConfig
24
+ from accelerate.utils import FullyShardedDataParallelPlugin
25
+
26
+
27
+ class LmHeadWrapper(torch.nn.Module):
28
+ def __init__(self, lm_head):
29
+ super().__init__()
30
+ self.lm_head = lm_head
31
+
32
+ def forward(self, x):
33
+ return self.lm_head(x)
34
+
35
+
36
+ def build_simple_dataloader(tokenizer, seq_len=64, batch_size=2):
37
+ """Build a simple dataloader for reproduction."""
38
+ # Load small dataset
39
+ raw = load_dataset("wikitext", "wikitext-2-raw-v1", split="train[:1%]")
40
+ raw = raw.filter(lambda x: len(tokenizer(x["text"])["input_ids"]) > 0)
41
+ raw = raw.select(range(min(100, len(raw)))) # Use only 100 samples
42
+
43
+ def tok_fn(examples):
44
+ return tokenizer(examples["text"], truncation=True, max_length=seq_len)
45
+
46
+ ds = raw.map(tok_fn, batched=True, remove_columns=["text"])
47
+ ds.set_format(type="torch", columns=["input_ids"])
48
+
49
+ def collate(batch):
50
+ ids = [b["input_ids"] for b in batch]
51
+ labels = [x.clone() for x in ids]
52
+ pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id
53
+ x = torch.nn.utils.rnn.pad_sequence(ids, batch_first=True, padding_value=pad_id)
54
+ y = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=-100)
55
+ return {"input_ids": x, "labels": y}
56
+
57
+ return DataLoader(ds, batch_size=batch_size, shuffle=False, collate_fn=collate)
58
+
59
+
60
+ def main():
61
+ # Configuration
62
+ MODEL_NAME = "Qwen/Qwen3-0.6B"
63
+ BATCH_SIZE = 2
64
+ SEQ_LEN = 64
65
+ TP = 2
66
+ DP = 4 // TP
67
+
68
+ # Setup Accelerator with FSDP2
69
+ init_kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=1800))
70
+ pc = ParallelismConfig(dp_shard_size=DP, tp_size=TP)
71
+
72
+ fsdp_plugin = FullyShardedDataParallelPlugin(
73
+ fsdp_version=2,
74
+ reshard_after_forward=True,
75
+ auto_wrap_policy="transformer_based_wrap",
76
+ state_dict_type="SHARDED_STATE_DICT",
77
+ activation_checkpointing=False,
78
+ cpu_ram_efficient_loading=True,
79
+ )
80
+
81
+ accelerator = Accelerator(kwargs_handlers=[init_kwargs], parallelism_config=pc, fsdp_plugin=fsdp_plugin)
82
+
83
+ rank = accelerator.process_index
84
+ print(f"[Rank {rank}] Initializing...")
85
+
86
+ # Load model with TP if needed
87
+ model_kwargs = {"tp_size": TP, "tp_plan": "auto", "device_mesh": accelerator.torch_device_mesh} if TP > 1 else {}
88
+
89
+ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, use_cache=False, **model_kwargs)
90
+
91
+ model.lm_head = LmHeadWrapper(model.lm_head)
92
+
93
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
94
+ optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
95
+
96
+ print(f"[Rank {rank}] Building dataloader...")
97
+ loader = build_simple_dataloader(tokenizer, seq_len=SEQ_LEN, batch_size=BATCH_SIZE)
98
+
99
+ print(f"[Rank {rank}] Preparing with accelerator...")
100
+ # ERROR OCCURS HERE AT LINE 110 in original script
101
+ model, optimizer, loader = accelerator.prepare(model, optimizer, loader)
102
+
103
+ print(f"[Rank {rank}] Preparation successful!")
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()
tasks/tasksmith-f1fb6bb8619d/environment/source/tests/tp/fsdp2_tp_preparation_config.yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FSDP2 Single Node Configuration
2
+ # Status: CURRENT - Recommended for new single-node usage
3
+
4
+ compute_environment: LOCAL_MACHINE
5
+ debug: false
6
+ distributed_type: FSDP
7
+ downcast_bf16: 'no'
8
+ machine_rank: 0
9
+ main_training_function: main
10
+ mixed_precision: 'no'
11
+ num_machines: 1
12
+ num_processes: 4 # Adjust for your GPU count
13
+ rdzv_backend: static
14
+ same_network: true
15
+ tpu_env: []
16
+ tpu_use_cluster: false
17
+ tpu_use_sudo: false
18
+ use_cpu: false
tasks/tasksmith-f1fb6bb8619d/environment/source/tests/tp/test_tp.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ import os
17
+
18
+ from accelerate.test_utils.testing import (
19
+ TempDirTestCase,
20
+ execute_subprocess_async,
21
+ get_launch_command,
22
+ path_in_accelerate_package,
23
+ require_multi_device,
24
+ require_non_torch_xla,
25
+ require_tp,
26
+ require_transformers,
27
+ run_first,
28
+ slow,
29
+ )
30
+ from accelerate.utils import patch_environment
31
+
32
+
33
+ @require_non_torch_xla
34
+ @require_multi_device
35
+ @require_transformers
36
+ @require_tp
37
+ @run_first
38
+ @slow
39
+ class TPIntegrationTest(TempDirTestCase):
40
+ test_scripts_folder = path_in_accelerate_package("test_utils", "scripts", "external_deps")
41
+
42
+ def setUp(self):
43
+ super().setUp()
44
+ self.test_tp_size = 2
45
+ self.model_name_or_path = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
46
+ self.batch_size = 1
47
+ from accelerate.utils import set_seed
48
+
49
+ set_seed(42)
50
+
51
+ def test_working_of_tp(self):
52
+ self.test_file_path = self.test_scripts_folder / "test_performance.py"
53
+ cmd = get_launch_command(num_processes=self.test_tp_size, num_machines=1, machine_rank=0)
54
+ cmd.extend(
55
+ [
56
+ self.test_file_path,
57
+ f"--output_dir={self.tmpdir}",
58
+ f"--model_name_or_path={self.model_name_or_path}",
59
+ "--add_pad_token=true",
60
+ "--tp_plan=auto",
61
+ f"--tp_size={self.test_tp_size}",
62
+ ]
63
+ )
64
+ with patch_environment(omp_num_threads=1):
65
+ execute_subprocess_async(cmd)
66
+
67
+ def test_working_of_tp_and_fsdp(self):
68
+ current_dir = os.path.dirname(os.path.abspath(__file__))
69
+ self.test_file_path = os.path.join(current_dir, "fsdp2_tp_preparation.py")
70
+ self.test_config_path = os.path.join(current_dir, "fsdp2_tp_preparation_config.yaml")
71
+ cmd = get_launch_command()
72
+ cmd.extend(
73
+ [
74
+ f"--config_file={self.test_config_path}",
75
+ self.test_file_path,
76
+ ]
77
+ )
78
+ with patch_environment(omp_num_threads=4):
79
+ execute_subprocess_async(cmd)
tasks/tasksmith-f1fb6bb8619d/environment/source/tests/xla_spawn.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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
+ """
16
+ A simple launcher script for TPU training
17
+
18
+ Inspired by https://github.com/pytorch/pytorch/blob/master/torch/distributed/launch.py
19
+
20
+ ::
21
+ >>> python xla_spawn.py --num_cores=NUM_CORES_YOU_HAVE
22
+ YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other
23
+ arguments of your training script)
24
+
25
+ """
26
+
27
+ import importlib
28
+ import sys
29
+ from argparse import REMAINDER, ArgumentParser
30
+ from pathlib import Path
31
+
32
+ import torch_xla.distributed.xla_multiprocessing as xmp
33
+ from torch_xla import device_count
34
+
35
+
36
+ def parse_args():
37
+ """
38
+ Helper function parsing the command line options
39
+ @retval ArgumentParser
40
+ """
41
+ parser = ArgumentParser(
42
+ description=(
43
+ "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"
44
+ )
45
+ )
46
+
47
+ # Optional arguments for the launch helper
48
+ num_devices = device_count()
49
+ parser.add_argument(
50
+ "--num_cores",
51
+ type=int,
52
+ default=num_devices,
53
+ help="Number of TPU cores to use (1 or number of available devices).",
54
+ )
55
+
56
+ # positional
57
+ parser.add_argument(
58
+ "training_script",
59
+ type=str,
60
+ help=(
61
+ "The full path to the single TPU training "
62
+ "program/script to be launched in parallel, "
63
+ "followed by all the arguments for the "
64
+ "training script"
65
+ ),
66
+ )
67
+
68
+ # rest from the training program
69
+ parser.add_argument("training_script_args", nargs=REMAINDER)
70
+
71
+ return parser.parse_args()
72
+
73
+
74
+ def main():
75
+ args = parse_args()
76
+
77
+ # Import training_script as a module.
78
+ script_fpath = Path(args.training_script)
79
+ sys.path.append(str(script_fpath.parent.resolve()))
80
+ mod_name = script_fpath.stem
81
+ mod = importlib.import_module(mod_name)
82
+
83
+ # Patch sys.argv
84
+ sys.argv = [args.training_script] + args.training_script_args
85
+ num_cores = args.num_cores
86
+ if num_cores == device_count() and num_cores != 1:
87
+ # There is an error in xmp.spawn that causes it to fail when num_cores is specified and not 1, so we set it to
88
+ # None when it matches the number of devices.
89
+ num_cores = None
90
+ xmp.spawn(mod._mp_fn, args=(), nprocs=args.num_cores)
91
+
92
+
93
+ if __name__ == "__main__":
94
+ main()
tasks/tasksmith-f1fb6bb8619d/environment/source/utils/log_reports.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import json
15
+ import os
16
+ from datetime import date
17
+ from pathlib import Path
18
+
19
+ from tabulate import DataRow, TableFormat, tabulate
20
+
21
+
22
+ hf_table_format = TableFormat(
23
+ lineabove=None,
24
+ linebelowheader=None,
25
+ linebetweenrows=None,
26
+ linebelow=None,
27
+ headerrow=DataRow("", "|", "|"),
28
+ datarow=DataRow("", "|", "|"),
29
+ padding=1,
30
+ with_header_hide=None,
31
+ )
32
+
33
+
34
+ failed = []
35
+ group_info = []
36
+
37
+ no_error_payload = {"type": "section", "text": {"type": "plain_text", "text": "No failed tests! 🤗", "emoji": True}}
38
+
39
+ payload = [
40
+ {
41
+ "type": "header",
42
+ "text": {
43
+ "type": "plain_text",
44
+ "text": f"🤗 Accelerate nightly {os.environ.get('TEST_TYPE', '')} test results",
45
+ "emoji": True,
46
+ },
47
+ }
48
+ ]
49
+
50
+ total_num_failed = 0
51
+ for log in Path().glob("*.log"):
52
+ section_num_failed = 0
53
+ with open(log) as f:
54
+ for line in f:
55
+ line = json.loads(line)
56
+ if line.get("nodeid", "") != "":
57
+ test = line["nodeid"]
58
+ if line.get("duration", None) is not None:
59
+ duration = f"{line['duration']:.4f}"
60
+ if line.get("outcome", "") == "failed":
61
+ section_num_failed += 1
62
+ failed.append([test, duration, log.name.split("_")[0]])
63
+ total_num_failed += 1
64
+ group_info.append([str(log), section_num_failed, failed])
65
+ failed = []
66
+ log.unlink()
67
+
68
+ message = ""
69
+ all_files2failed = []
70
+ if total_num_failed > 0:
71
+ for name, num_failed, failed_tests in group_info:
72
+ if num_failed > 0:
73
+ if num_failed == 1:
74
+ message += f"*{name[1:]}: {num_failed} failed test*\n"
75
+ else:
76
+ message += f"*{name[1:]}: {num_failed} failed tests*\n"
77
+ failed_table = []
78
+ files2failed = {}
79
+ for test in failed_tests:
80
+ data = test[0].split("::")
81
+ data[0] = data[0].split("/")[-1]
82
+ if data[0] not in files2failed:
83
+ files2failed[data[0]] = [data[1:]]
84
+ else:
85
+ files2failed[data[0]] += [data[1:]]
86
+ failed_table.append(data)
87
+
88
+ files = [test[0] for test in failed_table]
89
+ individual_files = list(set(files))
90
+ # Count number of instances in failed_tests
91
+ table = []
92
+ for file in individual_files:
93
+ table.append([file, len(files2failed[file])])
94
+
95
+ failed_table = tabulate(
96
+ table,
97
+ headers=["Test Location", "Num Failed"],
98
+ tablefmt=hf_table_format,
99
+ stralign="right",
100
+ )
101
+ message += f"\n```\n{failed_table}\n```"
102
+ all_files2failed.append(files2failed)
103
+ if len(message) > 3000:
104
+ err = "Too many failed tests, please see the full report in the Action results."
105
+ offset = len(err) + 10
106
+ message = message[: 3000 - offset] + f"\n...\n```\n{err}"
107
+ print(f"### {message}")
108
+ else:
109
+ message = "No failed tests! 🤗"
110
+ print(f"## {message}")
111
+ payload.append(no_error_payload)
112
+
113
+ if os.environ.get("TEST_TYPE", "") != "":
114
+ from slack_sdk import WebClient
115
+
116
+ client = WebClient(token=os.environ["SLACK_API_TOKEN"])
117
+ if message != "No failed tests! 🤗":
118
+ md_report = {
119
+ "type": "section",
120
+ "text": {
121
+ "type": "mrkdwn",
122
+ "text": message,
123
+ },
124
+ }
125
+ payload.append(md_report)
126
+ action_button = {
127
+ "type": "section",
128
+ "text": {
129
+ "type": "mrkdwn",
130
+ "text": "*For more details:*",
131
+ },
132
+ "accessory": {
133
+ "type": "button",
134
+ "text": {
135
+ "type": "plain_text",
136
+ "text": "Check Action results",
137
+ "emoji": True,
138
+ },
139
+ "url": f"https://github.com/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}",
140
+ },
141
+ }
142
+ payload.append(action_button)
143
+ date_report = {
144
+ "type": "context",
145
+ "elements": [
146
+ {
147
+ "type": "plain_text",
148
+ "text": f"Nightly {os.environ.get('TEST_TYPE')} test results for {date.today()}",
149
+ }
150
+ ],
151
+ }
152
+ payload.append(date_report)
153
+ response = client.chat_postMessage(channel="#accelerate-ci-daily", text=message, blocks=payload)
154
+ ts = response.data["ts"]
155
+ for failed_file in all_files2failed:
156
+ for test_location, test_failures in failed_file.items():
157
+ # Keep only the first instance of the test name
158
+ test_class = ""
159
+ for i, row in enumerate(test_failures):
160
+ if row[0] != test_class:
161
+ test_class = row[0]
162
+ else:
163
+ test_failures[i][0] = ""
164
+
165
+ payload = {
166
+ "type": "section",
167
+ "text": {
168
+ "type": "mrkdwn",
169
+ "text": f"Test location: {test_location}\n```\n{tabulate(test_failures, headers=['Class', 'Test'], tablefmt=hf_table_format, stralign='right')}\n```",
170
+ },
171
+ }
172
+
173
+ client.chat_postMessage(
174
+ channel="#accelerate-ci-daily",
175
+ thread_ts=ts,
176
+ blocks=[payload],
177
+ )
tasks/tasksmith-f1fb6bb8619d/environment/source/utils/stale.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team, the AllenNLP library authors. 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
+ Script to close stale issue. Taken in part from the AllenNLP repository.
16
+ https://github.com/allenai/allennlp.
17
+ """
18
+
19
+ import os
20
+ from datetime import datetime as dt
21
+ from datetime import timezone
22
+
23
+ from github import Github
24
+
25
+
26
+ LABELS_TO_EXEMPT = [
27
+ "good first issue",
28
+ "feature request",
29
+ "wip",
30
+ ]
31
+
32
+
33
+ def main():
34
+ g = Github(os.environ["GITHUB_TOKEN"])
35
+ repo = g.get_repo("huggingface/accelerate")
36
+ open_issues = repo.get_issues(state="open")
37
+
38
+ for issue in open_issues:
39
+ comments = sorted([comment for comment in issue.get_comments()], key=lambda i: i.created_at, reverse=True)
40
+ last_comment = comments[0] if len(comments) > 0 else None
41
+ current_time = dt.now(timezone.utc)
42
+ days_since_updated = (current_time - issue.updated_at).days
43
+ days_since_creation = (current_time - issue.created_at).days
44
+ if (
45
+ last_comment is not None
46
+ and last_comment.user.login == "github-actions[bot]"
47
+ and days_since_updated > 7
48
+ and days_since_creation >= 30
49
+ and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels())
50
+ ):
51
+ # Close issue since it has been 7 days of inactivity since bot mention.
52
+ issue.edit(state="closed")
53
+ elif (
54
+ days_since_updated > 23
55
+ and days_since_creation >= 30
56
+ and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels())
57
+ ):
58
+ # Add stale comment
59
+ issue.create_comment(
60
+ "This issue has been automatically marked as stale because it has not had "
61
+ "recent activity. If you think this still needs to be addressed "
62
+ "please comment on this thread.\n\nPlease note that issues that do not follow the "
63
+ "[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) "
64
+ "are likely to be ignored."
65
+ )
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
tasks/tasksmith-f1fb6bb8619d/instruction.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Extend `BatchSamplerShard` (in `src/accelerate/data_loader.py`) to support variable-length (dynamic) batch sizes — samplers where `batch_size` is `None` — when `even_batches=True`.
2
+
3
+ **Current broken behaviour (base branch):** constructing `BatchSamplerShard` with a sampler that has no `batch_size` attribute and `even_batches=True` raises `ValueError: "You need to use even_batches=False when the batch sampler has no batch size"`.
4
+
5
+ **Required behaviour after the fix:**
6
+
7
+ 1. **`even_batches=True` with `batch_size=None` must work.** Each shard receives every `num_processes`-th batch (round-robin). When the total number of batches is not a round multiple of `num_processes`, the short processes are padded by cycling whole batches from the first `num_processes` batches seen, preserving each batch as an intact list rather than flattening indices. Example with 2 processes and batches `[[0,1,2],[3,4],[5,6,7,8],[9,10,11],[12,13]]`:
8
+ - process 0 → `[[0,1,2], [5,6,7,8], [12,13]]`
9
+ - process 1 → `[[3,4], [9,10,11], [0,1,2]]` ← padded with the first batch
10
+
11
+ 2. **`split_batches=True` must raise `ValueError` whenever `batch_size` is `None`** (in addition to the existing check that the batch size must be divisible by `num_processes`). Both conditions use the same error message mentioning "split_batches" and "round multiple".
12
+
13
+ 3. **Existing behaviour is fully preserved:** fixed batch sizes with `even_batches=True`/`False`, `drop_last=True`, and `split_batches=True` with a divisible fixed batch size all continue to work as before.
14
+
15
+ Work in `/workspace`. Submit your fix in the existing Python source files under `src/accelerate/data_loader.py`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files.
tasks/tasksmith-f1fb6bb8619d/solution/reference/src/accelerate/data_loader.py ADDED
@@ -0,0 +1,1469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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 importlib
16
+ import math
17
+ from contextlib import suppress
18
+ from typing import Callable, Optional, Union
19
+
20
+ import torch
21
+ from packaging import version
22
+ from torch.utils.data import BatchSampler, DataLoader, IterableDataset, RandomSampler
23
+
24
+ from .logging import get_logger
25
+ from .state import DistributedType, GradientState, PartialState, is_torch_xla_available
26
+ from .utils import (
27
+ RNGType,
28
+ broadcast,
29
+ broadcast_object_list,
30
+ compare_versions,
31
+ concatenate,
32
+ find_batch_size,
33
+ get_data_structure,
34
+ initialize_tensors,
35
+ is_datasets_available,
36
+ is_torch_version,
37
+ is_torchdata_stateful_dataloader_available,
38
+ send_to_device,
39
+ slice_tensors,
40
+ synchronize_rng_states,
41
+ )
42
+
43
+
44
+ logger = get_logger(__name__)
45
+
46
+ # kwargs of the DataLoader in min version 2.0
47
+ _PYTORCH_DATALOADER_KWARGS = {
48
+ "batch_size": 1,
49
+ "shuffle": False,
50
+ "sampler": None,
51
+ "batch_sampler": None,
52
+ "num_workers": 0,
53
+ "collate_fn": None,
54
+ "pin_memory": False,
55
+ "drop_last": False,
56
+ "timeout": 0,
57
+ "worker_init_fn": None,
58
+ "multiprocessing_context": None,
59
+ "generator": None,
60
+ "prefetch_factor": 2,
61
+ "persistent_workers": False,
62
+ "pin_memory_device": "",
63
+ }
64
+
65
+ # kwargs added after by version
66
+ _PYTORCH_DATALOADER_ADDITIONAL_KWARGS = {"2.6.0": {"in_order": True}}
67
+
68
+ for v, additional_kwargs in _PYTORCH_DATALOADER_ADDITIONAL_KWARGS.items():
69
+ if is_torch_version(">=", v):
70
+ _PYTORCH_DATALOADER_KWARGS.update(additional_kwargs)
71
+
72
+
73
+ class SeedableRandomSampler(RandomSampler):
74
+ """
75
+ Same as a random sampler, except that in `__iter__` a seed can be used.
76
+
77
+ Needed specifically in distributed cases, when the random generator for each GPU needs to start from the same seed
78
+ and be fully reproducible on multiple iterations.
79
+
80
+ If a custom `generator` is passed, it will rely on its initial seed as well as the current iteration it is on
81
+ (stored in `self.epoch`).
82
+ """
83
+
84
+ def __init__(self, *args, **kwargs):
85
+ data_seed = kwargs.pop("data_seed", None)
86
+ super().__init__(*args, **kwargs)
87
+
88
+ self.initial_seed = data_seed if data_seed is not None else torch.random.initial_seed()
89
+ self.epoch = 0
90
+
91
+ def __iter__(self):
92
+ if self.generator is None:
93
+ self.generator = torch.Generator(
94
+ device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"
95
+ )
96
+ self.generator.manual_seed(self.initial_seed)
97
+
98
+ # Allow `self.epoch` to modify the seed of the generator
99
+ seed = self.epoch + self.initial_seed
100
+ # print("Setting seed at epoch", self.epoch, seed)
101
+ self.generator.manual_seed(seed)
102
+ yield from super().__iter__()
103
+ self.set_epoch(self.epoch + 1)
104
+
105
+ def set_epoch(self, epoch: int):
106
+ "Sets the current iteration of the sampler."
107
+ self.epoch = epoch
108
+
109
+
110
+ class BatchSamplerShard(BatchSampler):
111
+ """
112
+ Wraps a PyTorch `BatchSampler` to generate batches for one of the processes only. Instances of this class will
113
+ always yield a number of batches that is a round multiple of `num_processes` and that all have the same size.
114
+ Depending on the value of the `drop_last` attribute of the batch sampler passed, it will either stop the iteration
115
+ at the first batch that would be too small / not present on all processes or loop with indices from the beginning.
116
+
117
+ Args:
118
+ batch_sampler (`torch.utils.data.sampler.BatchSampler`):
119
+ The batch sampler to split in several shards.
120
+ num_processes (`int`, *optional*, defaults to 1):
121
+ The number of processes running concurrently.
122
+ process_index (`int`, *optional*, defaults to 0):
123
+ The index of the current process.
124
+ split_batches (`bool`, *optional*, defaults to `False`):
125
+ Whether the shards should be created by splitting a batch to give a piece of it on each process, or by
126
+ yielding different full batches on each process.
127
+
128
+ On two processes with a sampler of `[[0, 1, 2, 3], [4, 5, 6, 7]]`, this will result in:
129
+
130
+ - the sampler on process 0 to yield `[0, 1, 2, 3]` and the sampler on process 1 to yield `[4, 5, 6, 7]` if
131
+ this argument is set to `False`.
132
+ - the sampler on process 0 to yield `[0, 1]` then `[4, 5]` and the sampler on process 1 to yield `[2, 3]`
133
+ then `[6, 7]` if this argument is set to `True`.
134
+ even_batches (`bool`, *optional*, defaults to `True`):
135
+ Whether or not to loop back at the beginning of the sampler when the number of samples is not a round
136
+ multiple of (original batch size / number of processes).
137
+
138
+ <Tip warning={true}>
139
+
140
+ `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`
141
+ equal to `False`
142
+
143
+ </Tip>"""
144
+
145
+ def __init__(
146
+ self,
147
+ batch_sampler: BatchSampler,
148
+ num_processes: int = 1,
149
+ process_index: int = 0,
150
+ split_batches: bool = False,
151
+ even_batches: bool = True,
152
+ ):
153
+ self.batch_sampler = batch_sampler
154
+ self.num_processes = num_processes
155
+ self.process_index = process_index
156
+ self.split_batches = split_batches
157
+ self.even_batches = even_batches
158
+ self.batch_size = getattr(batch_sampler, "batch_size", None)
159
+ self.drop_last = getattr(batch_sampler, "drop_last", False)
160
+ if split_batches and (self.batch_size is None or self.batch_size % num_processes != 0):
161
+ raise ValueError(
162
+ f"To use `BatchSamplerShard` in `split_batches` mode, the batch size ({self.batch_size}) "
163
+ f"needs to be a round multiple of the number of processes ({num_processes})."
164
+ )
165
+
166
+ @property
167
+ def total_length(self):
168
+ return len(self.batch_sampler)
169
+
170
+ def __len__(self):
171
+ if self.split_batches:
172
+ # Split batches does not change the length of the batch sampler
173
+ return len(self.batch_sampler)
174
+ if len(self.batch_sampler) % self.num_processes == 0:
175
+ # If the length is a round multiple of the number of processes, it's easy.
176
+ return len(self.batch_sampler) // self.num_processes
177
+ length = len(self.batch_sampler) // self.num_processes
178
+ if self.drop_last:
179
+ # Same if we drop the remainder.
180
+ return length
181
+ elif self.even_batches:
182
+ # When we even batches we always get +1
183
+ return length + 1
184
+ else:
185
+ # Otherwise it depends on the process index.
186
+ return length + 1 if self.process_index < len(self.batch_sampler) % self.num_processes else length
187
+
188
+ def __iter__(self):
189
+ return self._iter_with_split() if self.split_batches else self._iter_with_no_split()
190
+
191
+ def _iter_with_split(self):
192
+ initial_data = []
193
+ batch_length = self.batch_sampler.batch_size // self.num_processes
194
+ for idx, batch in enumerate(self.batch_sampler):
195
+ if idx == 0:
196
+ initial_data = batch
197
+ if len(batch) == self.batch_size:
198
+ # If the batch is full, we yield the part of it this process is responsible of.
199
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
200
+
201
+ # If drop_last is True of the last batch was full, iteration is over, otherwise...
202
+ if not self.drop_last and len(initial_data) > 0 and len(batch) < self.batch_size:
203
+ if not self.even_batches:
204
+ if len(batch) > batch_length * self.process_index:
205
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
206
+ else:
207
+ # For degenerate cases where the dataset has less than num_process * batch_size samples
208
+ while len(initial_data) < self.batch_size:
209
+ initial_data += initial_data
210
+ batch = batch + initial_data
211
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
212
+
213
+ def _iter_with_no_split(self):
214
+ initial_data = []
215
+ batch_to_yield = None
216
+ for idx, batch in enumerate(self.batch_sampler):
217
+ # We gather the initial indices in case we need to circle back at the end.
218
+ if not self.drop_last and idx < self.num_processes:
219
+ if self.batch_size is None:
220
+ # If batch size is None, `batch` is considered to be a list of indices with dynamic length.
221
+ initial_data.append(batch)
222
+ else:
223
+ initial_data += batch
224
+ # We identify the batch to yield but wait until we ar sure every process gets a full batch before actually
225
+ # yielding it.
226
+ if idx % self.num_processes == self.process_index:
227
+ batch_to_yield = batch
228
+ if idx % self.num_processes == self.num_processes - 1 and (
229
+ self.batch_size is None or len(batch) == self.batch_size
230
+ ):
231
+ yield batch_to_yield
232
+ batch_to_yield = None
233
+
234
+ # If drop_last is True, iteration is over, otherwise...
235
+ if not self.drop_last and len(initial_data) > 0:
236
+ if not self.even_batches:
237
+ if batch_to_yield:
238
+ yield batch_to_yield
239
+ else:
240
+ # ... we yield the complete batch we had saved before if it has the proper length
241
+ if batch_to_yield and (self.batch_size is None or len(batch_to_yield) == self.batch_size):
242
+ yield batch_to_yield
243
+
244
+ # For degenerate cases where the dataset has less than num_process * batch_size samples
245
+ _min_length_needed = (
246
+ self.num_processes * self.batch_size if self.batch_size is not None else self.num_processes
247
+ )
248
+ while len(initial_data) < _min_length_needed:
249
+ initial_data += initial_data
250
+
251
+ # If the last batch seen was of the proper size, it has been yielded by its process so we move to the next
252
+ if self.batch_size is None or len(batch) == self.batch_size:
253
+ batch = []
254
+ idx += 1
255
+
256
+ # Make sure we yield a multiple of self.num_processes batches
257
+ cycle_index = 0
258
+ while idx % self.num_processes != 0 or len(batch) > 0:
259
+ if self.batch_size is None:
260
+ batch = initial_data[cycle_index]
261
+ if idx % self.num_processes == self.process_index:
262
+ yield batch
263
+ cycle_index += 1
264
+ else:
265
+ end_index = cycle_index + self.batch_size - len(batch)
266
+ batch += initial_data[cycle_index:end_index]
267
+ if idx % self.num_processes == self.process_index:
268
+ yield batch
269
+ cycle_index = end_index
270
+ batch = []
271
+ idx += 1
272
+
273
+
274
+ class IterableDatasetShard(IterableDataset):
275
+ """
276
+ Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will
277
+ always yield a number of samples that is a round multiple of the actual batch size (depending of the value of
278
+ `split_batches`, this is either `batch_size` or `batch_size x num_processes`). Depending on the value of the
279
+ `drop_last` attribute of the batch sampler passed, it will either stop the iteration at the first batch that would
280
+ be too small or loop with indices from the beginning.
281
+
282
+ Args:
283
+ dataset (`torch.utils.data.dataset.IterableDataset`):
284
+ The batch sampler to split in several shards.
285
+ batch_size (`int`, *optional*, defaults to 1):
286
+ The size of the batches per shard (if `split_batches=False`) or the size of the batches (if
287
+ `split_batches=True`).
288
+ drop_last (`bool`, *optional*, defaults to `False`):
289
+ Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the
290
+ beginning.
291
+ num_processes (`int`, *optional*, defaults to 1):
292
+ The number of processes running concurrently.
293
+ process_index (`int`, *optional*, defaults to 0):
294
+ The index of the current process.
295
+ split_batches (`bool`, *optional*, defaults to `False`):
296
+ Whether the shards should be created by splitting a batch to give a piece of it on each process, or by
297
+ yielding different full batches on each process.
298
+
299
+ On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7]`, this will result in:
300
+
301
+ - the shard on process 0 to yield `[0, 1, 2, 3]` and the shard on process 1 to yield `[4, 5, 6, 7]` if this
302
+ argument is set to `False`.
303
+ - the shard on process 0 to yield `[0, 1, 4, 5]` and the sampler on process 1 to yield `[2, 3, 6, 7]` if
304
+ this argument is set to `True`.
305
+ """
306
+
307
+ def __init__(
308
+ self,
309
+ dataset: IterableDataset,
310
+ batch_size: int = 1,
311
+ drop_last: bool = False,
312
+ num_processes: int = 1,
313
+ process_index: int = 0,
314
+ split_batches: bool = False,
315
+ ):
316
+ if split_batches and batch_size > 1 and batch_size % num_processes != 0:
317
+ raise ValueError(
318
+ f"To use `IterableDatasetShard` in `split_batches` mode, the batch size ({batch_size}) "
319
+ f"needs to be a round multiple of the number of processes ({num_processes})."
320
+ )
321
+ self.dataset: IterableDataset = dataset
322
+ self.batch_size = batch_size
323
+ self.drop_last = drop_last
324
+ self.num_processes = num_processes
325
+ self.process_index = process_index
326
+ self.split_batches = split_batches
327
+
328
+ def set_epoch(self, epoch):
329
+ self.epoch = epoch
330
+ if hasattr(self.dataset, "set_epoch"):
331
+ self.dataset.set_epoch(epoch)
332
+
333
+ def __len__(self):
334
+ # We will just raise the downstream error if the underlying dataset is not sized
335
+ if self.drop_last:
336
+ return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size
337
+ else:
338
+ return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size
339
+
340
+ def __iter__(self):
341
+ if (
342
+ not hasattr(self.dataset, "set_epoch")
343
+ and hasattr(self.dataset, "generator")
344
+ and isinstance(self.dataset.generator, torch.Generator)
345
+ ):
346
+ self.dataset.generator.manual_seed(self.epoch)
347
+ real_batch_size = self.batch_size if self.split_batches else (self.batch_size * self.num_processes)
348
+ process_batch_size = (self.batch_size // self.num_processes) if self.split_batches else self.batch_size
349
+ process_slice = range(self.process_index * process_batch_size, (self.process_index + 1) * process_batch_size)
350
+
351
+ first_batch = None
352
+ current_batch = []
353
+ for element in self.dataset:
354
+ current_batch.append(element)
355
+ # Wait to have a full batch before yielding elements.
356
+ if len(current_batch) == real_batch_size:
357
+ for i in process_slice:
358
+ yield current_batch[i]
359
+ if first_batch is None:
360
+ first_batch = current_batch.copy()
361
+ current_batch = []
362
+
363
+ # Finished if drop_last is True, otherwise complete the last batch with elements from the beginning.
364
+ if not self.drop_last and len(current_batch) > 0:
365
+ if first_batch is None:
366
+ first_batch = current_batch.copy()
367
+ while len(current_batch) < real_batch_size:
368
+ current_batch += first_batch
369
+ for i in process_slice:
370
+ yield current_batch[i]
371
+
372
+
373
+ class DataLoaderStateMixin:
374
+ """
375
+ Mixin class that adds a state to a `DataLoader` to keep track of the status inside the dataloader such as at the
376
+ end of the iteration, the number of items in the dataset in the last batch relative to the batch size, and other
377
+ useful information that might be needed.
378
+
379
+ **Available attributes:**
380
+
381
+ - **end_of_dataloader** (`bool`) -- Whether at the last iteration or batch
382
+ - **remainder** (`int`) -- The number of items that are remaining in the last batch, relative to the total
383
+ batch size
384
+
385
+ <Tip warning={true}>
386
+
387
+ Inheriters of this class should ensure that the class creates a `GradientState()` instance, stored in
388
+ `self.gradient_state`.
389
+
390
+ </Tip>
391
+
392
+ """
393
+
394
+ def __init_subclass__(cls, **kwargs):
395
+ cls.end_of_dataloader = False
396
+ cls.remainder = -1
397
+
398
+ def reset(self):
399
+ self.end_of_dataloader = False
400
+ self.remainder = -1
401
+
402
+ def begin(self):
403
+ "Prepares the gradient state for the current dataloader"
404
+ self.reset()
405
+ with suppress(Exception):
406
+ if not self._drop_last:
407
+ length = getattr(self.dataset, "total_dataset_length", len(self.dataset))
408
+ self.remainder = length % self.total_batch_size
409
+ self.gradient_state._add_dataloader(self)
410
+
411
+ def end(self):
412
+ "Cleans up the gradient state after exiting the dataloader"
413
+ self.gradient_state._remove_dataloader(self)
414
+
415
+
416
+ class DataLoaderAdapter:
417
+ """
418
+ A class which wraps around a PyTorch `DataLoader` (or variants of it) to be used with the `Accelerator`. For
419
+ compatibility reasons, this class inherits from the class it wraps around, so it can be used as a drop-in.
420
+ """
421
+
422
+ def __init__(self, dataset, use_stateful_dataloader=False, batch_sampler=None, **kwargs):
423
+ self.use_stateful_dataloader = use_stateful_dataloader
424
+ if is_torchdata_stateful_dataloader_available():
425
+ from torchdata.stateful_dataloader import StatefulDataLoader
426
+
427
+ if use_stateful_dataloader and not is_torchdata_stateful_dataloader_available():
428
+ raise ImportError(
429
+ "StatefulDataLoader is not available. Please install torchdata version 0.8.0 or higher to use it."
430
+ )
431
+ if use_stateful_dataloader:
432
+ torchdata_version = version.parse(importlib.metadata.version("torchdata"))
433
+ if (
434
+ "in_order" in kwargs
435
+ and compare_versions(torchdata_version, "<", "0.11")
436
+ and is_torch_version(">=", "2.6.0")
437
+ ):
438
+ kwargs.pop("in_order")
439
+ self.base_dataloader = StatefulDataLoader(dataset, batch_sampler=batch_sampler, **kwargs)
440
+ else:
441
+ self.base_dataloader = DataLoader(dataset, batch_sampler=batch_sampler, **kwargs)
442
+
443
+ if hasattr(self.base_dataloader, "state_dict"):
444
+ self.dl_state_dict = self.base_dataloader.state_dict()
445
+
446
+ def __getattr__(self, name):
447
+ # Avoid infinite recursion if we try to access a nonexistent base_dataloader attribute.
448
+ if name == "base_dataloader":
449
+ raise AttributeError()
450
+ # Delegate attribute access to the internal dataloader
451
+ return getattr(self.base_dataloader, name)
452
+
453
+ def state_dict(self):
454
+ return self.dl_state_dict
455
+
456
+ def load_state_dict(self, state_dict):
457
+ self.base_dataloader.load_state_dict(state_dict)
458
+
459
+ @property
460
+ def __class__(self):
461
+ """
462
+ In order to maintain backwards compatibility with other code, we need to ensure `isinstance(obj, DataLoader)`
463
+ returns true. This is because some downstream code assumes that the `DataLoader` is the base class of the
464
+ object.
465
+ """
466
+ return self.base_dataloader.__class__
467
+
468
+ def __len__(self):
469
+ return len(self.base_dataloader)
470
+
471
+ def adjust_state_dict_for_prefetch(self):
472
+ """
473
+ Adjusts the state dict for prefetching. Natively, this will adjust all of the iters yielded keys in
474
+ `self.dl_state_dict` by a factor of `num_processes - 1`, however if a custom correction is needed, this can be
475
+ overridden.
476
+
477
+ This should modify `self.dl_state_dict` directly
478
+ """
479
+ # The state dict will be off by a factor of `n-1` batch too many during DDP,
480
+ # so we need to adjust it here
481
+ if PartialState().distributed_type != DistributedType.NO:
482
+ factor = PartialState().num_processes - 1
483
+ # When num_workers > 0, StatefulDataLoader uses _MultiProcessingDataLoaderIter
484
+ # which may not have _sampler_iter_yielded or _num_yielded in its state_dict
485
+ if "_sampler_iter_yielded" in self.dl_state_dict and self.dl_state_dict["_sampler_iter_yielded"] > 0:
486
+ self.dl_state_dict["_sampler_iter_yielded"] -= factor
487
+ if "_num_yielded" in self.dl_state_dict and self.dl_state_dict["_num_yielded"] > 0:
488
+ self.dl_state_dict["_num_yielded"] -= factor
489
+ if self.dl_state_dict.get("_index_sampler_state") is not None:
490
+ if (
491
+ "samples_yielded" in self.dl_state_dict["_index_sampler_state"]
492
+ and self.dl_state_dict["_index_sampler_state"]["samples_yielded"] > 0
493
+ ):
494
+ self.dl_state_dict["_index_sampler_state"]["samples_yielded"] -= self.batch_size * factor
495
+
496
+ def _update_state_dict(self):
497
+ # The state_dict of the underlying base_dataloader may be ahead of what is currently being yielded.
498
+ # E.g. the implementation of DataLoaderShard involves having an underlying iterator 1 element ahead of
499
+ # what it wants to yield.
500
+ #
501
+ # _update_state_dict is called to snapshot the state_dict that would properly recover the DataLoaderAdapter.
502
+ if hasattr(self.base_dataloader, "state_dict"):
503
+ self.dl_state_dict = self.base_dataloader.state_dict()
504
+ # Potentially modify the state_dict to adjust for prefetching
505
+ self.adjust_state_dict_for_prefetch()
506
+ # Then tag if we are at the end of the dataloader
507
+ self.dl_state_dict["_iterator_finished"] = self.end_of_dataloader
508
+
509
+
510
+ class DataLoaderShard(DataLoaderAdapter, DataLoaderStateMixin):
511
+ """
512
+ Subclass of `DataLoaderAdapter` that will deal with device placement and current distributed setup.
513
+
514
+ Args:
515
+ dataset (`torch.utils.data.dataset.Dataset`):
516
+ The dataset to use to build this dataloader.
517
+ device (`torch.device`, *optional*):
518
+ If passed, the device to put all batches on.
519
+ rng_types (list of `str` or [`~utils.RNGType`]):
520
+ The list of random number generators to synchronize at the beginning of each iteration. Should be one or
521
+ several of:
522
+
523
+ - `"torch"`: the base torch random number generator
524
+ - `"cuda"`: the CUDA random number generator (GPU only)
525
+ - `"xla"`: the XLA random number generator (TPU only)
526
+ - `"generator"`: an optional `torch.Generator`
527
+ synchronized_generator (`torch.Generator`, *optional*):
528
+ A random number generator to keep synchronized across processes.
529
+ skip_batches (`int`, *optional*, defaults to 0):
530
+ The number of batches to skip at the beginning.
531
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
532
+ Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`.
533
+ **kwargs (additional keyword arguments, *optional*):
534
+ All other keyword arguments to pass to the regular `DataLoader` initialization.
535
+
536
+ **Available attributes:**
537
+
538
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
539
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
540
+ number of processes
541
+
542
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
543
+ """
544
+
545
+ def __init__(
546
+ self,
547
+ dataset,
548
+ device=None,
549
+ rng_types=None,
550
+ synchronized_generator=None,
551
+ skip_batches=0,
552
+ use_stateful_dataloader=False,
553
+ _drop_last: bool = False,
554
+ _non_blocking: bool = False,
555
+ torch_device_mesh=None,
556
+ **kwargs,
557
+ ):
558
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
559
+ self.device = device
560
+ self.rng_types = rng_types
561
+ self.synchronized_generator = synchronized_generator
562
+ self.skip_batches = skip_batches
563
+ self.gradient_state = GradientState()
564
+ self._drop_last = _drop_last
565
+ self._non_blocking = _non_blocking
566
+ self.iteration = 0
567
+
568
+ def adjust_state_dict_for_prefetch(self):
569
+ # DataLoaderShard does not need the DDP prefetch adjustment that DataLoaderDispatcher needs.
570
+ # In DataLoaderShard, each process has its own sharded base dataloader and the 1-batch
571
+ # look-ahead is already accounted for by the timing of _update_state_dict() calls
572
+ # (called before the inner next(), so the captured state already equals the number of
573
+ # batches yielded to the user).
574
+ pass
575
+
576
+ def __iter__(self):
577
+ if self.rng_types is not None:
578
+ synchronize_rng_states(self.rng_types, self.synchronized_generator)
579
+ self.begin()
580
+
581
+ self.set_epoch(self.iteration)
582
+ dataloader_iter = self.base_dataloader.__iter__()
583
+ # We iterate one batch ahead to check when we are at the end
584
+ try:
585
+ current_batch = next(dataloader_iter)
586
+ except StopIteration:
587
+ self.end()
588
+ return
589
+
590
+ batch_index = 0
591
+ while True:
592
+ try:
593
+ # But we still move it to the device so it is done before `StopIteration` is reached
594
+ if self.device is not None:
595
+ current_batch = send_to_device(current_batch, self.device, non_blocking=self._non_blocking)
596
+ self._update_state_dict()
597
+ next_batch = next(dataloader_iter)
598
+ if batch_index >= self.skip_batches:
599
+ yield current_batch
600
+ batch_index += 1
601
+ current_batch = next_batch
602
+ except StopIteration:
603
+ self.end_of_dataloader = True
604
+ self._update_state_dict()
605
+ if batch_index >= self.skip_batches:
606
+ yield current_batch
607
+ break
608
+
609
+ self.iteration += 1
610
+ self.end()
611
+
612
+ def __reduce__(self):
613
+ """
614
+ Define the `__reduce__` method to ensure a `DataLoaderShard` can be pickled and unpickled. This needs to be
615
+ explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
616
+ `__class__` member.
617
+ """
618
+ args = super().__reduce__()
619
+ return (DataLoaderShard, *args[1:])
620
+
621
+ def set_epoch(self, epoch: int):
622
+ # In case it is manually passed in, the user can set it to what they like
623
+ if self.iteration != epoch:
624
+ self.iteration = epoch
625
+ if hasattr(self.batch_sampler, "set_epoch"):
626
+ self.batch_sampler.set_epoch(epoch)
627
+ if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"):
628
+ self.batch_sampler.sampler.set_epoch(epoch)
629
+ if (
630
+ hasattr(self.batch_sampler, "batch_sampler")
631
+ and hasattr(self.batch_sampler.batch_sampler, "sampler")
632
+ and hasattr(self.batch_sampler.batch_sampler.sampler, "set_epoch")
633
+ ):
634
+ self.batch_sampler.batch_sampler.sampler.set_epoch(epoch)
635
+ # We support if a custom `Dataset` implementation has `set_epoch`
636
+ # or in general HF datasets `Datasets`
637
+ elif hasattr(self.dataset, "set_epoch"):
638
+ self.dataset.set_epoch(epoch)
639
+
640
+ @property
641
+ def total_batch_size(self):
642
+ batch_sampler = self.sampler if isinstance(self.sampler, BatchSampler) else self.batch_sampler
643
+ return (
644
+ batch_sampler.batch_size
645
+ if getattr(batch_sampler, "split_batches", False)
646
+ else (batch_sampler.batch_size * getattr(batch_sampler, "num_processes", 1))
647
+ )
648
+
649
+ @property
650
+ def total_dataset_length(self):
651
+ if hasattr(self.dataset, "total_length"):
652
+ return self.dataset.total_length
653
+ else:
654
+ return len(self.dataset)
655
+
656
+ def get_sampler(self):
657
+ return get_sampler(self)
658
+
659
+ def set_sampler(self, sampler):
660
+ sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler)
661
+ if sampler_is_batch_sampler:
662
+ self.sampler.sampler = sampler
663
+ else:
664
+ self.batch_sampler.sampler = sampler
665
+ if hasattr(self.batch_sampler, "batch_sampler"):
666
+ self.batch_sampler.batch_sampler.sampler = sampler
667
+
668
+
669
+ if is_torch_xla_available():
670
+ import torch_xla.distributed.parallel_loader as xpl
671
+
672
+ class MpDeviceLoaderWrapper(xpl.MpDeviceLoader):
673
+ """
674
+ Wrapper for the xpl.MpDeviceLoader class that knows the total batch size.
675
+
676
+ XLA preloading threads will all call DataLoaderShard's __iter__(). Remove rng_types from DataLoaderShard to
677
+ prevent it from using the XLA device in the preloading threads, and synchronize the RNG once from the main
678
+ thread only.
679
+
680
+ **Available attributes:**
681
+
682
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
683
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
684
+ number of processes
685
+
686
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
687
+ """
688
+
689
+ def __init__(self, dataloader: DataLoaderShard, device: torch.device):
690
+ super().__init__(dataloader, device)
691
+ self._rng_types = self._loader.rng_types
692
+ self._loader.rng_types = None
693
+ self.device = device
694
+
695
+ def __iter__(self):
696
+ if self._rng_types is not None:
697
+ synchronize_rng_states(self._rng_types, self._loader.synchronized_generator)
698
+
699
+ return super().__iter__()
700
+
701
+ def set_epoch(self, epoch: int):
702
+ if hasattr(self.dataloader, "set_epoch"):
703
+ self.dataloader.set_epoch(epoch)
704
+
705
+ @property
706
+ def total_batch_size(self):
707
+ return self._loader.total_batch_size
708
+
709
+ @property
710
+ def total_dataset_length(self):
711
+ return self._loader.total_dataset_length
712
+
713
+ @property
714
+ def batch_sampler(self):
715
+ return self._loader.batch_sampler
716
+
717
+ @property
718
+ def dataloader(self):
719
+ return self._loader
720
+
721
+
722
+ class DataLoaderDispatcher(DataLoaderAdapter, DataLoaderStateMixin):
723
+ """
724
+ Subclass of `DataLoaderAdapter` that will iterate and preprocess on process 0 only, then dispatch on each process
725
+ their part of the batch.
726
+
727
+ Args:
728
+ split_batches (`bool`, *optional*, defaults to `False`):
729
+ Whether the resulting `DataLoader` should split the batches of the original data loader across devices or
730
+ yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of
731
+ `num_processes` batches at each iteration). Another way to see this is that the observed batch size will be
732
+ the same as the initial `dataloader` if this option is set to `True`, the batch size of the initial
733
+ `dataloader` multiplied by `num_processes` otherwise. Setting this option to `True` requires that the batch
734
+ size of the `dataloader` is a round multiple of `batch_size`.
735
+ skip_batches (`int`, *optional*, defaults to 0):
736
+ The number of batches to skip at the beginning of an iteration.
737
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
738
+ Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`.
739
+
740
+ **Available attributes:**
741
+
742
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
743
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
744
+ number of processes
745
+
746
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
747
+ """
748
+
749
+ def __init__(
750
+ self,
751
+ dataset,
752
+ split_batches: bool = False,
753
+ skip_batches=0,
754
+ use_stateful_dataloader=False,
755
+ _drop_last: bool = False,
756
+ _non_blocking: bool = False,
757
+ slice_fn=None,
758
+ torch_device_mesh=None,
759
+ **kwargs,
760
+ ):
761
+ shuffle = False
762
+ from torch.utils.data.datapipes.iter.combinatorics import ShufflerIterDataPipe
763
+
764
+ # We need to save the shuffling state of the DataPipe
765
+ if isinstance(dataset, ShufflerIterDataPipe):
766
+ shuffle = dataset._shuffle_enabled
767
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
768
+ self.split_batches = split_batches
769
+ if shuffle:
770
+ torch.utils.data.graph_settings.apply_shuffle_settings(dataset, shuffle=shuffle)
771
+
772
+ self.gradient_state = GradientState()
773
+ self.state = PartialState()
774
+ self._drop_last = _drop_last
775
+ self._non_blocking = _non_blocking
776
+ self.skip_batches = skip_batches
777
+ self.torch_device_mesh = torch_device_mesh
778
+
779
+ self.slice_fn = slice_tensors if slice_fn is None else slice_fn
780
+ self.iteration = 0
781
+
782
+ # if a device mesh is provided extract each dimension (dp, fsdp, tp)
783
+ # device mesh may hold any number of dimensions, however,
784
+ # below code is for targeted support for dp, fsdp and tp
785
+
786
+ # device mesh will be used only if there is tp involved
787
+ # or any multi-dimensional parallelism involving tp
788
+ # (dp, tp) (fsdp, tp) (dp, fsdp, tp)
789
+ # otherwise the default behaviour not using device mesh should be sufficient
790
+ # since multi dimensional parallelism devoid of tp would anyway need
791
+ # different batches for each process irrespective of dp or fsdp
792
+ self.submesh_tp = None
793
+ self.submesh_dp = None
794
+ self.submesh_fsdp = None
795
+ if self.torch_device_mesh and "tp" in self.torch_device_mesh.mesh_dim_names:
796
+ self.submesh_tp = self.torch_device_mesh["tp"]
797
+ if "dp" in self.torch_device_mesh.mesh_dim_names:
798
+ self.submesh_dp = self.torch_device_mesh["dp"]
799
+ if "fsdp" in self.torch_device_mesh.mesh_dim_names:
800
+ self.submesh_fsdp = self.torch_device_mesh["fsdp"]
801
+ if self.submesh_tp and (self.submesh_dp or self.submesh_fsdp):
802
+ raise ValueError("TP + (DP/FSDP) is not yet supported in dispatch mode")
803
+
804
+ def _fetch_batches(self, iterator):
805
+ batches, batch = None, None
806
+ # On process 0, we gather the batch to dispatch.
807
+ if self.state.process_index == 0:
808
+ # Procedure to support TP only is simpler
809
+ # since we want to dispatch the same batch of samples across all ranks
810
+ # this removes complexity of handling multiple tp rank groups when TP + DP
811
+ # combination is involved.
812
+
813
+ try:
814
+ # for TP case avoid using split_batches
815
+ # since it would mean that the dataloader should be spilling out
816
+ # duplicates of batches.
817
+ if self.split_batches:
818
+ # One batch of the main iterator is dispatched and split.
819
+ if self.submesh_tp:
820
+ logger.warning(
821
+ "Use of split_batches for TP would need the dataloader to produce duplicate batches,"
822
+ "otherwise, use dispatch_batches=True instead."
823
+ )
824
+ self._update_state_dict()
825
+ batch = next(iterator)
826
+ else:
827
+ # num_processes batches of the main iterator are concatenated then dispatched and split.
828
+ # We add the batches one by one so we have the remainder available when drop_last=False.
829
+ batches = []
830
+ if self.submesh_tp:
831
+ # when tp, extract single batch and then replicate
832
+ self._update_state_dict()
833
+ batch = next(iterator)
834
+ batches = [batch] * self.state.num_processes
835
+ else:
836
+ for _ in range(self.state.num_processes):
837
+ self._update_state_dict()
838
+ batches.append(next(iterator))
839
+ try:
840
+ batch = concatenate(batches, dim=0)
841
+ except RuntimeError as e:
842
+ raise RuntimeError(
843
+ "You can't use batches of different size with `dispatch_batches=True` or when using an `IterableDataset`."
844
+ "either pass `dispatch_batches=False` and have each process fetch its own batch "
845
+ " or pass `split_batches=True`. By doing so, the main process will fetch a full batch and "
846
+ "slice it into `num_processes` batches for each process."
847
+ ) from e
848
+ # In both cases, we need to get the structure of the batch that we will broadcast on other
849
+ # processes to initialize the tensors with the right shape.
850
+ # data_structure, stop_iteration
851
+ batch_info = [get_data_structure(batch), False]
852
+ except StopIteration:
853
+ batch_info = [None, True]
854
+ else:
855
+ batch_info = [None, self._stop_iteration]
856
+ # This is inplace, so after this instruction, every process has the same `batch_info` as process 0.
857
+ broadcast_object_list(batch_info)
858
+ self._stop_iteration = batch_info[1]
859
+ if self._stop_iteration:
860
+ # If drop_last is False and split_batches is False, we may have a remainder to take care of.
861
+ if not self.split_batches and not self._drop_last:
862
+ if self.state.process_index == 0 and len(batches) > 0:
863
+ batch = concatenate(batches, dim=0)
864
+ batch_info = [get_data_structure(batch), False]
865
+ else:
866
+ batch_info = [None, True]
867
+ broadcast_object_list(batch_info)
868
+ return batch, batch_info
869
+
870
+ def __iter__(self):
871
+ self.begin()
872
+ self.set_epoch(self.iteration)
873
+ main_iterator = None
874
+ if is_torch_version(">=", "2.0.1"):
875
+ # NOTE PyTorch DataLoader adds forward compatibilities for DataPipes, which broadcasts
876
+ # shared seed to all dist processes. Thus, we need to create iterator for all dist processes.
877
+ # But, we only iterate through the DataLoader on process 0.
878
+ main_iterator = self.base_dataloader.__iter__()
879
+ elif self.state.process_index == 0:
880
+ main_iterator = self.base_dataloader.__iter__()
881
+ stop_iteration = False
882
+ self._stop_iteration = False
883
+ first_batch = None
884
+ next_batch, next_batch_info = self._fetch_batches(main_iterator)
885
+ batch_index = 0
886
+ while not stop_iteration:
887
+ batch, batch_info = next_batch, next_batch_info
888
+
889
+ if self.state.process_index != 0:
890
+ # Initialize tensors on other processes than process 0.
891
+ batch = initialize_tensors(batch_info[0])
892
+ batch = send_to_device(batch, self.state.device, non_blocking=self._non_blocking)
893
+ # Broadcast the batch before splitting it.
894
+ batch = broadcast(batch, from_process=0)
895
+
896
+ if not self._drop_last and first_batch is None:
897
+ # We keep at least num processes elements of the first batch to be able to complete the last batch
898
+ first_batch = self.slice_fn(
899
+ batch,
900
+ slice(0, self.state.num_processes),
901
+ process_index=self.state.process_index,
902
+ num_processes=self.state.num_processes,
903
+ )
904
+
905
+ if batch is None:
906
+ raise ValueError(
907
+ f"Batch does not contain any data (`{batch}`). At the end of all iterable data available before expected stop iteration."
908
+ )
909
+
910
+ observed_batch_size = find_batch_size(batch)
911
+ batch_size = observed_batch_size // self.state.num_processes
912
+
913
+ stop_iteration = self._stop_iteration
914
+ if not stop_iteration:
915
+ # We may still be at the end of the dataloader without knowing it yet: if there is nothing left in
916
+ # the dataloader since the number of batches is a round multiple of the number of processes.
917
+ next_batch, next_batch_info = self._fetch_batches(main_iterator)
918
+ # next_batch_info[0] is None when there are no more batches, otherwise we still need to process them.
919
+ if self._stop_iteration and next_batch_info[0] is None:
920
+ stop_iteration = True
921
+
922
+ if not self._drop_last and stop_iteration and observed_batch_size % self.state.num_processes != 0:
923
+ # If the last batch is not complete, let's add the first batch to it.
924
+ batch = concatenate([batch, first_batch], dim=0)
925
+ # Batch size computation above is wrong, it's off by 1 so we fix it.
926
+ batch_size += 1
927
+
928
+ data_slice = slice(self.state.process_index * batch_size, (self.state.process_index + 1) * batch_size)
929
+ batch = self.slice_fn(
930
+ batch,
931
+ data_slice,
932
+ process_index=self.state.process_index,
933
+ num_processes=self.state.num_processes,
934
+ )
935
+
936
+ if stop_iteration:
937
+ self.end_of_dataloader = True
938
+ self._update_state_dict()
939
+ self.remainder = observed_batch_size
940
+ if batch_index >= self.skip_batches:
941
+ yield batch
942
+ batch_index += 1
943
+ self.iteration += 1
944
+ self.end()
945
+
946
+ def set_epoch(self, epoch: int):
947
+ # In case it is manually passed in, the user can set it to what they like
948
+ if self.iteration != epoch:
949
+ self.iteration = epoch
950
+ if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"):
951
+ self.batch_sampler.sampler.set_epoch(epoch)
952
+ elif hasattr(self.dataset, "set_epoch"):
953
+ self.dataset.set_epoch(epoch)
954
+
955
+ def __len__(self):
956
+ whole_length = len(self.base_dataloader)
957
+ if self.split_batches:
958
+ return whole_length
959
+ elif self._drop_last:
960
+ return whole_length // self.state.num_processes
961
+ else:
962
+ return math.ceil(whole_length / self.state.num_processes)
963
+
964
+ def __reduce__(self):
965
+ """
966
+ Define the `__reduce__` method to ensure a `DataLoaderDispatcher` can be pickled and unpickled. This needs to
967
+ be explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
968
+ `__class__` member.
969
+ """
970
+ args = super().__reduce__()
971
+ return (DataLoaderDispatcher, *args[1:])
972
+
973
+ @property
974
+ def total_batch_size(self):
975
+ return (
976
+ self.dataset.batch_size if self.split_batches else (self.dataset.batch_size * self.dataset.num_processes)
977
+ )
978
+
979
+ @property
980
+ def total_dataset_length(self):
981
+ return len(self.dataset)
982
+
983
+ def get_sampler(self):
984
+ return get_sampler(self)
985
+
986
+ def set_sampler(self, sampler):
987
+ sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler)
988
+ if sampler_is_batch_sampler:
989
+ self.sampler.sampler = sampler
990
+ else:
991
+ self.batch_sampler.sampler = sampler
992
+ if hasattr(self.batch_sampler, "batch_sampler"):
993
+ self.batch_sampler.batch_sampler.sampler = sampler
994
+
995
+
996
+ def get_sampler(dataloader):
997
+ """
998
+ Get the sampler associated to the dataloader
999
+
1000
+ Args:
1001
+ dataloader (`torch.utils.data.dataloader.DataLoader`):
1002
+ The data loader to split across several devices.
1003
+ Returns:
1004
+ `torch.utils.data.Sampler`: The sampler associated to the dataloader
1005
+ """
1006
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
1007
+ if sampler_is_batch_sampler:
1008
+ sampler = getattr(dataloader.sampler, "sampler", None)
1009
+ else:
1010
+ sampler = getattr(dataloader.batch_sampler, "sampler", None)
1011
+ return sampler
1012
+
1013
+
1014
+ def prepare_data_loader(
1015
+ dataloader: DataLoader,
1016
+ device: Optional[torch.device] = None,
1017
+ num_processes: Optional[int] = None,
1018
+ process_index: Optional[int] = None,
1019
+ split_batches: bool = False,
1020
+ put_on_device: bool = False,
1021
+ rng_types: Optional[list[Union[str, RNGType]]] = None,
1022
+ dispatch_batches: Optional[bool] = None,
1023
+ even_batches: bool = True,
1024
+ slice_fn_for_dispatch: Optional[Callable] = None,
1025
+ use_seedable_sampler: bool = False,
1026
+ data_seed: Optional[int] = None,
1027
+ non_blocking: bool = False,
1028
+ use_stateful_dataloader: bool = False,
1029
+ torch_device_mesh=None,
1030
+ ) -> DataLoader:
1031
+ """
1032
+ Wraps a PyTorch `DataLoader` to generate batches for one of the processes only.
1033
+
1034
+ Depending on the value of the `drop_last` attribute of the `dataloader` passed, it will either stop the iteration
1035
+ at the first batch that would be too small / not present on all processes or loop with indices from the beginning.
1036
+
1037
+ Args:
1038
+ dataloader (`torch.utils.data.dataloader.DataLoader`):
1039
+ The data loader to split across several devices.
1040
+ device (`torch.device`):
1041
+ The target device for the returned `DataLoader`.
1042
+ num_processes (`int`, *optional*):
1043
+ The number of processes running concurrently. Will default to the value given by [`~state.PartialState`].
1044
+ process_index (`int`, *optional*):
1045
+ The index of the current process. Will default to the value given by [`~state.PartialState`].
1046
+ split_batches (`bool`, *optional*, defaults to `False`):
1047
+ Whether the resulting `DataLoader` should split the batches of the original data loader across devices or
1048
+ yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of
1049
+ `num_processes` batches at each iteration).
1050
+
1051
+ Another way to see this is that the observed batch size will be the same as the initial `dataloader` if
1052
+ this option is set to `True`, the batch size of the initial `dataloader` multiplied by `num_processes`
1053
+ otherwise.
1054
+
1055
+ Setting this option to `True` requires that the batch size of the `dataloader` is a round multiple of
1056
+ `batch_size`.
1057
+ put_on_device (`bool`, *optional*, defaults to `False`):
1058
+ Whether or not to put the batches on `device` (only works if the batches are nested list, tuples or
1059
+ dictionaries of tensors).
1060
+ rng_types (list of `str` or [`~utils.RNGType`]):
1061
+ The list of random number generators to synchronize at the beginning of each iteration. Should be one or
1062
+ several of:
1063
+
1064
+ - `"torch"`: the base torch random number generator
1065
+ - `"cuda"`: the CUDA random number generator (GPU only)
1066
+ - `"xla"`: the XLA random number generator (TPU only)
1067
+ - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your
1068
+ dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type.
1069
+
1070
+ dispatch_batches (`bool`, *optional*):
1071
+ If set to `True`, the dataloader prepared is only iterated through on the main process and then the batches
1072
+ are split and broadcast to each process. Will default to `True` when the underlying dataset is an
1073
+ `IterableDataset`, `False` otherwise.
1074
+ even_batches (`bool`, *optional*, defaults to `True`):
1075
+ If set to `True`, in cases where the total batch size across all processes does not exactly divide the
1076
+ dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among
1077
+ all workers.
1078
+ slice_fn_for_dispatch (`Callable`, *optional*`):
1079
+ If passed, this function will be used to slice tensors across `num_processes`. Will default to
1080
+ [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will be
1081
+ ignored otherwise.
1082
+ use_seedable_sampler (`bool`, *optional*, defaults to `False`):
1083
+ Whether to use the [`~data_loader.SeedableRandomSampler`] instead of a `RandomSampler` for better
1084
+ reproducibility. Comes at a cost of potentially different performances due to different shuffling
1085
+ algorithms but ensures results will be the *exact* same. Should be paired with `set_seed()` at every
1086
+ `self.set_epoch`
1087
+ data_seed (`int`, *optional*, defaults to `None`):
1088
+ The seed to use for the underlying generator when using `use_seedable_sampler`. If `None`, the generator
1089
+ will use the current default seed from torch.
1090
+ non_blocking (`bool`, *optional*, defaults to `False`):
1091
+ If set to `True`, dataloader will utilize non-blocking host-to-device transfers. If the dataloader has
1092
+ `pin_memory` set to `True`, this will help to increase overlap between data transfer and computations.
1093
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
1094
+ "If set to true, the dataloader prepared by the Accelerator will be backed by "
1095
+ "[torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader).
1096
+ This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed."
1097
+ torch_device_mesh (`torch.distributed.DeviceMesh`, *optional*, defaults to `None`):
1098
+ PyTorch device mesh.
1099
+
1100
+
1101
+ Returns:
1102
+ `torch.utils.data.dataloader.DataLoader`: A new data loader that will yield the portion of the batches
1103
+
1104
+ <Tip warning={true}>
1105
+
1106
+ `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`
1107
+ equal to `False`
1108
+
1109
+ </Tip>
1110
+ """
1111
+ if dispatch_batches is None:
1112
+ if not put_on_device:
1113
+ dispatch_batches = False
1114
+ else:
1115
+ dispatch_batches = isinstance(dataloader.dataset, IterableDataset)
1116
+
1117
+ if dispatch_batches and not put_on_device:
1118
+ raise ValueError("Using `dispatch_batches=True` requires `put_on_device=True`.")
1119
+ # Grab defaults from PartialState
1120
+ state = PartialState()
1121
+ if num_processes is None:
1122
+ num_processes = state.num_processes
1123
+
1124
+ if process_index is None:
1125
+ process_index = state.process_index
1126
+
1127
+ if torch_device_mesh:
1128
+ if state.distributed_type == DistributedType.DEEPSPEED:
1129
+ # In DeepSpeed, the optimizer sharing level in DP is determined by the config file.
1130
+ # Only considers "dp" and "tp".
1131
+ # Given a device mesh (dp, tp) = (2, 3):
1132
+ # - From the data parallel perspective, ranks should be structured as: 0 0 0 1 1 1
1133
+ # - Processes with the same DP rank will receive the same batch.
1134
+ submesh_tp_size = 1
1135
+ if "tp" in torch_device_mesh.mesh_dim_names:
1136
+ submesh_tp_size = torch_device_mesh["tp"].size()
1137
+ process_index = process_index // submesh_tp_size
1138
+ num_processes = num_processes // submesh_tp_size
1139
+ else:
1140
+ # when device mesh is used, specifically with TP
1141
+ # then there is need to update process_index and num_processes
1142
+ # to bring in the effect of generating same batch across TP ranks
1143
+ # and different batch across FSDP and DP ranks.
1144
+ # Example:
1145
+ # if device mesh is (dp,fsdp,tp) = (2, 2, 3)
1146
+ # ranks would range from 0...11
1147
+ # from data angle ranks should look like 0 0 0 1 1 1 2 2 2 3 3 3
1148
+ # processes with same ranks/ids would receive the same batch
1149
+ # for CP the same as TP applies
1150
+ submesh_fsdp_size = 1
1151
+ submesh_dp_size = 1
1152
+ submesh_tp_size = 1
1153
+ submesh_cp_size = 1
1154
+ if "tp" in torch_device_mesh.mesh_dim_names:
1155
+ submesh_tp_size = torch_device_mesh["tp"].size()
1156
+ if "cp" in torch_device_mesh.mesh_dim_names:
1157
+ submesh_cp_size = torch_device_mesh["cp"].size()
1158
+ if "dp_replicate" in torch_device_mesh.mesh_dim_names:
1159
+ submesh_dp_size = torch_device_mesh["dp_replicate"].size()
1160
+ if "dp_shard" in torch_device_mesh.mesh_dim_names:
1161
+ submesh_fsdp_size = torch_device_mesh["dp_shard"].size()
1162
+ process_index = process_index // (submesh_tp_size * submesh_cp_size)
1163
+ num_processes = submesh_fsdp_size * submesh_dp_size
1164
+
1165
+ # Sanity check
1166
+ if split_batches:
1167
+ if dataloader.batch_size is not None:
1168
+ batch_size_for_check = dataloader.batch_size
1169
+ else:
1170
+ # For custom batch_sampler
1171
+ if hasattr(dataloader.batch_sampler, "batch_size"):
1172
+ batch_size_for_check = dataloader.batch_sampler.batch_size
1173
+ else:
1174
+ raise ValueError(
1175
+ "In order to use `split_batches==True` you must have a `batch_size` attribute either in the passed "
1176
+ "`dataloader` or `dataloader.batch_sampler` objects, and it has to return a natural number. "
1177
+ "Your `dataloader.batch_size` is None and `dataloader.batch_sampler` "
1178
+ f"(`{type(dataloader.batch_sampler)}`) does not have the `batch_size` attribute set."
1179
+ )
1180
+
1181
+ if batch_size_for_check > 1 and batch_size_for_check % num_processes != 0:
1182
+ raise ValueError(
1183
+ f"To use a `DataLoader` in `split_batches` mode, the batch size ({dataloader.batch_size}) "
1184
+ f"needs to be a round multiple of the number of processes ({num_processes})."
1185
+ )
1186
+
1187
+ new_dataset = dataloader.dataset
1188
+ # Iterable dataset doesn't like batch_sampler, but data_loader creates a default one for it
1189
+ new_batch_sampler = dataloader.batch_sampler if not isinstance(new_dataset, IterableDataset) else None
1190
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
1191
+ synchronized_generator = None
1192
+
1193
+ sampler = get_sampler(dataloader)
1194
+ if isinstance(sampler, RandomSampler) and use_seedable_sampler:
1195
+ # When iterating through the dataloader during distributed processes
1196
+ # we want to ensure that on each process we are iterating through the same
1197
+ # samples in the same order if a seed is set. This requires a tweak
1198
+ # to the `torch.utils.data.RandomSampler` class (if used).
1199
+ sampler = SeedableRandomSampler(
1200
+ data_source=sampler.data_source,
1201
+ replacement=sampler.replacement,
1202
+ num_samples=sampler._num_samples,
1203
+ generator=getattr(
1204
+ sampler,
1205
+ "generator",
1206
+ torch.Generator(device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"),
1207
+ ),
1208
+ data_seed=data_seed,
1209
+ )
1210
+
1211
+ if isinstance(dataloader.sampler, RandomSampler) and state.distributed_type == DistributedType.XLA:
1212
+ # isinstance(dataloader.sampler, RandomSampler) indicates the original dataloader has `shuffle` enabled.
1213
+ generator = torch.Generator(
1214
+ device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"
1215
+ )
1216
+ seed = int(torch.empty((), dtype=torch.int64).random_().item())
1217
+ generator.manual_seed(seed)
1218
+ dataloader.generator = generator
1219
+ dataloader.sampler.generator = generator
1220
+ # No change if no multiprocess
1221
+ if (num_processes != 1 or state.distributed_type == DistributedType.MEGATRON_LM) and not dispatch_batches:
1222
+ if is_datasets_available():
1223
+ from datasets import IterableDataset as DatasetsIterableDataset
1224
+ if (
1225
+ is_datasets_available()
1226
+ and isinstance(new_dataset, DatasetsIterableDataset)
1227
+ and not split_batches
1228
+ and new_dataset.n_shards >= num_processes
1229
+ ):
1230
+ new_dataset = new_dataset.shard(num_shards=num_processes, index=process_index)
1231
+ elif isinstance(new_dataset, IterableDataset):
1232
+ if getattr(dataloader.dataset, "generator", None) is not None:
1233
+ synchronized_generator = dataloader.dataset.generator
1234
+ new_dataset = IterableDatasetShard(
1235
+ new_dataset,
1236
+ batch_size=dataloader.batch_size,
1237
+ drop_last=dataloader.drop_last,
1238
+ num_processes=num_processes,
1239
+ process_index=process_index,
1240
+ split_batches=split_batches,
1241
+ )
1242
+ else:
1243
+ if not use_seedable_sampler and hasattr(sampler, "generator"):
1244
+ if sampler.generator is None:
1245
+ sampler.generator = torch.Generator(
1246
+ device=torch.get_default_device() if hasattr(torch, "get_default_device") else "cpu"
1247
+ )
1248
+ seed = int(torch.empty((), dtype=torch.int64).random_().item())
1249
+ sampler.generator.manual_seed(seed)
1250
+ synchronized_generator = sampler.generator
1251
+ batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler
1252
+ new_batch_sampler = BatchSamplerShard(
1253
+ batch_sampler,
1254
+ num_processes=num_processes,
1255
+ process_index=process_index,
1256
+ split_batches=split_batches,
1257
+ even_batches=even_batches,
1258
+ )
1259
+
1260
+ # We ignore all of those since they are all dealt with by our new_batch_sampler
1261
+ ignore_kwargs = [
1262
+ "batch_size",
1263
+ "shuffle",
1264
+ "sampler",
1265
+ "batch_sampler",
1266
+ "drop_last",
1267
+ ]
1268
+
1269
+ if rng_types is not None and synchronized_generator is None and "generator" in rng_types:
1270
+ rng_types.remove("generator")
1271
+
1272
+ kwargs = {
1273
+ k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])
1274
+ for k in _PYTORCH_DATALOADER_KWARGS
1275
+ if k not in ignore_kwargs
1276
+ }
1277
+
1278
+ # Need to provide batch_size as batch_sampler is None for Iterable dataset
1279
+ if new_batch_sampler is None:
1280
+ kwargs["drop_last"] = dataloader.drop_last
1281
+ kwargs["batch_size"] = (
1282
+ dataloader.batch_size // num_processes if split_batches and not dispatch_batches else dataloader.batch_size
1283
+ )
1284
+ if dispatch_batches:
1285
+ kwargs.pop("generator")
1286
+ dataloader = DataLoaderDispatcher(
1287
+ new_dataset,
1288
+ split_batches=split_batches,
1289
+ batch_sampler=new_batch_sampler,
1290
+ _drop_last=dataloader.drop_last,
1291
+ _non_blocking=non_blocking,
1292
+ slice_fn=slice_fn_for_dispatch,
1293
+ use_stateful_dataloader=use_stateful_dataloader,
1294
+ torch_device_mesh=torch_device_mesh,
1295
+ **kwargs,
1296
+ )
1297
+ elif sampler_is_batch_sampler:
1298
+ dataloader = DataLoaderShard(
1299
+ new_dataset,
1300
+ device=device if put_on_device and state.distributed_type != DistributedType.XLA else None,
1301
+ sampler=new_batch_sampler,
1302
+ batch_size=dataloader.batch_size,
1303
+ rng_types=rng_types,
1304
+ _drop_last=dataloader.drop_last,
1305
+ _non_blocking=non_blocking,
1306
+ synchronized_generator=synchronized_generator,
1307
+ use_stateful_dataloader=use_stateful_dataloader,
1308
+ **kwargs,
1309
+ )
1310
+ else:
1311
+ dataloader = DataLoaderShard(
1312
+ new_dataset,
1313
+ device=device if put_on_device and state.distributed_type != DistributedType.XLA else None,
1314
+ batch_sampler=new_batch_sampler,
1315
+ rng_types=rng_types,
1316
+ synchronized_generator=synchronized_generator,
1317
+ _drop_last=dataloader.drop_last,
1318
+ _non_blocking=non_blocking,
1319
+ use_stateful_dataloader=use_stateful_dataloader,
1320
+ **kwargs,
1321
+ )
1322
+
1323
+ if isinstance(sampler, SeedableRandomSampler) and use_seedable_sampler:
1324
+ dataloader.set_sampler(sampler)
1325
+ if state.distributed_type == DistributedType.XLA:
1326
+ return MpDeviceLoaderWrapper(dataloader, device)
1327
+ return dataloader
1328
+
1329
+
1330
+ class SkipBatchSampler(BatchSampler):
1331
+ """
1332
+ A `torch.utils.data.BatchSampler` that skips the first `n` batches of another `torch.utils.data.BatchSampler`.
1333
+ Should not be used if the original dataloader is a `StatefulDataLoader`.
1334
+ """
1335
+
1336
+ def __init__(self, batch_sampler, skip_batches=0):
1337
+ self.batch_sampler = batch_sampler
1338
+ self.skip_batches = skip_batches
1339
+
1340
+ def __iter__(self):
1341
+ for index, samples in enumerate(self.batch_sampler):
1342
+ if index >= self.skip_batches:
1343
+ yield samples
1344
+
1345
+ @property
1346
+ def total_length(self):
1347
+ return len(self.batch_sampler)
1348
+
1349
+ def __len__(self):
1350
+ return len(self.batch_sampler) - self.skip_batches
1351
+
1352
+
1353
+ class SkipDataLoader(DataLoaderAdapter, DataLoaderStateMixin):
1354
+ """
1355
+ Subclass of a PyTorch `DataLoader` that will skip the first batches. Generally it's preferable to use
1356
+ `skip_first_batches`/`torchdata.StatefulDataLoader` instead of this class.
1357
+
1358
+ Args:
1359
+ dataset (`torch.utils.data.dataset.Dataset`):
1360
+ The dataset to use to build this dataloader.
1361
+ skip_batches (`int`, *optional*, defaults to 0):
1362
+ The number of batches to skip at the beginning.
1363
+ kwargs:
1364
+ All other keyword arguments to pass to the regular `DataLoader` initialization.
1365
+ """
1366
+
1367
+ def __init__(self, dataset, skip_batches=0, use_stateful_dataloader=False, **kwargs):
1368
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
1369
+ self.skip_batches = skip_batches
1370
+ self.gradient_state = GradientState()
1371
+
1372
+ def __iter__(self):
1373
+ self.begin()
1374
+ for index, batch in enumerate(self.base_dataloader.__iter__()):
1375
+ if index >= self.skip_batches:
1376
+ self._update_state_dict()
1377
+ yield batch
1378
+ self.end()
1379
+
1380
+ def __len__(self):
1381
+ return len(self.base_dataloader) - self.skip_batches
1382
+
1383
+ def __reduce__(self):
1384
+ """
1385
+ Define the `__reduce__` method to ensure a `SkipDataLoader` can be pickled and unpickled. This needs to be
1386
+ explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
1387
+ `__class__` member.
1388
+ """
1389
+ args = super().__reduce__()
1390
+ return (SkipDataLoader, *args[1:])
1391
+
1392
+
1393
+ def skip_first_batches(dataloader, num_batches=0):
1394
+ """
1395
+ Creates a `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`. Should not be used if
1396
+ the original dataloader is a `StatefulDataLoader`.
1397
+ """
1398
+ state = PartialState()
1399
+ if state.distributed_type == DistributedType.XLA:
1400
+ device = dataloader.device
1401
+ dataloader = dataloader.dataloader
1402
+
1403
+ dataset = dataloader.dataset
1404
+ sampler_is_batch_sampler = False
1405
+ if isinstance(dataset, IterableDataset):
1406
+ new_batch_sampler = None
1407
+ else:
1408
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
1409
+ batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler
1410
+ new_batch_sampler = SkipBatchSampler(batch_sampler, skip_batches=num_batches)
1411
+
1412
+ # We ignore all of those since they are all dealt with by our new_batch_sampler
1413
+ ignore_kwargs = [
1414
+ "batch_size",
1415
+ "shuffle",
1416
+ "sampler",
1417
+ "batch_sampler",
1418
+ "drop_last",
1419
+ ]
1420
+
1421
+ kwargs = {
1422
+ k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])
1423
+ for k in _PYTORCH_DATALOADER_KWARGS
1424
+ if k not in ignore_kwargs
1425
+ }
1426
+
1427
+ # Need to provide batch_size as batch_sampler is None for Iterable dataset
1428
+ if new_batch_sampler is None:
1429
+ kwargs["drop_last"] = dataloader.drop_last
1430
+ kwargs["batch_size"] = dataloader.batch_size
1431
+
1432
+ if isinstance(dataloader, DataLoaderDispatcher):
1433
+ if new_batch_sampler is None:
1434
+ # Need to manually skip batches in the dataloader
1435
+ kwargs["skip_batches"] = num_batches
1436
+ dataloader = DataLoaderDispatcher(
1437
+ dataset,
1438
+ split_batches=dataloader.split_batches,
1439
+ batch_sampler=new_batch_sampler,
1440
+ _drop_last=dataloader._drop_last,
1441
+ **kwargs,
1442
+ )
1443
+ elif isinstance(dataloader, DataLoaderShard):
1444
+ if new_batch_sampler is None:
1445
+ # Need to manually skip batches in the dataloader
1446
+ kwargs["skip_batches"] = num_batches
1447
+ elif sampler_is_batch_sampler:
1448
+ kwargs["sampler"] = new_batch_sampler
1449
+ kwargs["batch_size"] = dataloader.batch_size
1450
+ else:
1451
+ kwargs["batch_sampler"] = new_batch_sampler
1452
+ dataloader = DataLoaderShard(
1453
+ dataset,
1454
+ device=dataloader.device,
1455
+ rng_types=dataloader.rng_types,
1456
+ synchronized_generator=dataloader.synchronized_generator,
1457
+ **kwargs,
1458
+ )
1459
+ else:
1460
+ if new_batch_sampler is None:
1461
+ # Need to manually skip batches in the dataloader
1462
+ dataloader = SkipDataLoader(dataset, skip_batches=num_batches, **kwargs)
1463
+ else:
1464
+ dataloader = DataLoader(dataset, batch_sampler=new_batch_sampler, **kwargs)
1465
+
1466
+ if state.distributed_type == DistributedType.XLA:
1467
+ dataloader = MpDeviceLoaderWrapper(dataloader, device)
1468
+
1469
+ return dataloader
tasks/tasksmith-f1fb6bb8619d/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ cp /solution/reference/src/accelerate/data_loader.py /workspace/src/accelerate/data_loader.py
tasks/tasksmith-f1fb6bb8619d/task.toml ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.3"
2
+ artifacts = [
3
+ { source = "/workspace/src/accelerate/data_loader.py" },
4
+ ]
5
+
6
+ [task]
7
+ name = "repo2rlenv/tasksmith-f1fb6bb8619d"
8
+
9
+ [metadata.repo2env]
10
+ recipe = "tasksmith"
11
+ recipe_version = "1"
12
+ source_url = "https://github.com/huggingface/accelerate/pull/3969"
13
+ source_head = "bac18660fa05e7f731d4f7bdaedf11750c2224c9"
14
+ source_base = "77eb5cf6087d91227d77ebbe65121501eb56d098"
15
+ workspace_strategy = "head_minus_source_patch"
16
+ source_diff_sha256 = "33f38bf995a0d750e77dad7f3722e8f849657251b7c27593b21179eb5a74d24f"
17
+ acceptance_profile = "practical-generation-v1"
18
+ reward_kinds = [
19
+ "test_execution",
20
+ ]
21
+ quality_status = "exported"
22
+ fail_to_pass_count = 3
23
+ pass_to_pass_count = 2
24
+ bundle_hash = "sha256:065ab8284cef357f9d8a48ed9642e66e0ecc54fb3b8eedce4a70333475b50dff"
25
+
26
+ [metadata.repo2env.evaluation]
27
+ schema_version = "1"
28
+ status = "verified"
29
+ stage = "complete"
30
+ reason_codes = [
31
+ "quality_verified",
32
+ ]
33
+ detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile."
34
+ checked_at = "2026-09-14T05:11:11.816846Z"
35
+ provenance = "unknown"
36
+ subject_bundle_hash = "sha256:065ab8284cef357f9d8a48ed9642e66e0ecc54fb3b8eedce4a70333475b50dff"
37
+ profile = "practical-generation-v1"
38
+ source_task_path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-hf-scale/quality-recovery-v4/f1fb6bb8619d/revisions/r0/tasksmith-f1fb6bb8619d"
39
+ source_task_toml_sha256 = "2f1590cab00957ef7f1df246aaeb76c66b9cac5608d5fb1bc0daae5180239ea9"
40
+
41
+ [[metadata.repo2env.evaluation.evidence]]
42
+ kind = "quality_result"
43
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-hf-scale/delivery/evidence/tasksmith-f1fb6bb8619d/quality-result.json"
44
+ sha256 = "3c35b85ad41fbfc67f8e589d457dda871ffacdf93bb66175c4eb1c4294a8338c"
45
+ subject_bundle_hash = "sha256:065ab8284cef357f9d8a48ed9642e66e0ecc54fb3b8eedce4a70333475b50dff"
46
+
47
+ [[metadata.repo2env.evaluation.evidence]]
48
+ kind = "baseline"
49
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-hf-scale/first-ten-v2/candidates/f1fb6bb8619d/quality/trials/r1-baseline/ts-48f70f9184b6-q-f1fb6bb8-r1-baseline/tasksmith-f1fb6bb8619d__mgd2vTU/result.json"
50
+ sha256 = "0b0849dd1e342233999923269fa9faea79cd4140d883e4c6b0d822de65702c36"
51
+ subject_bundle_hash = "sha256:065ab8284cef357f9d8a48ed9642e66e0ecc54fb3b8eedce4a70333475b50dff"
52
+ harbor_task_checksum = "5fa7942ddfc60d970b84218ca0eb0429d1692379cefa1e09ef6a4117d934130e"
53
+
54
+ [[metadata.repo2env.evaluation.evidence]]
55
+ kind = "oracle"
56
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-hf-scale/first-ten-v2/candidates/f1fb6bb8619d/quality/trials/r1-oracle/ts-48f70f9184b6-q-f1fb6bb8-r1-oracle/tasksmith-f1fb6bb8619d__fuMhyPb/result.json"
57
+ sha256 = "2c31c84c82ebddc874436d2488b9f9e9527b1f6d5dc334e541933babf36b7998"
58
+ subject_bundle_hash = "sha256:065ab8284cef357f9d8a48ed9642e66e0ecc54fb3b8eedce4a70333475b50dff"
59
+ harbor_task_checksum = "5fa7942ddfc60d970b84218ca0eb0429d1692379cefa1e09ef6a4117d934130e"
60
+
61
+ [[metadata.repo2env.evaluation.evidence]]
62
+ kind = "rollout"
63
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-hf-scale/first-ten-v2/candidates/f1fb6bb8619d/quality/trials/r1-rollout/ts-48f70f9184b6-q-f1fb6bb8-r1-rollout/tasksmith-f1fb6bb8619d__TK5n48S/result.json"
64
+ sha256 = "19b3e53bb4d210b33f654f7ea3f5aa4f8202f4559bc248423b172008b9bed66e"
65
+ subject_bundle_hash = "sha256:065ab8284cef357f9d8a48ed9642e66e0ecc54fb3b8eedce4a70333475b50dff"
66
+ harbor_task_checksum = "5fa7942ddfc60d970b84218ca0eb0429d1692379cefa1e09ef6a4117d934130e"
67
+
68
+ [[metadata.repo2env.evaluation.evidence]]
69
+ kind = "probe"
70
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-hf-scale/quality-recovery-v4/f1fb6bb8619d/trials/r0-probe0/hfqr-fcdb3925fe38-f1fb6bb8619d-r0-probe0/tasksmith-f1fb6bb8619d__H62ML3j/result.json"
71
+ sha256 = "247a016e51ade66ffdfda652e8acf5336d8fa653abbcd53474be3be97f835bad"
72
+ subject_bundle_hash = "sha256:c43f3cd7be4bbca16838fa5e31590db2d9af668df6df6ee26d65fe4eb3a977a2"
73
+ harbor_task_checksum = "f25952fb22f0816e31d6ecb66013e4cbef970c8bfe109a8055393c8b111c5d3a"
74
+
75
+ [[metadata.repo2env.evaluation.evidence]]
76
+ kind = "probe"
77
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-hf-scale/quality-recovery-v4/f1fb6bb8619d/trials/r0-probe1/hfqr-fcdb3925fe38-f1fb6bb8619d-r0-probe1/tasksmith-f1fb6bb8619d__3L94UD4/result.json"
78
+ sha256 = "9c6eed1546c25975cbd501cd7b91d059bacb67907a024a918ba8316b43bb7a34"
79
+ subject_bundle_hash = "sha256:201f082677d20e0eb53406136a976220daf6ca7eeac48a124d4ad9177f065f07"
80
+ harbor_task_checksum = "c23a84e09414b77c4916b2d7c3b06598ef7cd2b794d847a76dc18b1ef6bc1371"
81
+
82
+ [environment]
83
+ cpus = 1
84
+ memory_mb = 2048
85
+ build_timeout_sec = 600
86
+ network_mode = "no-network"
87
+
88
+ [agent]
89
+ timeout_sec = 600
90
+ user = "learner"
91
+ network_mode = "no-network"
92
+
93
+ [verifier]
94
+ timeout_sec = 90
95
+ user = "root"
96
+ network_mode = "no-network"
97
+ environment_mode = "separate"
98
+
99
+ [verifier.environment]
100
+ network_mode = "no-network"
101
+ cpus = 1
102
+ memory_mb = 2048
tasks/tasksmith-f1fb6bb8619d/tests/Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim-bookworm
2
+ WORKDIR /workspace
3
+ RUN python -m pip install --no-cache-dir anyio==4.15.1 certifi==2026.7.22 filelock==3.32.3 fsspec==2026.7.0 huggingface_hub==1.31.0 iniconfig==2.3.0 mpmath==1.3.0 networkx==3.6.1 numpy==2.5.3 packaging==26.3 parameterized==0.9.0 pluggy==1.6.0 psutil==7.2.2 pytest==8.4.2 PyYAML==6.0.3 safetensors==0.8.0 setuptools==78.1.0 sympy==1.14.0 torch==2.11.0+cpu tqdm==4.70.1 typing_extensions==4.16.0 --extra-index-url https://download.pytorch.org/whl/cpu
4
+ COPY source /workspace
5
+ RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e .
6
+ ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
7
+ RUN useradd -m -u 1001 grader
8
+ COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/
9
+ RUN chmod 755 /tests && chmod 644 /tests/*
tasks/tasksmith-f1fb6bb8619d/tests/contract.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"expected_passes": ["tests.test_data_loader.DataLoaderTester::test_batch_sampler_shards_with_no_splits", "tests.test_data_loader.DataLoaderTester::test_batch_sampler_shards_with_splits", "tests.test_data_loader.DataLoaderTester::test_batch_sampler_shards_with_no_splits_no_even", "tests.test_data_loader.DataLoaderTester::test_batch_sampler_shards_with_splits_no_even", "tests.test_data_loader.DataLoaderTester::test_batch_sampler_varying_batch_size_even_batches", "tests.test_data_loader.DataLoaderTester::test_batch_sampler_varying_batch_size_many_processes", "tests.test_data_loader.DataLoaderTester::test_split_batches_validates_dynamic_batch_size", "tests.test_data_loader.DataLoaderTester::test_batch_sampler_with_varying_batch_size", "tests.test_data_loader.DataLoaderTester::test_split_batches_validates_non_divisible_batch_size"], "submitted_files": ["src/accelerate/data_loader.py"], "test_paths": ["tests/test_data_loader.py::DataLoaderTester::test_batch_sampler_shards_with_no_splits", "tests/test_data_loader.py::DataLoaderTester::test_batch_sampler_shards_with_splits", "tests/test_data_loader.py::DataLoaderTester::test_batch_sampler_shards_with_no_splits_no_even", "tests/test_data_loader.py::DataLoaderTester::test_batch_sampler_shards_with_splits_no_even", "tests/test_data_loader.py::DataLoaderTester::test_batch_sampler_with_varying_batch_size", "tests/test_data_loader.py::DataLoaderTester::test_batch_sampler_varying_batch_size_even_batches", "tests/test_data_loader.py::DataLoaderTester::test_batch_sampler_varying_batch_size_many_processes", "tests/test_data_loader.py::DataLoaderTester::test_split_batches_validates_dynamic_batch_size", "tests/test_data_loader.py::DataLoaderTester::test_split_batches_validates_non_divisible_batch_size"], "timeout_sec": 60}
tasks/tasksmith-f1fb6bb8619d/tests/grade.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone trusted entry point; copied into each separate verifier image.
2
+
3
+ No Repo2RLEnv installation is needed to grade an exported task. Submitted Python
4
+ runs as an unprivileged user; this parent owns the result parser and reward file.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import importlib.util
10
+ import json
11
+ import os
12
+ import signal
13
+ import stat
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ from pathlib import Path
18
+
19
+
20
+ def main() -> None:
21
+ directory = Path("/tests")
22
+ parser_spec = importlib.util.spec_from_file_location(
23
+ "test_results", directory / "test_results.py"
24
+ )
25
+ parser = importlib.util.module_from_spec(parser_spec)
26
+ sys.modules[parser_spec.name] = parser
27
+ parser_spec.loader.exec_module(parser)
28
+ contract = json.loads((directory / "contract.json").read_text())
29
+ logs = Path("/logs/verifier")
30
+ logs.mkdir(parents=True, exist_ok=True)
31
+ logs.chmod(0o755)
32
+ reward = logs / "reward.txt"
33
+ reward.write_text("0\n")
34
+ reward.chmod(0o644)
35
+ for relative in contract["submitted_files"]:
36
+ path = Path("/workspace") / relative
37
+ # Artifact uploads are data. Refuse link traversal and special files
38
+ # before the child imports any learner-controlled code.
39
+ for component in (path, *path.parents):
40
+ if component.is_symlink():
41
+ raise ValueError("Submitted source contains a symlink")
42
+ if not stat.S_ISREG(path.stat().st_mode) or path.stat().st_size > 8 * 1024 * 1024:
43
+ raise ValueError("Submitted source is not a bounded regular file")
44
+ os.chown(path, 0, 0)
45
+ path.chmod(0o644)
46
+ with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary:
47
+ working = Path(temporary)
48
+ os.chown(working, 1001, 1001)
49
+ working.chmod(0o700)
50
+ report = working / "results.xml"
51
+ command = [
52
+ "/usr/local/bin/python",
53
+ "-I",
54
+ "/tests/test_driver.py",
55
+ *contract["test_paths"],
56
+ "-q",
57
+ "--tb=short",
58
+ "-p",
59
+ "no:cacheprovider",
60
+ f"--junitxml={report}",
61
+ ]
62
+ with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr:
63
+ process = subprocess.Popen(
64
+ command,
65
+ cwd="/workspace",
66
+ stdout=stdout,
67
+ stderr=stderr,
68
+ user=1001,
69
+ group=1001,
70
+ extra_groups=[],
71
+ start_new_session=True,
72
+ env={
73
+ "PATH": "/usr/local/bin:/usr/bin:/bin",
74
+ "HOME": temporary,
75
+ "PYTHONDONTWRITEBYTECODE": "1",
76
+ "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
77
+ },
78
+ )
79
+ try:
80
+ code = process.wait(timeout=contract["timeout_sec"])
81
+ finally:
82
+ # Terminate descendants too: they must not keep modifying the
83
+ # child-owned report while the trusted parent checks it.
84
+ try:
85
+ os.killpg(process.pid, signal.SIGKILL)
86
+ except ProcessLookupError:
87
+ pass
88
+ process.wait()
89
+ if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024:
90
+ (logs / "result.json").write_text(
91
+ json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"})
92
+ )
93
+ return
94
+ text = report.read_text()
95
+ (logs / "results.xml").write_text(text)
96
+ try:
97
+ parsed = parser.parse_junit(text, returncode=code)
98
+ except ValueError as exc:
99
+ (logs / "result.json").write_text(
100
+ json.dumps({"passed": False, "returncode": code, "reason": str(exc)})
101
+ )
102
+ return
103
+ expected = set(contract["expected_passes"])
104
+ passed = code == 0 and bool(expected) and parsed.passed == expected
105
+ (logs / "result.json").write_text(
106
+ json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses})
107
+ )
108
+ reward.write_text("1\n" if passed else "0\n")
109
+
110
+
111
+ if __name__ == "__main__":
112
+ main()
tasks/tasksmith-f1fb6bb8619d/tests/source/.devcontainer/devcontainer.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // File only needed for VSCode users to have proper Docker based interpreters
2
+ {
3
+ "name": "accelerate_dev_environment",
4
+ "build": {
5
+ // ACTION NEEDED: comment/uncomment the relevant line depending on whether you are in a CPU/GPU environment
6
+ "dockerfile": "../docker/accelerate-cpu/Dockerfile"
7
+ // "dockerfile": "../docker/accelerate-gpu/Dockerfile"
8
+ },
9
+ "runArgs": [
10
+ // ACTION NEEDED: uncomment the next line if your local machine has GPUs available
11
+ // "--gpus", "all",
12
+ // Enable the docker container to access system resources
13
+ "--ipc", "host"
14
+ ],
15
+ "remoteEnv": {
16
+ "PYTHONPATH": "${containerEnv:PATH}:${containerWorkspaceFolder}"
17
+ },
18
+ "customizations": {
19
+ "vscode": {
20
+ "extensions": [
21
+ // Ensure we have IntelliSense in VSCode when running inside container
22
+ "ms-python.python"
23
+ ]
24
+ }
25
+ },
26
+ "workspaceFolder": "/workspaces/accelerate",
27
+ // Need git for VSCode to color code modifications. Only runs when building environment.
28
+ "onCreateCommand": "apt-get update && apt-get install -y git && pip install -e '.[dev]'"
29
+ }
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "\U0001F41B Bug Report"
2
+ description: Submit a bug report to help us improve Accelerate
3
+ body:
4
+ - type: markdown
5
+ attributes:
6
+ value: |
7
+ Thanks for taking the time to submit a bug report! 🐛
8
+ If this is not a bug related to the Accelerate library directly, but instead a general question about your code or the library specifically please use the [forums](https://discuss.huggingface.co/c/accelerate/18).
9
+
10
+ - type: textarea
11
+ id: system-info
12
+ attributes:
13
+ label: System Info
14
+ description: Please share your accelerate configuration with us. You can run the command `accelerate env` and copy-paste its outputs below
15
+ render: Shell
16
+ placeholder: accelerate version, OS, python version, numpy version, torch version, and accelerate's configuration
17
+ validations:
18
+ required: true
19
+
20
+ - type: checkboxes
21
+ id: information-scripts-examples
22
+ attributes:
23
+ label: Information
24
+ description: 'The problem arises when using:'
25
+ options:
26
+ - label: "The official example scripts"
27
+ - label: "My own modified scripts"
28
+
29
+ - type: checkboxes
30
+ id: information-tasks
31
+ attributes:
32
+ label: Tasks
33
+ description: "The tasks I am working on are:"
34
+ options:
35
+ - label: "One of the scripts in the examples/ folder of Accelerate or an officially supported `no_trainer` script in the `examples` folder of the `transformers` repo (such as `run_no_trainer_glue.py`)"
36
+ - label: "My own task or dataset (give details below)"
37
+
38
+ - type: textarea
39
+ id: reproduction
40
+ validations:
41
+ required: true
42
+ attributes:
43
+ label: Reproduction
44
+ description: |
45
+ Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet.
46
+ If you have code snippets, error messages, stack traces please provide them here as well.
47
+ Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting
48
+ Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.
49
+
50
+ placeholder: |
51
+ Steps to reproduce the behavior:
52
+
53
+ 1.
54
+ 2.
55
+ 3.
56
+
57
+ - type: textarea
58
+ id: expected-behavior
59
+ validations:
60
+ required: true
61
+ attributes:
62
+ label: Expected behavior
63
+ description: "A clear and concise description of what you would expect to happen."
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/PULL_REQUEST_TEMPLATE.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # What does this PR do?
2
+
3
+ <!--
4
+ Congratulations! You've made it this far! You're not quite done yet though.
5
+
6
+ Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.
7
+
8
+ Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.
9
+
10
+ Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
11
+ -->
12
+
13
+ <!-- Remove if not applicable -->
14
+
15
+ Fixes # (issue)
16
+
17
+
18
+ ## Before submitting
19
+ - [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
20
+ - [ ] Did you read the [contributor guideline](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md#submitting-a-pull-request-pr),
21
+ Pull Request section?
22
+ - [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
23
+ to it if that's the case.
24
+ - [ ] Did you make sure to update the documentation with your changes? Here are the
25
+ [documentation guidelines](https://github.com/huggingface/accelerate/tree/main/docs), and
26
+ [here are tips on formatting docstrings](https://github.com/huggingface/accelerate/tree/main/docs#writing-documentation---specification).
27
+ - [ ] Did you write any new necessary tests?
28
+
29
+
30
+ ## Who can review?
31
+
32
+ Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
33
+ members/contributors who may be interested in your PR.
34
+
35
+ <!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @
36
+
37
+ If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
38
+
39
+ - Big modeling: @SunMarc
40
+ - Fully-Sharded Data Parallism: @SunMarc
41
+ - DeepSpeed: @SunMarc
42
+ - Command Line Interface: @SunMarc
43
+ - Documentation: @SunMarc
44
+ - Core parts of the library: @BenjaminBossan @SunMarc
45
+ - Maintained examples: @SunMarc
46
+
47
+ -->
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/dependabot.yml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "github-actions"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "weekly"
7
+ cooldown:
8
+ default-days: 7
9
+ groups:
10
+ actions:
11
+ patterns: ["*"]
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/build-docker-images-release.yml ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build Docker images (releases)
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ release:
6
+ types: [published]
7
+
8
+ concurrency:
9
+ group: docker-image-builds
10
+ cancel-in-progress: false
11
+
12
+ jobs:
13
+ get-version:
14
+ runs-on: ubuntu-latest
15
+ outputs:
16
+ version: ${{ steps.step1.outputs.version }}
17
+ steps:
18
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
19
+ - id: step1
20
+ run: |
21
+ version=$(python setup.py --version)
22
+ if ! echo "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(\.[0-9]+)?([a-zA-Z0-9.-]*)?$'; then
23
+ echo "Invalid version format: $version" >&2
24
+ exit 1
25
+ fi
26
+ echo "version=$version" >> $GITHUB_OUTPUT
27
+
28
+ version-cpu:
29
+ name: "Latest Accelerate CPU [version]"
30
+ runs-on:
31
+ group: aws-general-8-plus
32
+ needs: get-version
33
+ steps:
34
+ - name: Set up Docker Buildx
35
+ uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0
36
+ - name: Login to DockerHub
37
+ uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
38
+ with:
39
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
40
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
41
+
42
+ - name: Build and Push CPU
43
+ uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0
44
+ with:
45
+ file: docker/accelerate-cpu/Dockerfile
46
+ push: true
47
+ tags: huggingface/accelerate:cpu-release-${{ needs.get-version.outputs.version }}
48
+
49
+ version-cuda:
50
+ name: "Latest Accelerate GPU [version]"
51
+ runs-on:
52
+ group: aws-g6-4xlarge-plus
53
+ needs: get-version
54
+ steps:
55
+ - name: Set up Docker Buildx
56
+ uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0
57
+ - name: Login to DockerHub
58
+ uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
59
+ with:
60
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
61
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
62
+
63
+ - name: Build and Push GPU
64
+ uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0
65
+ with:
66
+ file: docker/accelerate-gpu/Dockerfile
67
+ push: true
68
+ tags: huggingface/accelerate:gpu-release-${{needs.get-version.outputs.version}}
69
+
70
+ version-cuda-deepspeed:
71
+ name: "Latest Accelerate GPU DeepSpeed [version]"
72
+ runs-on:
73
+ group: aws-g6-4xlarge-plus
74
+ needs: get-version
75
+ steps:
76
+ - name: Set up Docker Buildx
77
+ uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0
78
+ - name: Login to DockerHub
79
+ uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
80
+ with:
81
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
82
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
83
+
84
+ - name: Build and Push GPU
85
+ uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0
86
+ with:
87
+ file: docker/accelerate-gpu-deepspeed/Dockerfile
88
+ push: true
89
+ tags: huggingface/accelerate:gpu-deepspeed-release-${{needs.get-version.outputs.version}}
90
+
91
+ version-cuda-fp8-transformerengine:
92
+ name: "Latest Accelerate GPU FP8 TransformerEngine [version]"
93
+ runs-on:
94
+ group: aws-g6-4xlarge-plus
95
+ needs: get-version
96
+ steps:
97
+ - name: Set up Docker Buildx
98
+ uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0
99
+ - name: Login to DockerHub
100
+ uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
101
+ with:
102
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
103
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
104
+
105
+ - name: Build and Push GPU
106
+ uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0
107
+ with:
108
+ file: docker/accelerate-gpu/Dockerfile
109
+ push: true
110
+ tags: huggingface/accelerate:gpu-fp8-transformerengine-release-${{needs.get-version.outputs.version}}
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/build_and_run_tests.yml ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Trigger docker images and run tests
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ workflow_dispatch:
8
+
9
+ env:
10
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
11
+
12
+ jobs:
13
+ check-for-source:
14
+ runs-on: ubuntu-latest
15
+ name: Check if setup was changed
16
+ outputs:
17
+ changed: ${{ steps.was_changed.outputs.changed }}
18
+ steps:
19
+ - uses: actions/checkout@v6
20
+ with:
21
+ fetch-depth: "2"
22
+
23
+ - name: Get changed files
24
+ id: changed-files
25
+ uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 #v42
26
+
27
+ - name: Was setup changed
28
+ id: was_changed
29
+ run: |
30
+ for file in ${{ steps.changed-files.outputs.all_changed_files }}; do
31
+ if [ `basename "${file}"` == "setup.py" ]; then
32
+ echo "changed=1" >> $GITHUB_OUTPUT
33
+ fi
34
+ done
35
+
36
+ build-docker-containers:
37
+ needs: check-for-source
38
+ if: (github.event_name == 'push') && (needs.check-for-source.outputs.changed == '1')
39
+ uses: ./.github/workflows/build_docker_images.yml
40
+ secrets: inherit
41
+
42
+ run-merge-tests:
43
+ needs: build-docker-containers
44
+ if: always()
45
+ uses: ./.github/workflows/run_merge_tests.yml
46
+
47
+ run-integration-tests:
48
+ needs: build-docker-containers
49
+ if: always()
50
+ uses: ./.github/workflows/self_hosted_integration_tests.yml
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/build_docker_images.yml ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build Docker images (scheduled)
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ workflow_call:
6
+ schedule:
7
+ - cron: "0 1 * * *"
8
+
9
+ concurrency:
10
+ group: docker-image-builds
11
+ cancel-in-progress: false
12
+
13
+ jobs:
14
+ latest-cpu:
15
+ name: "Latest Accelerate CPU [dev]"
16
+ runs-on:
17
+ group: aws-general-8-plus
18
+ steps:
19
+ - name: Set up Docker Buildx
20
+ uses: docker/setup-buildx-action@v4
21
+ - name: Login to DockerHub
22
+ uses: docker/login-action@v4
23
+ with:
24
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
25
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
26
+ - name: Get current date
27
+ id: date
28
+ run: |
29
+ echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV
30
+ - name: Build and Push CPU
31
+ uses: docker/build-push-action@v7
32
+ with:
33
+ file: docker/accelerate-cpu/Dockerfile
34
+ push: true
35
+ tags: |
36
+ huggingface/accelerate:cpu-nightly
37
+ huggingface/accelerate:cpu-nightly-${{ env.date }}
38
+
39
+ latest-cuda:
40
+ name: "Latest Accelerate GPU [dev]"
41
+ runs-on:
42
+ group: aws-g6-4xlarge-plus
43
+ steps:
44
+ - name: Set up Docker Buildx
45
+ uses: docker/setup-buildx-action@v4
46
+ - name: Login to DockerHub
47
+ uses: docker/login-action@v4
48
+ with:
49
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
50
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
51
+ - name: Get current date
52
+ id: date
53
+ run: |
54
+ echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV
55
+ - name: Build and Push GPU
56
+ uses: docker/build-push-action@v7
57
+ with:
58
+ file: docker/accelerate-gpu/Dockerfile
59
+ push: true
60
+ tags: |
61
+ huggingface/accelerate:gpu-nightly
62
+ huggingface/accelerate:gpu-nightly-${{ env.date }}
63
+
64
+ latest-cuda-deepspeed:
65
+ name: "Latest Accelerate GPU DeepSpeed [dev]"
66
+ runs-on:
67
+ group: aws-g6-4xlarge-plus
68
+ steps:
69
+ - name: Set up Docker Buildx
70
+ uses: docker/setup-buildx-action@v4
71
+ - name: Login to DockerHub
72
+ uses: docker/login-action@v4
73
+ with:
74
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
75
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
76
+ - name: Get current date
77
+ id: date
78
+ run: |
79
+ echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV
80
+ - name: Build and Push GPU
81
+ uses: docker/build-push-action@v7
82
+ with:
83
+ file: docker/accelerate-gpu-deepspeed/Dockerfile
84
+ push: true
85
+ tags: |
86
+ huggingface/accelerate:gpu-deepspeed-nightly
87
+ huggingface/accelerate:gpu-deepspeed-nightly-${{ env.date }}
88
+
89
+ latest-cuda-fp8-transformerengine:
90
+ name: "Latest Accelerate GPU FP8 TransformerEngine [dev]"
91
+ runs-on:
92
+ group: aws-g6-4xlarge-plus
93
+ steps:
94
+ - name: Set up Docker Buildx
95
+ uses: docker/setup-buildx-action@v4
96
+ - name: Login to DockerHub
97
+ uses: docker/login-action@v4
98
+ with:
99
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
100
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
101
+ - name: Get current date
102
+ id: date
103
+ run: |
104
+ echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV
105
+ # Get the previous month
106
+ echo "base_year=$(date -d 'last month' '+%y')" >> $GITHUB_ENV
107
+ echo "base_month=$(date -d 'last month' '+%m')" >> $GITHUB_ENV
108
+ - name: Build and Push GPU
109
+ uses: docker/build-push-action@v7
110
+ with:
111
+ file: benchmarks/fp8/transformer_engine/Dockerfile
112
+ push: true
113
+ tags: huggingface/accelerate:gpu-fp8-transformerengine-nightly-${{ env.date }}
114
+ build-args: |
115
+ BASE_YEAR=${{ env.base_year }}
116
+ BASE_MONTH=${{ env.base_month }}
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/build_documentation.yml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build documentation
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ - doc-builder*
8
+ - v*-release
9
+
10
+ jobs:
11
+ build:
12
+ uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@bcff59fca682130d2e7271ca8589911b7ac0b8bf # main
13
+ with:
14
+ commit_sha: ${{ github.sha }}
15
+ package: accelerate
16
+ custom_container: huggingface/transformers-doc-builder
17
+ secrets:
18
+ hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/build_pr_documentation.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build PR Documentation
2
+
3
+ on:
4
+ pull_request:
5
+
6
+ concurrency:
7
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
8
+ cancel-in-progress: true
9
+
10
+ jobs:
11
+ build:
12
+ uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@bcff59fca682130d2e7271ca8589911b7ac0b8bf # main
13
+ with:
14
+ commit_sha: ${{ github.event.pull_request.head.sha }}
15
+ pr_number: ${{ github.event.number }}
16
+ package: accelerate
17
+ custom_container: huggingface/transformers-doc-builder
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/fp8_runner.yml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Test FP8 Runner
2
+
3
+ on:
4
+ workflow_dispatch:
5
+
6
+ env:
7
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
8
+ jobs:
9
+ set-prev-day:
10
+ runs-on: ubuntu-latest
11
+ outputs:
12
+ prev-day: ${{ steps.set-prev-day.outputs.prev-day }}
13
+ steps:
14
+ - name: Set PREV_DAY
15
+ id: set-prev-day
16
+ run: |
17
+ PREV_DAY=$(date -d "yesterday" '+%Y-%m-%d')
18
+ echo "prev-day=$PREV_DAY" >> $GITHUB_OUTPUT
19
+ run-fp8-tests:
20
+ needs: set-prev-day
21
+ runs-on:
22
+ group: aws-g6e-12xlarge
23
+ container:
24
+ image: huggingface/accelerate:gpu-fp8-transformerengine-nightly-${{ needs.set-prev-day.outputs.prev-day }}
25
+ options: --gpus all --shm-size "16gb"
26
+ steps:
27
+ - uses: actions/checkout@v6
28
+ - name: Install the library
29
+ run: |
30
+ pip install -e .[test_prod,test_fp8]
31
+ - name: Show installed libraries
32
+ run: |
33
+ pip freeze
34
+ - name: Run TE FP8 tests
35
+ run: |
36
+ python -m pytest -s -v ./tests/test_fp8.py
37
+
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/gaudi3_scheduled.yml ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Gaudi3 tests (scheduled)
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ schedule: # every day at 6 AM UTC
6
+ - cron: "0 6 * * *"
7
+
8
+ concurrency:
9
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
10
+ cancel-in-progress: true
11
+
12
+ jobs:
13
+ run-gaudi3-tests:
14
+ runs-on:
15
+ group: itac-bm-emr-gaudi3-dell-2gaudi
16
+
17
+ container:
18
+ image: docker://vault.habana.ai/gaudi-docker/1.21.1/ubuntu22.04/habanalabs/pytorch-installer-2.6.0:latest
19
+ options: --runtime=habana --shm-size=64G --cap-add=sys_nice --env HABANA_VISIBLE_DEVICES
20
+ env:
21
+ OMPI_MCA_btl_vader_single_copy_mechanism: none
22
+ PT_ENABLE_INT64_SUPPORT: 1
23
+ PT_HPU_LAZY_MODE: 0
24
+ RUN_SLOW: 1
25
+
26
+ steps:
27
+ - name: HL-SMI (1)
28
+ run: |
29
+ hl-smi
30
+ echo "HABANA_VISIBLE_DEVICES=${HABANA_VISIBLE_DEVICES}"
31
+ echo "HABANA_VISIBLE_MODULES=${HABANA_VISIBLE_MODULES}"
32
+
33
+ - name: Extract HPU visible modules
34
+ id: add-modules
35
+ run: |
36
+ export HABANA_VISIBLE_MODULES=$(hl-smi -Q module_id -f csv,noheader | tr '\n' ',' | sed 's/,$//')
37
+ echo "HABANA_VISIBLE_MODULES=${HABANA_VISIBLE_MODULES}" >> $GITHUB_ENV
38
+
39
+ - name: HL-SMI (2)
40
+ run: |
41
+ hl-smi
42
+ echo "HABANA_VISIBLE_DEVICES=${HABANA_VISIBLE_DEVICES}"
43
+ echo "HABANA_VISIBLE_MODULES=${HABANA_VISIBLE_MODULES}"
44
+
45
+ - name: Checkout to Accelerate
46
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
47
+
48
+ - name: Install Accelerate with Transformers & DeepSpeed
49
+ run: |
50
+ pip install -e .[testing] \
51
+ git+https://github.com/HabanaAI/[email protected] \
52
+ git+https://github.com/huggingface/transformers.git
53
+
54
+ - name: Run CLI tests
55
+ if: ${{ !cancelled() && (success() || failure()) }}
56
+ run: |
57
+ make test_cli
58
+
59
+ - name: Run Core tests
60
+ if: ${{ !cancelled() && (success() || failure()) }}
61
+ run: |
62
+ make test_core
63
+
64
+ - name: Run Big Modeling tests
65
+ if: ${{ !cancelled() && (success() || failure()) }}
66
+ run: |
67
+ make test_big_modeling
68
+
69
+ - name: Run DeepSpeed integration tests
70
+ if: ${{ !cancelled() && (success() || failure()) }}
71
+ run: |
72
+ make test_deepspeed
73
+
74
+ - name: Run FSDP integration tests
75
+ if: ${{ !cancelled() && (success() || failure()) }}
76
+ run: |
77
+ make test_fsdp
78
+
79
+ - name: Run TP integration tests
80
+ if: ${{ !cancelled() && (success() || failure()) }}
81
+ run: |
82
+ make test_tp
83
+
84
+ - name: Run Examples tests
85
+ if: ${{ !cancelled() && (success() || failure()) }}
86
+ run: |
87
+ make test_examples
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/integration_tests.yml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CI for specifically ensuring integrations work fine (`transformers` mainly)
2
+ # Useful tips:
3
+ # - New integrations to test should have its own job, and follow a strategy method where we check both
4
+ # the pypi and github versions.
5
+ # - When checking the latest release of the integration, use
6
+ # git checkout $(git describe --tags `git rev-list --tags --max-count=1`) to get the latest release.
7
+
8
+ name: Integration Tests
9
+
10
+ on:
11
+ pull_request:
12
+ paths:
13
+ - "src/**"
14
+ - "tests/**"
15
+ - ".github/**"
16
+ - "examples/**"
17
+ - "setup.py"
18
+ types: [opened, synchronize, reopened]
19
+
20
+ env:
21
+ HF_HOME: ~/hf_cache
22
+
23
+ jobs:
24
+ run-trainer-tests:
25
+ runs-on: ubuntu-latest
26
+ strategy:
27
+ fail-fast: false
28
+ steps:
29
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
30
+ - name: Set up python 3.10
31
+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
32
+ with:
33
+ python-version: '3.10'
34
+ cache: 'pip'
35
+ cache-dependency-path: 'setup.py'
36
+
37
+ - name: Install Accelerate from source
38
+ run: |
39
+ pip install --upgrade pip
40
+ pip install -e .
41
+
42
+ - name: Clone and install transformers
43
+ run: |
44
+ cd ..
45
+ git clone https://github.com/huggingface/transformers
46
+ cd transformers
47
+ pip install .[torch,testing]
48
+
49
+ - name: Show installed libraries
50
+ run: |
51
+ pip freeze
52
+
53
+ - name: Run Trainer tests
54
+ env:
55
+ WANDB_DISABLED: true
56
+ run: |
57
+ cd ../transformers
58
+ pytest -sv tests/trainer
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/nightly.yml ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Self-hosted runner with slow tests (scheduled)
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ schedule:
6
+ - cron: "0 2 * * *"
7
+
8
+ env:
9
+ RUN_SLOW: "yes"
10
+ IS_GITHUB_CI: "1"
11
+ SLACK_API_TOKEN: ${{ secrets.SLACK_API_TOKEN }}
12
+
13
+
14
+ jobs:
15
+ run_core_tests_single_gpu:
16
+ runs-on:
17
+ group: aws-g6-4xlarge-plus
18
+ env:
19
+ CUDA_VISIBLE_DEVICES: "0"
20
+ TEST_TYPE: "single_gpu"
21
+ container:
22
+ image: huggingface/accelerate:gpu-nightly
23
+ options: --gpus all --shm-size "16gb"
24
+ defaults:
25
+ run:
26
+ shell: bash
27
+ steps:
28
+ - name: Update clone & pip install
29
+ run: |
30
+ source activate accelerate
31
+ git clone https://github.com/huggingface/accelerate;
32
+ cd accelerate;
33
+ git checkout ${{ github.sha }};
34
+ pip install -e . --no-deps
35
+ pip install pytest-reportlog tabulate
36
+
37
+ - name: Show installed libraries
38
+ run: |
39
+ source activate accelerate;
40
+ pip freeze
41
+
42
+ - name: Run test on GPUs
43
+ working-directory: accelerate
44
+ run: |
45
+ source activate accelerate
46
+ make test
47
+
48
+ - name: Run examples on GPUs
49
+ working-directory: accelerate
50
+ if: always()
51
+ run: |
52
+ source activate accelerate
53
+ pip uninstall comet_ml -y
54
+ make test_examples
55
+
56
+ - name: Generate Report
57
+ working-directory: accelerate
58
+ if: always()
59
+ run: |
60
+ pip install slack_sdk tabulate
61
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
62
+
63
+ run_deepspeed_tests_single_gpu:
64
+ runs-on:
65
+ group: aws-g6-4xlarge-plus
66
+ env:
67
+ CUDA_VISIBLE_DEVICES: "0"
68
+ TEST_TYPE: "single_gpu_deepspeed"
69
+ container:
70
+ image: huggingface/accelerate:gpu-deepspeed-nightly
71
+ options: --gpus all --shm-size "16gb"
72
+ defaults:
73
+ run:
74
+ shell: bash
75
+ steps:
76
+ - name: Update clone & pip install
77
+ run: |
78
+ source activate accelerate
79
+ git clone https://github.com/huggingface/accelerate;
80
+ cd accelerate;
81
+ git checkout ${{ github.sha }};
82
+ pip install -e . --no-deps
83
+ pip install pytest-reportlog tabulate
84
+
85
+ - name: Show installed libraries
86
+ run: |
87
+ source activate accelerate;
88
+ pip freeze
89
+
90
+ - name: Run test on GPUs
91
+ working-directory: accelerate
92
+ run: |
93
+ source activate accelerate
94
+ make test_deepspeed
95
+
96
+ - name: Run Integration tests on GPUs
97
+ working-directory: accelerate
98
+ if: always()
99
+ run: |
100
+ source activate accelerate
101
+ make test_integrations
102
+
103
+ - name: Run examples on GPUs
104
+ working-directory: accelerate
105
+ if: always()
106
+ run: |
107
+ source activate accelerate
108
+ pip uninstall comet_ml -y
109
+ make test_examples
110
+
111
+ - name: Generate Report
112
+ working-directory: accelerate
113
+ if: always()
114
+ run: |
115
+ pip install slack_sdk tabulate
116
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
117
+
118
+ run_core_tests_multi_gpu:
119
+ runs-on:
120
+ group: aws-g6-12xlarge-plus
121
+ env:
122
+ CUDA_VISIBLE_DEVICES: "0,1"
123
+ TEST_TYPE: "multi_gpu"
124
+ container:
125
+ image: huggingface/accelerate:gpu-nightly
126
+ options: --gpus all --shm-size "16gb"
127
+ defaults:
128
+ run:
129
+ shell: bash
130
+ steps:
131
+ - name: Update clone
132
+ run: |
133
+ source activate accelerate
134
+ git clone https://github.com/huggingface/accelerate;
135
+ cd accelerate;
136
+ git checkout ${{ github.sha }};
137
+ pip install -e . --no-deps
138
+ pip install pytest-reportlog tabulate
139
+
140
+ - name: Show installed libraries
141
+ run: |
142
+ source activate accelerate;
143
+ pip freeze
144
+
145
+ - name: Run core tests on GPUs
146
+ working-directory: accelerate
147
+ run: |
148
+ source activate accelerate
149
+ make test_core
150
+
151
+ - name: Run big modeling tests on GPUs
152
+ working-directory: accelerate
153
+ if: always()
154
+ run: |
155
+ source activate accelerate
156
+ make test_big_modeling
157
+
158
+ - name: Run CLI tests on GPUs
159
+ working-directory: accelerate
160
+ if: always()
161
+ run: |
162
+ source activate accelerate
163
+ make test_cli
164
+
165
+ - name: Run Integration tests on GPUs
166
+ working-directory: accelerate
167
+ if: always()
168
+ run: |
169
+ source activate accelerate
170
+ make test_integrations
171
+
172
+ - name: Run examples on GPUs
173
+ working-directory: accelerate
174
+ if: always()
175
+ run: |
176
+ source activate accelerate
177
+ pip uninstall comet_ml -y
178
+ make test_examples
179
+
180
+ - name: Generate Report
181
+ working-directory: accelerate
182
+ if: always()
183
+ run: |
184
+ pip install slack_sdk tabulate
185
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
186
+
187
+ run_deepspeed_tests_multi_gpu:
188
+ runs-on:
189
+ group: aws-g6-12xlarge-plus
190
+ env:
191
+ CUDA_VISIBLE_DEVICES: "0,1"
192
+ TEST_TYPE: "multi_gpu_deepspeed"
193
+ container:
194
+ image: huggingface/accelerate:gpu-deepspeed-nightly
195
+ options: --gpus all --shm-size "16gb"
196
+ defaults:
197
+ run:
198
+ shell: bash
199
+ steps:
200
+ - name: Update clone
201
+ run: |
202
+ source activate accelerate
203
+ git clone https://github.com/huggingface/accelerate;
204
+ cd accelerate;
205
+ git checkout ${{ github.sha }};
206
+ pip install -e . --no-deps
207
+ pip install pytest-reportlog tabulate
208
+
209
+ - name: Show installed libraries
210
+ run: |
211
+ source activate accelerate;
212
+ pip freeze
213
+
214
+ - name: Run DeepSpeed tests
215
+ working-directory: accelerate
216
+ run: |
217
+ source activate accelerate
218
+ make test_deepspeed
219
+
220
+ - name: Run Integration tests on GPUs
221
+ working-directory: accelerate
222
+ if: always()
223
+ run: |
224
+ source activate accelerate
225
+ make test_integrations
226
+
227
+ - name: Run examples on GPUs
228
+ working-directory: accelerate
229
+ if: always()
230
+ run: |
231
+ source activate accelerate
232
+ pip uninstall comet_ml -y
233
+ make test_examples
234
+
235
+ - name: Generate Report
236
+ working-directory: accelerate
237
+ if: always()
238
+ run: |
239
+ pip install slack_sdk tabulate
240
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
241
+
242
+
243
+ run-integration-tests:
244
+ if: always()
245
+ uses: ./.github/workflows/self_hosted_integration_tests.yml
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/pr_style_bot.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # To run this bot, comment "@bot /style" on a PR
2
+ name: Style Bot
3
+
4
+ on:
5
+ issue_comment:
6
+ types: [created]
7
+
8
+ permissions:
9
+ pull-requests: write
10
+ contents: read
11
+
12
+ jobs:
13
+ style:
14
+ uses: huggingface/huggingface_hub/.github/workflows/style-bot-action.yml@e2867e92c07d15e1bf18994d0a945ef5ad6b8d65
15
+ with:
16
+ python_quality_dependencies: "[quality]"
17
+ style_command_type: "default"
18
+ secrets:
19
+ app_id: ${{ secrets.HF_BOT_STYLE_APP_ID }}
20
+ app_private_key: ${{ secrets.HF_BOT_STYLE_SECRET_PEM }}
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/quality.yml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Quality Check
2
+
3
+ on: [pull_request]
4
+
5
+ jobs:
6
+ quality:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v6
10
+ - name: Set up Python 3.10
11
+ uses: actions/setup-python@v6
12
+ with:
13
+ python-version: '3.10'
14
+ cache: 'pip'
15
+ cache-dependency-path: 'setup.py'
16
+ - name: Install Python dependencies
17
+ run: pip install -e .[quality]
18
+ - name: Run Quality check
19
+ run: make quality
20
+ - name: Check if failure
21
+ if: ${{ failure() }}
22
+ run: |
23
+ echo "Quality check failed. Please ensure the right dependency versions are installed with 'pip install -e .[quality]' and rerun 'make style; make quality;'" >> $GITHUB_STEP_SUMMARY
24
+
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/run_merge_tests.yml ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Self-hosted runner tests (push to "main")
2
+
3
+ on:
4
+ workflow_call:
5
+ workflow_dispatch:
6
+
7
+ env:
8
+ TESTING_MOCKED_DATALOADERS: "1"
9
+ IS_GITHUB_CI: "1"
10
+
11
+ jobs:
12
+ run_core_tests_single_gpu:
13
+ runs-on:
14
+ group: aws-g6-4xlarge-plus
15
+ env:
16
+ CUDA_VISIBLE_DEVICES: "0"
17
+ container:
18
+ image: huggingface/accelerate:gpu-nightly
19
+ options: --gpus all --shm-size "16gb"
20
+ defaults:
21
+ run:
22
+ shell: bash
23
+ steps:
24
+ - name: Install accelerate
25
+ run: |
26
+ source activate accelerate;
27
+ git clone https://github.com/huggingface/accelerate;
28
+ cd accelerate;
29
+ git checkout ${{ github.sha }};
30
+ pip install -e .[testing,test_trackers] -U;
31
+ pip install pytest-reportlog tabulate ;
32
+
33
+ - name: Show installed libraries
34
+ run: |
35
+ source activate accelerate;
36
+ pip freeze
37
+
38
+ - name: Run CLI tests (use make cli)
39
+ working-directory: accelerate
40
+ run: |
41
+ source activate accelerate;
42
+ make test_cli
43
+
44
+ - name: Run test on GPUs
45
+ working-directory: accelerate
46
+ if: always()
47
+ run: |
48
+ source activate accelerate;
49
+ make test
50
+ - name: Run examples on GPUs
51
+ working-directory: accelerate
52
+ if: always()
53
+ run: |
54
+ source activate accelerate;
55
+ pip uninstall comet_ml -y;
56
+ make test_examples
57
+
58
+ - name: Generate Report
59
+ working-directory: accelerate
60
+ if: always()
61
+ run: |
62
+ pip install tabulate;
63
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
64
+
65
+ run_deepspeed_tests_single_gpu:
66
+ runs-on:
67
+ group: aws-g6-4xlarge-plus
68
+ env:
69
+ CUDA_VISIBLE_DEVICES: "0"
70
+ container:
71
+ image: huggingface/accelerate:gpu-deepspeed-nightly
72
+ options: --gpus all --shm-size "16gb"
73
+ defaults:
74
+ run:
75
+ shell: bash
76
+ steps:
77
+ - name: Install accelerate
78
+ run: |
79
+ source activate accelerate;
80
+ git clone https://github.com/huggingface/accelerate;
81
+ cd accelerate;
82
+ git checkout ${{ github.sha }};
83
+ pip install -e .[testing,test_trackers] -U;
84
+ pip install pytest-reportlog tabulate ;
85
+
86
+ - name: Show installed libraries
87
+ run: |
88
+ source activate accelerate;
89
+ pip freeze
90
+
91
+ - name: Run test on GPUs
92
+ working-directory: accelerate
93
+ if: always()
94
+ run: |
95
+ source activate accelerate;
96
+ make test_deepspeed
97
+
98
+ - name: Generate Report
99
+ working-directory: accelerate
100
+ if: always()
101
+ run: |
102
+ pip install tabulate;
103
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
104
+
105
+ run_core_tests_multi_gpu:
106
+ runs-on:
107
+ group: aws-g6-12xlarge-plus
108
+ env:
109
+ CUDA_VISIBLE_DEVICES: 0,1
110
+ container:
111
+ image: huggingface/accelerate:gpu-nightly
112
+ options: --gpus all --shm-size "16gb"
113
+ defaults:
114
+ run:
115
+ shell: bash
116
+ steps:
117
+ - name: Update clone
118
+ run: |
119
+ source activate accelerate;
120
+ git clone https://github.com/huggingface/accelerate;
121
+ cd accelerate;
122
+ git checkout ${{ github.sha }};
123
+ pip install -e .[testing,test_trackers] -U;
124
+ pip install pytest-reportlog tabulate
125
+
126
+ - name: Show installed libraries
127
+ run: |
128
+ source activate accelerate;
129
+ pip freeze
130
+
131
+ - name: Run test on GPUs
132
+ working-directory: accelerate
133
+ run: |
134
+ source activate accelerate;
135
+ make test
136
+
137
+ - name: Run examples on GPUs
138
+ working-directory: accelerate
139
+ if: always()
140
+ run: |
141
+ source activate accelerate;
142
+ pip uninstall comet_ml -y;
143
+ make test_examples
144
+
145
+ - name: Generate Report
146
+ working-directory: accelerate
147
+ if: always()
148
+ run: |
149
+ source activate accelerate;
150
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
151
+
152
+ run_deepspeed_tests_multi_gpu:
153
+ runs-on:
154
+ group: aws-g6-12xlarge-plus
155
+ container:
156
+ image: huggingface/accelerate:gpu-deepspeed-nightly
157
+ options: --gpus all --shm-size "16gb"
158
+ defaults:
159
+ run:
160
+ shell: bash
161
+ steps:
162
+ - name: Install accelerate
163
+ run: |
164
+ source activate accelerate;
165
+ git clone https://github.com/huggingface/accelerate;
166
+ cd accelerate;
167
+ git checkout ${{ github.sha }};
168
+ pip install -e .[testing,test_trackers] -U;
169
+ pip install pytest-reportlog tabulate ;
170
+
171
+ - name: Show installed libraries
172
+ run: |
173
+ source activate accelerate;
174
+ pip freeze
175
+
176
+ - name: Run test on GPUs
177
+ working-directory: accelerate
178
+ if: always()
179
+ run: |
180
+ source activate accelerate;
181
+ make test_deepspeed
182
+
183
+ - name: Generate Report
184
+ working-directory: accelerate
185
+ if: always()
186
+ run: |
187
+ pip install tabulate;
188
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/self_hosted_integration_tests.yml ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CI for specifically ensuring integrations work fine (`transformers` mainly) on GPUs
2
+ # Useful tips:
3
+ # - `working-directory` should be set to the root of the repo, which is cloned on the actual CI runner.
4
+ # It follows the directory structure of `actions-runner/_work/{repo_name}/{repo_name}/{cloned_repo} on
5
+ # prem, but in Actions setting `working-directory` looks just in the `{repo_name}` level.
6
+ # - New integrations to test should have its own job, and follow a strategy method where we check both
7
+ # the pypi and github versions.
8
+ # - Workflow call lets this be called from `build_and_run_tests.yml`
9
+ # - When using a docker container, it's recommended to set `--shm-size`, we use 16gb.
10
+ name: Integration Tests (push to "main")
11
+
12
+ on:
13
+ workflow_call:
14
+ workflow_dispatch:
15
+
16
+ env:
17
+ HF_HOME: ~/hf_cache
18
+
19
+ defaults:
20
+ run:
21
+ shell: bash
22
+
23
+ jobs:
24
+ run-trainer-tests:
25
+ container:
26
+ image: huggingface/accelerate:gpu-deepspeed-nightly
27
+ options: --gpus all --shm-size "16gb"
28
+ runs-on:
29
+ group: aws-g6-12xlarge-plus
30
+ strategy:
31
+ fail-fast: false
32
+ matrix:
33
+ cuda_visible_devices: [
34
+ "0",
35
+ "0,1"
36
+ ]
37
+ steps:
38
+ - name: Install transformers
39
+ run: |
40
+ source activate accelerate;
41
+ git clone https://github.com/huggingface/transformers --depth 1;
42
+ cd transformers;
43
+ pip install .[torch,deepspeed-testing];
44
+ cd ..;
45
+
46
+ - name: Install accelerate
47
+ run: |
48
+ source activate accelerate;
49
+ git clone https://github.com/huggingface/accelerate;
50
+ cd accelerate;
51
+ git checkout ${{ github.sha }} ;
52
+ pip install -e .[testing];
53
+ pip uninstall comet_ml wandb dvclive -y
54
+ cd ..;
55
+
56
+ - name: Show installed libraries
57
+ run: |
58
+ source activate accelerate;
59
+ pip freeze
60
+
61
+ - name: Run trainer tests
62
+ working-directory: transformers/
63
+ env:
64
+ CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }}
65
+ WANDB_DISABLED: true
66
+ run: |
67
+ source activate accelerate;
68
+ pytest -sv tests/trainer
69
+
70
+ - name: Run deepspeed tests
71
+ working-directory: transformers/
72
+ env:
73
+ CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }}
74
+ WANDB_DISABLED: true
75
+ if: always()
76
+ run: |
77
+ source activate accelerate;
78
+ pytest -sv tests/deepspeed
79
+
80
+ - name: Run transformers examples tests
81
+ working-directory: transformers/
82
+ env:
83
+ CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }}
84
+ WANDB_DISABLED: true
85
+ run: |
86
+ source activate accelerate
87
+ pip install -r examples/pytorch/_tests_requirements.txt
88
+ pytest -sv examples/pytorch/test_accelerate_examples.py examples/pytorch/test_pytorch_examples.py
89
+
90
+ run-skorch-tests:
91
+ container:
92
+ image: huggingface/accelerate:gpu-nightly
93
+ options: --gpus all --shm-size "16gb"
94
+ runs-on:
95
+ group: aws-g6-12xlarge-plus
96
+ strategy:
97
+ fail-fast: false
98
+ steps:
99
+ - name: Install accelerate
100
+ run:
101
+ source activate accelerate;
102
+ git clone https://github.com/huggingface/accelerate;
103
+ cd accelerate;
104
+ git checkout ${{ github.sha }};
105
+ pip install -e .[testing];
106
+ cd ..
107
+
108
+ - name: Install skorch
109
+ run: |
110
+ source activate accelerate
111
+ git clone https://github.com/skorch-dev/skorch;
112
+ cd skorch;
113
+ git config --global --add safe.directory '*'
114
+ git checkout master && git pull
115
+ pip install .[test]
116
+ pip install flaky
117
+
118
+ - name: Show installed libraries
119
+ run: |
120
+ source activate accelerate;
121
+ pip freeze
122
+
123
+ - name: Run skorch tests
124
+ working-directory: skorch/
125
+ run: |
126
+ source activate accelerate;
127
+ pytest -sv -k TestAccelerate
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/stale.yml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Stale Bot
2
+
3
+ on:
4
+ schedule:
5
+ - cron: "0 15 * * *"
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ close_stale_issues:
10
+ name: Close Stale Issues
11
+ if: github.repository == 'huggingface/accelerate'
12
+ runs-on: ubuntu-latest
13
+ permissions:
14
+ issues: write
15
+ pull-requests: write
16
+ env:
17
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
18
+ steps:
19
+ - uses: actions/checkout@v6
20
+
21
+ - name: Setup Python
22
+ uses: actions/setup-python@v6
23
+ with:
24
+ python-version: '3.10'
25
+ cache: 'pip'
26
+ cache-dependency-path: 'setup.py'
27
+
28
+ - name: Install requirements
29
+ run: |
30
+ pip install PyGithub
31
+ - name: Close stale issues
32
+ run: |
33
+ python utils/stale.py
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/test.yml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Tests
2
+
3
+ on:
4
+ pull_request:
5
+ paths:
6
+ - "src/**"
7
+ - "tests/**"
8
+ - ".github/**"
9
+ - "examples/**"
10
+ - "setup.py"
11
+ types: [opened, synchronize, reopened]
12
+
13
+ env:
14
+ HF_HOME: ~/hf_cache
15
+ TESTING_MOCKED_DATALOADERS: "1"
16
+ IS_GITHUB_CI: "1"
17
+
18
+ jobs:
19
+ run-tests:
20
+ runs-on:
21
+ group: aws-general-8-plus
22
+ strategy:
23
+ fail-fast: false
24
+ matrix:
25
+ pytorch-version: [
26
+ latest,
27
+ minimum,
28
+ ]
29
+ test-kind: [
30
+ test_prod,
31
+ test_core,
32
+ test_cli,
33
+ test_big_modeling,
34
+ test_deepspeed,
35
+ test_fsdp,
36
+ test_example_differences,
37
+ test_checkpoint_step,
38
+ test_checkpoint_epoch,
39
+ test_rest
40
+ ]
41
+ steps:
42
+ - uses: actions/checkout@v6
43
+ - name: Set up python 3.10
44
+ uses: actions/setup-python@v6
45
+ with:
46
+ python-version: '3.10'
47
+ cache: 'pip'
48
+ cache-dependency-path: 'setup.py'
49
+
50
+ - name: Install the library
51
+ run: |
52
+ if [[ ${{ matrix.test-kind }} = test_prod ]]; then pip install -e .[test_prod]; fi
53
+ if [[ ${{ matrix.test-kind }} != test_prod ]]; then pip install -e .[testing,test_trackers]; fi
54
+ if [[ ${{ matrix.test-kind }} = test_rest ]]; then pip uninstall comet_ml -y; fi
55
+ if [[ ${{ matrix.pytorch-version }} = minimum ]]; then pip install torchvision==0.19.0 torch==2.4.0; fi
56
+ pip install pytest-reportlog tabulate setuptools importlib_metadata
57
+
58
+ - name: Show installed libraries
59
+ run: |
60
+ pip freeze
61
+
62
+ - name: Run Tests
63
+ env:
64
+ PYTORCH_VERSION: ${{ matrix.pytorch-version }}
65
+ run: |
66
+ make ${{ matrix.test-kind }}
67
+
68
+ - name: Generate Report
69
+ if: always()
70
+ run: |
71
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/test_imports.yml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Import Tests
2
+
3
+ on:
4
+ pull_request:
5
+ paths:
6
+ - "src/**"
7
+ - "tests/**"
8
+ - ".github/**"
9
+ - "examples/**"
10
+ - "setup.py"
11
+ types: [opened, synchronize, reopened]
12
+
13
+ env:
14
+ HF_HOME: ~/hf_cache
15
+ TESTING_MOCKED_DATALOADERS: "1"
16
+ IS_GITHUB_CI: "1"
17
+
18
+ jobs:
19
+ run-tests:
20
+ runs-on: ubuntu-latest
21
+ strategy:
22
+ fail-fast: false
23
+ matrix:
24
+ pytorch-version: [
25
+ latest,
26
+ minimum,
27
+ ]
28
+ steps:
29
+ - uses: actions/checkout@v6
30
+ - name: Set up python 3.10
31
+ uses: actions/setup-python@v6
32
+ with:
33
+ python-version: '3.10'
34
+ cache: 'pip'
35
+ cache-dependency-path: 'setup.py'
36
+
37
+ - name: Install the library
38
+ run: |
39
+ pip install -e .
40
+ pip install pytest-reportlog tabulate setuptools git+https://github.com/muellerzr/import-timer
41
+
42
+ - name: Show installed libraries
43
+ run: |
44
+ pip freeze
45
+
46
+ - name: Run Import Tests
47
+ env:
48
+ PYTORCH_VERSION: ${{ matrix.pytorch-version }}
49
+ run: |
50
+ pytest -sv tests/test_imports.py
51
+
52
+ - name: Generate Report
53
+ if: always()
54
+ run: |
55
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/trufflehog.yml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ on:
2
+ push:
3
+
4
+ name: Secret Leaks
5
+
6
+ jobs:
7
+ trufflehog:
8
+ runs-on: ubuntu-latest
9
+ steps:
10
+ - name: Checkout code
11
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
12
+ with:
13
+ fetch-depth: 0
14
+ - name: Secret Scanning
15
+ uses: trufflesecurity/trufflehog@d411fff7b8879a62509f3fa98c07f247ac089a51 # main
tasks/tasksmith-f1fb6bb8619d/tests/source/.github/workflows/upload_pr_documentation.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Upload PR Documentation
2
+
3
+ on:
4
+ workflow_run:
5
+ workflows: ["Build PR Documentation"]
6
+ types:
7
+ - completed
8
+
9
+ permissions:
10
+ contents: read
11
+ packages: read
12
+
13
+ jobs:
14
+ build:
15
+ uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@bcff59fca682130d2e7271ca8589911b7ac0b8bf # main
16
+ with:
17
+ package_name: accelerate
18
+ secrets:
19
+ hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
20
+ comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }}
tasks/tasksmith-f1fb6bb8619d/tests/source/.gitignore ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ .python-version
86
+
87
+ # pipenv
88
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
90
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
91
+ # install all needed dependencies.
92
+ #Pipfile.lock
93
+
94
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95
+ __pypackages__/
96
+
97
+ # Celery stuff
98
+ celerybeat-schedule
99
+ celerybeat.pid
100
+
101
+ # SageMath parsed files
102
+ *.sage.py
103
+
104
+ # Environments
105
+ .env
106
+ .venv
107
+ env/
108
+ venv/
109
+ ENV/
110
+ env.bak/
111
+ venv.bak/
112
+
113
+ # Spyder project settings
114
+ .spyderproject
115
+ .spyproject
116
+
117
+ # Rope project settings
118
+ .ropeproject
119
+
120
+ # mkdocs documentation
121
+ /site
122
+
123
+ # mypy
124
+ .mypy_cache/
125
+ .dmypy.json
126
+ dmypy.json
127
+
128
+ # Pyre type checker
129
+ .pyre/
130
+
131
+ # VSCode
132
+ .vscode
133
+
134
+ # IntelliJ
135
+ .idea
136
+
137
+ # Mac .DS_Store
138
+ .DS_Store
139
+
140
+ # More test things
141
+ wandb
142
+
143
+ # ruff
144
+ .ruff_cache
tasks/tasksmith-f1fb6bb8619d/tests/source/.pre-commit-config.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/astral-sh/ruff-pre-commit
3
+ rev: v0.2.1
4
+ hooks:
5
+ - id: ruff
6
+ args:
7
+ - --fix
8
+ - id: ruff-format
9
+ - repo: https://github.com/pre-commit/pre-commit-hooks
10
+ rev: v4.5.0
11
+ hooks:
12
+ - id: check-merge-conflict
13
+ - id: check-yaml
tasks/tasksmith-f1fb6bb8619d/tests/source/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Contributor Covenant Code of Conduct
3
+
4
+ ## Our Pledge
5
+
6
+ We as members, contributors, and leaders pledge to make participation in our
7
+ community a harassment-free experience for everyone, regardless of age, body
8
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
9
+ identity and expression, level of experience, education, socio-economic status,
10
+ nationality, personal appearance, race, religion, or sexual identity
11
+ and orientation.
12
+
13
+ We pledge to act and interact in ways that contribute to an open, welcoming,
14
+ diverse, inclusive, and healthy community.
15
+
16
+ ## Our Standards
17
+
18
+ Examples of behavior that contributes to a positive environment for our
19
+ community include:
20
+
21
+ * Demonstrating empathy and kindness toward other people
22
+ * Being respectful of differing opinions, viewpoints, and experiences
23
+ * Giving and gracefully accepting constructive feedback
24
+ * Accepting responsibility and apologizing to those affected by our mistakes,
25
+ and learning from the experience
26
+ * Focusing on what is best not just for us as individuals, but for the
27
+ overall community
28
+
29
+ Examples of unacceptable behavior include:
30
+
31
+ * The use of sexualized language or imagery, and sexual attention or
32
+ advances of any kind
33
+ * Trolling, insulting or derogatory comments, and personal or political attacks
34
+ * Public or private harassment
35
+ * Publishing others' private information, such as a physical or email
36
+ address, without their explicit permission
37
+ * Other conduct which could reasonably be considered inappropriate in a
38
+ professional setting
39
+
40
+ ## Enforcement Responsibilities
41
+
42
+ Community leaders are responsible for clarifying and enforcing our standards of
43
+ acceptable behavior and will take appropriate and fair corrective action in
44
+ response to any behavior that they deem inappropriate, threatening, offensive,
45
+ or harmful.
46
+
47
+ Community leaders have the right and responsibility to remove, edit, or reject
48
+ comments, commits, code, wiki edits, issues, and other contributions that are
49
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
50
+ decisions when appropriate.
51
+
52
+ ## Scope
53
+
54
+ This Code of Conduct applies within all community spaces, and also applies when
55
+ an individual is officially representing the community in public spaces.
56
+ Examples of representing our community include using an official e-mail address,
57
+ posting via an official social media account, or acting as an appointed
58
+ representative at an online or offline event.
59
+
60
+ ## Enforcement
61
+
62
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
63
+ reported to the community leaders responsible for enforcement at
64
65
+ All complaints will be reviewed and investigated promptly and fairly.
66
+
67
+ All community leaders are obligated to respect the privacy and security of the
68
+ reporter of any incident.
69
+
70
+ ## Enforcement Guidelines
71
+
72
+ Community leaders will follow these Community Impact Guidelines in determining
73
+ the consequences for any action they deem in violation of this Code of Conduct:
74
+
75
+ ### 1. Correction
76
+
77
+ **Community Impact**: Use of inappropriate language or other behavior deemed
78
+ unprofessional or unwelcome in the community.
79
+
80
+ **Consequence**: A private, written warning from community leaders, providing
81
+ clarity around the nature of the violation and an explanation of why the
82
+ behavior was inappropriate. A public apology may be requested.
83
+
84
+ ### 2. Warning
85
+
86
+ **Community Impact**: A violation through a single incident or series
87
+ of actions.
88
+
89
+ **Consequence**: A warning with consequences for continued behavior. No
90
+ interaction with the people involved, including unsolicited interaction with
91
+ those enforcing the Code of Conduct, for a specified period of time. This
92
+ includes avoiding interactions in community spaces as well as external channels
93
+ like social media. Violating these terms may lead to a temporary or
94
+ permanent ban.
95
+
96
+ ### 3. Temporary Ban
97
+
98
+ **Community Impact**: A serious violation of community standards, including
99
+ sustained inappropriate behavior.
100
+
101
+ **Consequence**: A temporary ban from any sort of interaction or public
102
+ communication with the community for a specified period of time. No public or
103
+ private interaction with the people involved, including unsolicited interaction
104
+ with those enforcing the Code of Conduct, is allowed during this period.
105
+ Violating these terms may lead to a permanent ban.
106
+
107
+ ### 4. Permanent Ban
108
+
109
+ **Community Impact**: Demonstrating a pattern of violation of community
110
+ standards, including sustained inappropriate behavior, harassment of an
111
+ individual, or aggression toward or disparagement of classes of individuals.
112
+
113
+ **Consequence**: A permanent ban from any sort of public interaction within
114
+ the community.
115
+
116
+ ## Attribution
117
+
118
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119
+ version 2.0, available at
120
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
121
+
122
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
123
+ enforcement ladder](https://github.com/mozilla/diversity).
124
+
125
+ [homepage]: https://www.contributor-covenant.org
126
+
127
+ For answers to common questions about this code of conduct, see the FAQ at
128
+ https://www.contributor-covenant.org/faq. Translations are available at
129
+ https://www.contributor-covenant.org/translations.
tasks/tasksmith-f1fb6bb8619d/tests/source/CONTRIBUTING.md ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2022 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ # How to contribute to 🤗 Accelerate?
18
+
19
+ Everyone is welcome to contribute, and we value everybody's contribution. Code
20
+ is thus not the only way to help the community. Answering questions, helping
21
+ others, reaching out and improving the documentations are immensely valuable to
22
+ the community.
23
+
24
+ It also helps us if you spread the word: reference the library from blog posts
25
+ on the awesome projects it made possible, shout out on Twitter every time it has
26
+ helped you, or simply star the repo to say "thank you".
27
+
28
+ Whichever way you choose to contribute, please be mindful to respect our
29
+ [code of conduct](https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md).
30
+
31
+ ## You can contribute in so many ways!
32
+
33
+ Some of the ways you can contribute to Accelerate:
34
+ * Fixing outstanding issues with the existing code;
35
+ * Contributing to the examples or to the documentation;
36
+ * Submitting issues related to bugs or desired new features.
37
+
38
+ ## Submitting a new issue or feature request
39
+
40
+ Do your best to follow these guidelines when submitting an issue or a feature
41
+ request. It will make it easier for us to come back to you quickly and with good
42
+ feedback.
43
+
44
+ ### Did you find a bug?
45
+
46
+ The 🤗 Accelerate library is robust and reliable thanks to the users who notify us of
47
+ the problems they encounter. So thank you for reporting an issue.
48
+
49
+ First, we would really appreciate it if you could **make sure the bug was not
50
+ already reported** (use the search bar on Github under Issues).
51
+
52
+ Did not find it? :( So we can act quickly on it, please follow these steps:
53
+
54
+ * Include your **OS type and version**, the versions of **Python** and **PyTorch**.
55
+ * A short, self-contained, code snippet that allows us to reproduce the bug in
56
+ less than 30s;
57
+ * Provide the with your Accelerate configuration (located by default in `~/.cache/huggingface/accelerate/default_config.yaml`)
58
+
59
+ ### Do you want a new feature?
60
+
61
+ A good feature request addresses the following points:
62
+
63
+ 1. Motivation first:
64
+ * Is it related to a problem/frustration with the library? If so, please explain
65
+ why. Providing a code snippet that demonstrates the problem is best.
66
+ * Is it related to something you would need for a project? We'd love to hear
67
+ about it!
68
+ * Is it something you worked on and think could benefit the community?
69
+ Awesome! Tell us what problem it solved for you.
70
+ 2. Write a *full paragraph* describing the feature;
71
+ 3. Provide a **code snippet** that demonstrates its future use;
72
+ 4. In case this is related to a paper, please attach a link;
73
+ 5. Attach any additional information (drawings, screenshots, etc.) you think may help.
74
+
75
+ If your issue is well written we're already 80% of the way there by the time you
76
+ post it.
77
+
78
+ ## Submitting a pull request (PR)
79
+
80
+ Before writing code, we strongly advise you to search through the existing PRs or
81
+ issues to make sure that nobody is already working on the same thing. If you are
82
+ unsure, it is always a good idea to open an issue to get some feedback.
83
+
84
+ You will need basic `git` proficiency to be able to contribute to
85
+ 🤗 Accelerate. `git` is not the easiest tool to use but it has the greatest
86
+ manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro
87
+ Git](https://git-scm.com/book/en/v2) is a very good reference.
88
+
89
+ Follow these steps to start contributing:
90
+
91
+ 1. Fork the [repository](https://github.com/huggingface/accelerate) by
92
+ clicking on the 'Fork' button on the repository's page. This creates a copy of the code
93
+ under your GitHub user account.
94
+
95
+ 2. Clone your fork to your local disk, and add the base repository as a remote. The following command
96
+ assumes you have your public SSH key uploaded to GitHub. See the following guide for more
97
+ [information](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository).
98
+
99
+ ```bash
100
+ $ git clone [email protected]:<your Github handle>/accelerate.git
101
+ $ cd accelerate
102
+ $ git remote add upstream https://github.com/huggingface/accelerate.git
103
+ ```
104
+
105
+ 3. Create a new branch to hold your development changes, and do this for every new PR you work on.
106
+
107
+ Start by synchronizing your `main` branch with the `upstream/main` branch (ore details in the [GitHub Docs](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/syncing-a-fork)):
108
+
109
+ ```bash
110
+ $ git checkout main
111
+ $ git fetch upstream
112
+ $ git merge upstream/main
113
+ ```
114
+
115
+ Once your `main` branch is synchronized, create a new branch from it:
116
+
117
+ ```bash
118
+ $ git checkout -b a-descriptive-name-for-my-changes
119
+ ```
120
+
121
+ **Do not** work on the `main` branch.
122
+
123
+ 4. Set up a development environment by running the following command in a conda or a virtual environment you've created for working on this library:
124
+
125
+ ```bash
126
+ $ pip install -e ".[dev]"
127
+ ```
128
+
129
+ This will install all testing and linting/code quality dependencies for the library (see `quality`, `test_dev`,
130
+ `test_prod` targets in [`setup.py`](./setup.py)).
131
+
132
+ (If accelerate was already installed in the virtual environment, remove
133
+ it with `pip uninstall accelerate` before reinstalling it in editable
134
+ mode with the `-e` flag).
135
+
136
+ Alternatively, if you are using [Visual Studio Code](https://code.visualstudio.com/Download), the fastest way to get set up is by using
137
+ the provided Dev Container. Documentation on how to get started with dev containers is available [here](https://code.visualstudio.com/docs/remote/containers).
138
+
139
+ 5. Develop the features on your branch.
140
+
141
+ As you work on the features, you should make sure that the test suite
142
+ passes. You should run the tests impacted by your changes like this (see
143
+ below an explanation regarding the environment variable):
144
+
145
+ ```bash
146
+ $ pytest tests/<TEST_TO_RUN>.py
147
+ ```
148
+
149
+ > For the following commands leveraging the `make` utility, we recommend using the WSL system when running on
150
+ > Windows. More information [here](https://docs.microsoft.com/en-us/windows/wsl/about).
151
+
152
+ You can also run the full suite with the following command.
153
+
154
+ ```bash
155
+ $ make test
156
+ ```
157
+
158
+ `accelerate` relies on `ruff` to format its source code
159
+ consistently. After you make changes, apply automatic style corrections and code verifications
160
+ that can't be automated in one go with:
161
+
162
+ This target is also optimized to only work with files modified by the PR you're working on.
163
+
164
+ If you prefer to run the checks one after the other, the following command apply the
165
+ style corrections:
166
+
167
+ ```bash
168
+ $ make style
169
+ ```
170
+
171
+ `accelerate` also uses a few custom scripts to check for coding mistakes. Quality
172
+ control runs in CI, however you can also run the same checks with:
173
+
174
+ ```bash
175
+ $ make quality
176
+ ```
177
+
178
+ You can also set up [`pre-commit`](https://pre-commit.com/) to run these checks
179
+ automatically as Git commit hooks.
180
+
181
+ ```bash
182
+ $ pip install pre-commit
183
+ $ pre-commit install
184
+ ```
185
+
186
+ Once you're happy with your changes, add changed files using `git add` and
187
+ make a commit with `git commit` to record your changes locally:
188
+
189
+ ```bash
190
+ $ git add modified_file.py
191
+ $ git commit
192
+ ```
193
+
194
+ Please write [good commit messages](https://chris.beams.io/posts/git-commit/).
195
+
196
+ It is a good idea to sync your copy of the code with the original
197
+ repository regularly. This way you can quickly account for changes:
198
+
199
+ ```bash
200
+ $ git fetch upstream
201
+ $ git rebase upstream/main
202
+ ```
203
+
204
+ Push the changes to your account using:
205
+
206
+ ```bash
207
+ $ git push -u origin a-descriptive-name-for-my-changes
208
+ ```
209
+
210
+ 6. Once you are satisfied (**and the checklist below is happy too**), go to the
211
+ webpage of your fork on GitHub. Click on 'Pull request' to send your changes
212
+ to the project maintainers for review.
213
+
214
+ 7. It's ok if maintainers ask you for changes. It happens to core contributors
215
+ too! So everyone can see the changes in the Pull request, work in your local
216
+ branch and push the changes to your fork. They will automatically appear in
217
+ the pull request.
218
+
219
+
220
+ ### Checklist
221
+
222
+ 1. The title of your pull request should be a summary of its contribution;
223
+ 2. If your pull request addresses an issue, please mention the issue number in
224
+ the pull request description to make sure they are linked (and people
225
+ consulting the issue know you are working on it);
226
+ 3. To indicate a work in progress please prefix the title with `[WIP]`, or mark
227
+ the PR as a draft PR. These are useful to avoid duplicated work, and to differentiate
228
+ it from PRs ready to be merged;
229
+ 4. Make sure existing tests pass;
230
+ 5. Add high-coverage tests. No quality testing = no merge.
231
+
232
+ See an example of a good PR here: https://github.com/huggingface/accelerate/pull/255
233
+
234
+ ### Tests
235
+
236
+ An extensive test suite is included to test the library behavior and several examples. Library tests can be found in
237
+ the [tests folder](https://github.com/huggingface/accelerate/tree/main/tests).
238
+
239
+ We use `pytest` in order to run the tests. From the root of the
240
+ repository, here's how to run tests with `pytest` for the library:
241
+
242
+ ```bash
243
+ $ python -m pytest -sv ./tests
244
+ ```
245
+
246
+ In fact, that's how `make test` is implemented (sans the `pip install` line)!
247
+
248
+ You can specify a smaller set of tests in order to test only the feature
249
+ you're working on.
tasks/tasksmith-f1fb6bb8619d/tests/source/Dockerfile ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim-bookworm
2
+ WORKDIR /workspace
3
+ RUN python -m pip install --no-cache-dir anyio==4.15.1 certifi==2026.7.22 filelock==3.32.3 fsspec==2026.7.0 huggingface_hub==1.31.0 iniconfig==2.3.0 mpmath==1.3.0 networkx==3.6.1 numpy==2.5.3 packaging==26.3 parameterized==0.9.0 pluggy==1.6.0 psutil==7.2.2 pytest==8.4.2 PyYAML==6.0.3 safetensors==0.8.0 setuptools==78.1.0 sympy==1.14.0 torch==2.11.0+cpu tqdm==4.70.1 typing_extensions==4.16.0 --extra-index-url https://download.pytorch.org/whl/cpu
4
+ COPY . /workspace
5
+ RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e .
6
+ RUN rm -rf /workspace/.git /root/.cache/pip
7
+ ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
tasks/tasksmith-f1fb6bb8619d/tests/source/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
tasks/tasksmith-f1fb6bb8619d/tests/source/Makefile ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: quality style test docs utils
2
+
3
+ check_dirs := .
4
+
5
+ # Check that source code meets quality standards
6
+
7
+ extra_quality_checks:
8
+ python utils/check_copies.py
9
+ python utils/check_dummies.py
10
+ python utils/check_repo.py
11
+
12
+ # this target runs checks on all files
13
+ quality:
14
+ ruff check $(check_dirs)
15
+ ruff format --check $(check_dirs)
16
+
17
+ # Format source code automatically and check is there are any problems left that need manual fixing
18
+ style:
19
+ ruff check $(check_dirs) --fix
20
+ ruff format $(check_dirs)
21
+
22
+ # Run tests for the library
23
+ test_core:
24
+ python -m pytest -s -v ./tests/ \
25
+ --ignore=./tests/test_big_modeling.py \
26
+ --ignore=./tests/test_modeling_utils.py \
27
+ --ignore=./tests/test_examples.py \
28
+ --ignore=./tests/test_cli.py \
29
+ --ignore=./tests/deepspeed \
30
+ --ignore=./tests/fsdp \
31
+ --ignore=./tests/tp \
32
+ $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_core.log",)
33
+
34
+ test_cli:
35
+ python -m pytest -s -v ./tests/test_cli.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_cli.log",)
36
+
37
+ test_big_modeling:
38
+ python -m pytest -s -v ./tests/test_big_modeling.py ./tests/test_modeling_utils.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_big_modeling.log",)
39
+
40
+ test_deepspeed:
41
+ python -m pytest -s -v ./tests/deepspeed $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_deepspeed.log",)
42
+
43
+ test_fsdp:
44
+ python -m pytest -s -v ./tests/fsdp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_fsdp.log",)
45
+
46
+ test_tp:
47
+ python -m pytest -s -v ./tests/tp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_tp.log",)
48
+
49
+ # Since the new version of pytest will *change* how things are collected, we need `deepspeed` to
50
+ # run after test_core and test_cli
51
+ test:
52
+ $(MAKE) test_core
53
+ $(MAKE) test_cli
54
+ $(MAKE) test_big_modeling
55
+ $(MAKE) test_deepspeed
56
+ $(MAKE) test_fsdp
57
+ $(MAKE) test_tp
58
+
59
+ test_examples:
60
+ python -m pytest -s -v ./tests/test_examples.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_examples.log",)
61
+
62
+ # Broken down example tests for the CI runners
63
+ test_integrations:
64
+ python -m pytest -s -v ./tests/fsdp ./tests/tp ./tests/deepspeed $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_integrations.log",)
65
+
66
+ test_example_differences:
67
+ python -m pytest -s -v ./tests/test_examples.py::ExampleDifferenceTests $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_example_diff.log",)
68
+
69
+ test_checkpoint_epoch:
70
+ python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_epoch" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_epoch.log",)
71
+
72
+ test_checkpoint_step:
73
+ python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_step" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_step.log",)
74
+
75
+ # Same as test but used to install only the base dependencies
76
+ test_prod:
77
+ $(MAKE) test_core
78
+
79
+ test_rest:
80
+ python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "not by_step and not by_epoch" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_rest.log",)
81
+
82
+ # For developers to prepare a release
83
+ prepare_release:
84
+ rm -rf dist build
85
+ python setup.py bdist_wheel sdist
86
+
87
+ # Make sure this is ran in a fresh venv of some form
88
+ install_test_release:
89
+ pip uninstall accelerate -y
90
+ pip install -i https://testpypi.python.org/pypi --extra-index-url https://pypi.org/simple accelerate$(if $(version),==$(version),)
91
+
92
+ # Run as `make target=testpypi upload_release`
93
+ upload_release:
94
+ @if [ "$(target)" != "testpypi" ] && [ "$(target)" != "pypi" ]; then \
95
+ echo "Error: target must be either 'testpypi' or 'pypi'"; \
96
+ exit 1; \
97
+ fi
98
+ twine upload dist/* -r $(target)
tasks/tasksmith-f1fb6bb8619d/tests/source/README.md ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!---
2
+ Copyright 2021 The HuggingFace Team. All rights reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ -->
16
+
17
+ <p align="center">
18
+ <br>
19
+ <img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/accelerate_logo.png" width="400"/>
20
+ <br>
21
+ <p>
22
+
23
+ <p align="center">
24
+ <!-- Uncomment when CircleCI is set up
25
+ <a href="https://circleci.com/gh/huggingface/accelerate"><img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/master"></a>
26
+ -->
27
+ <a href="https://github.com/huggingface/accelerate/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/huggingface/accelerate.svg?color=blue"></a>
28
+ <a href="https://huggingface.co/docs/accelerate/index.html"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/accelerate/index.html.svg?down_color=red&down_message=offline&up_message=online"></a>
29
+ <a href="https://github.com/huggingface/accelerate/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/accelerate.svg"></a>
30
+ <a href="https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg"></a>
31
+ </p>
32
+
33
+ <h3 align="center">
34
+ <p>Run your *raw* PyTorch training script on any kind of device
35
+ </h3>
36
+
37
+ <h3 align="center">
38
+ <a href="https://hf.co/course"><img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/course_banner.png"></a>
39
+ </h3>
40
+
41
+ ## Easy to integrate
42
+
43
+ 🤗 Accelerate was created for PyTorch users who like to write the training loop of PyTorch models but are reluctant to write and maintain the boilerplate code needed to use multi-GPUs/TPU/fp16.
44
+
45
+ 🤗 Accelerate abstracts exactly and only the boilerplate code related to multi-GPUs/TPU/fp16 and leaves the rest of your code unchanged.
46
+
47
+ Here is an example:
48
+
49
+ ```diff
50
+ import torch
51
+ import torch.nn.functional as F
52
+ from datasets import load_dataset
53
+ + from accelerate import Accelerator
54
+
55
+ + accelerator = Accelerator()
56
+ - device = 'cpu'
57
+ + device = accelerator.device
58
+
59
+ model = torch.nn.Transformer().to(device)
60
+ optimizer = torch.optim.Adam(model.parameters())
61
+
62
+ dataset = load_dataset('my_dataset')
63
+ data = torch.utils.data.DataLoader(dataset, shuffle=True)
64
+
65
+ + model, optimizer, data = accelerator.prepare(model, optimizer, data)
66
+
67
+ model.train()
68
+ for epoch in range(10):
69
+ for source, targets in data:
70
+ source = source.to(device)
71
+ targets = targets.to(device)
72
+
73
+ optimizer.zero_grad()
74
+
75
+ output = model(source)
76
+ loss = F.cross_entropy(output, targets)
77
+
78
+ - loss.backward()
79
+ + accelerator.backward(loss)
80
+
81
+ optimizer.step()
82
+ ```
83
+
84
+ As you can see in this example, by adding 5-lines to any standard PyTorch training script you can now run on any kind of single or distributed node setting (single CPU, single GPU, multi-GPUs and TPUs) as well as with or without mixed precision (fp8, fp16, bf16).
85
+
86
+ In particular, the same code can then be run without modification on your local machine for debugging or your training environment.
87
+
88
+ 🤗 Accelerate even handles the device placement for you (which requires a few more changes to your code, but is safer in general), so you can even simplify your training loop further:
89
+
90
+ ```diff
91
+ import torch
92
+ import torch.nn.functional as F
93
+ from datasets import load_dataset
94
+ + from accelerate import Accelerator
95
+
96
+ - device = 'cpu'
97
+ + accelerator = Accelerator()
98
+
99
+ - model = torch.nn.Transformer().to(device)
100
+ + model = torch.nn.Transformer()
101
+ optimizer = torch.optim.Adam(model.parameters())
102
+
103
+ dataset = load_dataset('my_dataset')
104
+ data = torch.utils.data.DataLoader(dataset, shuffle=True)
105
+
106
+ + model, optimizer, data = accelerator.prepare(model, optimizer, data)
107
+
108
+ model.train()
109
+ for epoch in range(10):
110
+ for source, targets in data:
111
+ - source = source.to(device)
112
+ - targets = targets.to(device)
113
+
114
+ optimizer.zero_grad()
115
+
116
+ output = model(source)
117
+ loss = F.cross_entropy(output, targets)
118
+
119
+ - loss.backward()
120
+ + accelerator.backward(loss)
121
+
122
+ optimizer.step()
123
+ ```
124
+
125
+ Want to learn more? Check out the [documentation](https://huggingface.co/docs/accelerate) or have a look at our [examples](https://github.com/huggingface/accelerate/tree/main/examples).
126
+
127
+ ## Launching script
128
+
129
+ 🤗 Accelerate also provides an optional CLI tool that allows you to quickly configure and test your training environment before launching the scripts. No need to remember how to use `torch.distributed.run` or to write a specific launcher for TPU training!
130
+ On your machine(s) just run:
131
+
132
+ ```bash
133
+ accelerate config
134
+ ```
135
+
136
+ and answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doing
137
+
138
+ ```bash
139
+ accelerate launch my_script.py --args_to_my_script
140
+ ```
141
+
142
+ For instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo):
143
+
144
+ ```bash
145
+ accelerate launch examples/nlp_example.py
146
+ ```
147
+
148
+ This CLI tool is **optional**, and you can still use `python my_script.py` or `python -m torchrun my_script.py` at your convenience.
149
+
150
+ You can also directly pass in the arguments you would to `torchrun` as arguments to `accelerate launch` if you wish to not run` accelerate config`.
151
+
152
+ For example, here is how to launch on two GPUs:
153
+
154
+ ```bash
155
+ accelerate launch --multi_gpu --num_processes 2 examples/nlp_example.py
156
+ ```
157
+
158
+ To learn more, check the CLI documentation available [here](https://huggingface.co/docs/accelerate/package_reference/cli).
159
+
160
+ Or view the configuration zoo [here](https://github.com/huggingface/accelerate/blob/main/examples/config_yaml_templates/)
161
+
162
+ ## Launching multi-CPU run using MPI
163
+
164
+ 🤗 Here is another way to launch multi-CPU run using MPI. You can learn how to install Open MPI on [this page](https://www.open-mpi.org/faq/?category=building#easy-build). You can use Intel MPI or MVAPICH as well.
165
+ Once you have MPI setup on your cluster, just run:
166
+ ```bash
167
+ accelerate config
168
+ ```
169
+ Answer the questions that are asked, selecting to run using multi-CPU, and answer "yes" when asked if you want accelerate to launch mpirun.
170
+ Then, use `accelerate launch` with your script like:
171
+ ```bash
172
+ accelerate launch examples/nlp_example.py
173
+ ```
174
+ Alternatively, you can use mpirun directly, without using the CLI like:
175
+ ```bash
176
+ mpirun -np 2 python examples/nlp_example.py
177
+ ```
178
+
179
+ ## Launching training using DeepSpeed
180
+
181
+ 🤗 Accelerate supports training on single/multiple GPUs using DeepSpeed. To use it, you don't need to change anything in your training code; you can set everything using just `accelerate config`. However, if you desire to tweak your DeepSpeed related args from your Python script, we provide you the `DeepSpeedPlugin`.
182
+
183
+ ```python
184
+ from accelerate import Accelerator, DeepSpeedPlugin
185
+
186
+ # deepspeed needs to know your gradient accumulation steps beforehand, so don't forget to pass it
187
+ # Remember you still need to do gradient accumulation by yourself, just like you would have done without deepspeed
188
+ deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2)
189
+ accelerator = Accelerator(mixed_precision='fp16', deepspeed_plugin=deepspeed_plugin)
190
+
191
+ # How to save your 🤗 Transformer?
192
+ accelerator.wait_for_everyone()
193
+ unwrapped_model = accelerator.unwrap_model(model)
194
+ unwrapped_model.save_pretrained(save_dir, save_function=accelerator.save, state_dict=accelerator.get_state_dict(model))
195
+ ```
196
+
197
+ Note: DeepSpeed support is experimental for now. In case you get into some problem, please open an issue.
198
+
199
+ ## Launching your training from a notebook
200
+
201
+ 🤗 Accelerate also provides a `notebook_launcher` function you can use in a notebook to launch a distributed training. This is especially useful for Colab or Kaggle notebooks with a TPU backend. Just define your training loop in a `training_function` then in your last cell, add:
202
+
203
+ ```python
204
+ from accelerate import notebook_launcher
205
+
206
+ notebook_launcher(training_function)
207
+ ```
208
+
209
+ An example can be found in [this notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb). [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb)
210
+
211
+ ## Why should I use 🤗 Accelerate?
212
+
213
+ You should use 🤗 Accelerate when you want to easily run your training scripts in a distributed environment without having to renounce full control over your training loop. This is not a high-level framework above PyTorch, just a thin wrapper so you don't have to learn a new library. In fact, the whole API of 🤗 Accelerate is in one class, the `Accelerator` object.
214
+
215
+ ## Why shouldn't I use 🤗 Accelerate?
216
+
217
+ You shouldn't use 🤗 Accelerate if you don't want to write a training loop yourself. There are plenty of high-level libraries above PyTorch that will offer you that, 🤗 Accelerate is not one of them.
218
+
219
+ ## Frameworks using 🤗 Accelerate
220
+
221
+ If you like the simplicity of 🤗 Accelerate but would prefer a higher-level abstraction around its capabilities, some frameworks and libraries that are built on top of 🤗 Accelerate are listed below:
222
+
223
+ * [Amphion](https://github.com/open-mmlab/Amphion) is a toolkit for Audio, Music, and Speech Generation. Its purpose is to support reproducible research and help junior researchers and engineers get started in the field of audio, music, and speech generation research and development.
224
+ * [Animus](https://github.com/Scitator/animus) is a minimalistic framework to run machine learning experiments. Animus highlights common "breakpoints" in ML experiments and provides a unified interface for them within [IExperiment](https://github.com/Scitator/animus/blob/main/animus/core.py#L76).
225
+ * [Catalyst](https://github.com/catalyst-team/catalyst#getting-started) is a PyTorch framework for Deep Learning Research and Development. It focuses on reproducibility, rapid experimentation, and codebase reuse so you can create something new rather than write yet another train loop. Catalyst provides a [Runner](https://catalyst-team.github.io/catalyst/api/core.html#runner) to connect all parts of the experiment: hardware backend, data transformations, model training, and inference logic.
226
+ * [fastai](https://github.com/fastai/fastai#installing) is a PyTorch framework for Deep Learning that simplifies training fast and accurate neural nets using modern best practices. fastai provides a [Learner](https://docs.fast.ai/learner.html#Learner) to handle the training, fine-tuning, and inference of deep learning algorithms.
227
+ * [Finetuner](https://github.com/jina-ai/finetuner) is a service that enables models to create higher-quality embeddings for semantic search, visual similarity search, cross-modal text<->image search, recommendation systems, clustering, duplication detection, anomaly detection, or other uses.
228
+ * [InvokeAI](https://github.com/invoke-ai/InvokeAI) is a creative engine for Stable Diffusion models, offering industry-leading WebUI, terminal usage support, and serves as the foundation for many commercial products.
229
+ * [Kornia](https://kornia.readthedocs.io/en/latest/get-started/introduction.html) is a differentiable library that allows classical computer vision to be integrated into deep learning models. Kornia provides a [Trainer](https://kornia.readthedocs.io/en/latest/x.html#kornia.x.Trainer) with the specific purpose to train and fine-tune the supported deep learning algorithms within the library.
230
+ * [Open Assistant](https://projects.laion.ai/Open-Assistant/) is a chat-based assistant that understands tasks, can interact with their party systems, and retrieve information dynamically to do so.
231
+ * [pytorch-accelerated](https://github.com/Chris-hughes10/pytorch-accelerated) is a lightweight training library, with a streamlined feature set centered around a general-purpose [Trainer](https://pytorch-accelerated.readthedocs.io/en/latest/trainer.html), that places a huge emphasis on simplicity and transparency; enabling users to understand exactly what is going on under the hood, but without having to write and maintain the boilerplate themselves!
232
+ * [Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) is an open-source browser-based easy-to-use interface based on the Gradio library for Stable Diffusion.
233
+ * [torchkeras](https://github.com/lyhue1991/torchkeras) is a simple tool for training pytorch model just in a keras style, a dynamic and beautiful plot is provided in notebook to monitor your loss or metric.
234
+ * [transformers](https://github.com/huggingface/transformers) as a tool for helping train state-of-the-art machine learning models in PyTorch, Tensorflow, and JAX. (Accelerate is the backend for the PyTorch side).
235
+
236
+
237
+ ## Installation
238
+
239
+ This repository is tested on Python 3.8+ and PyTorch 1.10.0+
240
+
241
+ You should install 🤗 Accelerate in a [virtual environment](https://docs.python.org/3/library/venv.html). If you're unfamiliar with Python virtual environments, check out the [user guide](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
242
+
243
+ First, create a virtual environment with the version of Python you're going to use and activate it.
244
+
245
+ Then, you will need to install PyTorch: refer to the [official installation page](https://pytorch.org/get-started/locally/#start-locally) regarding the specific install command for your platform. Then 🤗 Accelerate can be installed using pip as follows:
246
+
247
+ ```bash
248
+ pip install accelerate
249
+ ```
250
+
251
+ ## Supported integrations
252
+
253
+ - CPU only
254
+ - multi-CPU on one node (machine)
255
+ - multi-CPU on several nodes (machines)
256
+ - single GPU
257
+ - multi-GPU on one node (machine)
258
+ - multi-GPU on several nodes (machines)
259
+ - TPU
260
+ - FP16/BFloat16 mixed precision
261
+ - FP8 mixed precision with [Transformer Engine](https://github.com/NVIDIA/TransformerEngine) or [MS-AMP](https://github.com/Azure/MS-AMP/)
262
+ - DeepSpeed support (Experimental)
263
+ - PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental)
264
+ - Megatron-LM support (Experimental)
265
+
266
+ ## Citing 🤗 Accelerate
267
+
268
+ If you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry.
269
+
270
+ ```bibtex
271
+ @Misc{accelerate,
272
+ title = {Accelerate: Training and inference at scale made simple, efficient and adaptable.},
273
+ author = {Sylvain Gugger and Lysandre Debut and Thomas Wolf and Philipp Schmid and Zachary Mueller and Sourab Mangrulkar and Marc Sun and Benjamin Bossan},
274
+ howpublished = {\url{https://github.com/huggingface/accelerate}},
275
+ year = {2022}
276
+ }
277
+ ```
tasks/tasksmith-f1fb6bb8619d/tests/source/benchmarks/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Benchmarks
2
+
3
+ The folders below contain suites to test various functionalities in Accelerate.
4
+
5
+ See their relevant README.md's for more information.
tasks/tasksmith-f1fb6bb8619d/tests/source/benchmarks/big_model_inference/README.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Big model inference benchmarks
2
+
3
+ Running inference with Accelerate on big models.
4
+
5
+ ## Setup
6
+
7
+ These benchmarks use the `transformers` library:
8
+
9
+ ```bash
10
+ pip install transformers
11
+ ```
12
+
13
+ To reproduce or test a new setup, run
14
+
15
+ ```py
16
+ python big_model_inference.py model_name
17
+ ```
18
+
19
+ This script supports `gpt-j-6b`, `gpt-neox`, `opt` (30B version) and `T0pp` out of the box, but you can specify any valid checkpoint for `model_name`.
20
+
21
+ To force a different `torch_dtype` than the one in the config: `--torch_dtype xxx`.
22
+
23
+ If you get an error linked to disk offload, you need to add the option `--disk-offload`
24
+
25
+ ## Results
26
+
27
+ On a setup with two Titan RTXs (24GB of RAM) and 32GB of RAM, we get the following benchmarks (T0pp does not run in float16, which is why it's not included).
28
+
29
+ | Model | Model load time | Generation time | dtype | GPU 0 use | GPU 1 use | CPU use | Disk offload |
30
+ |:-----:|:---------------:|:---------------:|:-----:|:---------:|:---------:|:-------:|:------------:|
31
+ | GPT-J-6B | 8.7s | 0.05s per token | float16 | 11.7GB | 0GB | 0GB | no |
32
+ | GPT-J-6B | 12.4s | 0.06s per token | float32 | 21.9GB | 1.5GB | 0GB | no |
33
+ | GPT-Neo-X-20B | 30.9s | 0.08s per token | float16 | 21.5GB | 18GB | 0GB | no |
34
+ | GPT-Neo-X-20B | 78.2s | 10.72s per token | float32 | 20.3GB | 22.7 GB | 24.4GB | yes |
35
+ | T0pp (11B) | 29.4s | 0.05s per token | float32 | 21.1GB | 21.3GB | 0GB | no |
36
+ | OPT-30B | 34.5s | 2.37s per token | float16 | 20.7GB | 22.3GB | 14.1GB | no |
37
+ | OPT-30B | 112.3s | 33.9s per token | float32 | 20.2GB | 21.2GB | 23.5GB | yes |
38
+
39
+ Note on the results:
40
+ - using two GPUs instead of one does not slow down generation
41
+ - using CPU offload slows down a bit (see OPT-30b)
42
+ - using disk offload slows down a lot (need to implement prefetching)
43
+
44
+ You will also note that Accelerate does not use anymore GPU and CPU RAM than necessary:
45
+ - peak GPU memory is exactly the size of the model put on a given GPU
46
+ - peak CPU memory is either the size of the biggest checkpoint shard or the part of the model offloaded on CPU, whichever is bigger.
tasks/tasksmith-f1fb6bb8619d/tests/source/benchmarks/big_model_inference/big_model_inference.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse
16
+ import time
17
+
18
+ import torch
19
+ import transformers
20
+ from measures_util import end_measure, log_measures, start_measure
21
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer
22
+
23
+ from accelerate.utils import compute_module_sizes
24
+
25
+
26
+ DEFAULT_MODELS = {
27
+ "gpt-j-6b": {"is_causal": True, "model": "sgugger/sharded-gpt-j-6B", "tokenizer": "EleutherAI/gpt-j-6B"},
28
+ "gpt-neox": {"is_causal": True, "model": "EleutherAI/gpt-neox-20b"},
29
+ "opt": {"is_causal": True, "model": "facebook/opt-30b"},
30
+ "T0pp": {"is_causal": False, "model": "bigscience/T0pp", "model_revision": "sharded"},
31
+ }
32
+
33
+ PROMPTS = [
34
+ "Hello, my name is",
35
+ "Are unicorns real? Unicorns are",
36
+ "For the first time in several years,",
37
+ "My name is Julien and I am",
38
+ "The goal of life is",
39
+ "Whenever I'm sad, I like to",
40
+ ]
41
+
42
+
43
+ def parse_args():
44
+ parser = argparse.ArgumentParser(description="Run and time generations on a big model using Accelerate.")
45
+ parser.add_argument("model_name", type=str, default=None, help="The name of the model to try.")
46
+ parser.add_argument(
47
+ "--tokenizer_name", type=str, default=None, help="The name of the tokenizer (if different from the model."
48
+ )
49
+ parser.add_argument("--is_causal", type=bool, default=None, help="Whether or not the model is causal.")
50
+ parser.add_argument(
51
+ "--model_revision", type=str, default=None, help="The revision to use for the model checkpoint."
52
+ )
53
+ parser.add_argument("--torch_dtype", type=str, default=None, help="The dtype for the model.")
54
+ parser.add_argument("--disk_offload", action="store_true")
55
+
56
+ args = parser.parse_args()
57
+
58
+ # Sanitize args
59
+ if args.model_name in DEFAULT_MODELS:
60
+ defaults = DEFAULT_MODELS[args.model_name]
61
+ args.model_name = defaults["model"]
62
+ if args.tokenizer_name is None:
63
+ args.tokenizer_name = defaults.get("tokenizer", args.model_name)
64
+ if args.is_causal is None:
65
+ args.is_causal = defaults["is_causal"]
66
+ if args.model_revision is None:
67
+ args.model_revision = defaults.get("model_revision", "main")
68
+
69
+ if args.is_causal is None:
70
+ raise ValueError("Could not infer the default for `--is_causal`, pass either True or False for it.")
71
+ if args.tokenizer_name is None:
72
+ args.tokenizer_name = args.model_name
73
+ if args.model_revision is None:
74
+ args.model_revision = "main"
75
+
76
+ return args
77
+
78
+
79
+ def main():
80
+ transformers.utils.logging.set_verbosity_error()
81
+ args = parse_args()
82
+
83
+ if args.torch_dtype is None:
84
+ config = AutoConfig.from_pretrained(args.model_name)
85
+ torch_dtype = getattr(config, "torch_dtype", torch.float32)
86
+ else:
87
+ torch_dtype = getattr(torch, args.torch_dtype)
88
+ model_cls = AutoModelForCausalLM if args.is_causal else AutoModelForSeq2SeqLM
89
+ kwargs = {
90
+ "torch_dtype": torch_dtype,
91
+ "revision": args.model_revision,
92
+ }
93
+ if args.disk_offload:
94
+ kwargs["offload_folder"] = "tmp_offload"
95
+ kwargs["offload_state_dict"] = True
96
+
97
+ start_measures = start_measure()
98
+ model = model_cls.from_pretrained(args.model_name, device_map="auto", **kwargs)
99
+ end_measures = end_measure(start_measures)
100
+ log_measures(end_measures, "Model loading")
101
+
102
+ module_sizes = compute_module_sizes(model)
103
+ device_size = {v: 0 for v in model.hf_device_map.values()}
104
+ for module, device in model.hf_device_map.items():
105
+ device_size[device] += module_sizes[module]
106
+ message = "\n".join([f"- {device}: {size // 2**20}MiB" for device, size in device_size.items()])
107
+ print(f"\nTheoretical use:\n{message}")
108
+
109
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name)
110
+
111
+ start_measures = start_measure()
112
+ generation_times = []
113
+ gen_tokens = []
114
+ texts_outs = []
115
+ for prompt in PROMPTS:
116
+ inputs = tokenizer(prompt, return_tensors="pt").to(0)
117
+ tokens = inputs["input_ids"][0].tolist()
118
+ before_generate = time.time()
119
+ outputs = model.generate(inputs["input_ids"])
120
+ after_generate = time.time()
121
+ outputs = outputs[0].tolist()
122
+ num_gen_tokens = len(outputs) if outputs[: len(tokens)] != tokens else len(outputs) - len(tokens)
123
+ generation_time = after_generate - before_generate
124
+
125
+ text_out = tokenizer.decode(outputs, skip_special_tokens=True)
126
+ texts_outs.append(text_out)
127
+ generation_times.append(generation_time)
128
+ gen_tokens.append(num_gen_tokens)
129
+ print(f"Prompt: {prompt}\nGeneration {text_out}\nIn {generation_time:.2f}s for {num_gen_tokens} tokens\n")
130
+
131
+ end_measures = end_measure(start_measures)
132
+ log_measures(end_measures, "Model generation")
133
+
134
+ generation_times_per_token = [gen / tok for gen, tok in zip(generation_times, gen_tokens)]
135
+ avg_gen = sum(generation_times_per_token) / len(generation_times)
136
+ print(f"Average time of generation per token: {avg_gen:.2f}s")
137
+ print(f"First generation (avg time per token): {generation_times_per_token[0]:.2f}s")
138
+ avg_gen = sum(generation_times_per_token[1:]) / (len(generation_times_per_token) - 1)
139
+ print(f"Average time of generation per token (excluding the first): {avg_gen:.2f}s")
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()