AdithyaSK HF Staff commited on
Commit
9a1553f
·
verified ·
1 Parent(s): f86eefa

Stage Harbor release files 52001-52500

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-6313a21e3910/tests/source/tests/test_scheduler.py +142 -0
  2. tasks/tasksmith-6313a21e3910/tests/source/tests/test_state_checkpointing.py +444 -0
  3. tasks/tasksmith-6313a21e3910/tests/source/tests/test_tpu.py +34 -0
  4. tasks/tasksmith-6313a21e3910/tests/source/tests/test_tracking.py +870 -0
  5. tasks/tasksmith-6313a21e3910/tests/source/tests/test_utils.py +681 -0
  6. tasks/tasksmith-6313a21e3910/tests/source/tests/tp/fsdp2_tp_preparation.py +107 -0
  7. tasks/tasksmith-6313a21e3910/tests/source/tests/tp/fsdp2_tp_preparation_config.yaml +18 -0
  8. tasks/tasksmith-6313a21e3910/tests/source/tests/tp/test_tp.py +79 -0
  9. tasks/tasksmith-6313a21e3910/tests/source/tests/xla_spawn.py +94 -0
  10. tasks/tasksmith-6313a21e3910/tests/source/utils/log_reports.py +177 -0
  11. tasks/tasksmith-6313a21e3910/tests/source/utils/stale.py +69 -0
  12. tasks/tasksmith-6313a21e3910/tests/test.sh +3 -0
  13. tasks/tasksmith-6313a21e3910/tests/test_driver.py +41 -0
  14. tasks/tasksmith-6313a21e3910/tests/test_results.py +65 -0
  15. tasks/tasksmith-64b21f14793e/environment/Dockerfile +11 -0
  16. tasks/tasksmith-64b21f14793e/environment/source/.devcontainer/devcontainer.json +29 -0
  17. tasks/tasksmith-64b21f14793e/environment/source/.github/ISSUE_TEMPLATE/bug-report.yml +63 -0
  18. tasks/tasksmith-64b21f14793e/environment/source/.github/PULL_REQUEST_TEMPLATE.md +47 -0
  19. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/build-docker-images-release.yml +104 -0
  20. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/build_and_run_tests.yml +50 -0
  21. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/build_docker_images.yml +116 -0
  22. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/build_documentation.yml +18 -0
  23. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/build_pr_documentation.yml +17 -0
  24. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/fp8_runner.yml +37 -0
  25. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/gaudi3_scheduled.yml +82 -0
  26. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/integration_tests.yml +58 -0
  27. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/nightly.yml +233 -0
  28. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/pr_style_bot.yml +19 -0
  29. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/quality.yml +24 -0
  30. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/run_merge_tests.yml +188 -0
  31. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/self_hosted_integration_tests.yml +127 -0
  32. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/stale.yml +33 -0
  33. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/test.yml +70 -0
  34. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/test_imports.yml +55 -0
  35. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/trufflehog.yml +15 -0
  36. tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/upload_pr_documentation.yml +16 -0
  37. tasks/tasksmith-64b21f14793e/environment/source/.gitignore +144 -0
  38. tasks/tasksmith-64b21f14793e/environment/source/.pre-commit-config.yaml +13 -0
  39. tasks/tasksmith-64b21f14793e/environment/source/CODE_OF_CONDUCT.md +129 -0
  40. tasks/tasksmith-64b21f14793e/environment/source/CONTRIBUTING.md +249 -0
  41. tasks/tasksmith-64b21f14793e/environment/source/LICENSE +201 -0
  42. tasks/tasksmith-64b21f14793e/environment/source/README.md +277 -0
  43. tasks/tasksmith-64b21f14793e/environment/source/pyproject.toml +43 -0
  44. tasks/tasksmith-64b21f14793e/environment/source/setup.py +126 -0
  45. tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/__init__.py +50 -0
  46. tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/accelerator.py +0 -0
  47. tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/big_modeling.py +749 -0
  48. tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/checkpointing.py +330 -0
  49. tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/commands/__init__.py +13 -0
  50. tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/commands/accelerate_cli.py +54 -0
tasks/tasksmith-6313a21e3910/tests/source/tests/test_scheduler.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 unittest
16
+ from functools import partial
17
+
18
+ import torch
19
+
20
+ from accelerate import Accelerator, debug_launcher
21
+ from accelerate.state import AcceleratorState, GradientState
22
+ from accelerate.test_utils import require_cpu, require_huggingface_suite
23
+ from accelerate.utils import GradientAccumulationPlugin
24
+
25
+
26
+ def one_cycle_test(num_processes=2, step_scheduler_with_optimizer=True, split_batches=False):
27
+ accelerator = Accelerator(step_scheduler_with_optimizer=step_scheduler_with_optimizer, split_batches=split_batches)
28
+ model = torch.nn.Linear(2, 4)
29
+ optimizer = torch.optim.AdamW(model.parameters(), lr=1.0)
30
+ scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.01, steps_per_epoch=2, epochs=1)
31
+ model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler)
32
+
33
+ # Optimizer has stepped
34
+ scheduler.step()
35
+ if step_scheduler_with_optimizer or (num_processes == 1):
36
+ assert scheduler.scheduler.last_epoch == num_processes, (
37
+ f"Last Epoch ({scheduler.scheduler.last_epoch}) != Num Processes ({num_processes})"
38
+ )
39
+ else:
40
+ assert scheduler.scheduler.last_epoch != num_processes, (
41
+ f"Last Epoch ({scheduler.scheduler.last_epoch}) == Num Processes ({num_processes})"
42
+ )
43
+
44
+
45
+ def lambda_test(num_processes=2, step_scheduler_with_optimizer=True, split_batches=False):
46
+ accelerator = Accelerator(step_scheduler_with_optimizer=step_scheduler_with_optimizer, split_batches=split_batches)
47
+ model = torch.nn.Linear(2, 4)
48
+ optimizer = torch.optim.AdamW(model.parameters(), lr=1.0)
49
+ scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda n: 1 - n / 10)
50
+ model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler)
51
+
52
+ # Optimizer has stepped
53
+ optimizer._is_overflow = False
54
+ scheduler.step()
55
+ expected_lr = 1 - (num_processes if (step_scheduler_with_optimizer and not split_batches) else 1) / 10
56
+ assert scheduler.get_last_lr()[0] == expected_lr, (
57
+ f"Wrong lr found at first step, expected {expected_lr}, got {scheduler.get_last_lr()[0]}"
58
+ )
59
+
60
+ # Optimizer has not stepped
61
+ optimizer._is_overflow = True
62
+ scheduler.step()
63
+ if not step_scheduler_with_optimizer:
64
+ expected_lr = 1 - 2 / 10
65
+ assert scheduler.get_last_lr()[0] == expected_lr, (
66
+ f"Wrong lr found at second step, expected {expected_lr}, got {scheduler.get_last_lr()[0]}"
67
+ )
68
+
69
+
70
+ def accumulation_test(num_processes: int = 2):
71
+ """
72
+ With this test, an observed batch size of 64 should result in negligible
73
+ differences in the scheduler after going through the correct number of steps.
74
+
75
+ Uses single, two, and four steps to test.
76
+ """
77
+ from transformers import get_linear_schedule_with_warmup
78
+
79
+ steps = [1, 2, 4]
80
+ for num_steps in steps:
81
+ plugin = GradientAccumulationPlugin(num_steps=num_steps, adjust_scheduler=num_steps > 1)
82
+ accelerator = Accelerator(gradient_accumulation_plugin=plugin)
83
+ model = torch.nn.Linear(2, 4)
84
+ optimizer = torch.optim.AdamW(model.parameters(), lr=10.0)
85
+ scheduler = get_linear_schedule_with_warmup(optimizer=optimizer, num_warmup_steps=0, num_training_steps=20)
86
+
87
+ model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler)
88
+
89
+ for i in range(10 * num_steps):
90
+ with accelerator.accumulate(model):
91
+ optimizer.step()
92
+ scheduler.step()
93
+
94
+ if i == (10 * num_steps - 2):
95
+ assert scheduler.get_last_lr()[0] != 0, (
96
+ f"Wrong lr found at second-to-last step, expected non-zero, got {scheduler.get_last_lr()[0]}. num_steps: {num_steps}"
97
+ )
98
+ assert scheduler.get_last_lr()[0] == 0, (
99
+ f"Wrong lr found at last step, expected 0, got {scheduler.get_last_lr()[0]}"
100
+ )
101
+ GradientState._reset_state()
102
+
103
+
104
+ @require_cpu
105
+ class SchedulerTester(unittest.TestCase):
106
+ def test_lambda_scheduler_steps_with_optimizer_single_process(self):
107
+ debug_launcher(partial(lambda_test, num_processes=1), num_processes=1)
108
+ debug_launcher(partial(lambda_test, num_processes=1, split_batches=True), num_processes=1)
109
+
110
+ def test_one_cycle_scheduler_steps_with_optimizer_single_process(self):
111
+ debug_launcher(partial(one_cycle_test, num_processes=1), num_processes=1)
112
+ debug_launcher(partial(one_cycle_test, num_processes=1, split_batches=True), num_processes=1)
113
+
114
+ def test_lambda_scheduler_not_step_with_optimizer_single_process(self):
115
+ debug_launcher(partial(lambda_test, num_processes=1, step_scheduler_with_optimizer=False), num_processes=1)
116
+
117
+ def test_one_cycle_scheduler_not_step_with_optimizer_single_process(self):
118
+ debug_launcher(partial(one_cycle_test, num_processes=1, step_scheduler_with_optimizer=False), num_processes=1)
119
+
120
+ def test_lambda_scheduler_steps_with_optimizer_multiprocess(self):
121
+ AcceleratorState._reset_state(True)
122
+ debug_launcher(lambda_test)
123
+ debug_launcher(partial(lambda_test, num_processes=1, split_batches=True), num_processes=1)
124
+
125
+ def test_one_cycle_scheduler_steps_with_optimizer_multiprocess(self):
126
+ AcceleratorState._reset_state(True)
127
+ debug_launcher(one_cycle_test)
128
+ debug_launcher(partial(one_cycle_test, num_processes=1, split_batches=True), num_processes=1)
129
+
130
+ def test_lambda_scheduler_not_step_with_optimizer_multiprocess(self):
131
+ AcceleratorState._reset_state(True)
132
+ debug_launcher(partial(lambda_test, step_scheduler_with_optimizer=False))
133
+
134
+ def test_one_cycle_scheduler_not_step_with_optimizer_multiprocess(self):
135
+ AcceleratorState._reset_state(True)
136
+ debug_launcher(partial(one_cycle_test, step_scheduler_with_optimizer=False))
137
+
138
+ @require_huggingface_suite
139
+ def test_accumulation(self):
140
+ AcceleratorState._reset_state(True)
141
+ debug_launcher(partial(accumulation_test, num_processes=1))
142
+ debug_launcher(accumulation_test)
tasks/tasksmith-6313a21e3910/tests/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-6313a21e3910/tests/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-6313a21e3910/tests/source/tests/test_tracking.py ADDED
@@ -0,0 +1,870 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import tensorboard.compat.proto.event_pb2 as 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
+
326
+ @require_comet_ml
327
+ class CometMLTest(unittest.TestCase):
328
+ @staticmethod
329
+ def get_value_from_key(log_list, key: str, is_param: bool = False):
330
+ "Extracts `key` from Comet `log`"
331
+ for log in log_list:
332
+ j = json.loads(log)["payload"]
333
+ if is_param and "param" in j.keys():
334
+ if j["param"]["paramName"] == key:
335
+ return j["param"]["paramValue"]
336
+ if "log_other" in j.keys():
337
+ if j["log_other"]["key"] == key:
338
+ return j["log_other"]["val"]
339
+ if "metric" in j.keys():
340
+ if j["metric"]["metricName"] == key:
341
+ return j["metric"]["metricValue"]
342
+ if j.get("key", None) == key:
343
+ return j["value"]
344
+
345
+ def test_init_trackers(self):
346
+ with tempfile.TemporaryDirectory() as d:
347
+ tracker = CometMLTracker(
348
+ "test_project_with_config", online=False, experiment_config=ExperimentConfig(offline_directory=d)
349
+ )
350
+ accelerator = Accelerator(log_with=tracker)
351
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
352
+ accelerator.init_trackers(None, config)
353
+ accelerator.end_training()
354
+ log = os.listdir(d)[0] # Comet is nice, it's just a zip file here
355
+ # We parse the raw logs
356
+ p = os.path.join(d, log)
357
+ archive = zipfile.ZipFile(p, "r")
358
+ log = archive.open("messages.json").read().decode("utf-8")
359
+ list_of_json = log.split("\n")[:-1]
360
+ assert self.get_value_from_key(list_of_json, "num_iterations", True) == 12
361
+ assert self.get_value_from_key(list_of_json, "learning_rate", True) == 0.01
362
+ assert self.get_value_from_key(list_of_json, "some_boolean", True) is False
363
+ assert self.get_value_from_key(list_of_json, "some_string", True) == "some_value"
364
+
365
+ def test_log(self):
366
+ with tempfile.TemporaryDirectory() as d:
367
+ tracker = CometMLTracker(
368
+ "test_project_with_config", online=False, experiment_config=ExperimentConfig(offline_directory=d)
369
+ )
370
+ accelerator = Accelerator(log_with=tracker)
371
+ accelerator.init_trackers(None)
372
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
373
+ accelerator.log(values, step=0)
374
+ accelerator.end_training()
375
+ log = os.listdir(d)[0] # Comet is nice, it's just a zip file here
376
+ # We parse the raw logs
377
+ p = os.path.join(d, log)
378
+ archive = zipfile.ZipFile(p, "r")
379
+ log = archive.open("messages.json").read().decode("utf-8")
380
+ list_of_json = log.split("\n")[:-1]
381
+ assert self.get_value_from_key(list_of_json, "curr_step", True) == 0
382
+ assert self.get_value_from_key(list_of_json, "total_loss") == 0.1
383
+ assert self.get_value_from_key(list_of_json, "iteration") == 1
384
+ assert self.get_value_from_key(list_of_json, "my_text") == "some_value"
385
+
386
+
387
+ @require_clearml
388
+ class ClearMLTest(TempDirTestCase, MockingTestCase):
389
+ def setUp(self):
390
+ super().setUp()
391
+ # ClearML offline session location is stored in CLEARML_CACHE_DIR
392
+ self.add_mocks(mock.patch.dict(os.environ, {"CLEARML_CACHE_DIR": str(self.tmpdir)}))
393
+
394
+ @staticmethod
395
+ def _get_offline_dir(accelerator):
396
+ from clearml.config import get_offline_dir
397
+
398
+ return get_offline_dir(task_id=accelerator.get_tracker("clearml", unwrap=True).id)
399
+
400
+ @staticmethod
401
+ def _get_metrics(offline_dir):
402
+ metrics = []
403
+ with open(os.path.join(offline_dir, "metrics.jsonl")) as f:
404
+ json_lines = f.readlines()
405
+ for json_line in json_lines:
406
+ metrics.extend(json.loads(json_line))
407
+ return metrics
408
+
409
+ def test_init_trackers(self):
410
+ from clearml import Task
411
+ from clearml.utilities.config import text_to_config_dict
412
+
413
+ Task.set_offline(True)
414
+ accelerator = Accelerator(log_with="clearml")
415
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
416
+ accelerator.init_trackers("test_project_with_config", config)
417
+
418
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
419
+ accelerator.end_training()
420
+
421
+ with open(os.path.join(offline_dir, "task.json")) as f:
422
+ offline_session = json.load(f)
423
+ clearml_offline_config = text_to_config_dict(offline_session["configuration"]["General"]["value"])
424
+ assert config == clearml_offline_config
425
+
426
+ def test_log(self):
427
+ from clearml import Task
428
+
429
+ Task.set_offline(True)
430
+ accelerator = Accelerator(log_with="clearml")
431
+ accelerator.init_trackers("test_project_with_log")
432
+ values_with_iteration = {"should_be_under_train": 1, "eval_value": 2, "test_value": 3.1, "train_value": 4.1}
433
+ accelerator.log(values_with_iteration, step=1)
434
+ single_values = {"single_value_1": 1.1, "single_value_2": 2.2}
435
+ accelerator.log(single_values)
436
+
437
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
438
+ accelerator.end_training()
439
+
440
+ metrics = ClearMLTest._get_metrics(offline_dir)
441
+ assert (len(values_with_iteration) + len(single_values)) == len(metrics)
442
+ for metric in metrics:
443
+ if metric["metric"] == "Summary":
444
+ assert metric["variant"] in single_values
445
+ assert metric["value"] == single_values[metric["variant"]]
446
+ elif metric["metric"] == "should_be_under_train":
447
+ assert metric["variant"] == "train"
448
+ assert metric["iter"] == 1
449
+ assert metric["value"] == values_with_iteration["should_be_under_train"]
450
+ else:
451
+ values_with_iteration_key = metric["variant"] + "_" + metric["metric"]
452
+ assert values_with_iteration_key in values_with_iteration
453
+ assert metric["iter"] == 1
454
+ assert metric["value"] == values_with_iteration[values_with_iteration_key]
455
+
456
+ def test_log_images(self):
457
+ from clearml import Task
458
+
459
+ Task.set_offline(True)
460
+ accelerator = Accelerator(log_with="clearml")
461
+ accelerator.init_trackers("test_project_with_log_images")
462
+
463
+ base_image = np.eye(256, 256, dtype=np.uint8) * 255
464
+ base_image_3d = np.concatenate((np.atleast_3d(base_image), np.zeros((256, 256, 2), dtype=np.uint8)), axis=2)
465
+ images = {
466
+ "base_image": base_image,
467
+ "base_image_3d": base_image_3d,
468
+ }
469
+ accelerator.get_tracker("clearml").log_images(images, step=1)
470
+
471
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
472
+ accelerator.end_training()
473
+
474
+ images_saved = Path(os.path.join(offline_dir, "data")).rglob("*.jpeg")
475
+ assert len(list(images_saved)) == len(images)
476
+
477
+ def test_log_table(self):
478
+ from clearml import Task
479
+
480
+ Task.set_offline(True)
481
+ accelerator = Accelerator(log_with="clearml")
482
+ accelerator.init_trackers("test_project_with_log_table")
483
+
484
+ accelerator.get_tracker("clearml").log_table(
485
+ "from lists with columns", columns=["A", "B", "C"], data=[[1, 3, 5], [2, 4, 6]]
486
+ )
487
+ accelerator.get_tracker("clearml").log_table("from lists", data=[["A2", "B2", "C2"], [7, 9, 11], [8, 10, 12]])
488
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
489
+ accelerator.end_training()
490
+
491
+ metrics = ClearMLTest._get_metrics(offline_dir)
492
+ assert len(metrics) == 2
493
+ for metric in metrics:
494
+ assert metric["metric"] in ("from lists", "from lists with columns")
495
+ plot = json.loads(metric["plot_str"])
496
+ if metric["metric"] == "from lists with columns":
497
+ print(plot["data"][0])
498
+ self.assertCountEqual(plot["data"][0]["header"]["values"], ["A", "B", "C"])
499
+ self.assertCountEqual(plot["data"][0]["cells"]["values"], [[1, 2], [3, 4], [5, 6]])
500
+ else:
501
+ self.assertCountEqual(plot["data"][0]["header"]["values"], ["A2", "B2", "C2"])
502
+ self.assertCountEqual(plot["data"][0]["cells"]["values"], [[7, 8], [9, 10], [11, 12]])
503
+
504
+ @require_pandas
505
+ def test_log_table_pandas(self):
506
+ import pandas as pd
507
+ from clearml import Task
508
+
509
+ Task.set_offline(True)
510
+ accelerator = Accelerator(log_with="clearml")
511
+ accelerator.init_trackers("test_project_with_log_table_pandas")
512
+
513
+ accelerator.get_tracker("clearml").log_table(
514
+ "from df", dataframe=pd.DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}), step=1
515
+ )
516
+
517
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
518
+ accelerator.end_training()
519
+
520
+ metrics = ClearMLTest._get_metrics(offline_dir)
521
+ assert len(metrics) == 1
522
+ assert metrics[0]["metric"] == "from df"
523
+ plot = json.loads(metrics[0]["plot_str"])
524
+ self.assertCountEqual(plot["data"][0]["header"]["values"], [["A"], ["B"], ["C"]])
525
+ self.assertCountEqual(plot["data"][0]["cells"]["values"], [[1, 2], [3, 4], [5, 6]])
526
+
527
+
528
+ @require_swanlab
529
+ @mock.patch.dict(os.environ, {"SWANLAB_MODE": "local"})
530
+ class SwanLabTrackingTest(TempDirTestCase, MockingTestCase):
531
+ def setUp(self):
532
+ super().setUp()
533
+ # Setting Path where SwanLab parsed log files are saved via the SWANLAB_LOG_DIR env var
534
+ self.add_mocks(mock.patch.dict(os.environ, {"SWANLAB_LOG_DIR": self.tmpdir}))
535
+
536
+ @skip
537
+ def test_swanlab(self):
538
+ # Disable hardware monitoring to prevent errors in test mode.
539
+ import swanlab
540
+ from swanlab.log.backup import BackupHandler
541
+ from swanlab.log.backup.datastore import DataStore
542
+ from swanlab.log.backup.models import ModelsParser
543
+
544
+ swanlab.merge_settings(swanlab.Settings(hardware_monitor=False))
545
+ # Start a fake training session.
546
+ accelerator = Accelerator(log_with="swanlab")
547
+ project_name = "test_project_with_config"
548
+ experiment_name = "test"
549
+ description = "test project for swanlab"
550
+ tags = ["my_tag"]
551
+ config = {
552
+ "epochs": 10,
553
+ "learning_rate": 0.01,
554
+ "offset": 0.1,
555
+ }
556
+ kwargs = {
557
+ "swanlab": {
558
+ "experiment_name": experiment_name,
559
+ "description": description,
560
+ "tags": tags,
561
+ }
562
+ }
563
+ accelerator.init_trackers(project_name, config, kwargs)
564
+ record_metrics = []
565
+ record_scalars = []
566
+ record_images_count = 0
567
+ record_logs = []
568
+ for epoch in range(1, swanlab.config.epochs):
569
+ acc = 1 - 2**-epoch - random.random() / epoch - 0.1
570
+ loss = 2**-epoch + random.random() / epoch + 0.1
571
+ ll = swanlab.log(
572
+ {
573
+ "accuracy": acc,
574
+ "loss": loss,
575
+ "image": swanlab.Image(np.random.random((3, 3, 3))),
576
+ },
577
+ step=epoch,
578
+ )
579
+ log = f"epoch={epoch}, accuracy={acc}, loss={loss}"
580
+ print(log)
581
+ record_scalars.extend([acc, loss])
582
+ record_images_count += 1
583
+ record_logs.append(log)
584
+ record_metrics.extend([x for _, x in ll.items()])
585
+ accelerator.end_training()
586
+
587
+ # Load latest offline log
588
+ run_dir = swanlab.get_run().public.run_dir
589
+ assert os.path.exists(run_dir) is True
590
+ ds = DataStore()
591
+ ds.open_for_scan(os.path.join(run_dir.__str__(), BackupHandler.BACKUP_FILE).__str__())
592
+ with ModelsParser() as models_parser:
593
+ for record in ds:
594
+ if record is None:
595
+ continue
596
+ models_parser.parse_record(record)
597
+ header, project, experiment, logs, runtime, columns, scalars, medias, footer = models_parser.get_parsed()
598
+
599
+ # test file header
600
+ assert header.backup_type == "DEFAULT"
601
+
602
+ # test project info
603
+ assert project.name == project_name
604
+ assert project.workspace is None
605
+ assert project.public is None
606
+
607
+ # test experiment info
608
+ assert experiment.name is not None
609
+ assert experiment.description == description
610
+ assert experiment.tags == tags
611
+
612
+ # test log record
613
+ backup_logs = [log.message for log in logs]
614
+ for record_log in record_logs:
615
+ assert record_log in backup_logs, "Log not found in backup logs: " + record_log
616
+
617
+ # test runtime info
618
+ runtime_info = runtime.to_file_model(os.path.join(run_dir.__str__(), "files"))
619
+ assert runtime_info.conda is None, "Not using conda, should be None"
620
+ assert isinstance(runtime_info.requirements, str), "Requirements should be a string"
621
+ assert isinstance(runtime_info.metadata, dict), "Metadata should be a dictionary"
622
+ assert isinstance(runtime_info.config, dict), "Config should be a dictionary"
623
+ for key in runtime_info.config:
624
+ assert key in config, f"Config key {key} not found in original config"
625
+ assert runtime_info.config[key]["value"] == config[key], (
626
+ f"Config value for {key} does not match original value"
627
+ )
628
+
629
+ # test scalar
630
+ assert len(scalars) + len(medias) == len(record_metrics), "Total metrics count does not match"
631
+ backup_scalars = [
632
+ metric.metric["data"]
633
+ for metric in record_metrics
634
+ if metric.column_info.chart_type.value.column_type == "FLOAT"
635
+ ]
636
+ assert len(backup_scalars) == len(scalars), "Total scalars count does not match"
637
+ for scalar in backup_scalars:
638
+ assert scalar in record_scalars, f"Scalar {scalar} not found in original scalars"
639
+ backup_images = [
640
+ metric for metric in record_metrics if metric.column_info.chart_type.value.column_type == "IMAGE"
641
+ ]
642
+ assert len(backup_images) == record_images_count, "Total images count does not match"
643
+
644
+
645
+ class MyCustomTracker(GeneralTracker):
646
+ "Basic tracker that writes to a csv for testing"
647
+
648
+ _col_names = [
649
+ "total_loss",
650
+ "iteration",
651
+ "my_text",
652
+ "learning_rate",
653
+ "num_iterations",
654
+ "some_boolean",
655
+ "some_string",
656
+ ]
657
+
658
+ name = "my_custom_tracker"
659
+ requires_logging_directory = False
660
+
661
+ def __init__(self, dir: str, **kwargs):
662
+ super().__init__(**kwargs)
663
+ self.log_dir = dir
664
+ self.f = None
665
+ self.writer = None
666
+
667
+ def start(self):
668
+ if self.f is None:
669
+ self.f = open(os.path.join(self.log_dir, "log.csv"), "w+")
670
+ self.writer = csv.DictWriter(self.f, fieldnames=self._col_names)
671
+ self.writer.writeheader()
672
+
673
+ @property
674
+ def tracker(self):
675
+ return self.writer
676
+
677
+ def store_init_configuration(self, values: dict):
678
+ logger.info("Call init")
679
+ self.writer.writerow(values)
680
+
681
+ def log(self, values: dict, step: Optional[int]):
682
+ logger.info("Call log")
683
+ self.writer.writerow(values)
684
+
685
+ def finish(self):
686
+ self.f.close()
687
+
688
+
689
+ class CustomTrackerTestCase(unittest.TestCase):
690
+ def test_init_trackers(self):
691
+ with tempfile.TemporaryDirectory() as d:
692
+ tracker = MyCustomTracker(d)
693
+ accelerator = Accelerator(log_with=tracker)
694
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
695
+ accelerator.init_trackers("Some name", config)
696
+ accelerator.end_training()
697
+ with open(f"{d}/log.csv") as f:
698
+ data = csv.DictReader(f)
699
+ data = next(data)
700
+ truth = {
701
+ "total_loss": "",
702
+ "iteration": "",
703
+ "my_text": "",
704
+ "learning_rate": "0.01",
705
+ "num_iterations": "12",
706
+ "some_boolean": "False",
707
+ "some_string": "some_value",
708
+ }
709
+ assert data == truth
710
+
711
+ def test_log(self):
712
+ with tempfile.TemporaryDirectory() as d:
713
+ tracker = MyCustomTracker(d)
714
+ accelerator = Accelerator(log_with=tracker)
715
+ accelerator.init_trackers("Some name")
716
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
717
+ accelerator.log(values, step=0)
718
+ accelerator.end_training()
719
+ with open(f"{d}/log.csv") as f:
720
+ data = csv.DictReader(f)
721
+ data = next(data)
722
+ truth = {
723
+ "total_loss": "0.1",
724
+ "iteration": "1",
725
+ "my_text": "some_value",
726
+ "learning_rate": "",
727
+ "num_iterations": "",
728
+ "some_boolean": "",
729
+ "some_string": "",
730
+ }
731
+ assert data == truth
732
+
733
+
734
+ @require_dvclive
735
+ @mock.patch("dvclive.live.get_dvc_repo", return_value=None)
736
+ class DVCLiveTrackingTest(unittest.TestCase):
737
+ def test_init_trackers(self, mock_repo):
738
+ project_name = "test_project_with_config"
739
+ with tempfile.TemporaryDirectory() as dirpath:
740
+ accelerator = Accelerator(log_with="dvclive")
741
+ config = {
742
+ "num_iterations": 12,
743
+ "learning_rate": 1e-2,
744
+ "some_boolean": False,
745
+ "some_string": "some_value",
746
+ }
747
+ init_kwargs = {"dvclive": {"dir": dirpath, "save_dvc_exp": False, "dvcyaml": None}}
748
+ accelerator.init_trackers(project_name, config, init_kwargs)
749
+ accelerator.end_training()
750
+ live = accelerator.trackers[0].live
751
+ params = load_yaml(live.params_file)
752
+ assert params == config
753
+
754
+ def test_log(self, mock_repo):
755
+ project_name = "test_project_with_log"
756
+ with tempfile.TemporaryDirectory() as dirpath:
757
+ accelerator = Accelerator(log_with="dvclive", project_dir=dirpath)
758
+ init_kwargs = {"dvclive": {"dir": dirpath, "save_dvc_exp": False, "dvcyaml": None}}
759
+ accelerator.init_trackers(project_name, init_kwargs=init_kwargs)
760
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
761
+ # Log step 0
762
+ accelerator.log(values)
763
+ # Log step 1
764
+ accelerator.log(values)
765
+ # Log step 3 (skip step 2)
766
+ accelerator.log(values, step=3)
767
+ accelerator.end_training()
768
+ live = accelerator.trackers[0].live
769
+ logs, latest = parse_metrics(live)
770
+ assert latest.pop("step") == 3
771
+ assert latest == values
772
+ scalars = os.path.join(live.plots_dir, Metric.subfolder)
773
+ for val in values.keys():
774
+ val_path = os.path.join(scalars, f"{val}.tsv")
775
+ steps = [int(row["step"]) for row in logs[val_path]]
776
+ assert steps == [0, 1, 3]
777
+
778
+
779
+ class TrackerDeferredInitializationTest(unittest.TestCase):
780
+ """
781
+ Tests tracker's deferred initialization via `start()` method, preventing
782
+ premature `PartialState` access (and `torch.distributed` init) before
783
+ `Accelerator` has configured the distributed environment, especially with
784
+ `InitProcessGroupKwargs`.
785
+ """
786
+
787
+ @require_tensorboard
788
+ def test_tensorboard_deferred_init(self):
789
+ """Test that TensorBoard tracker initialization doesn't initialize distributed"""
790
+ with tempfile.TemporaryDirectory() as temp_dir:
791
+ PartialState._reset_state()
792
+ tracker = TensorBoardTracker(run_name="test_tb", logging_dir=temp_dir)
793
+ self.assertEqual(PartialState._shared_state, {})
794
+ _ = Accelerator(log_with=tracker)
795
+ self.assertNotEqual(PartialState._shared_state, {})
796
+
797
+ @require_wandb
798
+ def test_wandb_deferred_init(self):
799
+ """Test that WandB tracker initialization doesn't initialize distributed"""
800
+ PartialState._reset_state()
801
+ tracker = WandBTracker(run_name="test_wandb")
802
+ self.assertEqual(PartialState._shared_state, {})
803
+ _ = Accelerator(log_with=tracker)
804
+ self.assertNotEqual(PartialState._shared_state, {})
805
+
806
+ @require_trackio
807
+ def test_trackio_deferred_init(self):
808
+ """Test that trackio tracker initialization doesn't initialize distributed"""
809
+ PartialState._reset_state()
810
+ tracker = TrackioTracker(run_name="test_trackio")
811
+ self.assertEqual(PartialState._shared_state, {})
812
+ _ = Accelerator(log_with=tracker)
813
+ self.assertNotEqual(PartialState._shared_state, {})
814
+
815
+ @require_comet_ml
816
+ def test_comet_ml_deferred_init(self):
817
+ """Test that CometML tracker initialization doesn't initialize distributed"""
818
+ PartialState._reset_state()
819
+ tracker = CometMLTracker(run_name="test_comet")
820
+ self.assertEqual(PartialState._shared_state, {})
821
+ _ = Accelerator(log_with=tracker)
822
+ self.assertNotEqual(PartialState._shared_state, {})
823
+
824
+ @require_aim
825
+ def test_aim_deferred_init(self):
826
+ """Test that Aim tracker initialization doesn't initialize distributed"""
827
+ with tempfile.TemporaryDirectory() as temp_dir:
828
+ PartialState._reset_state()
829
+ tracker = AimTracker(run_name="test_aim", repo=temp_dir)
830
+ self.assertEqual(PartialState._shared_state, {})
831
+ _ = Accelerator(log_with=tracker)
832
+ self.assertNotEqual(PartialState._shared_state, {})
833
+
834
+ @require_mlflow
835
+ def test_mlflow_deferred_init(self):
836
+ """Test that MLflow tracker initialization doesn't initialize distributed"""
837
+ with tempfile.TemporaryDirectory() as temp_dir:
838
+ PartialState._reset_state()
839
+ tracker = MLflowTracker(experiment_name="test_mlflow", logging_dir=temp_dir)
840
+ self.assertEqual(PartialState._shared_state, {})
841
+ _ = Accelerator(log_with=tracker)
842
+ self.assertNotEqual(PartialState._shared_state, {})
843
+
844
+ @require_clearml
845
+ def test_clearml_deferred_init(self):
846
+ """Test that ClearML tracker initialization doesn't initialize distributed"""
847
+ PartialState._reset_state()
848
+ tracker = ClearMLTracker(run_name="test_clearml")
849
+ self.assertEqual(PartialState._shared_state, {})
850
+ _ = Accelerator(log_with=tracker)
851
+ self.assertNotEqual(PartialState._shared_state, {})
852
+
853
+ @require_dvclive
854
+ def test_dvclive_deferred_init(self):
855
+ """Test that DVCLive tracker initialization doesn't initialize distributed"""
856
+ with tempfile.TemporaryDirectory() as temp_dir:
857
+ PartialState._reset_state()
858
+ tracker = DVCLiveTracker(dir=temp_dir)
859
+ self.assertEqual(PartialState._shared_state, {})
860
+ _ = Accelerator(log_with=tracker)
861
+ self.assertNotEqual(PartialState._shared_state, {})
862
+
863
+ @require_swanlab
864
+ def test_swanlab_deferred_init(self):
865
+ """Test that SwanLab tracker initialization doesn't initialize distributed"""
866
+ PartialState._reset_state()
867
+ tracker = SwanLabTracker(run_name="test_swanlab")
868
+ self.assertEqual(PartialState._shared_state, {})
869
+ _ = Accelerator(log_with=tracker)
870
+ self.assertNotEqual(PartialState._shared_state, {})
tasks/tasksmith-6313a21e3910/tests/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()
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-6313a21e3910/tests/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-6313a21e3910/tests/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-6313a21e3910/tests/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-6313a21e3910/tests/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-6313a21e3910/tests/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-6313a21e3910/tests/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-6313a21e3910/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ exec /opt/tasksmith-venv/bin/python -I /tests/grade.py
tasks/tasksmith-6313a21e3910/tests/test_driver.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Private pytest entry point with a bounded framework-tampering check.
2
+
3
+ The host still owns reward parsing. This guard detects replacement or in-place
4
+ editing of unittest assertions, a demonstrated attack against repository tests.
5
+ It does not claim to isolate arbitrary test and solution code in one interpreter.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ import unittest
12
+
13
+
14
+ def run(arguments: list[str]) -> int:
15
+ import pytest
16
+
17
+ # Capture before pytest imports any repository modules. Retain code objects
18
+ # too: an attacker can mutate function.__code__ without replacing a method.
19
+ original = {
20
+ name: (value, getattr(value, "__code__", None))
21
+ for name, value in vars(unittest.TestCase).items()
22
+ if name.startswith("assert") and callable(value)
23
+ }
24
+ case = unittest.TestCase
25
+ # The harness supplies selectors and reporting explicitly. Repository addopts
26
+ # often enable optional coverage/report plugins that are intentionally not
27
+ # auto-loaded in this isolated verifier; they are not test dependencies.
28
+ code = int(pytest.main(["-o", "addopts=", *arguments]))
29
+ changed = []
30
+ for name, (method, implementation) in original.items():
31
+ current = getattr(case, name, None)
32
+ if current is not method or getattr(current, "__code__", None) is not implementation:
33
+ changed.append(name)
34
+ if unittest.TestCase is not case or changed:
35
+ sys.stderr.write("Verifier framework was modified: " + ", ".join(changed) + "\n")
36
+ return 254
37
+ return code
38
+
39
+
40
+ if __name__ == "__main__":
41
+ raise SystemExit(run(sys.argv[1:]))
tasks/tasksmith-6313a21e3910/tests/test_results.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strict test evidence used by repository recipes and their exported verifiers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from xml.etree import ElementTree
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class TestResults:
11
+ __test__ = False
12
+ statuses: dict[str, str]
13
+ returncode: int
14
+
15
+ @property
16
+ def passed(self) -> set[str]:
17
+ return {name for name, status in self.statuses.items() if status == "passed"}
18
+
19
+
20
+ def parse_junit(text: str, *, returncode: int) -> TestResults:
21
+ if "<!DOCTYPE" in text.upper() or "<!ENTITY" in text.upper():
22
+ raise ValueError("JUnit must not contain a DTD or entity declaration")
23
+ if returncode not in {0, 1}:
24
+ raise ValueError(f"Test runner did not complete normally: exit {returncode}")
25
+ try:
26
+ root = ElementTree.fromstring(text)
27
+ except ElementTree.ParseError as exc:
28
+ raise ValueError("Invalid JUnit report") from exc
29
+ if root.tag not in {"testsuite", "testsuites"}:
30
+ raise ValueError("Expected a JUnit testsuite or testsuites root")
31
+ statuses = {}
32
+ for case in root.iter("testcase"):
33
+ name, classname = case.get("name"), case.get("classname")
34
+ if not name or not classname:
35
+ raise ValueError("Test cases require a name and class identity")
36
+ identity = f"{classname}::{name}"
37
+ if identity in statuses:
38
+ raise ValueError(f"Duplicate test identity: {identity}")
39
+ if case.find("error") is not None:
40
+ status = "error"
41
+ elif case.find("failure") is not None:
42
+ status = "failed"
43
+ elif case.find("skipped") is not None:
44
+ status = "skipped"
45
+ else:
46
+ status = "passed"
47
+ statuses[identity] = status
48
+ if not statuses:
49
+ raise ValueError("Empty test result is not execution evidence")
50
+ if returncode == 0 and any(status in {"failed", "error"} for status in statuses.values()):
51
+ raise ValueError("JUnit failures contradict the runner exit code")
52
+ return TestResults(statuses, returncode)
53
+
54
+
55
+ def execution_contrast(healthy: TestResults, defective: TestResults) -> dict[str, list[str]]:
56
+ if healthy.returncode != 0 or not healthy.passed:
57
+ raise ValueError("Reference must execute successfully with passing tests")
58
+ if healthy.statuses.keys() != defective.statuses.keys():
59
+ raise ValueError("Mutation changed test collection; contrast is not comparable")
60
+ failing = sorted(
61
+ name for name in healthy.passed if defective.statuses[name] in {"failed", "error"}
62
+ )
63
+ if not failing or defective.returncode != 1:
64
+ raise ValueError("No intended fail-to-pass contrast")
65
+ return {"FAIL_TO_PASS": failing, "PASS_TO_PASS": sorted(healthy.passed - set(failing))}
tasks/tasksmith-64b21f14793e/environment/Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime
2
+ WORKDIR /workspace
3
+ RUN apt-get update && apt-get install -y --no-install-recommends python3-venv && rm -rf /var/lib/apt/lists/*
4
+ RUN python -m venv --system-site-packages /opt/tasksmith-venv
5
+ ENV PATH=/opt/tasksmith-venv/bin:$PATH
6
+ RUN python -m pip install --no-cache-dir huggingface_hub==1.31.0 numpy==2.4.3 packaging==26.0 parameterized==0.9.0 pillow==12.1.1 psutil==7.2.2 pytest==8.4.2 safetensors==0.8.0 setuptools==81.0.0 wheel==0.46.3
7
+ COPY source /workspace
8
+ RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e .
9
+ ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
10
+ RUN apt-get update && apt-get install -y --no-install-recommends tmux && rm -rf /var/lib/apt/lists/*
11
+ RUN useradd -m learner && chown -R learner:learner /workspace
tasks/tasksmith-64b21f14793e/environment/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-64b21f14793e/environment/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-64b21f14793e/environment/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 @zach-huggingface
41
+ - DeepSpeed: @SunMarc @zach-huggingface
42
+ - Command Line Interface: @SunMarc @zach-huggingface
43
+ - Documentation: @SunMarc @zach-huggingface
44
+ - Core parts of the library: @BenjaminBossan @SunMarc @zach-huggingface
45
+ - Maintained examples: @SunMarc or @zach-huggingface
46
+
47
+ -->
tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/build-docker-images-release.yml ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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@4
19
+ - id: step1
20
+ run: echo "version=$(python setup.py --version)" >> $GITHUB_OUTPUT
21
+
22
+ version-cpu:
23
+ name: "Latest Accelerate CPU [version]"
24
+ runs-on:
25
+ group: aws-general-8-plus
26
+ needs: get-version
27
+ steps:
28
+ - name: Set up Docker Buildx
29
+ uses: docker/setup-buildx-action@v2
30
+ - name: Login to DockerHub
31
+ uses: docker/login-action@v2
32
+ with:
33
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
34
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
35
+
36
+ - name: Build and Push CPU
37
+ uses: docker/build-push-action@v4
38
+ with:
39
+ file: docker/accelerate-cpu/Dockerfile
40
+ push: true
41
+ tags: huggingface/accelerate:cpu-release-${{ needs.get-version.outputs.version }}
42
+
43
+ version-cuda:
44
+ name: "Latest Accelerate GPU [version]"
45
+ runs-on:
46
+ group: aws-g6-4xlarge-plus
47
+ needs: get-version
48
+ steps:
49
+ - name: Set up Docker Buildx
50
+ uses: docker/setup-buildx-action@v2
51
+ - name: Login to DockerHub
52
+ uses: docker/login-action@v2
53
+ with:
54
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
55
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
56
+
57
+ - name: Build and Push GPU
58
+ uses: docker/build-push-action@v4
59
+ with:
60
+ file: docker/accelerate-gpu/Dockerfile
61
+ push: true
62
+ tags: huggingface/accelerate:gpu-release-${{needs.get-version.outputs.version}}
63
+
64
+ version-cuda-deepspeed:
65
+ name: "Latest Accelerate GPU DeepSpeed [version]"
66
+ runs-on:
67
+ group: aws-g6-4xlarge-plus
68
+ needs: get-version
69
+ steps:
70
+ - name: Set up Docker Buildx
71
+ uses: docker/setup-buildx-action@v2
72
+ - name: Login to DockerHub
73
+ uses: docker/login-action@v2
74
+ with:
75
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
76
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
77
+
78
+ - name: Build and Push GPU
79
+ uses: docker/build-push-action@v4
80
+ with:
81
+ file: docker/accelerate-gpu-deepspeed/Dockerfile
82
+ push: true
83
+ tags: huggingface/accelerate:gpu-deepspeed-release-${{needs.get-version.outputs.version}}
84
+
85
+ version-cuda-fp8-transformerengine:
86
+ name: "Latest Accelerate GPU FP8 TransformerEngine [version]"
87
+ runs-on:
88
+ group: aws-g6-4xlarge-plus
89
+ needs: get-version
90
+ steps:
91
+ - name: Set up Docker Buildx
92
+ uses: docker/setup-buildx-action@v2
93
+ - name: Login to DockerHub
94
+ uses: docker/login-action@v2
95
+ with:
96
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
97
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
98
+
99
+ - name: Build and Push GPU
100
+ uses: docker/build-push-action@v4
101
+ with:
102
+ file: docker/accelerate-gpu/Dockerfile
103
+ push: true
104
+ tags: huggingface/accelerate:gpu-fp8-transformerengine-release-${{needs.get-version.outputs.version}}
tasks/tasksmith-64b21f14793e/environment/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@v4
20
+ with:
21
+ fetch-depth: "2"
22
+
23
+ - name: Get changed files
24
+ id: changed-files
25
+ uses: tj-actions/changed-files@3f54ebb830831fc121d3263c1857cfbdc310cdb9 #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-64b21f14793e/environment/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@v2
21
+ - name: Login to DockerHub
22
+ uses: docker/login-action@v2
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@v4
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@v2
46
+ - name: Login to DockerHub
47
+ uses: docker/login-action@v2
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@v4
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@v2
71
+ - name: Login to DockerHub
72
+ uses: docker/login-action@v2
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@v4
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@v2
96
+ - name: Login to DockerHub
97
+ uses: docker/login-action@v2
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@v4
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-64b21f14793e/environment/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@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-64b21f14793e/environment/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@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-64b21f14793e/environment/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@v3
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-64b21f14793e/environment/source/.github/workflows/gaudi3_scheduled.yml ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.20.0/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@v4
47
+
48
+ - name: Install Accelerate with Transformers & DeepSpeed
49
+ run: |
50
+ pip install -e .[testing] \
51
+ git+https://github.com/HabanaAI/DeepSpeed.git@1.20.0 \
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 FSDP integration tests
70
+ if: ${{ !cancelled() && (success() || failure()) }}
71
+ run: |
72
+ make test_fsdp
73
+
74
+ - name: Run DeepSpeed integration tests
75
+ if: ${{ !cancelled() && (success() || failure()) }}
76
+ run: |
77
+ make test_deepspeed
78
+
79
+ - name: Run Examples tests
80
+ if: ${{ !cancelled() && (success() || failure()) }}
81
+ run: |
82
+ make test_examples
tasks/tasksmith-64b21f14793e/environment/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@v4
30
+ - name: Set up python 3.9
31
+ uses: actions/setup-python@v5
32
+ with:
33
+ python-version: 3.9
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-64b21f14793e/environment/source/.github/workflows/nightly.yml ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 and big modeling tests on GPUs
146
+ working-directory: accelerate
147
+ run: |
148
+ source activate accelerate
149
+ make test_core
150
+ make test_big_modeling
151
+ make test_cli
152
+
153
+ - name: Run Integration tests on GPUs
154
+ working-directory: accelerate
155
+ if: always()
156
+ run: |
157
+ source activate accelerate
158
+ make test_integrations
159
+
160
+ - name: Run examples on GPUs
161
+ working-directory: accelerate
162
+ if: always()
163
+ run: |
164
+ source activate accelerate
165
+ pip uninstall comet_ml -y
166
+ make test_examples
167
+
168
+ - name: Generate Report
169
+ working-directory: accelerate
170
+ if: always()
171
+ run: |
172
+ pip install slack_sdk tabulate
173
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
174
+
175
+ run_deepspeed_tests_multi_gpu:
176
+ runs-on:
177
+ group: aws-g6-12xlarge-plus
178
+ env:
179
+ CUDA_VISIBLE_DEVICES: "0,1"
180
+ TEST_TYPE: "multi_gpu_deepspeed"
181
+ container:
182
+ image: huggingface/accelerate:gpu-deepspeed-nightly
183
+ options: --gpus all --shm-size "16gb"
184
+ defaults:
185
+ run:
186
+ shell: bash
187
+ steps:
188
+ - name: Update clone
189
+ run: |
190
+ source activate accelerate
191
+ git clone https://github.com/huggingface/accelerate;
192
+ cd accelerate;
193
+ git checkout ${{ github.sha }};
194
+ pip install -e . --no-deps
195
+ pip install pytest-reportlog tabulate
196
+
197
+ - name: Show installed libraries
198
+ run: |
199
+ source activate accelerate;
200
+ pip freeze
201
+
202
+ - name: Run DeepSpeed tests
203
+ working-directory: accelerate
204
+ run: |
205
+ source activate accelerate
206
+ make test_deepspeed
207
+
208
+ - name: Run Integration tests on GPUs
209
+ working-directory: accelerate
210
+ if: always()
211
+ run: |
212
+ source activate accelerate
213
+ make test_integrations
214
+
215
+ - name: Run examples on GPUs
216
+ working-directory: accelerate
217
+ if: always()
218
+ run: |
219
+ source activate accelerate
220
+ pip uninstall comet_ml -y
221
+ make test_examples
222
+
223
+ - name: Generate Report
224
+ working-directory: accelerate
225
+ if: always()
226
+ run: |
227
+ pip install slack_sdk tabulate
228
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
229
+
230
+
231
+ run-integration-tests:
232
+ if: always()
233
+ uses: ./.github/workflows/self_hosted_integration_tests.yml
tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/pr_style_bot.yml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ contents: write
10
+ pull-requests: write
11
+
12
+ jobs:
13
+ style:
14
+ uses: huggingface/huggingface_hub/.github/workflows/style-bot-action.yml@main
15
+ with:
16
+ python_quality_dependencies: "[quality]"
17
+ style_command_type: "default"
18
+ secrets:
19
+ bot_token: ${{ secrets.GITHUB_TOKEN }}
tasks/tasksmith-64b21f14793e/environment/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@v4
10
+ - name: Set up Python 3.9
11
+ uses: actions/setup-python@v5
12
+ with:
13
+ python-version: 3.9
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-64b21f14793e/environment/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-64b21f14793e/environment/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 .[testing]
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-64b21f14793e/environment/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@v4
20
+
21
+ - name: Setup Python
22
+ uses: actions/setup-python@v5
23
+ with:
24
+ python-version: 3.9
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-64b21f14793e/environment/source/.github/workflows/test.yml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: ubuntu-latest
21
+ strategy:
22
+ fail-fast: false
23
+ matrix:
24
+ pytorch-version: [
25
+ latest,
26
+ minimum,
27
+ ]
28
+ test-kind: [
29
+ test_prod,
30
+ test_core,
31
+ test_cli,
32
+ test_big_modeling,
33
+ test_deepspeed,
34
+ test_fsdp,
35
+ test_example_differences,
36
+ test_checkpoint_step,
37
+ test_checkpoint_epoch,
38
+ test_rest
39
+ ]
40
+ steps:
41
+ - uses: actions/checkout@v4
42
+ - name: Set up python 3.9
43
+ uses: actions/setup-python@v5
44
+ with:
45
+ python-version: 3.9
46
+ cache: 'pip'
47
+ cache-dependency-path: 'setup.py'
48
+
49
+ - name: Install the library
50
+ run: |
51
+ if [[ ${{ matrix.test-kind }} = test_prod ]]; then pip install -e .[test_prod]; fi
52
+ if [[ ${{ matrix.test-kind }} != test_prod ]]; then pip install -e .[testing,test_trackers]; fi
53
+ if [[ ${{ matrix.test-kind }} = test_rest ]]; then pip uninstall comet_ml -y; fi
54
+ if [[ ${{ matrix.pytorch-version }} = minimum ]]; then pip install torchvision==0.18.1 torch==2.3.1; fi
55
+ pip install pytest-reportlog tabulate setuptools importlib_metadata
56
+
57
+ - name: Show installed libraries
58
+ run: |
59
+ pip freeze
60
+
61
+ - name: Run Tests
62
+ env:
63
+ PYTORCH_VERSION: ${{ matrix.pytorch-version }}
64
+ run: |
65
+ make ${{ matrix.test-kind }}
66
+
67
+ - name: Generate Report
68
+ if: always()
69
+ run: |
70
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
tasks/tasksmith-64b21f14793e/environment/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@v4
30
+ - name: Set up python 3.9
31
+ uses: actions/setup-python@v5
32
+ with:
33
+ python-version: 3.9
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-64b21f14793e/environment/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@v4
12
+ with:
13
+ fetch-depth: 0
14
+ - name: Secret Scanning
15
+ uses: trufflesecurity/trufflehog@main
tasks/tasksmith-64b21f14793e/environment/source/.github/workflows/upload_pr_documentation.yml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Upload PR Documentation
2
+
3
+ on:
4
+ workflow_run:
5
+ workflows: ["Build PR Documentation"]
6
+ types:
7
+ - completed
8
+
9
+ jobs:
10
+ build:
11
+ uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@main
12
+ with:
13
+ package_name: accelerate
14
+ secrets:
15
+ hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
16
+ comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }}
tasks/tasksmith-64b21f14793e/environment/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-64b21f14793e/environment/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-64b21f14793e/environment/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
+ feedback@huggingface.co.
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-64b21f14793e/environment/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 git@github.com:<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-64b21f14793e/environment/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-64b21f14793e/environment/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-64b21f14793e/environment/source/pyproject.toml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.ruff]
2
+ line-length = 119
3
+ target-version = "py39"
4
+
5
+ [tool.ruff.lint]
6
+ preview = true
7
+ extend-select = [
8
+ "B009", # static getattr
9
+ "B010", # static setattr
10
+ "CPY", # Copyright
11
+ "E", # PEP8 errors
12
+ "F", # PEP8 formatting
13
+ "I", # Import sorting
14
+ "TID251", # Banned API
15
+ "UP", # Pyupgrade
16
+ "W", # PEP8 warnings
17
+ ]
18
+ ignore = [
19
+ "E501", # Line length (handled by ruff-format)
20
+ "E741", # Ambiguous variable name
21
+ "W605", # Invalid escape sequence
22
+ "UP007", # X | Y type annotations
23
+ ]
24
+
25
+ [tool.ruff.lint.per-file-ignores]
26
+ "__init__.py" = [
27
+ "F401", # Ignore seemingly unused imports (they're meant for re-export)
28
+ ]
29
+ "manim_animations/*" = ["ALL"]
30
+
31
+ [tool.ruff.lint.isort]
32
+ lines-after-imports = 2
33
+ known-first-party = ["accelerate"]
34
+
35
+ [tool.ruff.format]
36
+ exclude = [
37
+ "manim_animations/*"
38
+ ]
39
+
40
+ [tool.ruff.lint.flake8-tidy-imports.banned-api]
41
+ "os.getenv".msg = "Use os.environ instead"
42
+ "os.putenv".msg = "Use os.environ instead"
43
+ "os.unsetenv".msg = "Use os.environ instead"
tasks/tasksmith-64b21f14793e/environment/source/setup.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from setuptools import find_packages, setup
16
+
17
+
18
+ extras = {}
19
+ extras["quality"] = [
20
+ "black ~= 23.1", # hf-doc-builder has a hidden dependency on `black`
21
+ "hf-doc-builder >= 0.3.0",
22
+ "ruff ~= 0.11.2",
23
+ ]
24
+ extras["docs"] = []
25
+ extras["test_prod"] = ["pytest>=7.2.0,<=8.0.0", "pytest-xdist", "pytest-subtests", "parameterized", "pytest-order"]
26
+ extras["test_dev"] = [
27
+ "datasets",
28
+ "diffusers",
29
+ "evaluate",
30
+ "torchdata>=0.8.0",
31
+ "torchpippy>=0.2.0",
32
+ "transformers",
33
+ "scipy",
34
+ "scikit-learn",
35
+ "tqdm",
36
+ "bitsandbytes",
37
+ "timm",
38
+ ]
39
+ extras["testing"] = extras["test_prod"] + extras["test_dev"]
40
+ extras["deepspeed"] = ["deepspeed"]
41
+ extras["rich"] = ["rich"]
42
+
43
+ extras["test_fp8"] = ["torchao"] # note: TE for now needs to be done via pulling down the docker image directly
44
+ extras["test_trackers"] = [
45
+ "wandb",
46
+ "comet-ml",
47
+ "tensorboard",
48
+ "dvclive",
49
+ "mlflow",
50
+ "matplotlib",
51
+ "swanlab",
52
+ ]
53
+ extras["dev"] = extras["quality"] + extras["testing"] + extras["rich"]
54
+
55
+ extras["sagemaker"] = [
56
+ "sagemaker", # boto3 is a required package in sagemaker
57
+ ]
58
+
59
+ setup(
60
+ name="accelerate",
61
+ version="1.9.0.dev0",
62
+ description="Accelerate",
63
+ long_description=open("README.md", encoding="utf-8").read(),
64
+ long_description_content_type="text/markdown",
65
+ keywords="deep learning",
66
+ license="Apache",
67
+ author="The HuggingFace team",
68
+ author_email="zach.mueller@huggingface.co",
69
+ url="https://github.com/huggingface/accelerate",
70
+ package_dir={"": "src"},
71
+ packages=find_packages("src"),
72
+ entry_points={
73
+ "console_scripts": [
74
+ "accelerate=accelerate.commands.accelerate_cli:main",
75
+ "accelerate-config=accelerate.commands.config:main",
76
+ "accelerate-estimate-memory=accelerate.commands.estimate:main",
77
+ "accelerate-launch=accelerate.commands.launch:main",
78
+ "accelerate-merge-weights=accelerate.commands.merge:main",
79
+ ]
80
+ },
81
+ python_requires=">=3.9.0",
82
+ install_requires=[
83
+ "numpy>=1.17,<3.0.0",
84
+ "packaging>=20.0",
85
+ "psutil",
86
+ "pyyaml",
87
+ "torch>=2.0.0",
88
+ "huggingface_hub>=0.21.0",
89
+ "safetensors>=0.4.3",
90
+ ],
91
+ extras_require=extras,
92
+ classifiers=[
93
+ "Development Status :: 5 - Production/Stable",
94
+ "Intended Audience :: Developers",
95
+ "Intended Audience :: Education",
96
+ "Intended Audience :: Science/Research",
97
+ "License :: OSI Approved :: Apache Software License",
98
+ "Operating System :: OS Independent",
99
+ "Programming Language :: Python :: 3",
100
+ "Programming Language :: Python :: 3.9",
101
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
102
+ ],
103
+ )
104
+
105
+ # Release checklist
106
+ # 1. Checkout the release branch (for a patch the current release branch, for a new minor version, create one):
107
+ # git checkout -b vXX.xx-release
108
+ # The -b is only necessary for creation (so remove it when doing a patch)
109
+ # 2. Change the version in __init__.py and setup.py to the proper value.
110
+ # 3. Commit these changes with the message: "Release: v<VERSION>"
111
+ # 4. Add a tag in git to mark the release:
112
+ # git tag v<VERSION> -m 'Adds tag v<VERSION> for pypi'
113
+ # Push the tag and release commit to git: git push --tags origin vXX.xx-release
114
+ # 5. Run the following commands in the top-level directory:
115
+ # make prepare_release
116
+ # 6. Upload the package to the pypi test server first:
117
+ # make target=testpypi upload_release
118
+ # 7. Check that you can install it in a virtualenv by running:
119
+ # make install_test_release
120
+ # accelerate env
121
+ # accelerate test
122
+ # 8. Upload the final version to actual pypi:
123
+ # make target=pypi upload_release
124
+ # 9. Add release notes to the tag in github once everything is looking hunky-dory.
125
+ # 10. Go back to the main branch and update the version in __init__.py, setup.py to the new version ".dev" and push to
126
+ # main.
tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/__init__.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 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
+ __version__ = "1.9.0.dev0"
15
+
16
+ from .accelerator import Accelerator
17
+ from .big_modeling import (
18
+ cpu_offload,
19
+ cpu_offload_with_hook,
20
+ disk_offload,
21
+ dispatch_model,
22
+ init_empty_weights,
23
+ init_on_device,
24
+ load_checkpoint_and_dispatch,
25
+ )
26
+ from .data_loader import skip_first_batches
27
+ from .inference import prepare_pippy
28
+ from .launchers import debug_launcher, notebook_launcher
29
+ from .state import PartialState
30
+ from .utils import (
31
+ AutocastKwargs,
32
+ DataLoaderConfiguration,
33
+ DDPCommunicationHookType,
34
+ DeepSpeedPlugin,
35
+ DistributedDataParallelKwargs,
36
+ DistributedType,
37
+ FullyShardedDataParallelPlugin,
38
+ GradScalerKwargs,
39
+ InitProcessGroupKwargs,
40
+ ProfileKwargs,
41
+ find_executable_batch_size,
42
+ infer_auto_device_map,
43
+ is_rich_available,
44
+ load_checkpoint_in_model,
45
+ synchronize_rng_states,
46
+ )
47
+
48
+
49
+ if is_rich_available():
50
+ from .utils import rich
tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/accelerator.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/big_modeling.py ADDED
@@ -0,0 +1,749 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 logging
16
+ import os
17
+ import re
18
+ from contextlib import contextmanager
19
+ from functools import wraps
20
+ from typing import Optional, Union
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+
25
+ from .hooks import (
26
+ AlignDevicesHook,
27
+ CpuOffload,
28
+ LayerwiseCastingHook,
29
+ UserCpuOffloadHook,
30
+ add_hook_to_module,
31
+ attach_align_device_hook,
32
+ attach_align_device_hook_on_blocks,
33
+ )
34
+ from .utils import (
35
+ OffloadedWeightsLoader,
36
+ check_cuda_p2p_ib_support,
37
+ check_device_map,
38
+ extract_submodules_state_dict,
39
+ find_tied_parameters,
40
+ get_balanced_memory,
41
+ infer_auto_device_map,
42
+ is_bnb_available,
43
+ is_mlu_available,
44
+ is_musa_available,
45
+ is_npu_available,
46
+ is_sdaa_available,
47
+ is_xpu_available,
48
+ load_checkpoint_in_model,
49
+ offload_state_dict,
50
+ parse_flag_from_env,
51
+ retie_parameters,
52
+ )
53
+ from .utils.constants import SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING
54
+ from .utils.other import recursive_getattr
55
+
56
+
57
+ logger = logging.getLogger(__name__)
58
+
59
+
60
+ @contextmanager
61
+ def init_empty_weights(include_buffers: bool = None):
62
+ """
63
+ A context manager under which models are initialized with all parameters on the meta device, therefore creating an
64
+ empty model. Useful when just initializing the model would blow the available RAM.
65
+
66
+ Args:
67
+ include_buffers (`bool`, *optional*):
68
+ Whether or not to also put all buffers on the meta device while initializing.
69
+
70
+ Example:
71
+
72
+ ```python
73
+ import torch.nn as nn
74
+ from accelerate import init_empty_weights
75
+
76
+ # Initialize a model with 100 billions parameters in no time and without using any RAM.
77
+ with init_empty_weights():
78
+ tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
79
+ ```
80
+
81
+ <Tip warning={true}>
82
+
83
+ Any model created under this context manager has no weights. As such you can't do something like
84
+ `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
85
+ Make sure to overwrite the default device_map param for [`load_checkpoint_and_dispatch`], otherwise dispatch is not
86
+ called.
87
+
88
+ </Tip>
89
+ """
90
+ if include_buffers is None:
91
+ include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False)
92
+ with init_on_device(torch.device("meta"), include_buffers=include_buffers) as f:
93
+ yield f
94
+
95
+
96
+ @contextmanager
97
+ def init_on_device(device: torch.device, include_buffers: bool = None):
98
+ """
99
+ A context manager under which models are initialized with all parameters on the specified device.
100
+
101
+ Args:
102
+ device (`torch.device`):
103
+ Device to initialize all parameters on.
104
+ include_buffers (`bool`, *optional*):
105
+ Whether or not to also put all buffers on the meta device while initializing.
106
+
107
+ Example:
108
+
109
+ ```python
110
+ import torch.nn as nn
111
+ from accelerate import init_on_device
112
+
113
+ with init_on_device(device=torch.device("cuda")):
114
+ tst = nn.Linear(100, 100) # on `cuda` device
115
+ ```
116
+ """
117
+ if include_buffers is None:
118
+ include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False)
119
+
120
+ if include_buffers:
121
+ with device:
122
+ yield
123
+ return
124
+
125
+ old_register_parameter = nn.Module.register_parameter
126
+ if include_buffers:
127
+ old_register_buffer = nn.Module.register_buffer
128
+
129
+ def register_empty_parameter(module, name, param):
130
+ old_register_parameter(module, name, param)
131
+ if param is not None:
132
+ param_cls = type(module._parameters[name])
133
+ kwargs = module._parameters[name].__dict__
134
+ kwargs["requires_grad"] = param.requires_grad
135
+ module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
136
+
137
+ def register_empty_buffer(module, name, buffer, persistent=True):
138
+ old_register_buffer(module, name, buffer, persistent=persistent)
139
+ if buffer is not None:
140
+ module._buffers[name] = module._buffers[name].to(device)
141
+
142
+ # Patch tensor creation
143
+ if include_buffers:
144
+ tensor_constructors_to_patch = {
145
+ torch_function_name: getattr(torch, torch_function_name)
146
+ for torch_function_name in ["empty", "zeros", "ones", "full"]
147
+ }
148
+ else:
149
+ tensor_constructors_to_patch = {}
150
+
151
+ def patch_tensor_constructor(fn):
152
+ def wrapper(*args, **kwargs):
153
+ kwargs["device"] = device
154
+ return fn(*args, **kwargs)
155
+
156
+ return wrapper
157
+
158
+ try:
159
+ nn.Module.register_parameter = register_empty_parameter
160
+ if include_buffers:
161
+ nn.Module.register_buffer = register_empty_buffer
162
+ for torch_function_name in tensor_constructors_to_patch.keys():
163
+ setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
164
+ yield
165
+ finally:
166
+ nn.Module.register_parameter = old_register_parameter
167
+ if include_buffers:
168
+ nn.Module.register_buffer = old_register_buffer
169
+ for torch_function_name, old_torch_function in tensor_constructors_to_patch.items():
170
+ setattr(torch, torch_function_name, old_torch_function)
171
+
172
+
173
+ def cpu_offload(
174
+ model: nn.Module,
175
+ execution_device: Optional[torch.device] = None,
176
+ offload_buffers: bool = False,
177
+ state_dict: Optional[dict[str, torch.Tensor]] = None,
178
+ preload_module_classes: Optional[list[str]] = None,
179
+ ):
180
+ """
181
+ Activates full CPU offload for a model. As a result, all parameters of the model will be offloaded and only one
182
+ copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that
183
+ state dict and put on the execution device passed as they are needed, then offloaded again.
184
+
185
+ Args:
186
+ model (`torch.nn.Module`):
187
+ The model to offload.
188
+ execution_device (`torch.device`, *optional*):
189
+ The device on which the forward pass of the model will be executed (should be a GPU). Will default to the
190
+ model first parameter device.
191
+ offload_buffers (`bool`, *optional*, defaults to `False`):
192
+ Whether or not to offload the buffers with the model parameters.
193
+ state_dict (`Dict[str, torch.Tensor]`, *optional*):
194
+ The state dict of the model that will be kept on CPU.
195
+ preload_module_classes (`List[str]`, *optional*):
196
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
197
+ of the forward. This should only be used for classes that have submodules which are registered but not
198
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
199
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
200
+ """
201
+ if execution_device is None:
202
+ execution_device = next(iter(model.parameters())).device
203
+ if state_dict is None:
204
+ state_dict = {n: p.to("cpu") for n, p in model.state_dict().items()}
205
+
206
+ add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True)
207
+ attach_align_device_hook(
208
+ model,
209
+ execution_device=execution_device,
210
+ offload=True,
211
+ offload_buffers=offload_buffers,
212
+ weights_map=state_dict,
213
+ preload_module_classes=preload_module_classes,
214
+ )
215
+
216
+ return model
217
+
218
+
219
+ def cpu_offload_with_hook(
220
+ model: torch.nn.Module,
221
+ execution_device: Optional[Union[int, str, torch.device]] = None,
222
+ prev_module_hook: Optional[UserCpuOffloadHook] = None,
223
+ ):
224
+ """
225
+ Offloads a model on the CPU and puts it back to an execution device when executed. The difference with
226
+ [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when
227
+ the `offload` method of the returned `hook` is called. Useful for pipelines running a model in a loop.
228
+
229
+ Args:
230
+ model (`torch.nn.Module`):
231
+ The model to offload.
232
+ execution_device(`str`, `int` or `torch.device`, *optional*):
233
+ The device on which the model should be executed. Will default to the MPS device if it's available, then
234
+ GPU 0 if there is a GPU, and finally to the CPU.
235
+ prev_module_hook (`UserCpuOffloadHook`, *optional*):
236
+ The hook sent back by this function for a previous model in the pipeline you are running. If passed, its
237
+ offload method will be called just before the forward of the model to which this hook is attached.
238
+
239
+ Example:
240
+
241
+ ```py
242
+ model_1, hook_1 = cpu_offload_with_hook(model_1, cuda_device)
243
+ model_2, hook_2 = cpu_offload_with_hook(model_2, cuda_device, prev_module_hook=hook_1)
244
+ model_3, hook_3 = cpu_offload_with_hook(model_3, cuda_device, prev_module_hook=hook_2)
245
+
246
+ hid_1 = model_1(input)
247
+ for i in range(50):
248
+ # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop.
249
+ hid_2 = model_2(hid_1)
250
+ # model2 is offloaded to the CPU just before this forward.
251
+ hid_3 = model_3(hid_3)
252
+
253
+ # For model3, you need to manually call the hook offload method.
254
+ hook_3.offload()
255
+ ```
256
+ """
257
+ hook = CpuOffload(execution_device=execution_device, prev_module_hook=prev_module_hook)
258
+ add_hook_to_module(model, hook, append=True)
259
+ user_hook = UserCpuOffloadHook(model, hook)
260
+ return model, user_hook
261
+
262
+
263
+ def disk_offload(
264
+ model: nn.Module,
265
+ offload_dir: Union[str, os.PathLike],
266
+ execution_device: Optional[torch.device] = None,
267
+ offload_buffers: bool = False,
268
+ preload_module_classes: Optional[list[str]] = None,
269
+ ):
270
+ """
271
+ Activates full disk offload for a model. As a result, all parameters of the model will be offloaded as
272
+ memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and
273
+ put on the execution device passed as they are needed, then offloaded again.
274
+
275
+ Args:
276
+ model (`torch.nn.Module`): The model to offload.
277
+ offload_dir (`str` or `os.PathLike`):
278
+ The folder in which to offload the model weights (or where the model weights are already offloaded).
279
+ execution_device (`torch.device`, *optional*):
280
+ The device on which the forward pass of the model will be executed (should be a GPU). Will default to the
281
+ model's first parameter device.
282
+ offload_buffers (`bool`, *optional*, defaults to `False`):
283
+ Whether or not to offload the buffers with the model parameters.
284
+ preload_module_classes (`List[str]`, *optional*):
285
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
286
+ of the forward. This should only be used for classes that have submodules which are registered but not
287
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
288
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
289
+ """
290
+ if not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")):
291
+ offload_state_dict(offload_dir, model.state_dict())
292
+ if execution_device is None:
293
+ execution_device = next(iter(model.parameters())).device
294
+ weights_map = OffloadedWeightsLoader(save_folder=offload_dir)
295
+
296
+ add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True)
297
+ attach_align_device_hook(
298
+ model,
299
+ execution_device=execution_device,
300
+ offload=True,
301
+ offload_buffers=offload_buffers,
302
+ weights_map=weights_map,
303
+ preload_module_classes=preload_module_classes,
304
+ )
305
+
306
+ return model
307
+
308
+
309
+ def dispatch_model(
310
+ model: nn.Module,
311
+ device_map: dict[str, Union[str, int, torch.device]],
312
+ main_device: Optional[torch.device] = None,
313
+ state_dict: Optional[dict[str, torch.Tensor]] = None,
314
+ offload_dir: Optional[Union[str, os.PathLike]] = None,
315
+ offload_index: Optional[dict[str, str]] = None,
316
+ offload_buffers: bool = False,
317
+ skip_keys: Optional[Union[str, list[str]]] = None,
318
+ preload_module_classes: Optional[list[str]] = None,
319
+ force_hooks: bool = False,
320
+ ):
321
+ """
322
+ Dispatches a model according to a given device map. Layers of the model might be spread across GPUs, offloaded on
323
+ the CPU or even the disk.
324
+
325
+ Args:
326
+ model (`torch.nn.Module`):
327
+ The model to dispatch.
328
+ device_map (`Dict[str, Union[str, int, torch.device]]`):
329
+ A dictionary mapping module names in the models `state_dict` to the device they should go to. Note that
330
+ `"disk"` is accepted even if it's not a proper value for `torch.device`.
331
+ main_device (`str`, `int` or `torch.device`, *optional*):
332
+ The main execution device. Will default to the first device in the `device_map` different from `"cpu"` or
333
+ `"disk"`.
334
+ state_dict (`Dict[str, torch.Tensor]`, *optional*):
335
+ The state dict of the part of the model that will be kept on CPU.
336
+ offload_dir (`str` or `os.PathLike`):
337
+ The folder in which to offload the model weights (or where the model weights are already offloaded).
338
+ offload_index (`Dict`, *optional*):
339
+ A dictionary from weight name to their information (`dtype`/ `shape` or safetensors filename). Will default
340
+ to the index saved in `save_folder`.
341
+ offload_buffers (`bool`, *optional*, defaults to `False`):
342
+ Whether or not to offload the buffers with the model parameters.
343
+ skip_keys (`str` or `List[str]`, *optional*):
344
+ A list of keys to ignore when moving inputs or outputs between devices.
345
+ preload_module_classes (`List[str]`, *optional*):
346
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
347
+ of the forward. This should only be used for classes that have submodules which are registered but not
348
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
349
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
350
+ force_hooks (`bool`, *optional*, defaults to `False`):
351
+ Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a
352
+ single device.
353
+ """
354
+ # Error early if the device map is incomplete.
355
+ check_device_map(model, device_map)
356
+
357
+ # We need to force hook for quantized model that can't be moved with to()
358
+ if getattr(model, "quantization_method", "bitsandbytes") == "bitsandbytes":
359
+ # since bnb 0.43.2, we can move 4-bit model
360
+ if getattr(model, "is_loaded_in_8bit", False) or (
361
+ getattr(model, "is_loaded_in_4bit", False) and not is_bnb_available(min_version="0.43.2")
362
+ ):
363
+ force_hooks = True
364
+
365
+ # We attach hooks if the device_map has at least 2 different devices or if
366
+ # force_hooks is set to `True`. Otherwise, the model in already loaded
367
+ # in the unique device and the user can decide where to dispatch the model.
368
+ # If the model is quantized, we always force-dispatch the model
369
+ if (len(set(device_map.values())) > 1) or force_hooks:
370
+ if main_device is None:
371
+ if set(device_map.values()) == {"cpu"} or set(device_map.values()) == {"cpu", "disk"}:
372
+ main_device = "cpu"
373
+ else:
374
+ main_device = [d for d in device_map.values() if d not in ["cpu", "disk"]][0]
375
+
376
+ if main_device != "cpu":
377
+ cpu_modules = [name for name, device in device_map.items() if device == "cpu"]
378
+ if state_dict is None and len(cpu_modules) > 0:
379
+ state_dict = extract_submodules_state_dict(model.state_dict(), cpu_modules)
380
+
381
+ disk_modules = [name for name, device in device_map.items() if device == "disk"]
382
+ if offload_dir is None and offload_index is None and len(disk_modules) > 0:
383
+ raise ValueError(
384
+ "We need an `offload_dir` to dispatch this model according to this `device_map`, the following submodules "
385
+ f"need to be offloaded: {', '.join(disk_modules)}."
386
+ )
387
+ if (
388
+ len(disk_modules) > 0
389
+ and offload_index is None
390
+ and (not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")))
391
+ ):
392
+ disk_state_dict = extract_submodules_state_dict(model.state_dict(), disk_modules)
393
+ offload_state_dict(offload_dir, disk_state_dict)
394
+
395
+ execution_device = {
396
+ name: main_device if device in ["cpu", "disk"] else device for name, device in device_map.items()
397
+ }
398
+ execution_device[""] = main_device
399
+ offloaded_devices = ["disk"] if main_device == "cpu" or main_device == "mps" else ["cpu", "disk"]
400
+ offload = {name: device in offloaded_devices for name, device in device_map.items()}
401
+ save_folder = offload_dir if len(disk_modules) > 0 else None
402
+ if state_dict is not None or save_folder is not None or offload_index is not None:
403
+ device = main_device if offload_index is not None else None
404
+ weights_map = OffloadedWeightsLoader(
405
+ state_dict=state_dict, save_folder=save_folder, index=offload_index, device=device
406
+ )
407
+ else:
408
+ weights_map = None
409
+
410
+ # When dispatching the model's parameters to the devices specified in device_map, we want to avoid allocating memory several times for the
411
+ # tied parameters. The dictionary tied_params_map keeps track of the already allocated data for a given tied parameter (represented by its
412
+ # original pointer) on each devices.
413
+ tied_params = find_tied_parameters(model)
414
+
415
+ tied_params_map = {}
416
+ for group in tied_params:
417
+ for param_name in group:
418
+ # data_ptr() is enough here, as `find_tied_parameters` finds tied params simply by comparing `param1 is param2`, so we don't need
419
+ # to care about views of tensors through storage_offset.
420
+ data_ptr = recursive_getattr(model, param_name).data_ptr()
421
+ tied_params_map[data_ptr] = {}
422
+
423
+ # Note: To handle the disk offloading case, we can not simply use weights_map[param_name].data_ptr() as the reference pointer,
424
+ # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
425
+
426
+ attach_align_device_hook_on_blocks(
427
+ model,
428
+ execution_device=execution_device,
429
+ offload=offload,
430
+ offload_buffers=offload_buffers,
431
+ weights_map=weights_map,
432
+ skip_keys=skip_keys,
433
+ preload_module_classes=preload_module_classes,
434
+ tied_params_map=tied_params_map,
435
+ )
436
+
437
+ # warn if there is any params on the meta device
438
+ offloaded_devices_str = " and ".join(
439
+ [device for device in set(device_map.values()) if device in ("cpu", "disk")]
440
+ )
441
+ if len(offloaded_devices_str) > 0:
442
+ logger.warning(
443
+ f"Some parameters are on the meta device because they were offloaded to the {offloaded_devices_str}."
444
+ )
445
+
446
+ # Attaching the hook may break tied weights, so we retie them
447
+ retie_parameters(model, tied_params)
448
+
449
+ # add warning to cuda and to method
450
+ def add_warning(fn, model):
451
+ @wraps(fn)
452
+ def wrapper(*args, **kwargs):
453
+ warning_msg = "You shouldn't move a model that is dispatched using accelerate hooks."
454
+ if str(fn.__name__) == "to":
455
+ to_device = torch._C._nn._parse_to(*args, **kwargs)[0]
456
+ if to_device is not None:
457
+ logger.warning(warning_msg)
458
+ else:
459
+ logger.warning(warning_msg)
460
+ for param in model.parameters():
461
+ if param.device == torch.device("meta"):
462
+ raise RuntimeError("You can't move a model that has some modules offloaded to cpu or disk.")
463
+ return fn(*args, **kwargs)
464
+
465
+ return wrapper
466
+
467
+ # Make sure to update _accelerate_added_attributes in hooks.py if you add any hook
468
+ model.to = add_warning(model.to, model)
469
+ if is_npu_available():
470
+ model.npu = add_warning(model.npu, model)
471
+ elif is_mlu_available():
472
+ model.mlu = add_warning(model.mlu, model)
473
+ elif is_sdaa_available():
474
+ model.sdaa = add_warning(model.sdaa, model)
475
+ elif is_musa_available():
476
+ model.musa = add_warning(model.musa, model)
477
+ elif is_xpu_available():
478
+ model.xpu = add_warning(model.xpu, model)
479
+ else:
480
+ model.cuda = add_warning(model.cuda, model)
481
+
482
+ # Check if we are using multi-gpus with RTX 4000 series
483
+ use_multi_gpu = len([device for device in set(device_map.values()) if device not in ("cpu", "disk")]) > 1
484
+ if use_multi_gpu and not check_cuda_p2p_ib_support():
485
+ logger.warning(
486
+ "We've detected an older driver with an RTX 4000 series GPU. These drivers have issues with P2P. "
487
+ "This can affect the multi-gpu inference when using accelerate device_map."
488
+ "Please make sure to update your driver to the latest version which resolves this."
489
+ )
490
+ else:
491
+ device = list(device_map.values())[0]
492
+ # `torch.Tensor.to(<int num>)` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)).
493
+ if is_npu_available() and isinstance(device, int):
494
+ device = f"npu:{device}"
495
+ elif is_mlu_available() and isinstance(device, int):
496
+ device = f"mlu:{device}"
497
+ elif is_sdaa_available() and isinstance(device, int):
498
+ device = f"sdaa:{device}"
499
+ elif is_musa_available() and isinstance(device, int):
500
+ device = f"musa:{device}"
501
+ if device != "disk":
502
+ model.to(device)
503
+ else:
504
+ raise ValueError(
505
+ "You are trying to offload the whole model to the disk. Please use the `disk_offload` function instead."
506
+ )
507
+ # Convert OrderedDict back to dict for easier usage
508
+ model.hf_device_map = dict(device_map)
509
+ return model
510
+
511
+
512
+ def load_checkpoint_and_dispatch(
513
+ model: nn.Module,
514
+ checkpoint: Union[str, os.PathLike],
515
+ device_map: Optional[Union[str, dict[str, Union[int, str, torch.device]]]] = None,
516
+ max_memory: Optional[dict[Union[int, str], Union[int, str]]] = None,
517
+ no_split_module_classes: Optional[list[str]] = None,
518
+ offload_folder: Optional[Union[str, os.PathLike]] = None,
519
+ offload_buffers: bool = False,
520
+ dtype: Optional[Union[str, torch.dtype]] = None,
521
+ offload_state_dict: Optional[bool] = None,
522
+ skip_keys: Optional[Union[str, list[str]]] = None,
523
+ preload_module_classes: Optional[list[str]] = None,
524
+ force_hooks: bool = False,
525
+ strict: bool = False,
526
+ full_state_dict: bool = True,
527
+ broadcast_from_rank0: bool = False,
528
+ ):
529
+ """
530
+ Loads a (potentially sharded) checkpoint inside a model, potentially sending weights to a given device as they are
531
+ loaded and adds the various hooks that will make this model run properly (even if split across devices).
532
+
533
+ Args:
534
+ model (`torch.nn.Module`): The model in which we want to load a checkpoint.
535
+ checkpoint (`str` or `os.PathLike`):
536
+ The folder checkpoint to load. It can be:
537
+ - a path to a file containing a whole model state dict
538
+ - a path to a `.json` file containing the index to a sharded checkpoint
539
+ - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint.
540
+ device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*):
541
+ A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer
542
+ name, once a given module name is inside, every submodule of it will be sent to the same device.
543
+
544
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For more
545
+ information about each option see [here](../concept_guides/big_model_inference#designing-a-device-map).
546
+ Defaults to None, which means [`dispatch_model`] will not be called.
547
+ max_memory (`Dict`, *optional*):
548
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each GPU
549
+ and the available CPU RAM if unset.
550
+ no_split_module_classes (`List[str]`, *optional*):
551
+ A list of layer class names that should never be split across device (for instance any layer that has a
552
+ residual connection).
553
+ offload_folder (`str` or `os.PathLike`, *optional*):
554
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
555
+ offload_buffers (`bool`, *optional*, defaults to `False`):
556
+ In the layers that are offloaded on the CPU or the hard drive, whether or not to offload the buffers as
557
+ well as the parameters.
558
+ dtype (`str` or `torch.dtype`, *optional*):
559
+ If provided, the weights will be converted to that type when loaded.
560
+ offload_state_dict (`bool`, *optional*):
561
+ If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if
562
+ the weight of the CPU state dict + the biggest shard does not fit. Will default to `True` if the device map
563
+ picked contains `"disk"` values.
564
+ skip_keys (`str` or `List[str]`, *optional*):
565
+ A list of keys to ignore when moving inputs or outputs between devices.
566
+ preload_module_classes (`List[str]`, *optional*):
567
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
568
+ of the forward. This should only be used for classes that have submodules which are registered but not
569
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
570
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
571
+ force_hooks (`bool`, *optional*, defaults to `False`):
572
+ Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a
573
+ single device.
574
+ strict (`bool`, *optional*, defaults to `False`):
575
+ Whether to strictly enforce that the keys in the checkpoint state_dict match the keys of the model's
576
+ state_dict.
577
+ full_state_dict (`bool`, *optional*, defaults to `True`): if this is set to `True`, all the tensors in the
578
+ loaded state_dict will be gathered. No ShardedTensor and DTensor will be in the loaded state_dict.
579
+ broadcast_from_rank0 (`False`, *optional*, defaults to `False`): when the option is `True`, a distributed
580
+ `ProcessGroup` must be initialized. rank0 should receive a full state_dict and will broadcast the tensors
581
+ in the state_dict one by one to other ranks. Other ranks will receive the tensors and shard (if applicable)
582
+ according to the local shards in the model.
583
+
584
+ Example:
585
+
586
+ ```python
587
+ >>> from accelerate import init_empty_weights, load_checkpoint_and_dispatch
588
+ >>> from huggingface_hub import hf_hub_download
589
+ >>> from transformers import AutoConfig, AutoModelForCausalLM
590
+
591
+ >>> # Download the Weights
592
+ >>> checkpoint = "EleutherAI/gpt-j-6B"
593
+ >>> weights_location = hf_hub_download(checkpoint, "pytorch_model.bin")
594
+
595
+ >>> # Create a model and initialize it with empty weights
596
+ >>> config = AutoConfig.from_pretrained(checkpoint)
597
+ >>> with init_empty_weights():
598
+ ... model = AutoModelForCausalLM.from_config(config)
599
+
600
+ >>> # Load the checkpoint and dispatch it to the right devices
601
+ >>> model = load_checkpoint_and_dispatch(
602
+ ... model, weights_location, device_map="auto", no_split_module_classes=["GPTJBlock"]
603
+ ... )
604
+ ```
605
+ """
606
+ if isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
607
+ raise ValueError(
608
+ "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or 'sequential'."
609
+ )
610
+ if isinstance(device_map, str):
611
+ if device_map != "sequential":
612
+ max_memory = get_balanced_memory(
613
+ model,
614
+ max_memory=max_memory,
615
+ no_split_module_classes=no_split_module_classes,
616
+ dtype=dtype,
617
+ low_zero=(device_map == "balanced_low_0"),
618
+ )
619
+ device_map = infer_auto_device_map(
620
+ model,
621
+ max_memory=max_memory,
622
+ no_split_module_classes=no_split_module_classes,
623
+ dtype=dtype,
624
+ offload_buffers=offload_buffers,
625
+ )
626
+ if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
627
+ offload_state_dict = True
628
+ load_checkpoint_in_model(
629
+ model,
630
+ checkpoint,
631
+ device_map=device_map,
632
+ offload_folder=offload_folder,
633
+ dtype=dtype,
634
+ offload_state_dict=offload_state_dict,
635
+ offload_buffers=offload_buffers,
636
+ strict=strict,
637
+ full_state_dict=full_state_dict,
638
+ broadcast_from_rank0=broadcast_from_rank0,
639
+ )
640
+ if device_map is None:
641
+ return model
642
+ return dispatch_model(
643
+ model,
644
+ device_map=device_map,
645
+ offload_dir=offload_folder,
646
+ offload_buffers=offload_buffers,
647
+ skip_keys=skip_keys,
648
+ preload_module_classes=preload_module_classes,
649
+ force_hooks=force_hooks,
650
+ )
651
+
652
+
653
+ def attach_layerwise_casting_hooks(
654
+ module: torch.nn.Module,
655
+ storage_dtype: torch.dtype,
656
+ compute_dtype: torch.dtype,
657
+ skip_modules_pattern: Union[str, tuple[str, ...]] = None,
658
+ skip_modules_classes: Optional[tuple[type[torch.nn.Module], ...]] = None,
659
+ non_blocking: bool = False,
660
+ ) -> None:
661
+ r"""
662
+ Applies layerwise casting to a given module. The module expected here is a PyTorch `nn.Module`. This is helpful for
663
+ reducing memory requirements when one doesn't want to fully quantize a model. Model params can be kept in say,
664
+ `torch.float8_e4m3fn` and upcasted to a higher precision like `torch.bfloat16` during forward pass and downcasted
665
+ back to `torch.float8_e4m3fn` to realize memory savings.
666
+
667
+ Args:
668
+ module (`torch.nn.Module`):
669
+ The module whose leaf modules will be cast to a high precision dtype for computation, and to a low
670
+ precision dtype for storage.
671
+ storage_dtype (`torch.dtype`):
672
+ The dtype to cast the module to before/after the forward pass for storage.
673
+ compute_dtype (`torch.dtype`):
674
+ The dtype to cast the module to during the forward pass for computation.
675
+ skip_modules_pattern (`tuple[str, ...]`, defaults to `None`):
676
+ A list of patterns to match the names of the modules to skip during the layerwise casting process. If set
677
+ to `None` alongside `skip_modules_classes` being `None`, the layerwise casting is applied directly to the
678
+ module instead of its internal submodules.
679
+ skip_modules_classes (`tuple[type[torch.nn.Module], ...]`, defaults to `None`):
680
+ A list of module classes to skip during the layerwise casting process.
681
+ non_blocking (`bool`, defaults to `False`):
682
+ If `True`, the weight casting operations are non-blocking.
683
+
684
+ Example:
685
+
686
+ ```python
687
+ >>> from accelerate.hooks import attach_layerwise_casting_hooks
688
+ >>> from transformers import AutoModelForCausalLM
689
+ >>> import torch
690
+
691
+ >>> # Model
692
+ >>> checkpoint = "EleutherAI/gpt-j-6B"
693
+ >>> model = AutoModelForCausalLM.from_pretrained(checkpoint)
694
+
695
+ >>> # Attach hooks and perform inference
696
+ >>> attach_layerwise_casting_hooks(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
697
+ >>> with torch.no_grad():
698
+ ... model(...)
699
+ ```
700
+
701
+ Users can also pass modules they want to avoid from getting downcasted.
702
+
703
+ ```py
704
+ >>> attach_layerwise_casting_hooks(
705
+ ... model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16, skip_modules_pattern=["norm"]
706
+ ... )
707
+ ```
708
+ """
709
+ _attach_layerwise_casting_hooks(
710
+ module, storage_dtype, compute_dtype, skip_modules_pattern, skip_modules_classes, non_blocking
711
+ )
712
+
713
+
714
+ def _attach_layerwise_casting_hooks(
715
+ module: torch.nn.Module,
716
+ storage_dtype: torch.dtype,
717
+ compute_dtype: torch.dtype,
718
+ skip_modules_pattern: Union[str, tuple[str, ...]] = None,
719
+ skip_modules_classes: Optional[tuple[type[torch.nn.Module], ...]] = None,
720
+ non_blocking: bool = False,
721
+ _prefix: str = "",
722
+ ):
723
+ should_skip = (skip_modules_classes is not None and isinstance(module, skip_modules_classes)) or (
724
+ skip_modules_pattern is not None and any(re.search(pattern, _prefix) for pattern in skip_modules_pattern)
725
+ )
726
+ if should_skip:
727
+ logger.debug(f'Skipping layerwise casting for layer "{_prefix}"')
728
+ return
729
+
730
+ if isinstance(module, SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING):
731
+ logger.debug(f'Applying layerwise casting to layer "{_prefix}"')
732
+ add_hook_to_module(
733
+ module,
734
+ LayerwiseCastingHook(storage_dtype=storage_dtype, compute_dtype=compute_dtype, non_blocking=non_blocking),
735
+ append=True,
736
+ )
737
+ return
738
+
739
+ for name, submodule in module.named_children():
740
+ layer_name = f"{_prefix}.{name}" if _prefix else name
741
+ _attach_layerwise_casting_hooks(
742
+ submodule,
743
+ storage_dtype,
744
+ compute_dtype,
745
+ skip_modules_pattern,
746
+ skip_modules_classes,
747
+ non_blocking,
748
+ _prefix=layer_name,
749
+ )
tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/checkpointing.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 random
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import torch
20
+ from safetensors.torch import load_model
21
+
22
+ from .utils import (
23
+ MODEL_NAME,
24
+ OPTIMIZER_NAME,
25
+ RNG_STATE_NAME,
26
+ SAFE_MODEL_NAME,
27
+ SAFE_WEIGHTS_NAME,
28
+ SAMPLER_NAME,
29
+ SCALER_NAME,
30
+ SCHEDULER_NAME,
31
+ WEIGHTS_NAME,
32
+ get_pretty_name,
33
+ is_cuda_available,
34
+ is_hpu_available,
35
+ is_mlu_available,
36
+ is_musa_available,
37
+ is_sdaa_available,
38
+ is_torch_version,
39
+ is_torch_xla_available,
40
+ is_xpu_available,
41
+ load,
42
+ save,
43
+ )
44
+
45
+
46
+ if is_torch_version(">=", "2.4.0"):
47
+ from torch.amp import GradScaler
48
+ else:
49
+ from torch.cuda.amp import GradScaler
50
+
51
+ if is_torch_xla_available():
52
+ import torch_xla.core.xla_model as xm
53
+
54
+ from .logging import get_logger
55
+ from .state import PartialState
56
+
57
+
58
+ logger = get_logger(__name__)
59
+
60
+
61
+ def save_accelerator_state(
62
+ output_dir: str,
63
+ model_states: list[dict],
64
+ optimizers: list,
65
+ schedulers: list,
66
+ dataloaders: list,
67
+ process_index: int,
68
+ step: int,
69
+ scaler: GradScaler = None,
70
+ save_on_each_node: bool = False,
71
+ safe_serialization: bool = True,
72
+ ):
73
+ """
74
+ Saves the current states of the models, optimizers, scaler, and RNG generators to a given directory.
75
+
76
+ <Tip>
77
+
78
+ If `safe_serialization` is `True`, models will be saved with `safetensors` while the rest are saved using native
79
+ `pickle`.
80
+
81
+ </Tip>
82
+
83
+ Args:
84
+ output_dir (`str` or `os.PathLike`):
85
+ The name of the folder to save all relevant weights and states.
86
+ model_states (`List[torch.nn.Module]`):
87
+ A list of model states
88
+ optimizers (`List[torch.optim.Optimizer]`):
89
+ A list of optimizer instances
90
+ schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
91
+ A list of learning rate schedulers
92
+ dataloaders (`List[torch.utils.data.DataLoader]`):
93
+ A list of dataloader instances to save their sampler states
94
+ process_index (`int`):
95
+ The current process index in the Accelerator state
96
+ step (`int`):
97
+ The current step in the internal step tracker
98
+ scaler (`torch.amp.GradScaler`, *optional*):
99
+ An optional gradient scaler instance to save;
100
+ save_on_each_node (`bool`, *optional*):
101
+ Whether to save on every node, or only the main node.
102
+ safe_serialization (`bool`, *optional*, defaults to `True`):
103
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
104
+ """
105
+ output_dir = Path(output_dir)
106
+ # Model states
107
+ for i, state in enumerate(model_states):
108
+ weights_name = WEIGHTS_NAME if not safe_serialization else SAFE_WEIGHTS_NAME
109
+ if i > 0:
110
+ weights_name = weights_name.replace(".", f"_{i}.")
111
+ output_model_file = output_dir.joinpath(weights_name)
112
+ save(state, output_model_file, save_on_each_node=save_on_each_node, safe_serialization=safe_serialization)
113
+ logger.info(f"Model weights saved in {output_model_file}")
114
+ # Optimizer states
115
+ for i, opt in enumerate(optimizers):
116
+ state = opt.state_dict()
117
+ optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin"
118
+ output_optimizer_file = output_dir.joinpath(optimizer_name)
119
+ save(state, output_optimizer_file, save_on_each_node=save_on_each_node, safe_serialization=False)
120
+ logger.info(f"Optimizer state saved in {output_optimizer_file}")
121
+ # Scheduler states
122
+ for i, scheduler in enumerate(schedulers):
123
+ state = scheduler.state_dict()
124
+ scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin"
125
+ output_scheduler_file = output_dir.joinpath(scheduler_name)
126
+ save(state, output_scheduler_file, save_on_each_node=save_on_each_node, safe_serialization=False)
127
+ logger.info(f"Scheduler state saved in {output_scheduler_file}")
128
+ # DataLoader states
129
+ for i, dataloader in enumerate(dataloaders):
130
+ sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin"
131
+ output_sampler_file = output_dir.joinpath(sampler_name)
132
+ # Only save if we have our custom sampler
133
+ from .data_loader import IterableDatasetShard, SeedableRandomSampler
134
+
135
+ if isinstance(dataloader.dataset, IterableDatasetShard):
136
+ sampler = dataloader.get_sampler()
137
+ if isinstance(sampler, SeedableRandomSampler):
138
+ save(sampler, output_sampler_file, save_on_each_node=save_on_each_node, safe_serialization=False)
139
+ if getattr(dataloader, "use_stateful_dataloader", False):
140
+ dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin"
141
+ output_dataloader_state_dict_file = output_dir.joinpath(dataloader_state_dict_name)
142
+ state_dict = dataloader.state_dict()
143
+ torch.save(state_dict, output_dataloader_state_dict_file)
144
+ logger.info(f"Sampler state for dataloader {i} saved in {output_sampler_file}")
145
+
146
+ # GradScaler state
147
+ if scaler is not None:
148
+ state = scaler.state_dict()
149
+ output_scaler_file = output_dir.joinpath(SCALER_NAME)
150
+ torch.save(state, output_scaler_file)
151
+ logger.info(f"Gradient scaler state saved in {output_scaler_file}")
152
+ # Random number generator states
153
+ states = {}
154
+ states_name = f"{RNG_STATE_NAME}_{process_index}.pkl"
155
+ states["step"] = step
156
+ states["random_state"] = random.getstate()
157
+ states["numpy_random_seed"] = np.random.get_state()
158
+ states["torch_manual_seed"] = torch.get_rng_state()
159
+ if is_xpu_available():
160
+ states["torch_xpu_manual_seed"] = torch.xpu.get_rng_state_all()
161
+ if is_mlu_available():
162
+ states["torch_mlu_manual_seed"] = torch.mlu.get_rng_state_all()
163
+ elif is_sdaa_available():
164
+ states["torch_sdaa_manual_seed"] = torch.sdaa.get_rng_state_all()
165
+ elif is_musa_available():
166
+ states["torch_musa_manual_seed"] = torch.musa.get_rng_state_all()
167
+ if is_hpu_available():
168
+ states["torch_hpu_manual_seed"] = torch.hpu.get_rng_state_all()
169
+ if is_cuda_available():
170
+ states["torch_cuda_manual_seed"] = torch.cuda.get_rng_state_all()
171
+ if is_torch_xla_available():
172
+ states["xm_seed"] = xm.get_rng_state()
173
+ output_states_file = output_dir.joinpath(states_name)
174
+ torch.save(states, output_states_file)
175
+ logger.info(f"Random states saved in {output_states_file}")
176
+ return output_dir
177
+
178
+
179
+ def load_accelerator_state(
180
+ input_dir,
181
+ models,
182
+ optimizers,
183
+ schedulers,
184
+ dataloaders,
185
+ process_index,
186
+ scaler=None,
187
+ map_location=None,
188
+ load_kwargs=None,
189
+ **load_model_func_kwargs,
190
+ ):
191
+ """
192
+ Loads states of the models, optimizers, scaler, and RNG generators from a given directory.
193
+
194
+ Args:
195
+ input_dir (`str` or `os.PathLike`):
196
+ The name of the folder to load all relevant weights and states.
197
+ models (`List[torch.nn.Module]`):
198
+ A list of model instances
199
+ optimizers (`List[torch.optim.Optimizer]`):
200
+ A list of optimizer instances
201
+ schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
202
+ A list of learning rate schedulers
203
+ process_index (`int`):
204
+ The current process index in the Accelerator state
205
+ scaler (`torch.amp.GradScaler`, *optional*):
206
+ An optional *GradScaler* instance to load
207
+ map_location (`str`, *optional*):
208
+ What device to load the optimizer state onto. Should be one of either "cpu" or "on_device".
209
+ load_kwargs (`dict`, *optional*):
210
+ Additional arguments that can be passed to the `load` function.
211
+ load_model_func_kwargs (`dict`, *optional*):
212
+ Additional arguments that can be passed to the model's `load_state_dict` method.
213
+
214
+ Returns:
215
+ `dict`: Contains the `Accelerator` attributes to override while loading the state.
216
+ """
217
+ # stores the `Accelerator` attributes to override
218
+ override_attributes = dict()
219
+ if map_location not in [None, "cpu", "on_device"]:
220
+ raise TypeError(
221
+ "Unsupported optimizer map location passed, please choose one of `None`, `'cpu'`, or `'on_device'`"
222
+ )
223
+ if map_location is None:
224
+ map_location = "cpu"
225
+ elif map_location == "on_device":
226
+ map_location = PartialState().device
227
+
228
+ if load_kwargs is None:
229
+ load_kwargs = {}
230
+
231
+ input_dir = Path(input_dir)
232
+ # Model states
233
+ for i, model in enumerate(models):
234
+ ending = f"_{i}" if i > 0 else ""
235
+ input_model_file = input_dir.joinpath(f"{SAFE_MODEL_NAME}{ending}.safetensors")
236
+ if input_model_file.exists():
237
+ load_model(model, input_model_file, device=str(map_location), **load_model_func_kwargs)
238
+ else:
239
+ # Load with torch
240
+ input_model_file = input_dir.joinpath(f"{MODEL_NAME}{ending}.bin")
241
+ state_dict = load(input_model_file, map_location=map_location)
242
+ model.load_state_dict(state_dict, **load_model_func_kwargs)
243
+ logger.info("All model weights loaded successfully")
244
+
245
+ # Optimizer states
246
+ for i, opt in enumerate(optimizers):
247
+ optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin"
248
+ input_optimizer_file = input_dir.joinpath(optimizer_name)
249
+ optimizer_state = load(input_optimizer_file, map_location=map_location, **load_kwargs)
250
+ optimizers[i].load_state_dict(optimizer_state)
251
+ logger.info("All optimizer states loaded successfully")
252
+
253
+ # Scheduler states
254
+ for i, scheduler in enumerate(schedulers):
255
+ scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin"
256
+ input_scheduler_file = input_dir.joinpath(scheduler_name)
257
+ scheduler_state = load(input_scheduler_file, **load_kwargs)
258
+ scheduler.load_state_dict(scheduler_state)
259
+ logger.info("All scheduler states loaded successfully")
260
+
261
+ for i, dataloader in enumerate(dataloaders):
262
+ sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin"
263
+ input_sampler_file = input_dir.joinpath(sampler_name)
264
+ # Only load if we have our custom sampler
265
+ from .data_loader import IterableDatasetShard, SeedableRandomSampler
266
+
267
+ if isinstance(dataloader.dataset, IterableDatasetShard):
268
+ sampler = dataloader.get_sampler()
269
+ if isinstance(sampler, SeedableRandomSampler):
270
+ sampler = dataloader.set_sampler(load(input_sampler_file))
271
+ if getattr(dataloader, "use_stateful_dataloader", False):
272
+ dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin"
273
+ input_dataloader_state_dict_file = input_dir.joinpath(dataloader_state_dict_name)
274
+ if input_dataloader_state_dict_file.exists():
275
+ state_dict = load(input_dataloader_state_dict_file, **load_kwargs)
276
+ dataloader.load_state_dict(state_dict)
277
+ logger.info("All dataloader sampler states loaded successfully")
278
+
279
+ # GradScaler state
280
+ if scaler is not None:
281
+ input_scaler_file = input_dir.joinpath(SCALER_NAME)
282
+ scaler_state = load(input_scaler_file)
283
+ scaler.load_state_dict(scaler_state)
284
+ logger.info("GradScaler state loaded successfully")
285
+
286
+ # Random states
287
+ try:
288
+ states = load(input_dir.joinpath(f"{RNG_STATE_NAME}_{process_index}.pkl"))
289
+ if "step" in states:
290
+ override_attributes["step"] = states["step"]
291
+ random.setstate(states["random_state"])
292
+ np.random.set_state(states["numpy_random_seed"])
293
+ torch.set_rng_state(states["torch_manual_seed"])
294
+ if is_xpu_available():
295
+ torch.xpu.set_rng_state_all(states["torch_xpu_manual_seed"])
296
+ if is_mlu_available():
297
+ torch.mlu.set_rng_state_all(states["torch_mlu_manual_seed"])
298
+ elif is_sdaa_available():
299
+ torch.sdaa.set_rng_state_all(states["torch_sdaa_manual_seed"])
300
+ elif is_musa_available():
301
+ torch.musa.set_rng_state_all(states["torch_musa_manual_seed"])
302
+ else:
303
+ torch.cuda.set_rng_state_all(states["torch_cuda_manual_seed"])
304
+ if is_torch_xla_available():
305
+ xm.set_rng_state(states["xm_seed"])
306
+ logger.info("All random states loaded successfully")
307
+ except Exception:
308
+ logger.info("Could not load random states")
309
+
310
+ return override_attributes
311
+
312
+
313
+ def save_custom_state(obj, path, index: int = 0, save_on_each_node: bool = False):
314
+ """
315
+ Saves the state of `obj` to `{path}/custom_checkpoint_{index}.pkl`
316
+ """
317
+ # Should this be the right way to get a qual_name type value from `obj`?
318
+ save_location = Path(path) / f"custom_checkpoint_{index}.pkl"
319
+ logger.info(f"Saving the state of {get_pretty_name(obj)} to {save_location}")
320
+ save(obj.state_dict(), save_location, save_on_each_node=save_on_each_node)
321
+
322
+
323
+ def load_custom_state(obj, path, index: int = 0):
324
+ """
325
+ Loads the state of `obj` at `{path}/custom_checkpoint_{index}.pkl`. Will always set `weights_only=False` when
326
+ loading the state.
327
+ """
328
+ load_location = f"{path}/custom_checkpoint_{index}.pkl"
329
+ logger.info(f"Loading the state of {get_pretty_name(obj)} from {load_location}")
330
+ obj.load_state_dict(load(load_location, map_location="cpu", weights_only=False))
tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/commands/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 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.
tasks/tasksmith-64b21f14793e/environment/source/src/accelerate/commands/accelerate_cli.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from accelerate.commands.config import get_config_parser
18
+ from accelerate.commands.env import env_command_parser
19
+ from accelerate.commands.estimate import estimate_command_parser
20
+ from accelerate.commands.launch import launch_command_parser
21
+ from accelerate.commands.merge import merge_command_parser
22
+ from accelerate.commands.test import test_command_parser
23
+ from accelerate.commands.to_fsdp2 import to_fsdp2_command_parser
24
+ from accelerate.commands.tpu import tpu_command_parser
25
+ from accelerate.commands.utils import CustomArgumentParser
26
+
27
+
28
+ def main():
29
+ parser = CustomArgumentParser("Accelerate CLI tool", usage="accelerate <command> [<args>]", allow_abbrev=False)
30
+ subparsers = parser.add_subparsers(help="accelerate command helpers")
31
+
32
+ # Register commands
33
+ get_config_parser(subparsers=subparsers)
34
+ estimate_command_parser(subparsers=subparsers)
35
+ env_command_parser(subparsers=subparsers)
36
+ launch_command_parser(subparsers=subparsers)
37
+ merge_command_parser(subparsers=subparsers)
38
+ tpu_command_parser(subparsers=subparsers)
39
+ test_command_parser(subparsers=subparsers)
40
+ to_fsdp2_command_parser(subparsers=subparsers)
41
+
42
+ # Let's go
43
+ args = parser.parse_args()
44
+
45
+ if not hasattr(args, "func"):
46
+ parser.print_help()
47
+ exit(1)
48
+
49
+ # Run
50
+ args.func(args)
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()