AdithyaSK HF Staff commited on
Commit
9f9964c
·
verified ·
1 Parent(s): da7e5c3

Stage Harbor release files 44501-45000

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-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_3.py +158 -0
  2. tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_4.py +156 -0
  3. tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_5.py +221 -0
  4. tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_0.py +32 -0
  5. tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_1.py +31 -0
  6. tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_2.py +176 -0
  7. tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_3.py +34 -0
  8. tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_4.py +52 -0
  9. tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_5.py +203 -0
  10. tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_6.py +193 -0
  11. tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_7.py +182 -0
  12. tasks/tasksmith-5db757e91a6e/tests/source/pyproject.toml +43 -0
  13. tasks/tasksmith-5db757e91a6e/tests/source/setup.py +122 -0
  14. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/__init__.py +50 -0
  15. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/accelerator.py +0 -0
  16. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/big_modeling.py +633 -0
  17. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/checkpointing.py +302 -0
  18. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/__init__.py +13 -0
  19. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/accelerate_cli.py +52 -0
  20. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/__init__.py +52 -0
  21. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/cluster.py +828 -0
  22. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config.py +89 -0
  23. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config_args.py +252 -0
  24. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config_utils.py +111 -0
  25. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/default.py +142 -0
  26. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/sagemaker.py +267 -0
  27. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/update.py +63 -0
  28. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/env.py +113 -0
  29. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/estimate.py +309 -0
  30. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/launch.py +1178 -0
  31. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/__init__.py +14 -0
  32. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/cursor.py +65 -0
  33. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/helpers.py +59 -0
  34. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/input.py +86 -0
  35. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/keymap.py +133 -0
  36. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/selection_menu.py +144 -0
  37. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/merge.py +69 -0
  38. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/test.py +65 -0
  39. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/tpu.py +157 -0
  40. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/utils.py +120 -0
  41. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/data_loader.py +1314 -0
  42. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/hooks.py +720 -0
  43. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/inference.py +184 -0
  44. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/launchers.py +302 -0
  45. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/local_sgd.py +103 -0
  46. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/logging.py +125 -0
  47. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/memory_utils.py +22 -0
  48. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/optimizer.py +205 -0
  49. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/scheduler.py +98 -0
  50. tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/state.py +1257 -0
tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_3.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 manim import *
16
+
17
+ class Stage3(Scene):
18
+ def construct(self):
19
+ mem = Rectangle(height=0.5,width=0.5)
20
+ meta_mem = Rectangle(height=0.25,width=0.25)
21
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
22
+
23
+ cpu_left_col_base = [mem.copy() for i in range(6)]
24
+ cpu_right_col_base = [mem.copy() for i in range(6)]
25
+ cpu_left_col = VGroup(*cpu_left_col_base).arrange(UP, buff=0)
26
+ cpu_right_col = VGroup(*cpu_right_col_base).arrange(UP, buff=0)
27
+ cpu_rects = VGroup(cpu_left_col,cpu_right_col).arrange(RIGHT, buff=0)
28
+ cpu_text = Text("CPU", font_size=24)
29
+ cpu = Group(cpu_rects,cpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
30
+ cpu.move_to([-2.5,-.5,0])
31
+ self.add(cpu)
32
+
33
+ gpu_base = [mem.copy() for i in range(4)]
34
+ gpu_rect = VGroup(*gpu_base).arrange(UP,buff=0)
35
+ gpu_text = Text("GPU", font_size=24)
36
+ gpu = Group(gpu_rect,gpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
37
+ gpu.move_to([-1,-1,0])
38
+ self.add(gpu)
39
+
40
+ model_base = [mem.copy() for i in range(6)]
41
+ model_rect = VGroup(*model_base).arrange(RIGHT,buff=0)
42
+
43
+ model_text = Text("Model", font_size=24)
44
+ model = Group(model_rect,model_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
45
+ model.move_to([3, -1., 0])
46
+ self.add(model)
47
+
48
+ model_arr = []
49
+ model_cpu_arr = []
50
+ model_meta_arr = []
51
+
52
+ for i,rect in enumerate(model_base):
53
+ rect.set_stroke(YELLOW)
54
+
55
+ cpu_target = Rectangle(height=0.46/4,width=0.46/3).set_stroke(width=0.).set_fill(YELLOW, opacity=0.7)
56
+
57
+ if i == 0:
58
+ cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN+LEFT), buff=0.02, direction=UP)
59
+ cpu_target.set_x(cpu_target.get_x()+0.1)
60
+ elif i == 3:
61
+ cpu_target.next_to(model_cpu_arr[0], direction=UP, buff=0.)
62
+ else:
63
+ cpu_target.next_to(model_cpu_arr[i-1], direction=RIGHT, buff=0.)
64
+ self.add(cpu_target)
65
+ model_cpu_arr.append(cpu_target)
66
+
67
+ self.add(*model_arr, *model_cpu_arr, *model_meta_arr)
68
+
69
+ checkpoint_base = [mem.copy() for i in range(6)]
70
+ checkpoint_rect = VGroup(*checkpoint_base).arrange(RIGHT,buff=0)
71
+
72
+ checkpoint_text = Text("Loaded Checkpoint", font_size=24)
73
+ checkpoint = Group(checkpoint_rect,checkpoint_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
74
+ checkpoint.move_to([3, .5, 0])
75
+
76
+ self.add(checkpoint)
77
+
78
+ ckpt_arr = []
79
+ ckpt_cpu_arr = []
80
+
81
+ for i,rect in enumerate(checkpoint_base):
82
+ target = fill.copy().set_fill(BLUE, opacity=0.7)
83
+ target.move_to(rect)
84
+ ckpt_arr.append(target)
85
+
86
+ cpu_target = target.copy()
87
+ if i < 5:
88
+ cpu_target.move_to(cpu_left_col_base[i+1])
89
+ else:
90
+ cpu_target.move_to(cpu_right_col_base[i-5])
91
+ ckpt_cpu_arr.append(cpu_target)
92
+ self.add(*ckpt_arr, *ckpt_cpu_arr)
93
+
94
+ key = Square(side_length=2.2)
95
+ key.move_to([-5, 2, 0])
96
+
97
+ key_text = MarkupText(
98
+ f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model",
99
+ font_size=18,
100
+ )
101
+
102
+ key_text.move_to([-5, 2.4, 0])
103
+
104
+ self.add(key_text, key)
105
+
106
+ blue_text = MarkupText(
107
+ f"<span fgcolor='{BLUE}'>●</span> Checkpoint",
108
+ font_size=18,
109
+ )
110
+
111
+ blue_text.next_to(key_text, DOWN*2.4, aligned_edge=key_text.get_left())
112
+ self.add(blue_text)
113
+
114
+ step_3 = MarkupText(
115
+ f'Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.',
116
+ font_size=24
117
+ )
118
+ step_3.move_to([2, 2, 0])
119
+
120
+ disk_left_col_base = [meta_mem.copy() for i in range(6)]
121
+ disk_right_col_base = [meta_mem.copy() for i in range(6)]
122
+ disk_left_col = VGroup(*disk_left_col_base).arrange(UP, buff=0)
123
+ disk_right_col = VGroup(*disk_right_col_base).arrange(UP, buff=0)
124
+ disk_rects = VGroup(disk_left_col,disk_right_col).arrange(RIGHT, buff=0)
125
+ disk_text = Text("Disk", font_size=24)
126
+ disk = Group(disk_rects,disk_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
127
+ disk.move_to([-4.,-1.25,0])
128
+ self.play(
129
+ Write(step_3, run_time=3),
130
+ Write(disk_text, run_time=1),
131
+ Create(disk_rects, run_time=1)
132
+ )
133
+
134
+ animations = []
135
+ for i,rect in enumerate(ckpt_cpu_arr):
136
+ target = rect.copy()
137
+ target.generate_target()
138
+ target.target.move_to(disk_left_col_base[i]).scale(0.5)
139
+ animations.append(MoveToTarget(target, run_time=1.5))
140
+ self.play(*animations)
141
+
142
+ self.play(FadeOut(step_3))
143
+
144
+ step_4 = MarkupText(
145
+ f'Then, the checkpoint is removed from memory\nthrough garbage collection.',
146
+ font_size=24
147
+ )
148
+ step_4.move_to([2, 2, 0])
149
+
150
+ self.play(
151
+ Write(step_4, run_time=3)
152
+ )
153
+
154
+ self.play(
155
+ FadeOut(checkpoint_rect, checkpoint_text, *ckpt_arr, *ckpt_cpu_arr),
156
+ )
157
+
158
+ self.wait()
tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_4.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 manim import *
16
+
17
+ class Stage4(Scene):
18
+ def construct(self):
19
+ mem = Rectangle(height=0.5,width=0.5)
20
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
21
+ meta_mem = Rectangle(height=0.25,width=0.25)
22
+
23
+ cpu_left_col_base = [mem.copy() for i in range(6)]
24
+ cpu_right_col_base = [mem.copy() for i in range(6)]
25
+ cpu_left_col = VGroup(*cpu_left_col_base).arrange(UP, buff=0)
26
+ cpu_right_col = VGroup(*cpu_right_col_base).arrange(UP, buff=0)
27
+ cpu_rects = VGroup(cpu_left_col,cpu_right_col).arrange(RIGHT, buff=0)
28
+ cpu_text = Text("CPU", font_size=24)
29
+ cpu = Group(cpu_rects,cpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
30
+ cpu.move_to([-2.5,-.5,0])
31
+ self.add(cpu)
32
+
33
+ gpu_base = [mem.copy() for i in range(4)]
34
+ gpu_rect = VGroup(*gpu_base).arrange(UP,buff=0)
35
+ gpu_text = Text("GPU", font_size=24)
36
+ gpu = Group(gpu_rect,gpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
37
+ gpu.move_to([-1,-1,0])
38
+ self.add(gpu)
39
+
40
+ model_base = [mem.copy() for i in range(6)]
41
+ model_rect = VGroup(*model_base).arrange(RIGHT,buff=0)
42
+
43
+ model_text = Text("Model", font_size=24)
44
+ model = Group(model_rect,model_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
45
+ model.move_to([3, -1., 0])
46
+ self.add(model)
47
+
48
+ model_cpu_arr = []
49
+ model_meta_arr = []
50
+
51
+ for i,rect in enumerate(model_base):
52
+ rect.set_stroke(YELLOW)
53
+
54
+ cpu_target = Rectangle(height=0.46/4,width=0.46/3).set_stroke(width=0.).set_fill(YELLOW, opacity=0.7)
55
+
56
+ if i == 0:
57
+ cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN+LEFT), buff=0.02, direction=UP)
58
+ cpu_target.set_x(cpu_target.get_x()+0.1)
59
+ elif i == 3:
60
+ cpu_target.next_to(model_cpu_arr[0], direction=UP, buff=0.)
61
+ else:
62
+ cpu_target.next_to(model_cpu_arr[i-1], direction=RIGHT, buff=0.)
63
+ self.add(cpu_target)
64
+ model_cpu_arr.append(cpu_target)
65
+
66
+ self.add(*model_cpu_arr, *model_meta_arr)
67
+
68
+ disk_left_col_base = [meta_mem.copy() for i in range(6)]
69
+ disk_right_col_base = [meta_mem.copy() for i in range(6)]
70
+ disk_left_col = VGroup(*disk_left_col_base).arrange(UP, buff=0)
71
+ disk_right_col = VGroup(*disk_right_col_base).arrange(UP, buff=0)
72
+ disk_rects = VGroup(disk_left_col,disk_right_col).arrange(RIGHT, buff=0)
73
+ disk_text = Text("Disk", font_size=24)
74
+ disk = Group(disk_rects,disk_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
75
+ disk.move_to([-4.,-1.25,0])
76
+ self.add(disk_text, disk_rects)
77
+
78
+ cpu_disk_arr = []
79
+
80
+ for i in range(6):
81
+ target = fill.copy().set_fill(BLUE, opacity=0.8)
82
+ target.move_to(disk_left_col_base[i]).scale(0.5)
83
+ cpu_disk_arr.append(target)
84
+
85
+ self.add(*cpu_disk_arr)
86
+
87
+ key = Square(side_length=2.2)
88
+ key.move_to([-5, 2, 0])
89
+
90
+ key_text = MarkupText(
91
+ f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model",
92
+ font_size=18,
93
+ )
94
+
95
+ key_text.move_to([-5, 2.4, 0])
96
+
97
+ self.add(key_text, key)
98
+
99
+ blue_text = MarkupText(
100
+ f"<span fgcolor='{BLUE}'>●</span> Checkpoint",
101
+ font_size=18,
102
+ )
103
+
104
+ blue_text.next_to(key_text, DOWN*2.4, aligned_edge=key_text.get_left())
105
+ self.add(blue_text)
106
+
107
+ step_5 = MarkupText(
108
+ f'The offloaded weights are all sent to the CPU.',
109
+ font_size=24
110
+ )
111
+ step_5.move_to([2, 2, 0])
112
+
113
+ self.play(Write(step_5, run_time=3))
114
+
115
+ for i in range(6):
116
+ rect = cpu_disk_arr[i]
117
+ cp2 = rect.copy().set_fill(BLUE, opacity=0.8).scale(2.0)
118
+ cp2.generate_target()
119
+ cp2.target.move_to(model_base[i])
120
+
121
+ if i == 0:
122
+ rect.set_fill(BLUE, opacity=0.8)
123
+ rect.generate_target()
124
+ rect.target.move_to(cpu_left_col_base[0]).scale(2.0)
125
+
126
+ self.remove(*model_meta_arr,
127
+ *model_cpu_arr,
128
+ )
129
+
130
+ else:
131
+ rect.generate_target()
132
+ rect.target.move_to(cpu_left_col_base[i]).scale(2.0)
133
+ self.play(
134
+ MoveToTarget(rect),
135
+ MoveToTarget(cp2),
136
+ model_base[i].animate.set_stroke(WHITE)
137
+ )
138
+ self.play(FadeOut(step_5))
139
+
140
+ step_5 = MarkupText(
141
+ f'Finally, hooks are added to each weight in the model\nto transfer the weights from CPU to GPU\n\t\tand back when needed.',
142
+ font_size=24
143
+ )
144
+ step_5.move_to([2, 2, 0])
145
+
146
+ self.play(Write(step_5, run_time=3))
147
+
148
+ arrows = []
149
+ animations = []
150
+ for i in range(6):
151
+ a = Arrow(start=UP, end=DOWN, color=RED, buff=.5)
152
+ a.next_to(model_base[i].get_left(), UP, buff=0.2)
153
+ arrows.append(a)
154
+ animations.append(Write(a))
155
+ self.play(*animations)
156
+ self.wait()
tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_5.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 manim import *
16
+
17
+ class Stage5(Scene):
18
+ def construct(self):
19
+ mem = Rectangle(height=0.5,width=0.5)
20
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
21
+
22
+ meta_mem = Rectangle(height=0.25,width=0.25)
23
+
24
+ cpu_left_col_base = [mem.copy() for i in range(6)]
25
+ cpu_right_col_base = [mem.copy() for i in range(6)]
26
+ cpu_left_col = VGroup(*cpu_left_col_base).arrange(UP, buff=0)
27
+ cpu_right_col = VGroup(*cpu_right_col_base).arrange(UP, buff=0)
28
+ cpu_rects = VGroup(cpu_left_col,cpu_right_col).arrange(RIGHT, buff=0)
29
+ cpu_text = Text("CPU", font_size=24)
30
+ cpu = Group(cpu_rects,cpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
31
+ cpu.move_to([-2.5,-.5,0])
32
+ self.add(cpu)
33
+
34
+ gpu_base = [mem.copy() for i in range(4)]
35
+ gpu_rect = VGroup(*gpu_base).arrange(UP,buff=0)
36
+ gpu_text = Text("GPU", font_size=24)
37
+ gpu = Group(gpu_rect,gpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
38
+ gpu.move_to([-1,-1,0])
39
+ self.add(gpu)
40
+
41
+ model_base = [mem.copy() for i in range(6)]
42
+ model_rect = VGroup(*model_base).arrange(RIGHT,buff=0)
43
+
44
+ model_text = Text("Model", font_size=24)
45
+ model = Group(model_rect,model_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
46
+ model.move_to([3, -1., 0])
47
+ self.add(model)
48
+
49
+ model_arr = []
50
+ model_cpu_arr = []
51
+
52
+ for i,rect in enumerate(model_base):
53
+ target = fill.copy().set_fill(BLUE, opacity=0.8)
54
+ target.move_to(rect)
55
+ model_arr.append(target)
56
+
57
+ cpu_target = Rectangle(height=0.46,width=0.46).set_stroke(width=0.).set_fill(BLUE, opacity=0.8)
58
+ cpu_target.move_to(cpu_left_col_base[i])
59
+ model_cpu_arr.append(cpu_target)
60
+
61
+ self.add(*model_arr, *model_cpu_arr)
62
+
63
+ disk_left_col_base = [meta_mem.copy() for i in range(6)]
64
+ disk_right_col_base = [meta_mem.copy() for i in range(6)]
65
+ disk_left_col = VGroup(*disk_left_col_base).arrange(UP, buff=0)
66
+ disk_right_col = VGroup(*disk_right_col_base).arrange(UP, buff=0)
67
+ disk_rects = VGroup(disk_left_col,disk_right_col).arrange(RIGHT, buff=0)
68
+ disk_text = Text("Disk", font_size=24)
69
+ disk = Group(disk_rects,disk_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
70
+ disk.move_to([-4,-1.25,0])
71
+ self.add(disk_text, disk_rects)
72
+
73
+ key = Square(side_length=2.2)
74
+ key.move_to([-5, 2, 0])
75
+
76
+ key_text = MarkupText(
77
+ f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model",
78
+ font_size=18,
79
+ )
80
+
81
+ key_text.move_to([-5, 2.4, 0])
82
+
83
+ self.add(key_text, key)
84
+
85
+ blue_text = MarkupText(
86
+ f"<span fgcolor='{BLUE}'>●</span> Checkpoint",
87
+ font_size=18,
88
+ )
89
+
90
+ blue_text.next_to(key_text, DOWN*2.4, aligned_edge=key_text.get_left())
91
+ self.add(blue_text)
92
+
93
+ step_6 = MarkupText(
94
+ f'Now watch as an input is passed through the model\nand how the memory is utilized and handled.',
95
+ font_size=24
96
+ )
97
+ step_6.move_to([2, 2, 0])
98
+
99
+ self.play(Write(step_6))
100
+
101
+ input = Square(0.3)
102
+ input.set_fill(RED, opacity=1.)
103
+ input.set_stroke(width=0.)
104
+ input.next_to(model_base[0], LEFT, buff=.5)
105
+
106
+ self.play(Write(input))
107
+
108
+ input.generate_target()
109
+ input.target.next_to(model_arr[0], direction=LEFT, buff=0.02)
110
+ self.play(MoveToTarget(input))
111
+
112
+ self.play(FadeOut(step_6))
113
+
114
+
115
+ a = Arrow(start=UP, end=DOWN, color=RED, buff=.5)
116
+ a.next_to(model_arr[0].get_left(), UP, buff=0.2)
117
+
118
+ model_cpu_arr[0].generate_target()
119
+ model_cpu_arr[0].target.move_to(gpu_rect[0])
120
+
121
+ step_7 = MarkupText(
122
+ f'As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.',
123
+ font_size=24
124
+ )
125
+ step_7.move_to([2, 2, 0])
126
+
127
+ self.play(Write(step_7, run_time=3))
128
+
129
+ circ_kwargs = {"run_time":1, "fade_in":True, "fade_out":True, "buff":0.02}
130
+
131
+ self.play(
132
+ Write(a),
133
+ Circumscribe(model_arr[0], color=ORANGE, **circ_kwargs),
134
+ Circumscribe(model_cpu_arr[0], color=ORANGE, **circ_kwargs),
135
+ Circumscribe(gpu_rect[0], color=ORANGE, **circ_kwargs),
136
+ )
137
+ self.play(
138
+ MoveToTarget(model_cpu_arr[0])
139
+ )
140
+
141
+ a_c = a.copy()
142
+ for i in range(6):
143
+ a_c.next_to(model_arr[i].get_right()+0.02, UP, buff=0.2)
144
+
145
+ input.generate_target()
146
+ input.target.move_to(model_arr[i].get_right()+0.02)
147
+
148
+ grp = AnimationGroup(
149
+ FadeOut(a, run_time=.5),
150
+ MoveToTarget(input, run_time=.5),
151
+ FadeIn(a_c, run_time=.5),
152
+ lag_ratio=0.2
153
+ )
154
+
155
+ self.play(grp)
156
+
157
+
158
+ model_cpu_arr[i].generate_target()
159
+ model_cpu_arr[i].target.move_to(cpu_left_col_base[i])
160
+
161
+
162
+ if i < 5:
163
+ model_cpu_arr[i+1].generate_target()
164
+ model_cpu_arr[i+1].target.move_to(gpu_rect[0])
165
+ if i >= 1:
166
+ circ_kwargs["run_time"] = .7
167
+
168
+ self.play(
169
+ Circumscribe(model_arr[i], **circ_kwargs),
170
+ Circumscribe(cpu_left_col_base[i], **circ_kwargs),
171
+ Circumscribe(cpu_left_col_base[i+1], color=ORANGE, **circ_kwargs),
172
+ Circumscribe(gpu_rect[0], color=ORANGE, **circ_kwargs),
173
+ Circumscribe(model_arr[i+1], color=ORANGE, **circ_kwargs),
174
+ )
175
+ if i < 1:
176
+ self.play(
177
+ MoveToTarget(model_cpu_arr[i]),
178
+ MoveToTarget(model_cpu_arr[i+1]),
179
+ )
180
+ else:
181
+ self.play(
182
+ MoveToTarget(model_cpu_arr[i], run_time=.7),
183
+ MoveToTarget(model_cpu_arr[i+1], run_time=.7),
184
+ )
185
+ else:
186
+ model_cpu_arr[i].generate_target()
187
+ model_cpu_arr[i].target.move_to(cpu_left_col_base[-1])
188
+ input.generate_target()
189
+ input.target.next_to(model_arr[-1].get_right(), RIGHT+0.02, buff=0.2)
190
+
191
+ self.play(
192
+ Circumscribe(model_arr[-1], color=ORANGE, **circ_kwargs),
193
+ Circumscribe(cpu_left_col_base[-1], color=ORANGE, **circ_kwargs),
194
+ Circumscribe(gpu_rect[0], color=ORANGE, **circ_kwargs),
195
+ )
196
+
197
+ self.play(
198
+ MoveToTarget(model_cpu_arr[i])
199
+ )
200
+
201
+ a = a_c
202
+ a_c = a_c.copy()
203
+
204
+ input.generate_target()
205
+ input.target.next_to(model_base[-1], RIGHT+0.02, buff=.5)
206
+ self.play(
207
+ FadeOut(step_7),
208
+ FadeOut(a, run_time=.5),
209
+ )
210
+
211
+ step_8 = MarkupText(
212
+ f'Inference on a model too large for GPU memory\nis successfully completed.', font_size=24
213
+ )
214
+ step_8.move_to([2, 2, 0])
215
+
216
+ self.play(
217
+ Write(step_8, run_time=3),
218
+ MoveToTarget(input)
219
+ )
220
+
221
+ self.wait()
tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_0.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 manim import *
16
+
17
+
18
+ class Stage0(Scene):
19
+ def construct(self):
20
+ mascot = ImageMobject("mascot_bookie.png")
21
+ mascot.scale(.35)
22
+ mascot.move_to([-3.75,-1,0])
23
+ text = Paragraph(
24
+ "Distributed Training,\nHugging Face Accelerate,\nand PyTorch DataLoaders\n\nHow do they all interact?",
25
+ font_size=36,
26
+ line_spacing=1,
27
+ alignment="center",
28
+ weight=BOLD,
29
+ )
30
+ text.move_to([1.75,.5,0])
31
+ self.add(mascot)
32
+ self.add(text)
tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_1.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 manim import *
16
+
17
+ class Stage01(Scene):
18
+ def construct(self):
19
+ mascot = ImageMobject("mascot_bookie.png")
20
+ mascot.scale(.35)
21
+ mascot.move_to([-3.75,-1,0])
22
+ text = Paragraph(
23
+ "Distributed Training,\nHugging Face Accelerate,\nand PyTorch DataLoaders\n\nHow do they all interact?",
24
+ font_size=36,
25
+ line_spacing=1,
26
+ alignment="center",
27
+ weight=BOLD,
28
+ )
29
+ text.move_to([1.75,.5,0])
30
+ self.add(mascot)
31
+ self.add(text)
tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_2.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 manim import *
16
+
17
+
18
+ class Stage2(Scene):
19
+ def construct(self):
20
+ # The dataset items
21
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
22
+ columns = [
23
+ VGroup(*[Rectangle(height=0.25,width=0.25,color="green") for i in range(8)]).arrange(RIGHT,buff=0)
24
+ for j in range(4)
25
+ ]
26
+ dataset_recs = VGroup(*columns).arrange(UP, buff=0)
27
+ dataset_text = Text("Dataset", font_size=24)
28
+ dataset = Group(dataset_recs,dataset_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
29
+ dataset.move_to([-2,0,0])
30
+ self.add(dataset)
31
+
32
+ code = Code(
33
+ code="dataloader = DataLoader(...)\nfor batch in dataloader():\n\t...",
34
+ tab_width=4,
35
+ background="window",
36
+ language="Python",
37
+ font="Monospace",
38
+ font_size=14,
39
+ corner_radius=.2,
40
+ insert_line_no=False,
41
+ line_spacing=.75,
42
+ style=Code.styles_list[1],
43
+ )
44
+ code.move_to([-3.5, 2.5, 0])
45
+ self.add(code)
46
+
47
+ # The dataloader itself
48
+ dataloader = Group(
49
+ Rectangle(color="red", height=2, width=2),
50
+ Text("DataLoader", font_size=24)
51
+ ).arrange(DOWN, buff=.5, aligned_edge=DOWN)
52
+
53
+ sampler = Group(
54
+ Rectangle(color="blue", height=1, width=1),
55
+ Text("Sampler", font_size=12)
56
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
57
+ dataloader.move_to([1, 0, 0])
58
+ sampler.move_to([.75,.25,0])
59
+ self.add(dataloader)
60
+ self.add(sampler)
61
+
62
+ gpu_1 = Group(
63
+ Rectangle(color="white", height=1, width=1),
64
+ Text("GPU 1", font_size=12)
65
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4, 2, 0])
66
+ gpu_2 = Group(
67
+ Rectangle(color="white", height=1, width=1),
68
+ Text("GPU 2", font_size=12)
69
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4, .5, 0])
70
+ gpu_3 = Group(
71
+ Rectangle(color="white", height=1, width=1),
72
+ Text("GPU 3", font_size=12)
73
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4, -1, 0])
74
+ gpu_4 = Group(
75
+ Rectangle(color="white", height=1, width=1),
76
+ Text("GPU 4", font_size=12)
77
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4, -2.5, 0])
78
+ gpus = [gpu_1[0], gpu_2[0], gpu_3[0], gpu_4[0]]
79
+ self.add(gpu_1, gpu_2, gpu_3, gpu_4)
80
+
81
+ # Animate their existence
82
+ self.play(
83
+ Create(gpu_1[0], run_time=0.5),
84
+ Create(gpu_2[0], run_time=0.5),
85
+ Create(gpu_3[0], run_time=0.5),
86
+ Create(gpu_4[0], run_time=0.5),
87
+ Create(dataset_recs, run_time=1),
88
+ Create(sampler[0], run_time=1),
89
+ Create(dataloader[0], run_time=1)
90
+ )
91
+
92
+ step_1 = MarkupText(
93
+ f"Without any special care, \nthe same data is sent though each sampler, \nand the same samples are spit out on each GPU",
94
+ font_size=18
95
+ )
96
+ step_1.move_to([0, -2.5, 0])
97
+ self.play(
98
+ Write(step_1, run_time=4),
99
+ )
100
+
101
+ first_animations = []
102
+ second_animations = []
103
+
104
+
105
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
106
+ current_color = colors[0]
107
+ buff = 0
108
+ lr_buff = .25
109
+ old_target = None
110
+ new_datasets = []
111
+ for i,data in enumerate(dataset_recs[-1]):
112
+ if i % 2 == 0:
113
+ # current_color = colors[i//2]
114
+ current_color = "BLUE_E"
115
+ dataset_target = Rectangle(height=0.46/2,width=0.46/2).set_stroke(width=0.).set_fill(current_color, opacity=0.7)
116
+ dataset_target.move_to(data)
117
+ dataset_target.generate_target()
118
+ aligned_edge = ORIGIN
119
+ if i % 2 == 0:
120
+ old_target = dataset_target.target
121
+ buff -= .25
122
+ aligned_edge = LEFT
123
+ dataset_target.target.next_to(
124
+ sampler, buff=buff, direction=UP,
125
+ aligned_edge=LEFT
126
+ )
127
+ else:
128
+ dataset_target.target.next_to(
129
+ old_target, direction=RIGHT, buff=0.01,
130
+ )
131
+ new_datasets.append(dataset_target)
132
+ first_animations.append(data.animate(run_time=0.5).set_stroke(current_color))
133
+ second_animations.append(MoveToTarget(dataset_target, run_time=1.5))
134
+ self.play(*first_animations)
135
+ self.play(*second_animations)
136
+ self.wait()
137
+
138
+ move_animation = []
139
+
140
+ for j,gpu in enumerate(gpus):
141
+ buff = 0
142
+ for i,data in enumerate(new_datasets):
143
+ if i % 2 == 0:
144
+ current_color = colors[i//2]
145
+ if j != 3:
146
+ data = data.copy()
147
+ data.generate_target()
148
+ aligned_edge = ORIGIN
149
+ if i % 2 == 0:
150
+ old_target = data.target
151
+ buff -= .25
152
+ aligned_edge = LEFT
153
+ data.target.next_to(
154
+ gpu, buff=buff, direction=UP,
155
+ aligned_edge=LEFT
156
+ )
157
+ else:
158
+ data.target.next_to(
159
+ old_target, direction=RIGHT, buff=0.01,
160
+ )
161
+ move_animation.append(MoveToTarget(data, run_time=1.5))
162
+
163
+
164
+ self.play(*move_animation)
165
+
166
+ self.remove(step_1)
167
+ step_2 = MarkupText(
168
+ f"This behavior is undesireable, because we want\neach GPU to see different data for efficient training.",
169
+ font_size=18
170
+ )
171
+ step_2.move_to([0, -2.5, 0])
172
+
173
+ self.play(
174
+ Write(step_2, run_time=2.5),
175
+ )
176
+ self.wait()
tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_3.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 manim import *
16
+
17
+ class Stage3(Scene):
18
+ def construct(self):
19
+ step_1 = MarkupText(
20
+ f"To combat this, Accelerate employs one of two different\nSampler wrapper methods depending on the scenario:",
21
+ font_size=24
22
+ )
23
+ step_1.move_to([0, 1.5, 0])
24
+ self.add(step_1)
25
+ step_2 = MarkupText(
26
+ f"1. Sharding the dataset before drawing:\n\t● <span fgcolor='{RED}'>IterableDatasetShard</span>\n\t● <span fgcolor='{RED}'>BatchSamplerShard</span>",
27
+ font_size=24,
28
+ ).next_to(step_1, direction=DOWN, aligned_edge=LEFT)
29
+ self.add(step_2)
30
+ step_3 = MarkupText(
31
+ f"\n\n2. Splitting the batch after drawing:\n\t● <span fgcolor='{BLUE}'>DataLoaderDispatcher</span>",
32
+ font_size=24,
33
+ ).next_to(step_2, direction=DOWN, aligned_edge=LEFT)
34
+ self.add(step_3)
tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_4.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 manim import *
16
+
17
+ class Stage4(Scene):
18
+ def construct(self):
19
+
20
+ step_1 = MarkupText(
21
+ f"To understand the next part fully, let's define two terms,\n<span fgcolor='{RED}'>`batch_size`</span> and <span fgcolor='{BLUE}'>`global_batch_size`</span>:",
22
+ font_size=18
23
+ )
24
+ step_1.move_to([0, 1.5, 0])
25
+ # <span fgcolor='{YELLOW}'>●</span>
26
+ step_2 = MarkupText(
27
+ f"\n\n● <span fgcolor='{RED}'>`batch_size`</span>: \n\tThis will be defined as the batch size seen on a given\n\t*individual* GPU",
28
+ font_size=18,
29
+ ).next_to(step_1, direction=DOWN, aligned_edge=LEFT)
30
+
31
+ step_3 = MarkupText(
32
+ f"\n\n● <span fgcolor='{BLUE}'>`global_batch_size`</span>:\n\tThis will be defined as the *total* number of\n\tdifferent items seen in the dataset, across all GPUs",
33
+ font_size=18,
34
+ ).next_to(step_2, direction=DOWN, aligned_edge=LEFT)
35
+
36
+ step_4 = MarkupText(
37
+ f"\n\nSo if we have a dataset of 64 items, 8 GPUs, \nand a `batch_size` of 8, each *step* will go through\nthe entire dataset one time as 8*8=64",
38
+ font_size=18,
39
+ ).next_to(step_3, direction=DOWN, aligned_edge=LEFT)
40
+ self.play(
41
+ Write(step_1, run_time=4),
42
+ )
43
+ self.play(
44
+ Write(step_2, run_time=4)
45
+ )
46
+ self.play(
47
+ Write(step_3, run_time=4)
48
+ )
49
+ self.play(
50
+ Write(step_4, run_time=6)
51
+ )
52
+ self.wait()
tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_5.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 manim import *
16
+
17
+ class Stage5(Scene):
18
+ def construct(self):
19
+ # The dataset items
20
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
21
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
22
+ columns = [
23
+ VGroup(*[Rectangle(height=0.25,width=0.25,color=colors[j]) for i in range(8)]).arrange(RIGHT,buff=0)
24
+ for j in range(4)
25
+ ]
26
+ dataset_recs = VGroup(*columns).arrange(UP, buff=0)
27
+ dataset_text = Text("Dataset", font_size=24)
28
+ dataset = Group(dataset_recs,dataset_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
29
+ dataset.move_to([-2,0,0])
30
+ self.add(dataset)
31
+ code = Code(
32
+ code="# We enable this by default\naccelerator = Accelerator()\ndataloader = DataLoader(...)\ndataloader = accelerator.prepare(dataloader)\nfor batch in dataloader:\n\t...",
33
+ tab_width=4,
34
+ background="window",
35
+ language="Python",
36
+ font="Monospace",
37
+ font_size=14,
38
+ corner_radius=.2,
39
+ insert_line_no=False,
40
+ line_spacing=.75,
41
+ style=Code.styles_list[1],
42
+ )
43
+ code.move_to([-3.5, 2.5, 0])
44
+ self.add(code)
45
+
46
+ # The dataloader itself
47
+
48
+ sampler_1 = Group(
49
+ Rectangle(color="blue", height=1, width=1),
50
+ Text("Sampler GPU 1", font_size=12)
51
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
52
+ sampler_2 = Group(
53
+ Rectangle(color="blue", height=1, width=1),
54
+ Text("Sampler GPU 2", font_size=12)
55
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
56
+ sampler_3 = Group(
57
+ Rectangle(color="blue", height=1, width=1),
58
+ Text("Sampler GPU 3", font_size=12)
59
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
60
+ sampler_4 = Group(
61
+ Rectangle(color="blue", height=1, width=1),
62
+ Text("Sampler GPU 4", font_size=12)
63
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
64
+ sampler_1.move_to([2,2,0])
65
+ sampler_2.move_to([2,.5,0])
66
+ sampler_3.move_to([2,-1.,0])
67
+ sampler_4.move_to([2,-2.5,0])
68
+ self.add(sampler_1, sampler_2, sampler_3, sampler_4)
69
+ samplers = [sampler_1[0], sampler_2[0], sampler_3[0], sampler_4[0]]
70
+
71
+ gpu_1 = Group(
72
+ Rectangle(color="white", height=1, width=1),
73
+ Text("Output GPU 1", font_size=12)
74
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, 2, 0])
75
+ gpu_2 = Group(
76
+ Rectangle(color="white", height=1, width=1),
77
+ Text("Output GPU 2", font_size=12)
78
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, .5, 0])
79
+ gpu_3 = Group(
80
+ Rectangle(color="white", height=1, width=1),
81
+ Text("Output GPU 3", font_size=12)
82
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -1, 0])
83
+ gpu_4 = Group(
84
+ Rectangle(color="white", height=1, width=1),
85
+ Text("Output GPU 4", font_size=12)
86
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -2.5, 0])
87
+ gpus = [gpu_1[0], gpu_2[0], gpu_3[0], gpu_4[0]]
88
+ self.add(gpu_1, gpu_2, gpu_3, gpu_4)
89
+
90
+ # Animate their existence
91
+ self.play(
92
+ Create(gpu_1[0], run_time=1),
93
+ Create(gpu_2[0], run_time=1),
94
+ Create(gpu_3[0], run_time=1),
95
+ Create(gpu_4[0], run_time=1),
96
+ Create(dataset_recs, run_time=1),
97
+ Create(sampler_1[0], run_time=1),
98
+ Create(sampler_2[0], run_time=1),
99
+ Create(sampler_3[0], run_time=1),
100
+ Create(sampler_4[0], run_time=1),
101
+ )
102
+
103
+ first_animations = []
104
+ second_animations = []
105
+
106
+
107
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
108
+ current_color = colors[0]
109
+ buff = 0
110
+ lr_buff = .25
111
+ old_target = None
112
+ new_datasets = []
113
+ for i,row_data in enumerate(dataset_recs):
114
+ new_row = []
115
+ current_color = colors[i]
116
+ if i == 0:
117
+ idx = -3
118
+ elif i == 1:
119
+ idx = -2
120
+ elif i == 2:
121
+ idx = -1
122
+ elif i == 3:
123
+ idx = 0
124
+ for j,indiv_data in enumerate(row_data):
125
+ dataset_target = Rectangle(height=0.46/2,width=0.46/2).set_stroke(width=0.).set_fill(current_color, opacity=0.7)
126
+ dataset_target.move_to(indiv_data)
127
+ dataset_target.generate_target()
128
+ aligned_edge = ORIGIN
129
+ if j % 8 == 0:
130
+ aligned_edge = LEFT
131
+ dataset_target.target.next_to(
132
+ samplers[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
133
+ )
134
+ dataset_target.target.set_x(dataset_target.target.get_x())
135
+ elif j % 4 == 0:
136
+ old_target = dataset_target.target
137
+ dataset_target.target.next_to(
138
+ samplers[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
139
+ )
140
+ dataset_target.target.set_x(dataset_target.target.get_x())
141
+ dataset_target.target.set_y(dataset_target.target.get_y()-.25)
142
+ else:
143
+ dataset_target.target.next_to(
144
+ old_target, direction=RIGHT, buff=0.02,
145
+ )
146
+ old_target = dataset_target.target
147
+ new_row.append(dataset_target)
148
+ first_animations.append(indiv_data.animate(run_time=0.5).set_stroke(current_color))
149
+ second_animations.append(MoveToTarget(dataset_target, run_time=1.5))
150
+
151
+ new_datasets.append(new_row)
152
+ step_1 = MarkupText(
153
+ f"Since we splice the dataset between each GPU,\nthe models weights can be averaged during `backward()`\nActing as though we did one giant epoch\nvery quickly.",
154
+ font_size=18
155
+ )
156
+ step_1.move_to([-2.5, -2, 0])
157
+
158
+ self.play(
159
+ Write(step_1, run_time=3),
160
+ )
161
+ self.play(
162
+ *first_animations,
163
+ )
164
+ self.play(*second_animations)
165
+ self.wait(duration=.5)
166
+
167
+ move_animation = []
168
+ import random
169
+ for i,row in enumerate(new_datasets):
170
+ # row = [row[k] for k in random.sample(range(8), 8)]
171
+ current_color = colors[i]
172
+ if i == 0:
173
+ idx = -3
174
+ elif i == 1:
175
+ idx = -2
176
+ elif i == 2:
177
+ idx = -1
178
+ elif i == 3:
179
+ idx = 0
180
+ for j,indiv_data in enumerate(row):
181
+ indiv_data.generate_target()
182
+ aligned_edge = ORIGIN
183
+ if j % 8 == 0:
184
+ aligned_edge = LEFT
185
+ indiv_data.target.next_to(
186
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
187
+ )
188
+ indiv_data.target.set_x(indiv_data.target.get_x())
189
+ elif j % 4 == 0:
190
+ indiv_data.target.next_to(
191
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
192
+ )
193
+ indiv_data.target.set_x(indiv_data.target.get_x())
194
+ indiv_data.target.set_y(indiv_data.target.get_y()-.25)
195
+ else:
196
+ indiv_data.target.next_to(
197
+ old_target, direction=RIGHT, buff=0.02,
198
+ )
199
+ old_target = indiv_data.target
200
+ move_animation.append(MoveToTarget(indiv_data, run_time=1.5))
201
+
202
+ self.play(*move_animation)
203
+ self.wait()
tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_6.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 manim import *
16
+
17
+
18
+ class Stage6(Scene):
19
+ def construct(self):
20
+ # The dataset items
21
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
22
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
23
+ columns = [
24
+ VGroup(*[Rectangle(height=0.25,width=0.25,color=colors[j]) for i in range(8)]).arrange(RIGHT,buff=0)
25
+ for j in range(4)
26
+ ]
27
+ dataset_recs = VGroup(*columns).arrange(UP, buff=0)
28
+ dataset_text = Text("Dataset", font_size=24)
29
+ dataset = Group(dataset_recs,dataset_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
30
+ dataset.move_to([-2,0,0])
31
+ self.add(dataset)
32
+ code = Code(
33
+ code="# We enable this by default\naccelerator = Accelerator()\ndataloader = DataLoader(..., shuffle=True)\ndataloader = accelerator.prepare(dataloader)\nfor batch in dataloader:\n\t...",
34
+ tab_width=4,
35
+ background="window",
36
+ language="Python",
37
+ font="Monospace",
38
+ font_size=14,
39
+ corner_radius=.2,
40
+ insert_line_no=False,
41
+ line_spacing=.75,
42
+ style=Code.styles_list[1],
43
+ )
44
+ code.move_to([-3.5, 2.5, 0])
45
+ self.add(code)
46
+
47
+ # The dataloader itself
48
+
49
+ sampler_1 = Group(
50
+ Rectangle(color="blue", height=1, width=1),
51
+ Text("Sampler GPU 1", font_size=12)
52
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
53
+ sampler_2 = Group(
54
+ Rectangle(color="blue", height=1, width=1),
55
+ Text("Sampler GPU 2", font_size=12)
56
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
57
+ sampler_3 = Group(
58
+ Rectangle(color="blue", height=1, width=1),
59
+ Text("Sampler GPU 3", font_size=12)
60
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
61
+ sampler_4 = Group(
62
+ Rectangle(color="blue", height=1, width=1),
63
+ Text("Sampler GPU 4", font_size=12)
64
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
65
+ sampler_1.move_to([2,2,0])
66
+ sampler_2.move_to([2,.5,0])
67
+ sampler_3.move_to([2,-1.,0])
68
+ sampler_4.move_to([2,-2.5,0])
69
+ self.add(sampler_1, sampler_2, sampler_3, sampler_4)
70
+ samplers = [sampler_1[0], sampler_2[0], sampler_3[0], sampler_4[0]]
71
+
72
+ gpu_1 = Group(
73
+ Rectangle(color="white", height=1, width=1),
74
+ Text("Output GPU 1", font_size=12)
75
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, 2, 0])
76
+ gpu_2 = Group(
77
+ Rectangle(color="white", height=1, width=1),
78
+ Text("Output GPU 2", font_size=12)
79
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, .5, 0])
80
+ gpu_3 = Group(
81
+ Rectangle(color="white", height=1, width=1),
82
+ Text("Output GPU 3", font_size=12)
83
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -1, 0])
84
+ gpu_4 = Group(
85
+ Rectangle(color="white", height=1, width=1),
86
+ Text("Output GPU 4", font_size=12)
87
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -2.5, 0])
88
+ gpus = [gpu_1[0], gpu_2[0], gpu_3[0], gpu_4[0]]
89
+ self.add(gpu_1, gpu_2, gpu_3, gpu_4)
90
+
91
+
92
+ first_animations = []
93
+ second_animations = []
94
+
95
+
96
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
97
+ current_color = colors[0]
98
+ buff = 0
99
+ lr_buff = .25
100
+ old_target = None
101
+ new_datasets = []
102
+ for i,row_data in enumerate(dataset_recs):
103
+ new_row = []
104
+ current_color = colors[i]
105
+ if i == 0:
106
+ idx = -3
107
+ elif i == 1:
108
+ idx = -2
109
+ elif i == 2:
110
+ idx = -1
111
+ elif i == 3:
112
+ idx = 0
113
+ for j,indiv_data in enumerate(row_data):
114
+ dataset_target = Rectangle(height=0.46/2,width=0.46/2).set_stroke(width=0.).set_fill(current_color, opacity=0.7)
115
+ dataset_target.move_to(indiv_data)
116
+ dataset_target.generate_target()
117
+ aligned_edge = ORIGIN
118
+ if j % 8 == 0:
119
+ aligned_edge = LEFT
120
+ old_target = dataset_target.target
121
+ dataset_target.target.next_to(
122
+ samplers[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
123
+ )
124
+ dataset_target.target.set_x(dataset_target.target.get_x())
125
+ elif j % 4 == 0:
126
+ old_target = dataset_target.target
127
+ dataset_target.target.next_to(
128
+ samplers[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
129
+ )
130
+ dataset_target.target.set_x(dataset_target.target.get_x())
131
+ dataset_target.target.set_y(dataset_target.target.get_y()-.25)
132
+ else:
133
+ dataset_target.target.next_to(
134
+ old_target, direction=RIGHT, buff=0.02,
135
+ )
136
+ old_target = dataset_target.target
137
+ new_row.append(dataset_target)
138
+ first_animations.append(indiv_data.animate(run_time=0.5).set_stroke(current_color))
139
+ second_animations.append(MoveToTarget(dataset_target, run_time=1.5))
140
+
141
+ new_datasets.append(new_row)
142
+ step_1 = MarkupText(
143
+ f"During shuffling, each mini-batch's\noutput order will be modified",
144
+ font_size=18
145
+ )
146
+ step_1.move_to([-1.5, -2, 0])
147
+
148
+ self.play(
149
+ Write(step_1, run_time=3),
150
+ )
151
+ self.play(
152
+ *first_animations,
153
+ )
154
+ self.play(*second_animations)
155
+ self.wait(duration=.5)
156
+
157
+ move_animation = []
158
+ import random
159
+ for i,row in enumerate(new_datasets):
160
+ row = [row[k] for k in random.sample(range(8), 8)]
161
+ current_color = colors[i]
162
+ if i == 0:
163
+ idx = -3
164
+ elif i == 1:
165
+ idx = -2
166
+ elif i == 2:
167
+ idx = -1
168
+ elif i == 3:
169
+ idx = 0
170
+ for j,indiv_data in enumerate(row):
171
+ indiv_data.generate_target()
172
+ aligned_edge = ORIGIN
173
+ if j % 8 == 0:
174
+ aligned_edge = LEFT
175
+ indiv_data.target.next_to(
176
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
177
+ )
178
+ indiv_data.target.set_x(indiv_data.target.get_x())
179
+ elif j % 4 == 0:
180
+ indiv_data.target.next_to(
181
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
182
+ )
183
+ indiv_data.target.set_x(indiv_data.target.get_x())
184
+ indiv_data.target.set_y(indiv_data.target.get_y()-.25)
185
+ else:
186
+ indiv_data.target.next_to(
187
+ old_target, direction=RIGHT, buff=0.02,
188
+ )
189
+ old_target = indiv_data.target
190
+ move_animation.append(MoveToTarget(indiv_data, run_time=1.5))
191
+
192
+ self.play(*move_animation)
193
+ self.wait()
tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_7.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 manim import *
16
+
17
+ class Stage7(Scene):
18
+ def construct(self):
19
+ # The dataset items
20
+ code = Code(
21
+ code="accelerator = Accelerator(dispatch_batches=True)\ndataloader = DataLoader(...)\ndataloader = accelerator.prepare(dataloader)\nfor batch in dataloader:\n\t...",
22
+ tab_width=4,
23
+ background="window",
24
+ language="Python",
25
+ font="Monospace",
26
+ font_size=14,
27
+ corner_radius=.2,
28
+ insert_line_no=False,
29
+ line_spacing=.75,
30
+ style=Code.styles_list[1],
31
+ )
32
+ code.move_to([-3.5, 2.5, 0])
33
+ self.add(code)
34
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
35
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
36
+ columns = [
37
+ VGroup(*[Rectangle(height=0.25,width=0.25,color=colors[j]) for i in range(8)]).arrange(RIGHT,buff=0)
38
+ for j in range(4)
39
+ ]
40
+ dataset_recs = VGroup(*columns).arrange(UP, buff=0)
41
+ dataset_text = Text("Dataset", font_size=24)
42
+ dataset = Group(dataset_recs,dataset_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
43
+ dataset.move_to([-2,0,0])
44
+ self.add(dataset)
45
+
46
+ # The dataloader itself
47
+
48
+ sampler_1 = Group(
49
+ Rectangle(color="blue", height=1.02, width=1.02),
50
+ Text("Sampler GPU 1", font_size=12)
51
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
52
+ sampler_2 = Group(
53
+ Rectangle(color="blue", height=1.02, width=1.02),
54
+ Text("Sampler GPU 2", font_size=12)
55
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
56
+ sampler_3 = Group(
57
+ Rectangle(color="blue", height=1.02, width=1.02),
58
+ Text("Sampler GPU 3", font_size=12)
59
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
60
+ sampler_4 = Group(
61
+ Rectangle(color="blue", height=1.02, width=1.02),
62
+ Text("Sampler GPU 4", font_size=12)
63
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
64
+ sampler_1.move_to([2,2,0])
65
+ sampler_2.move_to([2,.5,0])
66
+ sampler_3.move_to([2,-1.,0])
67
+ sampler_4.move_to([2,-2.5,0])
68
+ self.add(sampler_1, sampler_2, sampler_3, sampler_4)
69
+ samplers = [sampler_1[0], sampler_2[0], sampler_3[0], sampler_4[0]]
70
+
71
+ gpu_1 = Group(
72
+ Rectangle(color="white", height=1.02, width=.98),
73
+ Text("Output GPU 1", font_size=12)
74
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, 2, 0])
75
+ gpu_2 = Group(
76
+ Rectangle(color="white", height=1.02, width=.98),
77
+ Text("Output GPU 2", font_size=12)
78
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, .5, 0])
79
+ gpu_3 = Group(
80
+ Rectangle(color="white", height=1.02, width=.98),
81
+ Text("Output GPU 3", font_size=12)
82
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -1, 0])
83
+ gpu_4 = Group(
84
+ Rectangle(color="white", height=1.02, width=.98),
85
+ Text("Output GPU 4", font_size=12)
86
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -2.5, 0])
87
+ gpus = [gpu_1[0], gpu_2[0], gpu_3[0], gpu_4[0]]
88
+ self.add(gpu_1, gpu_2, gpu_3, gpu_4)
89
+
90
+ step_1 = MarkupText(
91
+ f"When using a `DataLoaderDispatcher`, all\nof the samples are collected from GPU 0's dataset,\nthen divided and sent to each GPU.\nAs a result, this will be slower.",
92
+ font_size=18
93
+ )
94
+ step_1.move_to([-2.5, -2, 0])
95
+
96
+ self.play(
97
+ Write(step_1, run_time=3.5),
98
+ )
99
+
100
+ first_animations = []
101
+ second_animations = []
102
+
103
+
104
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
105
+ current_color = colors[0]
106
+ ud_buff = 0.01
107
+ lr_buff = 0.01
108
+ old_target = None
109
+ new_datasets = []
110
+ for i,row_data in enumerate(dataset_recs):
111
+ new_row = []
112
+ current_color = colors[i]
113
+
114
+ for j,indiv_data in enumerate(row_data):
115
+ dataset_target = Rectangle(height=0.46/4,width=0.46/2).set_stroke(width=0.).set_fill(current_color, opacity=0.7)
116
+ dataset_target.move_to(indiv_data)
117
+ dataset_target.generate_target()
118
+ aligned_edge = ORIGIN
119
+ if j % 8 == 0:
120
+ aligned_edge = LEFT
121
+ dataset_target.target.next_to(
122
+ samplers[0].get_corner(DOWN+LEFT), buff=0.0125, direction=RIGHT+UP,
123
+ )
124
+ dataset_target.target.set_x(dataset_target.target.get_x())
125
+ dataset_target.target.set_y(dataset_target.target.get_y() + (.25 * i))
126
+ elif j % 4 == 0:
127
+ old_target = dataset_target.target
128
+ dataset_target.target.next_to(
129
+ samplers[0].get_corner(DOWN+LEFT), buff=0.0125, direction=RIGHT+UP,
130
+ )
131
+ dataset_target.target.set_x(dataset_target.target.get_x())
132
+ dataset_target.target.set_y(dataset_target.target.get_y()+.125 + (.25 * i))
133
+ else:
134
+ dataset_target.target.next_to(
135
+ old_target, direction=RIGHT, buff=0.0125,
136
+ )
137
+ old_target = dataset_target.target
138
+ new_row.append(dataset_target)
139
+ first_animations.append(indiv_data.animate(run_time=0.5).set_stroke(current_color))
140
+ second_animations.append(MoveToTarget(dataset_target, run_time=1.5))
141
+
142
+ new_datasets.append(new_row)
143
+ self.play(
144
+ *first_animations,
145
+ )
146
+ self.play(*second_animations)
147
+ move_animation = []
148
+ for i,row in enumerate(new_datasets):
149
+ current_color = colors[i]
150
+ if i == 0:
151
+ idx = -3
152
+ elif i == 1:
153
+ idx = -2
154
+ elif i == 2:
155
+ idx = -1
156
+ elif i == 3:
157
+ idx = 0
158
+ for j,indiv_data in enumerate(row):
159
+ indiv_data.generate_target()
160
+ indiv_data.animate.stretch_to_fit_height(0.46/2)
161
+ aligned_edge = ORIGIN
162
+ if j % 8 == 0:
163
+ aligned_edge = LEFT
164
+ indiv_data.target.next_to(
165
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.01, direction=RIGHT+DOWN,
166
+ )
167
+ indiv_data.target.set_x(indiv_data.target.get_x())
168
+ indiv_data.target.set_y(indiv_data.target.get_y()-.25)
169
+ elif j % 4 == 0:
170
+ indiv_data.target.next_to(
171
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.01, direction=RIGHT+DOWN,
172
+ )
173
+ indiv_data.target.set_x(indiv_data.target.get_x())
174
+ else:
175
+ indiv_data.target.next_to(
176
+ old_target, direction=RIGHT, buff=0.01,
177
+ )
178
+ old_target = indiv_data.target
179
+ move_animation.append(MoveToTarget(indiv_data, run_time=1.5))
180
+
181
+ self.play(*move_animation)
182
+ self.wait()
tasks/tasksmith-5db757e91a6e/tests/source/pyproject.toml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.ruff]
2
+ line-length = 119
3
+ target-version = "py38"
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-5db757e91a6e/tests/source/setup.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.6.4",
23
+ ]
24
+ extras["docs"] = []
25
+ extras["test_prod"] = ["pytest>=7.2.0,<=8.0.0", "pytest-xdist", "pytest-subtests", "parameterized"]
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_trackers"] = ["wandb", "comet-ml", "tensorboard", "dvclive"]
44
+ extras["dev"] = extras["quality"] + extras["testing"] + extras["rich"]
45
+
46
+ extras["sagemaker"] = [
47
+ "sagemaker", # boto3 is a required package in sagemaker
48
+ ]
49
+
50
+ setup(
51
+ name="accelerate",
52
+ version="0.35.0.dev0",
53
+ description="Accelerate",
54
+ long_description=open("README.md", encoding="utf-8").read(),
55
+ long_description_content_type="text/markdown",
56
+ keywords="deep learning",
57
+ license="Apache",
58
+ author="The HuggingFace team",
59
+ author_email="zach.mueller@huggingface.co",
60
+ url="https://github.com/huggingface/accelerate",
61
+ package_dir={"": "src"},
62
+ packages=find_packages("src"),
63
+ entry_points={
64
+ "console_scripts": [
65
+ "accelerate=accelerate.commands.accelerate_cli:main",
66
+ "accelerate-config=accelerate.commands.config:main",
67
+ "accelerate-estimate-memory=accelerate.commands.estimate:main",
68
+ "accelerate-launch=accelerate.commands.launch:main",
69
+ "accelerate-merge-weights=accelerate.commands.merge:main",
70
+ ]
71
+ },
72
+ python_requires=">=3.8.0",
73
+ install_requires=[
74
+ "numpy>=1.17,<3.0.0",
75
+ "packaging>=20.0",
76
+ "psutil",
77
+ "pyyaml",
78
+ "torch>=1.10.0",
79
+ "huggingface_hub>=0.21.0",
80
+ "safetensors>=0.4.3",
81
+ ],
82
+ extras_require=extras,
83
+ classifiers=[
84
+ "Development Status :: 5 - Production/Stable",
85
+ "Intended Audience :: Developers",
86
+ "Intended Audience :: Education",
87
+ "Intended Audience :: Science/Research",
88
+ "License :: OSI Approved :: Apache Software License",
89
+ "Operating System :: OS Independent",
90
+ "Programming Language :: Python :: 3",
91
+ "Programming Language :: Python :: 3.8",
92
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
93
+ ],
94
+ )
95
+
96
+ # Release checklist
97
+ # 1. Checkout the release branch (for a patch the current release branch, for a new minor version, create one):
98
+ # git checkout -b vXX.xx-release
99
+ # The -b is only necessary for creation (so remove it when doing a patch)
100
+ # 2. Change the version in __init__.py and setup.py to the proper value.
101
+ # 3. Commit these changes with the message: "Release: v<VERSION>"
102
+ # 4. Add a tag in git to mark the release:
103
+ # git tag v<VERSION> -m 'Adds tag v<VERSION> for pypi'
104
+ # Push the tag and release commit to git: git push --tags origin vXX.xx-release
105
+ # 5. Run the following commands in the top-level directory:
106
+ # rm -rf dist
107
+ # rm -rf build
108
+ # python setup.py bdist_wheel
109
+ # python setup.py sdist
110
+ # 6. Upload the package to the pypi test server first:
111
+ # twine upload dist/* -r testpypi
112
+ # 7. Check that you can install it in a virtualenv by running:
113
+ # pip install accelerate
114
+ # pip uninstall accelerate
115
+ # pip install -i https://testpypi.python.org/pypi accelerate
116
+ # accelerate env
117
+ # accelerate test
118
+ # 8. Upload the final version to actual pypi:
119
+ # twine upload dist/* -r pypi
120
+ # 9. Add release notes to the tag in github once everything is looking hunky-dory.
121
+ # 10. Go back to the main branch and update the version in __init__.py, setup.py to the new version ".dev" and push to
122
+ # main.
tasks/tasksmith-5db757e91a6e/tests/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__ = "0.35.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-5db757e91a6e/tests/source/src/accelerate/accelerator.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/big_modeling.py ADDED
@@ -0,0 +1,633 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from contextlib import contextmanager
18
+ from functools import wraps
19
+ from typing import Dict, List, Optional, Union
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+
24
+ from .hooks import (
25
+ AlignDevicesHook,
26
+ CpuOffload,
27
+ UserCpuOffloadHook,
28
+ add_hook_to_module,
29
+ attach_align_device_hook,
30
+ attach_align_device_hook_on_blocks,
31
+ )
32
+ from .utils import (
33
+ OffloadedWeightsLoader,
34
+ check_cuda_p2p_ib_support,
35
+ check_device_map,
36
+ extract_submodules_state_dict,
37
+ find_tied_parameters,
38
+ get_balanced_memory,
39
+ infer_auto_device_map,
40
+ is_mlu_available,
41
+ is_musa_available,
42
+ is_npu_available,
43
+ is_torch_version,
44
+ is_xpu_available,
45
+ load_checkpoint_in_model,
46
+ offload_state_dict,
47
+ parse_flag_from_env,
48
+ retie_parameters,
49
+ )
50
+ from .utils.other import recursive_getattr
51
+
52
+
53
+ logger = logging.getLogger(__name__)
54
+
55
+
56
+ @contextmanager
57
+ def init_empty_weights(include_buffers: bool = None):
58
+ """
59
+ A context manager under which models are initialized with all parameters on the meta device, therefore creating an
60
+ empty model. Useful when just initializing the model would blow the available RAM.
61
+
62
+ Args:
63
+ include_buffers (`bool`, *optional*):
64
+ Whether or not to also put all buffers on the meta device while initializing.
65
+
66
+ Example:
67
+
68
+ ```python
69
+ import torch.nn as nn
70
+ from accelerate import init_empty_weights
71
+
72
+ # Initialize a model with 100 billions parameters in no time and without using any RAM.
73
+ with init_empty_weights():
74
+ tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
75
+ ```
76
+
77
+ <Tip warning={true}>
78
+
79
+ Any model created under this context manager has no weights. As such you can't do something like
80
+ `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
81
+ Make sure to overwrite the default device_map param for [`load_checkpoint_and_dispatch`], otherwise dispatch is not
82
+ called.
83
+
84
+ </Tip>
85
+ """
86
+ if include_buffers is None:
87
+ include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False)
88
+ with init_on_device(torch.device("meta"), include_buffers=include_buffers) as f:
89
+ yield f
90
+
91
+
92
+ @contextmanager
93
+ def init_on_device(device: torch.device, include_buffers: bool = None):
94
+ """
95
+ A context manager under which models are initialized with all parameters on the specified device.
96
+
97
+ Args:
98
+ device (`torch.device`):
99
+ Device to initialize all parameters on.
100
+ include_buffers (`bool`, *optional*):
101
+ Whether or not to also put all buffers on the meta device while initializing.
102
+
103
+ Example:
104
+
105
+ ```python
106
+ import torch.nn as nn
107
+ from accelerate import init_on_device
108
+
109
+ with init_on_device(device=torch.device("cuda")):
110
+ tst = nn.Liner(100, 100) # on `cuda` device
111
+ ```
112
+ """
113
+ if include_buffers is None:
114
+ include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False)
115
+
116
+ # TODO(shingjan): remove the torch version check once older versions are deprecated
117
+ if is_torch_version(">=", "2.0") and include_buffers:
118
+ with device:
119
+ yield
120
+ return
121
+
122
+ old_register_parameter = nn.Module.register_parameter
123
+ if include_buffers:
124
+ old_register_buffer = nn.Module.register_buffer
125
+
126
+ def register_empty_parameter(module, name, param):
127
+ old_register_parameter(module, name, param)
128
+ if param is not None:
129
+ param_cls = type(module._parameters[name])
130
+ kwargs = module._parameters[name].__dict__
131
+ kwargs["requires_grad"] = param.requires_grad
132
+ module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
133
+
134
+ def register_empty_buffer(module, name, buffer, persistent=True):
135
+ old_register_buffer(module, name, buffer, persistent=persistent)
136
+ if buffer is not None:
137
+ module._buffers[name] = module._buffers[name].to(device)
138
+
139
+ # Patch tensor creation
140
+ if include_buffers:
141
+ tensor_constructors_to_patch = {
142
+ torch_function_name: getattr(torch, torch_function_name)
143
+ for torch_function_name in ["empty", "zeros", "ones", "full"]
144
+ }
145
+ else:
146
+ tensor_constructors_to_patch = {}
147
+
148
+ def patch_tensor_constructor(fn):
149
+ def wrapper(*args, **kwargs):
150
+ kwargs["device"] = device
151
+ return fn(*args, **kwargs)
152
+
153
+ return wrapper
154
+
155
+ try:
156
+ nn.Module.register_parameter = register_empty_parameter
157
+ if include_buffers:
158
+ nn.Module.register_buffer = register_empty_buffer
159
+ for torch_function_name in tensor_constructors_to_patch.keys():
160
+ setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
161
+ yield
162
+ finally:
163
+ nn.Module.register_parameter = old_register_parameter
164
+ if include_buffers:
165
+ nn.Module.register_buffer = old_register_buffer
166
+ for torch_function_name, old_torch_function in tensor_constructors_to_patch.items():
167
+ setattr(torch, torch_function_name, old_torch_function)
168
+
169
+
170
+ def cpu_offload(
171
+ model: nn.Module,
172
+ execution_device: Optional[torch.device] = None,
173
+ offload_buffers: bool = False,
174
+ state_dict: Optional[Dict[str, torch.Tensor]] = None,
175
+ preload_module_classes: Optional[List[str]] = None,
176
+ ):
177
+ """
178
+ Activates full CPU offload for a model. As a result, all parameters of the model will be offloaded and only one
179
+ copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that
180
+ state dict and put on the execution device passed as they are needed, then offloaded again.
181
+
182
+ Args:
183
+ model (`torch.nn.Module`):
184
+ The model to offload.
185
+ execution_device (`torch.device`, *optional*):
186
+ The device on which the forward pass of the model will be executed (should be a GPU). Will default to the
187
+ model first parameter device.
188
+ offload_buffers (`bool`, *optional*, defaults to `False`):
189
+ Whether or not to offload the buffers with the model parameters.
190
+ state_dict (`Dict[str, torch.Tensor]`, *optional*):
191
+ The state dict of the model that will be kept on CPU.
192
+ preload_module_classes (`List[str]`, *optional*):
193
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
194
+ of the forward. This should only be used for classes that have submodules which are registered but not
195
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
196
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
197
+ """
198
+ if execution_device is None:
199
+ execution_device = next(iter(model.parameters())).device
200
+ if state_dict is None:
201
+ state_dict = {n: p.to("cpu") for n, p in model.state_dict().items()}
202
+
203
+ add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True)
204
+ attach_align_device_hook(
205
+ model,
206
+ execution_device=execution_device,
207
+ offload=True,
208
+ offload_buffers=offload_buffers,
209
+ weights_map=state_dict,
210
+ preload_module_classes=preload_module_classes,
211
+ )
212
+
213
+ return model
214
+
215
+
216
+ def cpu_offload_with_hook(
217
+ model: torch.nn.Module,
218
+ execution_device: Optional[Union[int, str, torch.device]] = None,
219
+ prev_module_hook: Optional[UserCpuOffloadHook] = None,
220
+ ):
221
+ """
222
+ Offloads a model on the CPU and puts it back to an execution device when executed. The difference with
223
+ [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when
224
+ the `offload` method of the returned `hook` is called. Useful for pipelines running a model in a loop.
225
+
226
+ Args:
227
+ model (`torch.nn.Module`):
228
+ The model to offload.
229
+ execution_device(`str`, `int` or `torch.device`, *optional*):
230
+ The device on which the model should be executed. Will default to the MPS device if it's available, then
231
+ GPU 0 if there is a GPU, and finally to the CPU.
232
+ prev_module_hook (`UserCpuOffloadHook`, *optional*):
233
+ The hook sent back by this function for a previous model in the pipeline you are running. If passed, its
234
+ offload method will be called just before the forward of the model to which this hook is attached.
235
+
236
+ Example:
237
+
238
+ ```py
239
+ model_1, hook_1 = cpu_offload_with_hook(model_1, cuda_device)
240
+ model_2, hook_2 = cpu_offload_with_hook(model_2, cuda_device, prev_module_hook=hook_1)
241
+ model_3, hook_3 = cpu_offload_with_hook(model_3, cuda_device, prev_module_hook=hook_2)
242
+
243
+ hid_1 = model_1(input)
244
+ for i in range(50):
245
+ # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop.
246
+ hid_2 = model_2(hid_1)
247
+ # model2 is offloaded to the CPU just before this forward.
248
+ hid_3 = model_3(hid_3)
249
+
250
+ # For model3, you need to manually call the hook offload method.
251
+ hook_3.offload()
252
+ ```
253
+ """
254
+ hook = CpuOffload(execution_device=execution_device, prev_module_hook=prev_module_hook)
255
+ add_hook_to_module(model, hook, append=True)
256
+ user_hook = UserCpuOffloadHook(model, hook)
257
+ return model, user_hook
258
+
259
+
260
+ def disk_offload(
261
+ model: nn.Module,
262
+ offload_dir: Union[str, os.PathLike],
263
+ execution_device: Optional[torch.device] = None,
264
+ offload_buffers: bool = False,
265
+ preload_module_classes: Optional[List[str]] = None,
266
+ ):
267
+ """
268
+ Activates full disk offload for a model. As a result, all parameters of the model will be offloaded as
269
+ memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and
270
+ put on the execution device passed as they are needed, then offloaded again.
271
+
272
+ Args:
273
+ model (`torch.nn.Module`): The model to offload.
274
+ offload_dir (`str` or `os.PathLike`):
275
+ The folder in which to offload the model weights (or where the model weights are already offloaded).
276
+ execution_device (`torch.device`, *optional*):
277
+ The device on which the forward pass of the model will be executed (should be a GPU). Will default to the
278
+ model's first parameter device.
279
+ offload_buffers (`bool`, *optional*, defaults to `False`):
280
+ Whether or not to offload the buffers with the model parameters.
281
+ preload_module_classes (`List[str]`, *optional*):
282
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
283
+ of the forward. This should only be used for classes that have submodules which are registered but not
284
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
285
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
286
+ """
287
+ if not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")):
288
+ offload_state_dict(offload_dir, model.state_dict())
289
+ if execution_device is None:
290
+ execution_device = next(iter(model.parameters())).device
291
+ weights_map = OffloadedWeightsLoader(save_folder=offload_dir)
292
+
293
+ add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True)
294
+ attach_align_device_hook(
295
+ model,
296
+ execution_device=execution_device,
297
+ offload=True,
298
+ offload_buffers=offload_buffers,
299
+ weights_map=weights_map,
300
+ preload_module_classes=preload_module_classes,
301
+ )
302
+
303
+ return model
304
+
305
+
306
+ def dispatch_model(
307
+ model: nn.Module,
308
+ device_map: Dict[str, Union[str, int, torch.device]],
309
+ main_device: Optional[torch.device] = None,
310
+ state_dict: Optional[Dict[str, torch.Tensor]] = None,
311
+ offload_dir: Optional[Union[str, os.PathLike]] = None,
312
+ offload_index: Optional[Dict[str, str]] = None,
313
+ offload_buffers: bool = False,
314
+ skip_keys: Optional[Union[str, List[str]]] = None,
315
+ preload_module_classes: Optional[List[str]] = None,
316
+ force_hooks: bool = False,
317
+ ):
318
+ """
319
+ Dispatches a model according to a given device map. Layers of the model might be spread across GPUs, offloaded on
320
+ the CPU or even the disk.
321
+
322
+ Args:
323
+ model (`torch.nn.Module`):
324
+ The model to dispatch.
325
+ device_map (`Dict[str, Union[str, int, torch.device]]`):
326
+ A dictionary mapping module names in the models `state_dict` to the device they should go to. Note that
327
+ `"disk"` is accepted even if it's not a proper value for `torch.device`.
328
+ main_device (`str`, `int` or `torch.device`, *optional*):
329
+ The main execution device. Will default to the first device in the `device_map` different from `"cpu"` or
330
+ `"disk"`.
331
+ state_dict (`Dict[str, torch.Tensor]`, *optional*):
332
+ The state dict of the part of the model that will be kept on CPU.
333
+ offload_dir (`str` or `os.PathLike`):
334
+ The folder in which to offload the model weights (or where the model weights are already offloaded).
335
+ offload_index (`Dict`, *optional*):
336
+ A dictionary from weight name to their information (`dtype`/ `shape` or safetensors filename). Will default
337
+ to the index saved in `save_folder`.
338
+ offload_buffers (`bool`, *optional*, defaults to `False`):
339
+ Whether or not to offload the buffers with the model parameters.
340
+ skip_keys (`str` or `List[str]`, *optional*):
341
+ A list of keys to ignore when moving inputs or outputs between devices.
342
+ preload_module_classes (`List[str]`, *optional*):
343
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
344
+ of the forward. This should only be used for classes that have submodules which are registered but not
345
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
346
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
347
+ force_hooks (`bool`, *optional*, defaults to `False`):
348
+ Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a
349
+ single device.
350
+ """
351
+ # Error early if the device map is incomplete.
352
+ check_device_map(model, device_map)
353
+
354
+ # for backward compatibility
355
+ is_bnb_quantized = (
356
+ getattr(model, "is_quantized", False) or getattr(model, "is_loaded_in_8bit", False)
357
+ ) and getattr(model, "quantization_method", "bitsandbytes") == "bitsandbytes"
358
+
359
+ # We attach hooks if the device_map has at least 2 different devices or if
360
+ # force_hooks is set to `True`. Otherwise, the model in already loaded
361
+ # in the unique device and the user can decide where to dispatch the model.
362
+ # If the model is quantized, we always force-dispatch the model
363
+ if (len(set(device_map.values())) > 1) or is_bnb_quantized or force_hooks:
364
+ if main_device is None:
365
+ if set(device_map.values()) == {"cpu"} or set(device_map.values()) == {"cpu", "disk"}:
366
+ main_device = "cpu"
367
+ else:
368
+ main_device = [d for d in device_map.values() if d not in ["cpu", "disk"]][0]
369
+
370
+ if main_device != "cpu":
371
+ cpu_modules = [name for name, device in device_map.items() if device == "cpu"]
372
+ if state_dict is None and len(cpu_modules) > 0:
373
+ state_dict = extract_submodules_state_dict(model.state_dict(), cpu_modules)
374
+
375
+ disk_modules = [name for name, device in device_map.items() if device == "disk"]
376
+ if offload_dir is None and offload_index is None and len(disk_modules) > 0:
377
+ raise ValueError(
378
+ "We need an `offload_dir` to dispatch this model according to this `device_map`, the following submodules "
379
+ f"need to be offloaded: {', '.join(disk_modules)}."
380
+ )
381
+ if (
382
+ len(disk_modules) > 0
383
+ and offload_index is None
384
+ and (not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")))
385
+ ):
386
+ disk_state_dict = extract_submodules_state_dict(model.state_dict(), disk_modules)
387
+ offload_state_dict(offload_dir, disk_state_dict)
388
+
389
+ execution_device = {
390
+ name: main_device if device in ["cpu", "disk"] else device for name, device in device_map.items()
391
+ }
392
+ execution_device[""] = main_device
393
+ offloaded_devices = ["disk"] if main_device == "cpu" or main_device == "mps" else ["cpu", "disk"]
394
+ offload = {name: device in offloaded_devices for name, device in device_map.items()}
395
+ save_folder = offload_dir if len(disk_modules) > 0 else None
396
+ if state_dict is not None or save_folder is not None or offload_index is not None:
397
+ device = main_device if offload_index is not None else None
398
+ weights_map = OffloadedWeightsLoader(
399
+ state_dict=state_dict, save_folder=save_folder, index=offload_index, device=device
400
+ )
401
+ else:
402
+ weights_map = None
403
+
404
+ # When dispatching the model's parameters to the devices specified in device_map, we want to avoid allocating memory several times for the
405
+ # tied parameters. The dictionary tied_params_map keeps track of the already allocated data for a given tied parameter (represented by its
406
+ # original pointer) on each devices.
407
+ tied_params = find_tied_parameters(model)
408
+
409
+ tied_params_map = {}
410
+ for group in tied_params:
411
+ for param_name in group:
412
+ # data_ptr() is enough here, as `find_tied_parameters` finds tied params simply by comparing `param1 is param2`, so we don't need
413
+ # to care about views of tensors through storage_offset.
414
+ data_ptr = recursive_getattr(model, param_name).data_ptr()
415
+ tied_params_map[data_ptr] = {}
416
+
417
+ # Note: To handle the disk offloading case, we can not simply use weights_map[param_name].data_ptr() as the reference pointer,
418
+ # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
419
+
420
+ attach_align_device_hook_on_blocks(
421
+ model,
422
+ execution_device=execution_device,
423
+ offload=offload,
424
+ offload_buffers=offload_buffers,
425
+ weights_map=weights_map,
426
+ skip_keys=skip_keys,
427
+ preload_module_classes=preload_module_classes,
428
+ tied_params_map=tied_params_map,
429
+ )
430
+
431
+ # warn if there is any params on the meta device
432
+ offloaded_devices_str = " and ".join(
433
+ [device for device in set(device_map.values()) if device in ("cpu", "disk")]
434
+ )
435
+ if len(offloaded_devices_str) > 0:
436
+ logger.warning(
437
+ f"Some parameters are on the meta device because they were offloaded to the {offloaded_devices_str}."
438
+ )
439
+
440
+ # Attaching the hook may break tied weights, so we retie them
441
+ retie_parameters(model, tied_params)
442
+
443
+ # add warning to cuda and to method
444
+ def add_warning(fn, model):
445
+ @wraps(fn)
446
+ def wrapper(*args, **kwargs):
447
+ warning_msg = "You shouldn't move a model that is dispatched using accelerate hooks."
448
+ if str(fn.__name__) == "to":
449
+ to_device = torch._C._nn._parse_to(*args, **kwargs)[0]
450
+ if to_device is not None:
451
+ logger.warning(warning_msg)
452
+ else:
453
+ logger.warning(warning_msg)
454
+ for param in model.parameters():
455
+ if param.device == torch.device("meta"):
456
+ raise RuntimeError("You can't move a model that has some modules offloaded to cpu or disk.")
457
+ return fn(*args, **kwargs)
458
+
459
+ return wrapper
460
+
461
+ # Make sure to update _accelerate_added_attributes in hooks.py if you add any hook
462
+ model.to = add_warning(model.to, model)
463
+ if is_npu_available():
464
+ model.npu = add_warning(model.npu, model)
465
+ elif is_mlu_available():
466
+ model.mlu = add_warning(model.mlu, model)
467
+ elif is_musa_available():
468
+ model.musa = add_warning(model.musa, model)
469
+ elif is_xpu_available():
470
+ model.xpu = add_warning(model.xpu, model)
471
+ else:
472
+ model.cuda = add_warning(model.cuda, model)
473
+
474
+ # Check if we are using multi-gpus with RTX 4000 series
475
+ use_multi_gpu = len([device for device in set(device_map.values()) if device not in ("cpu", "disk")]) > 1
476
+ if use_multi_gpu and not check_cuda_p2p_ib_support():
477
+ logger.warning(
478
+ "We've detected an older driver with an RTX 4000 series GPU. These drivers have issues with P2P. "
479
+ "This can affect the multi-gpu inference when using accelerate device_map."
480
+ "Please make sure to update your driver to the latest version which resolves this."
481
+ )
482
+ else:
483
+ device = list(device_map.values())[0]
484
+ # `torch.Tensor.to(<int num>)` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)).
485
+ if is_npu_available() and isinstance(device, int):
486
+ device = f"npu:{device}"
487
+ elif is_mlu_available() and isinstance(device, int):
488
+ device = f"mlu:{device}"
489
+ elif is_musa_available() and isinstance(device, int):
490
+ device = f"musa:{device}"
491
+ elif is_xpu_available() and isinstance(device, int):
492
+ device = f"xpu:{device}"
493
+ if device != "disk":
494
+ model.to(device)
495
+ else:
496
+ raise ValueError(
497
+ "You are trying to offload the whole model to the disk. Please use the `disk_offload` function instead."
498
+ )
499
+ # Convert OrderedDict back to dict for easier usage
500
+ model.hf_device_map = dict(device_map)
501
+ return model
502
+
503
+
504
+ def load_checkpoint_and_dispatch(
505
+ model: nn.Module,
506
+ checkpoint: Union[str, os.PathLike],
507
+ device_map: Optional[Union[str, Dict[str, Union[int, str, torch.device]]]] = None,
508
+ max_memory: Optional[Dict[Union[int, str], Union[int, str]]] = None,
509
+ no_split_module_classes: Optional[List[str]] = None,
510
+ offload_folder: Optional[Union[str, os.PathLike]] = None,
511
+ offload_buffers: bool = False,
512
+ dtype: Optional[Union[str, torch.dtype]] = None,
513
+ offload_state_dict: Optional[bool] = None,
514
+ skip_keys: Optional[Union[str, List[str]]] = None,
515
+ preload_module_classes: Optional[List[str]] = None,
516
+ force_hooks: bool = False,
517
+ strict: bool = False,
518
+ ):
519
+ """
520
+ Loads a (potentially sharded) checkpoint inside a model, potentially sending weights to a given device as they are
521
+ loaded and adds the various hooks that will make this model run properly (even if split across devices).
522
+
523
+ Args:
524
+ model (`torch.nn.Module`): The model in which we want to load a checkpoint.
525
+ checkpoint (`str` or `os.PathLike`):
526
+ The folder checkpoint to load. It can be:
527
+ - a path to a file containing a whole model state dict
528
+ - a path to a `.json` file containing the index to a sharded checkpoint
529
+ - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint.
530
+ device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*):
531
+ A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer
532
+ name, once a given module name is inside, every submodule of it will be sent to the same device.
533
+
534
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For more
535
+ information about each option see [here](../concept_guides/big_model_inference#designing-a-device-map).
536
+ Defaults to None, which means [`dispatch_model`] will not be called.
537
+ max_memory (`Dict`, *optional*):
538
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each GPU
539
+ and the available CPU RAM if unset.
540
+ no_split_module_classes (`List[str]`, *optional*):
541
+ A list of layer class names that should never be split across device (for instance any layer that has a
542
+ residual connection).
543
+ offload_folder (`str` or `os.PathLike`, *optional*):
544
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
545
+ offload_buffers (`bool`, *optional*, defaults to `False`):
546
+ In the layers that are offloaded on the CPU or the hard drive, whether or not to offload the buffers as
547
+ well as the parameters.
548
+ dtype (`str` or `torch.dtype`, *optional*):
549
+ If provided, the weights will be converted to that type when loaded.
550
+ offload_state_dict (`bool`, *optional*):
551
+ If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if
552
+ the weight of the CPU state dict + the biggest shard does not fit. Will default to `True` if the device map
553
+ picked contains `"disk"` values.
554
+ skip_keys (`str` or `List[str]`, *optional*):
555
+ A list of keys to ignore when moving inputs or outputs between devices.
556
+ preload_module_classes (`List[str]`, *optional*):
557
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
558
+ of the forward. This should only be used for classes that have submodules which are registered but not
559
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
560
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
561
+ force_hooks (`bool`, *optional*, defaults to `False`):
562
+ Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a
563
+ single device.
564
+ strict (`bool`, *optional*, defaults to `False`):
565
+ Whether to strictly enforce that the keys in the checkpoint state_dict match the keys of the model's
566
+ state_dict.
567
+
568
+ Example:
569
+
570
+ ```python
571
+ >>> from accelerate import init_empty_weights, load_checkpoint_and_dispatch
572
+ >>> from huggingface_hub import hf_hub_download
573
+ >>> from transformers import AutoConfig, AutoModelForCausalLM
574
+
575
+ >>> # Download the Weights
576
+ >>> checkpoint = "EleutherAI/gpt-j-6B"
577
+ >>> weights_location = hf_hub_download(checkpoint, "pytorch_model.bin")
578
+
579
+ >>> # Create a model and initialize it with empty weights
580
+ >>> config = AutoConfig.from_pretrained(checkpoint)
581
+ >>> with init_empty_weights():
582
+ ... model = AutoModelForCausalLM.from_config(config)
583
+
584
+ >>> # Load the checkpoint and dispatch it to the right devices
585
+ >>> model = load_checkpoint_and_dispatch(
586
+ ... model, weights_location, device_map="auto", no_split_module_classes=["GPTJBlock"]
587
+ ... )
588
+ ```
589
+ """
590
+ if isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
591
+ raise ValueError(
592
+ "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or "
593
+ "'sequential'."
594
+ )
595
+ if isinstance(device_map, str):
596
+ if device_map != "sequential":
597
+ max_memory = get_balanced_memory(
598
+ model,
599
+ max_memory=max_memory,
600
+ no_split_module_classes=no_split_module_classes,
601
+ dtype=dtype,
602
+ low_zero=(device_map == "balanced_low_0"),
603
+ )
604
+ device_map = infer_auto_device_map(
605
+ model,
606
+ max_memory=max_memory,
607
+ no_split_module_classes=no_split_module_classes,
608
+ dtype=dtype,
609
+ offload_buffers=offload_buffers,
610
+ )
611
+ if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
612
+ offload_state_dict = True
613
+ load_checkpoint_in_model(
614
+ model,
615
+ checkpoint,
616
+ device_map=device_map,
617
+ offload_folder=offload_folder,
618
+ dtype=dtype,
619
+ offload_state_dict=offload_state_dict,
620
+ offload_buffers=offload_buffers,
621
+ strict=strict,
622
+ )
623
+ if device_map is None:
624
+ return model
625
+ return dispatch_model(
626
+ model,
627
+ device_map=device_map,
628
+ offload_dir=offload_folder,
629
+ offload_buffers=offload_buffers,
630
+ skip_keys=skip_keys,
631
+ preload_module_classes=preload_module_classes,
632
+ force_hooks=force_hooks,
633
+ )
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/checkpointing.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import List
18
+
19
+ import numpy as np
20
+ import torch
21
+ from safetensors.torch import load_model
22
+ from torch.cuda.amp import GradScaler
23
+
24
+ from .utils import (
25
+ MODEL_NAME,
26
+ OPTIMIZER_NAME,
27
+ RNG_STATE_NAME,
28
+ SAFE_MODEL_NAME,
29
+ SAFE_WEIGHTS_NAME,
30
+ SAMPLER_NAME,
31
+ SCALER_NAME,
32
+ SCHEDULER_NAME,
33
+ WEIGHTS_NAME,
34
+ get_pretty_name,
35
+ is_mlu_available,
36
+ is_torch_xla_available,
37
+ is_xpu_available,
38
+ save,
39
+ )
40
+
41
+
42
+ if is_torch_xla_available():
43
+ import torch_xla.core.xla_model as xm
44
+
45
+ from .logging import get_logger
46
+ from .state import PartialState
47
+
48
+
49
+ logger = get_logger(__name__)
50
+
51
+
52
+ def save_accelerator_state(
53
+ output_dir: str,
54
+ model_states: List[dict],
55
+ optimizers: list,
56
+ schedulers: list,
57
+ dataloaders: list,
58
+ process_index: int,
59
+ step: int,
60
+ scaler: GradScaler = None,
61
+ save_on_each_node: bool = False,
62
+ safe_serialization: bool = True,
63
+ ):
64
+ """
65
+ Saves the current states of the models, optimizers, scaler, and RNG generators to a given directory.
66
+
67
+ <Tip>
68
+
69
+ If `safe_serialization` is `True`, models will be saved with `safetensors` while the rest are saved using native
70
+ `pickle`.
71
+
72
+ </Tip>
73
+
74
+ Args:
75
+ output_dir (`str` or `os.PathLike`):
76
+ The name of the folder to save all relevant weights and states.
77
+ model_states (`List[torch.nn.Module]`):
78
+ A list of model states
79
+ optimizers (`List[torch.optim.Optimizer]`):
80
+ A list of optimizer instances
81
+ schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
82
+ A list of learning rate schedulers
83
+ dataloaders (`List[torch.utils.data.DataLoader]`):
84
+ A list of dataloader instances to save their sampler states
85
+ process_index (`int`):
86
+ The current process index in the Accelerator state
87
+ step (`int`):
88
+ The current step in the internal step tracker
89
+ scaler (`torch.amp.GradScaler`, *optional*):
90
+ An optional gradient scaler instance to save;
91
+ save_on_each_node (`bool`, *optional*):
92
+ Whether to save on every node, or only the main node.
93
+ safe_serialization (`bool`, *optional*, defaults to `True`):
94
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
95
+ """
96
+ output_dir = Path(output_dir)
97
+ # Model states
98
+ for i, state in enumerate(model_states):
99
+ weights_name = WEIGHTS_NAME if not safe_serialization else SAFE_WEIGHTS_NAME
100
+ if i > 0:
101
+ weights_name = weights_name.replace(".", f"_{i}.")
102
+ output_model_file = output_dir.joinpath(weights_name)
103
+ save(state, output_model_file, save_on_each_node=save_on_each_node, safe_serialization=safe_serialization)
104
+ logger.info(f"Model weights saved in {output_model_file}")
105
+ # Optimizer states
106
+ for i, opt in enumerate(optimizers):
107
+ state = opt.state_dict()
108
+ optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin"
109
+ output_optimizer_file = output_dir.joinpath(optimizer_name)
110
+ save(state, output_optimizer_file, save_on_each_node=save_on_each_node, safe_serialization=False)
111
+ logger.info(f"Optimizer state saved in {output_optimizer_file}")
112
+ # Scheduler states
113
+ for i, scheduler in enumerate(schedulers):
114
+ state = scheduler.state_dict()
115
+ scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin"
116
+ output_scheduler_file = output_dir.joinpath(scheduler_name)
117
+ save(state, output_scheduler_file, save_on_each_node=save_on_each_node, safe_serialization=False)
118
+ logger.info(f"Scheduler state saved in {output_scheduler_file}")
119
+ # DataLoader states
120
+ for i, dataloader in enumerate(dataloaders):
121
+ sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin"
122
+ output_sampler_file = output_dir.joinpath(sampler_name)
123
+ # Only save if we have our custom sampler
124
+ from .data_loader import IterableDatasetShard, SeedableRandomSampler
125
+
126
+ if isinstance(dataloader.dataset, IterableDatasetShard):
127
+ sampler = dataloader.get_sampler()
128
+ if isinstance(sampler, SeedableRandomSampler):
129
+ save(sampler, output_sampler_file, save_on_each_node=save_on_each_node, safe_serialization=False)
130
+ if getattr(dataloader, "use_stateful_dataloader", False):
131
+ dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin"
132
+ output_dataloader_state_dict_file = output_dir.joinpath(dataloader_state_dict_name)
133
+ state_dict = dataloader.state_dict()
134
+ torch.save(state_dict, output_dataloader_state_dict_file)
135
+ logger.info(f"Sampler state for dataloader {i} saved in {output_sampler_file}")
136
+
137
+ # GradScaler state
138
+ if scaler is not None:
139
+ state = scaler.state_dict()
140
+ output_scaler_file = output_dir.joinpath(SCALER_NAME)
141
+ torch.save(state, output_scaler_file)
142
+ logger.info(f"Gradient scaler state saved in {output_scaler_file}")
143
+ # Random number generator states
144
+ states = {}
145
+ states_name = f"{RNG_STATE_NAME}_{process_index}.pkl"
146
+ states["step"] = step
147
+ states["random_state"] = random.getstate()
148
+ states["numpy_random_seed"] = np.random.get_state()
149
+ states["torch_manual_seed"] = torch.get_rng_state()
150
+ if is_xpu_available():
151
+ states["torch_xpu_manual_seed"] = torch.xpu.get_rng_state_all()
152
+ if is_mlu_available():
153
+ states["torch_mlu_manual_seed"] = torch.mlu.get_rng_state_all()
154
+ else:
155
+ states["torch_cuda_manual_seed"] = torch.cuda.get_rng_state_all()
156
+ if is_torch_xla_available():
157
+ states["xm_seed"] = xm.get_rng_state()
158
+ output_states_file = output_dir.joinpath(states_name)
159
+ torch.save(states, output_states_file)
160
+ logger.info(f"Random states saved in {output_states_file}")
161
+ return output_dir
162
+
163
+
164
+ def load_accelerator_state(
165
+ input_dir,
166
+ models,
167
+ optimizers,
168
+ schedulers,
169
+ dataloaders,
170
+ process_index,
171
+ scaler=None,
172
+ map_location=None,
173
+ **load_model_func_kwargs,
174
+ ):
175
+ """
176
+ Loads states of the models, optimizers, scaler, and RNG generators from a given directory.
177
+
178
+ Args:
179
+ input_dir (`str` or `os.PathLike`):
180
+ The name of the folder to load all relevant weights and states.
181
+ models (`List[torch.nn.Module]`):
182
+ A list of model instances
183
+ optimizers (`List[torch.optim.Optimizer]`):
184
+ A list of optimizer instances
185
+ schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
186
+ A list of learning rate schedulers
187
+ process_index (`int`):
188
+ The current process index in the Accelerator state
189
+ scaler (`torch.amp.GradScaler`, *optional*):
190
+ An optional *GradScaler* instance to load
191
+ map_location (`str`, *optional*):
192
+ What device to load the optimizer state onto. Should be one of either "cpu" or "on_device".
193
+ load_model_func_kwargs (`dict`, *optional*):
194
+ Additional arguments that can be passed to the model's `load_state_dict` method.
195
+
196
+ Returns:
197
+ `dict`: Contains the `Accelerator` attributes to override while loading the state.
198
+ """
199
+ # stores the `Accelerator` attributes to override
200
+ override_attributes = dict()
201
+ if map_location not in [None, "cpu", "on_device"]:
202
+ raise TypeError(
203
+ "Unsupported optimizer map location passed, please choose one of `None`, `'cpu'`, or `'on_device'`"
204
+ )
205
+ if map_location is None:
206
+ map_location = "cpu"
207
+ elif map_location == "on_device":
208
+ map_location = PartialState().device
209
+
210
+ input_dir = Path(input_dir)
211
+ # Model states
212
+ for i, model in enumerate(models):
213
+ ending = f"_{i}" if i > 0 else ""
214
+ input_model_file = input_dir.joinpath(f"{SAFE_MODEL_NAME}{ending}.safetensors")
215
+ if input_model_file.exists():
216
+ load_model(model, input_model_file, device=str(map_location), **load_model_func_kwargs)
217
+ else:
218
+ # Load with torch
219
+ input_model_file = input_dir.joinpath(f"{MODEL_NAME}{ending}.bin")
220
+ state_dict = torch.load(input_model_file, map_location=map_location)
221
+ model.load_state_dict(state_dict, **load_model_func_kwargs)
222
+ logger.info("All model weights loaded successfully")
223
+
224
+ # Optimizer states
225
+ for i, opt in enumerate(optimizers):
226
+ optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin"
227
+ input_optimizer_file = input_dir.joinpath(optimizer_name)
228
+ optimizer_state = torch.load(input_optimizer_file, map_location=map_location)
229
+ optimizers[i].load_state_dict(optimizer_state)
230
+ logger.info("All optimizer states loaded successfully")
231
+
232
+ # Scheduler states
233
+ for i, scheduler in enumerate(schedulers):
234
+ scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin"
235
+ input_scheduler_file = input_dir.joinpath(scheduler_name)
236
+ scheduler.load_state_dict(torch.load(input_scheduler_file))
237
+ logger.info("All scheduler states loaded successfully")
238
+
239
+ for i, dataloader in enumerate(dataloaders):
240
+ sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin"
241
+ input_sampler_file = input_dir.joinpath(sampler_name)
242
+ # Only load if we have our custom sampler
243
+ from .data_loader import IterableDatasetShard, SeedableRandomSampler
244
+
245
+ if isinstance(dataloader.dataset, IterableDatasetShard):
246
+ sampler = dataloader.get_sampler()
247
+ if isinstance(sampler, SeedableRandomSampler):
248
+ sampler = dataloader.set_sampler(torch.load(input_sampler_file))
249
+ if getattr(dataloader, "use_stateful_dataloader", False):
250
+ dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin"
251
+ input_dataloader_state_dict_file = input_dir.joinpath(dataloader_state_dict_name)
252
+ if input_dataloader_state_dict_file.exists():
253
+ state_dict = torch.load(input_dataloader_state_dict_file)
254
+ dataloader.load_state_dict(state_dict)
255
+ logger.info("All dataloader sampler states loaded successfully")
256
+
257
+ # GradScaler state
258
+ if scaler is not None:
259
+ input_scaler_file = input_dir.joinpath(SCALER_NAME)
260
+ scaler.load_state_dict(torch.load(input_scaler_file))
261
+ logger.info("GradScaler state loaded successfully")
262
+
263
+ # Random states
264
+ try:
265
+ states = torch.load(input_dir.joinpath(f"{RNG_STATE_NAME}_{process_index}.pkl"))
266
+ if "step" in states:
267
+ override_attributes["step"] = states["step"]
268
+ random.setstate(states["random_state"])
269
+ np.random.set_state(states["numpy_random_seed"])
270
+ torch.set_rng_state(states["torch_manual_seed"])
271
+ if is_xpu_available():
272
+ torch.xpu.set_rng_state_all(states["torch_xpu_manual_seed"])
273
+ if is_mlu_available():
274
+ torch.mlu.set_rng_state_all(states["torch_mlu_manual_seed"])
275
+ else:
276
+ torch.cuda.set_rng_state_all(states["torch_cuda_manual_seed"])
277
+ if is_torch_xla_available():
278
+ xm.set_rng_state(states["xm_seed"])
279
+ logger.info("All random states loaded successfully")
280
+ except Exception:
281
+ logger.info("Could not load random states")
282
+
283
+ return override_attributes
284
+
285
+
286
+ def save_custom_state(obj, path, index: int = 0, save_on_each_node: bool = False):
287
+ """
288
+ Saves the state of `obj` to `{path}/custom_checkpoint_{index}.pkl`
289
+ """
290
+ # Should this be the right way to get a qual_name type value from `obj`?
291
+ save_location = Path(path) / f"custom_checkpoint_{index}.pkl"
292
+ logger.info(f"Saving the state of {get_pretty_name(obj)} to {save_location}")
293
+ save(obj.state_dict(), save_location, save_on_each_node=save_on_each_node)
294
+
295
+
296
+ def load_custom_state(obj, path, index: int = 0):
297
+ """
298
+ Loads the state of `obj` at `{path}/custom_checkpoint_{index}.pkl`
299
+ """
300
+ load_location = f"{path}/custom_checkpoint_{index}.pkl"
301
+ logger.info(f"Loading the state of {get_pretty_name(obj)} from {load_location}")
302
+ obj.load_state_dict(torch.load(load_location, map_location="cpu"))
tasks/tasksmith-5db757e91a6e/tests/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-5db757e91a6e/tests/source/src/accelerate/commands/accelerate_cli.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.tpu import tpu_command_parser
24
+ from accelerate.commands.utils import CustomArgumentParser
25
+
26
+
27
+ def main():
28
+ parser = CustomArgumentParser("Accelerate CLI tool", usage="accelerate <command> [<args>]", allow_abbrev=False)
29
+ subparsers = parser.add_subparsers(help="accelerate command helpers")
30
+
31
+ # Register commands
32
+ get_config_parser(subparsers=subparsers)
33
+ estimate_command_parser(subparsers=subparsers)
34
+ env_command_parser(subparsers=subparsers)
35
+ launch_command_parser(subparsers=subparsers)
36
+ merge_command_parser(subparsers=subparsers)
37
+ tpu_command_parser(subparsers=subparsers)
38
+ test_command_parser(subparsers=subparsers)
39
+
40
+ # Let's go
41
+ args = parser.parse_args()
42
+
43
+ if not hasattr(args, "func"):
44
+ parser.print_help()
45
+ exit(1)
46
+
47
+ # Run
48
+ args.func(args)
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/__init__.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import argparse
18
+
19
+ from .config import config_command_parser
20
+ from .config_args import default_config_file, load_config_from_file # noqa: F401
21
+ from .default import default_command_parser
22
+ from .update import update_command_parser
23
+
24
+
25
+ def get_config_parser(subparsers=None):
26
+ parent_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
27
+ # The main config parser
28
+ config_parser = config_command_parser(subparsers)
29
+ # The subparser to add commands to
30
+ subcommands = config_parser.add_subparsers(title="subcommands", dest="subcommand")
31
+
32
+ # Then add other parsers with the parent parser
33
+ default_command_parser(subcommands, parents=[parent_parser])
34
+ update_command_parser(subcommands, parents=[parent_parser])
35
+
36
+ return config_parser
37
+
38
+
39
+ def main():
40
+ config_parser = get_config_parser()
41
+ args = config_parser.parse_args()
42
+
43
+ if not hasattr(args, "func"):
44
+ config_parser.print_help()
45
+ exit(1)
46
+
47
+ # Run
48
+ args.func(args)
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/cluster.py ADDED
@@ -0,0 +1,828 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import os
18
+
19
+ from ...utils import (
20
+ ComputeEnvironment,
21
+ DistributedType,
22
+ is_deepspeed_available,
23
+ is_fp8_available,
24
+ is_mlu_available,
25
+ is_mps_available,
26
+ is_msamp_available,
27
+ is_musa_available,
28
+ is_npu_available,
29
+ is_transformer_engine_available,
30
+ is_transformers_available,
31
+ is_xpu_available,
32
+ )
33
+ from ...utils.constants import (
34
+ DEEPSPEED_MULTINODE_LAUNCHERS,
35
+ FSDP_AUTO_WRAP_POLICY,
36
+ FSDP_BACKWARD_PREFETCH,
37
+ FSDP_SHARDING_STRATEGY,
38
+ FSDP_STATE_DICT_TYPE,
39
+ TORCH_DYNAMO_MODES,
40
+ )
41
+ from .config_args import ClusterConfig
42
+ from .config_utils import (
43
+ DYNAMO_BACKENDS,
44
+ _ask_field,
45
+ _ask_options,
46
+ _convert_distributed_mode,
47
+ _convert_dynamo_backend,
48
+ _convert_fp8_backend,
49
+ _convert_mixed_precision,
50
+ _convert_yes_no_to_bool,
51
+ )
52
+
53
+
54
+ def get_cluster_input():
55
+ distributed_type = _ask_options(
56
+ "Which type of machine are you using?",
57
+ [
58
+ "No distributed training",
59
+ "multi-CPU",
60
+ "multi-XPU",
61
+ "multi-GPU",
62
+ "multi-NPU",
63
+ "multi-MLU",
64
+ "multi-MUSA",
65
+ "TPU",
66
+ ],
67
+ _convert_distributed_mode,
68
+ )
69
+
70
+ machine_rank = 0
71
+ num_machines = 1
72
+ num_processes = 1
73
+ gpu_ids = None
74
+ main_process_ip = None
75
+ main_process_port = None
76
+ rdzv_backend = "static"
77
+ same_network = True
78
+ debug = False
79
+
80
+ if distributed_type in [
81
+ DistributedType.MULTI_GPU,
82
+ DistributedType.MULTI_MLU,
83
+ DistributedType.MULTI_MUSA,
84
+ DistributedType.MULTI_NPU,
85
+ DistributedType.MULTI_XPU,
86
+ DistributedType.MULTI_CPU,
87
+ ]:
88
+ num_machines = _ask_field(
89
+ "How many different machines will you use (use more than 1 for multi-node training)? [1]: ",
90
+ int,
91
+ default=1,
92
+ )
93
+ if num_machines > 1:
94
+ machine_rank = _ask_options(
95
+ "What is the rank of this machine?",
96
+ list(range(num_machines)),
97
+ int,
98
+ )
99
+ main_process_ip = _ask_field(
100
+ "What is the IP address of the machine that will host the main process? ",
101
+ )
102
+ main_process_port = _ask_field(
103
+ "What is the port you will use to communicate with the main process? ",
104
+ int,
105
+ )
106
+ same_network = _ask_field(
107
+ "Are all the machines on the same local network? Answer `no` if nodes are on the cloud and/or on different network hosts [YES/no]: ",
108
+ _convert_yes_no_to_bool,
109
+ default=True,
110
+ error_message="Please enter yes or no.",
111
+ )
112
+ if not same_network:
113
+ rdzv_backend = _ask_field(
114
+ "What rendezvous backend will you use? ('static', 'c10d', ...): ", default="static"
115
+ )
116
+ debug = _ask_field(
117
+ "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ",
118
+ _convert_yes_no_to_bool,
119
+ default=False,
120
+ error_message="Please enter yes or no.",
121
+ )
122
+
123
+ if distributed_type == DistributedType.NO:
124
+ use_cpu = _ask_field(
125
+ "Do you want to run your training on CPU only (even if a GPU / Apple Silicon / Ascend NPU device is available)? [yes/NO]:",
126
+ _convert_yes_no_to_bool,
127
+ default=False,
128
+ error_message="Please enter yes or no.",
129
+ )
130
+ elif distributed_type == DistributedType.MULTI_CPU:
131
+ use_cpu = True
132
+ else:
133
+ use_cpu = False
134
+
135
+ ipex_config = {}
136
+ mpirun_config = {}
137
+ if use_cpu:
138
+ ipex_config["ipex"] = _ask_field(
139
+ "Do you want to use Intel PyTorch Extension (IPEX) to speed up training on CPU? [yes/NO]:",
140
+ _convert_yes_no_to_bool,
141
+ default=False,
142
+ error_message="Please enter yes or no.",
143
+ )
144
+ if distributed_type == DistributedType.MULTI_CPU:
145
+ use_mpirun = _ask_field(
146
+ "Do you want accelerate to launch mpirun? [yes/NO]: ",
147
+ _convert_yes_no_to_bool,
148
+ default=False,
149
+ error_message="Please enter yes or no.",
150
+ )
151
+ if use_mpirun:
152
+ mpirun_hostfile = _ask_field(
153
+ "Please enter the path to the hostfile to use with mpirun [~/hostfile]: ",
154
+ str,
155
+ default="~/hostfile",
156
+ )
157
+ mpirun_config["mpirun_hostfile"] = os.path.expanduser(mpirun_hostfile.strip())
158
+ mpirun_config["mpirun_ccl"] = _ask_field("Enter the number of oneCCL worker threads [1]: ", default=1)
159
+ if (
160
+ not use_cpu
161
+ and is_xpu_available()
162
+ and distributed_type
163
+ not in [
164
+ DistributedType.MULTI_GPU,
165
+ DistributedType.MULTI_NPU,
166
+ DistributedType.MULTI_MLU,
167
+ DistributedType.XLA,
168
+ DistributedType.MULTI_MUSA,
169
+ ]
170
+ ):
171
+ ipex_config["use_xpu"] = _ask_field(
172
+ "Do you want to use XPU plugin to speed up training on XPU? [yes/NO]:",
173
+ _convert_yes_no_to_bool,
174
+ default=False,
175
+ error_message="Please enter yes or no.",
176
+ )
177
+
178
+ dynamo_config = {}
179
+ use_dynamo = _ask_field(
180
+ "Do you wish to optimize your script with torch dynamo?[yes/NO]:",
181
+ _convert_yes_no_to_bool,
182
+ default=False,
183
+ error_message="Please enter yes or no.",
184
+ )
185
+ if use_dynamo:
186
+ prefix = "dynamo_"
187
+ dynamo_config[prefix + "backend"] = _ask_options(
188
+ "Which dynamo backend would you like to use?",
189
+ [x.lower() for x in DYNAMO_BACKENDS],
190
+ _convert_dynamo_backend,
191
+ default=2,
192
+ )
193
+ use_custom_options = _ask_field(
194
+ "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ",
195
+ _convert_yes_no_to_bool,
196
+ default=False,
197
+ error_message="Please enter yes or no.",
198
+ )
199
+
200
+ if use_custom_options:
201
+ dynamo_config[prefix + "mode"] = _ask_options(
202
+ "Which mode do you want to use?",
203
+ TORCH_DYNAMO_MODES,
204
+ lambda x: TORCH_DYNAMO_MODES[int(x)],
205
+ default=0,
206
+ )
207
+ dynamo_config[prefix + "use_fullgraph"] = _ask_field(
208
+ "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ",
209
+ _convert_yes_no_to_bool,
210
+ default=False,
211
+ error_message="Please enter yes or no.",
212
+ )
213
+ dynamo_config[prefix + "use_dynamic"] = _ask_field(
214
+ "Do you want to enable dynamic shape tracing? [yes/NO]: ",
215
+ _convert_yes_no_to_bool,
216
+ default=False,
217
+ error_message="Please enter yes or no.",
218
+ )
219
+
220
+ use_mps = not use_cpu and is_mps_available()
221
+ deepspeed_config = {}
222
+ if (
223
+ distributed_type
224
+ in [
225
+ DistributedType.MULTI_GPU,
226
+ DistributedType.MULTI_XPU,
227
+ DistributedType.MULTI_NPU,
228
+ DistributedType.MULTI_MLU,
229
+ DistributedType.MULTI_MUSA,
230
+ DistributedType.NO,
231
+ ]
232
+ and not use_mps
233
+ ):
234
+ use_deepspeed = _ask_field(
235
+ "Do you want to use DeepSpeed? [yes/NO]: ",
236
+ _convert_yes_no_to_bool,
237
+ default=False,
238
+ error_message="Please enter yes or no.",
239
+ )
240
+ if use_deepspeed:
241
+ distributed_type = DistributedType.DEEPSPEED
242
+ assert (
243
+ is_deepspeed_available()
244
+ ), "DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source"
245
+
246
+ if distributed_type == DistributedType.DEEPSPEED:
247
+ use_deepspeed_config = _ask_field(
248
+ "Do you want to specify a json file to a DeepSpeed config? [yes/NO]: ",
249
+ _convert_yes_no_to_bool,
250
+ default=False,
251
+ error_message="Please enter yes or no.",
252
+ )
253
+ if use_deepspeed_config:
254
+ deepspeed_config["deepspeed_config_file"] = _ask_field(
255
+ "Please enter the path to the json DeepSpeed config file: ",
256
+ str,
257
+ default="none",
258
+ )
259
+ else:
260
+ deepspeed_config["zero_stage"] = _ask_options(
261
+ "What should be your DeepSpeed's ZeRO optimization stage?",
262
+ [0, 1, 2, 3],
263
+ int,
264
+ default=2,
265
+ )
266
+
267
+ deepspeed_devices = ["none", "cpu", "nvme"]
268
+ if deepspeed_config["zero_stage"] >= 2:
269
+ deepspeed_config["offload_optimizer_device"] = _ask_options(
270
+ "Where to offload optimizer states?", deepspeed_devices, lambda x: deepspeed_devices[int(x)]
271
+ )
272
+ deepspeed_config["offload_param_device"] = _ask_options(
273
+ "Where to offload parameters?", deepspeed_devices, lambda x: deepspeed_devices[int(x)]
274
+ )
275
+ if deepspeed_config["offload_param_device"] == "nvme":
276
+ deepspeed_config["offload_param_nvme_path"] = _ask_field(
277
+ "Nvme Path to offload parameters?",
278
+ str,
279
+ default="/nvme",
280
+ )
281
+ if deepspeed_config["offload_optimizer_device"] == "nvme":
282
+ deepspeed_config["offload_optimizer_nvme_path"] = _ask_field(
283
+ "Nvme Path to offload optimizer states?",
284
+ str,
285
+ default="/nvme",
286
+ )
287
+ deepspeed_config["gradient_accumulation_steps"] = _ask_field(
288
+ "How many gradient accumulation steps you're passing in your script? [1]: ",
289
+ int,
290
+ default=1,
291
+ )
292
+ use_gradient_clipping = _ask_field(
293
+ "Do you want to use gradient clipping? [yes/NO]: ",
294
+ _convert_yes_no_to_bool,
295
+ default=False,
296
+ error_message="Please enter yes or no.",
297
+ )
298
+ if use_gradient_clipping:
299
+ deepspeed_config["gradient_clipping"] = _ask_field(
300
+ "What is the gradient clipping value? [1.0]: ",
301
+ float,
302
+ default=1.0,
303
+ )
304
+ if deepspeed_config["zero_stage"] == 3:
305
+ deepspeed_config["zero3_save_16bit_model"] = _ask_field(
306
+ "Do you want to save 16-bit model weights when using ZeRO Stage-3? [yes/NO]: ",
307
+ _convert_yes_no_to_bool,
308
+ default=False,
309
+ error_message="Please enter yes or no.",
310
+ )
311
+ deepspeed_config["zero3_init_flag"] = _ask_field(
312
+ "Do you want to enable `deepspeed.zero.Init` when using ZeRO Stage-3 for constructing massive models? [yes/NO]: ",
313
+ _convert_yes_no_to_bool,
314
+ default=False,
315
+ error_message="Please enter yes or no.",
316
+ )
317
+ if deepspeed_config["zero3_init_flag"]:
318
+ if not is_transformers_available():
319
+ raise Exception(
320
+ "When `zero3_init_flag` is set, it requires Transformers to be installed. "
321
+ "Please run `pip3 install transformers`."
322
+ )
323
+ use_moe = _ask_field(
324
+ "Do you want to enable Mixture-of-Experts training (MoE)? [yes/NO]: ",
325
+ _convert_yes_no_to_bool,
326
+ default=False,
327
+ error_message="Please enter yes or no.",
328
+ )
329
+ if use_moe:
330
+ deepspeed_config["deepspeed_moe_layer_cls_names"] = _ask_field(
331
+ "Specify the comma-separated list of transformers MoE layer class names (case-sensitive), e.g : "
332
+ " `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ... : ",
333
+ str,
334
+ )
335
+
336
+ if num_machines > 1:
337
+ launcher_query = "Which Type of launcher do you want to use?"
338
+ deepspeed_config["deepspeed_multinode_launcher"] = _ask_options(
339
+ launcher_query,
340
+ DEEPSPEED_MULTINODE_LAUNCHERS,
341
+ lambda x: DEEPSPEED_MULTINODE_LAUNCHERS[int(x)],
342
+ )
343
+
344
+ if deepspeed_config["deepspeed_multinode_launcher"] != DEEPSPEED_MULTINODE_LAUNCHERS[1]:
345
+ deepspeed_config["deepspeed_hostfile"] = _ask_field(
346
+ "DeepSpeed configures multi-node compute resources with hostfile. "
347
+ "Each row is of the format `hostname slots=[num_gpus]`, e.g., `localhost slots=2`; "
348
+ "for more information please refer official [documentation]"
349
+ "(https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node). "
350
+ "Please specify the location of hostfile: ",
351
+ str,
352
+ )
353
+
354
+ is_exclusion_filter = _ask_field(
355
+ "Do you want to specify exclusion filter string? [yes/NO]: ",
356
+ _convert_yes_no_to_bool,
357
+ default=False,
358
+ error_message="Please enter yes or no.",
359
+ )
360
+ if is_exclusion_filter:
361
+ deepspeed_config["deepspeed_exclusion_filter"] = _ask_field(
362
+ "DeepSpeed exclusion filter string: ",
363
+ str,
364
+ )
365
+
366
+ is_inclusion_filter = _ask_field(
367
+ "Do you want to specify inclusion filter string? [yes/NO]: ",
368
+ _convert_yes_no_to_bool,
369
+ default=False,
370
+ error_message="Please enter yes or no.",
371
+ )
372
+ if is_inclusion_filter:
373
+ deepspeed_config["deepspeed_inclusion_filter"] = _ask_field(
374
+ "DeepSpeed inclusion filter string: ",
375
+ str,
376
+ )
377
+
378
+ fsdp_config = {}
379
+ if distributed_type in [
380
+ DistributedType.MULTI_GPU,
381
+ DistributedType.MULTI_NPU,
382
+ DistributedType.MULTI_MLU,
383
+ DistributedType.MULTI_MUSA,
384
+ DistributedType.MULTI_XPU,
385
+ ]:
386
+ use_fsdp = _ask_field(
387
+ "Do you want to use FullyShardedDataParallel? [yes/NO]: ",
388
+ _convert_yes_no_to_bool,
389
+ default=False,
390
+ error_message="Please enter yes or no.",
391
+ )
392
+ if use_fsdp:
393
+ distributed_type = DistributedType.FSDP
394
+ if distributed_type == DistributedType.FSDP:
395
+ sharding_strategy_query = "What should be your sharding strategy?"
396
+ fsdp_config["fsdp_sharding_strategy"] = _ask_options(
397
+ sharding_strategy_query,
398
+ FSDP_SHARDING_STRATEGY,
399
+ lambda x: FSDP_SHARDING_STRATEGY[int(x)],
400
+ )
401
+ fsdp_config["fsdp_offload_params"] = _ask_field(
402
+ "Do you want to offload parameters and gradients to CPU? [yes/NO]: ",
403
+ _convert_yes_no_to_bool,
404
+ default=False,
405
+ error_message="Please enter yes or no.",
406
+ )
407
+ fsdp_wrap_query = "What should be your auto wrap policy?"
408
+ fsdp_config["fsdp_auto_wrap_policy"] = _ask_options(
409
+ fsdp_wrap_query,
410
+ FSDP_AUTO_WRAP_POLICY,
411
+ lambda x: FSDP_AUTO_WRAP_POLICY[int(x)],
412
+ )
413
+ if fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[0]:
414
+ use_no_split_modules = _ask_field(
415
+ "Do you want to use the model's `_no_split_modules` to wrap. Only applicable for 🤗 Transformers [yes/NO]: ",
416
+ _convert_yes_no_to_bool,
417
+ default=False,
418
+ error_message="Please enter yes or no.",
419
+ )
420
+ if not use_no_split_modules:
421
+ fsdp_config["fsdp_transformer_layer_cls_to_wrap"] = _ask_field(
422
+ "Specify the comma-separated list of transformer layer class names (case-sensitive) to wrap ,e.g, :"
423
+ "`BertLayer`, `GPTJBlock`, `T5Block`, `BertLayer,BertEmbeddings,BertSelfOutput` ...? : ",
424
+ str,
425
+ )
426
+ elif fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[1]:
427
+ fsdp_config["fsdp_min_num_params"] = _ask_field(
428
+ "What should be your FSDP's minimum number of parameters for Default Auto Wrapping Policy? [1e8]: ",
429
+ int,
430
+ default=100000000,
431
+ )
432
+ fsdp_backward_prefetch_query = "What should be your FSDP's backward prefetch policy?"
433
+ fsdp_config["fsdp_backward_prefetch"] = _ask_options(
434
+ fsdp_backward_prefetch_query,
435
+ FSDP_BACKWARD_PREFETCH,
436
+ lambda x: FSDP_BACKWARD_PREFETCH[int(x)],
437
+ )
438
+ fsdp_state_dict_type_query = "What should be your FSDP's state dict type?"
439
+ fsdp_config["fsdp_state_dict_type"] = _ask_options(
440
+ fsdp_state_dict_type_query,
441
+ FSDP_STATE_DICT_TYPE,
442
+ lambda x: FSDP_STATE_DICT_TYPE[int(x)],
443
+ default=2,
444
+ )
445
+ fsdp_config["fsdp_forward_prefetch"] = _ask_field(
446
+ "Do you want to enable FSDP's forward prefetch policy? [yes/NO]: ",
447
+ _convert_yes_no_to_bool,
448
+ default=False,
449
+ error_message="Please enter yes or no.",
450
+ )
451
+ fsdp_config["fsdp_use_orig_params"] = _ask_field(
452
+ "Do you want to enable FSDP's `use_orig_params` feature? [YES/no]: ",
453
+ _convert_yes_no_to_bool,
454
+ default=True,
455
+ error_message="Please enter yes or no.",
456
+ )
457
+ fsdp_config["fsdp_cpu_ram_efficient_loading"] = _ask_field(
458
+ "Do you want to enable CPU RAM efficient model loading? Only applicable for 🤗 Transformers models. [YES/no]: ",
459
+ _convert_yes_no_to_bool,
460
+ default=True,
461
+ error_message="Please enter yes or no.",
462
+ )
463
+ if fsdp_config["fsdp_cpu_ram_efficient_loading"]:
464
+ fsdp_config["fsdp_sync_module_states"] = True
465
+ else:
466
+ fsdp_config["fsdp_sync_module_states"] = _ask_field(
467
+ "Do you want each individually wrapped FSDP unit to broadcast module parameters from rank 0 at the start? [YES/no]: ",
468
+ _convert_yes_no_to_bool,
469
+ default=True,
470
+ error_message="Please enter yes or no.",
471
+ )
472
+ fsdp_config["fsdp_activation_checkpointing"] = _ask_field(
473
+ "Do you want to enable FSDP activation checkpointing? [yes/NO]: ",
474
+ _convert_yes_no_to_bool,
475
+ default=False,
476
+ error_message="Please enter yes or no.",
477
+ )
478
+
479
+ megatron_lm_config = {}
480
+ if distributed_type in [DistributedType.MULTI_GPU]:
481
+ use_megatron_lm = _ask_field(
482
+ "Do you want to use Megatron-LM ? [yes/NO]: ",
483
+ _convert_yes_no_to_bool,
484
+ default=False,
485
+ error_message="Please enter yes or no.",
486
+ )
487
+ if use_megatron_lm:
488
+ distributed_type = DistributedType.MEGATRON_LM
489
+ if distributed_type == DistributedType.MEGATRON_LM:
490
+ prefix = "megatron_lm_"
491
+ megatron_lm_config[prefix + "tp_degree"] = _ask_field(
492
+ "What is the Tensor Parallelism degree/size? [1]:",
493
+ int,
494
+ default=1,
495
+ error_message="Please enter an integer.",
496
+ )
497
+ if megatron_lm_config[prefix + "tp_degree"] > 1:
498
+ megatron_lm_config[prefix + "sequence_parallelism"] = _ask_field(
499
+ "Do you want to enable Sequence Parallelism? [YES/no]: ",
500
+ _convert_yes_no_to_bool,
501
+ default=True,
502
+ error_message="Please enter yes or no.",
503
+ )
504
+
505
+ megatron_lm_config[prefix + "pp_degree"] = _ask_field(
506
+ "What is the Pipeline Parallelism degree/size? [1]:",
507
+ int,
508
+ default=1,
509
+ error_message="Please enter an integer.",
510
+ )
511
+ if megatron_lm_config[prefix + "pp_degree"] > 1:
512
+ megatron_lm_config[prefix + "num_micro_batches"] = _ask_field(
513
+ "What is the number of micro-batches? [1]:",
514
+ int,
515
+ default=1,
516
+ error_message="Please enter an integer.",
517
+ )
518
+
519
+ megatron_lm_config[prefix + "recompute_activations"] = _ask_field(
520
+ "Do you want to enable selective activation recomputation? [YES/no]: ",
521
+ _convert_yes_no_to_bool,
522
+ default=True,
523
+ error_message="Please enter yes or no.",
524
+ )
525
+
526
+ megatron_lm_config[prefix + "use_distributed_optimizer"] = _ask_field(
527
+ "Do you want to use distributed optimizer "
528
+ "which shards optimizer state and gradients across data parallel ranks? [YES/no]: ",
529
+ _convert_yes_no_to_bool,
530
+ default=True,
531
+ error_message="Please enter yes or no.",
532
+ )
533
+
534
+ megatron_lm_config[prefix + "gradient_clipping"] = _ask_field(
535
+ "What is the gradient clipping value based on global L2 Norm (0 to disable)? [1.0]: ",
536
+ float,
537
+ default=1.0,
538
+ )
539
+ # TPU specific defaults
540
+ tpu_commands = None
541
+ tpu_command_file = None
542
+ tpu_downcast_bf16 = "no"
543
+ tpu_env = []
544
+ tpu_name = None
545
+ tpu_vm = None
546
+ tpu_zone = None
547
+ tpu_use_sudo = False
548
+ tpu_use_cluster = False
549
+
550
+ if distributed_type in [
551
+ DistributedType.MULTI_CPU,
552
+ DistributedType.MULTI_XPU,
553
+ DistributedType.MULTI_GPU,
554
+ DistributedType.MULTI_MLU,
555
+ DistributedType.MULTI_MUSA,
556
+ DistributedType.MULTI_NPU,
557
+ DistributedType.XLA,
558
+ ]:
559
+ machine_type = str(distributed_type).split(".")[1].replace("MULTI_", "")
560
+ if machine_type == "TPU":
561
+ machine_type += " cores"
562
+ elif machine_type == "CPU":
563
+ machine_type = "processes"
564
+ else:
565
+ machine_type += "(s)"
566
+ num_processes = _ask_field(
567
+ f"How many {machine_type} should be used for distributed training? [1]:",
568
+ int,
569
+ default=1,
570
+ error_message="Please enter an integer.",
571
+ )
572
+ elif distributed_type in [DistributedType.FSDP, DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]:
573
+ num_processes = _ask_field(
574
+ "How many GPU(s) should be used for distributed training? [1]:",
575
+ int,
576
+ default=1,
577
+ error_message="Please enter an integer.",
578
+ )
579
+ else:
580
+ num_processes = 1
581
+
582
+ if (distributed_type == DistributedType.MULTI_GPU) and (num_machines == 1) and (num_processes == 1):
583
+ raise ValueError(
584
+ f"Specified distributed type {distributed_type} but only using 1 GPU on a single machine. Please select `No distributed training` for the type of machine you are using."
585
+ )
586
+
587
+ if (
588
+ distributed_type
589
+ in [
590
+ DistributedType.MULTI_GPU,
591
+ DistributedType.MULTI_MLU,
592
+ DistributedType.MULTI_MUSA,
593
+ DistributedType.MULTI_NPU,
594
+ DistributedType.MULTI_XPU,
595
+ DistributedType.NO,
596
+ ]
597
+ and not use_cpu
598
+ and not use_mps
599
+ ):
600
+ if is_npu_available():
601
+ machine_type = "NPU(s)"
602
+ elif is_mlu_available():
603
+ machine_type = "MLU(s)"
604
+ elif is_musa_available():
605
+ machine_type = "MUSA(s)"
606
+ else:
607
+ machine_type = "GPU(s)"
608
+ gpu_ids = _ask_field(
609
+ f"What {machine_type} (by id) should be used for training on this machine as a comma-seperated list? [all]:",
610
+ default="all",
611
+ )
612
+
613
+ # CPU affinity is only supported on NVIDIA hardware for now
614
+ enable_cpu_affinity = False
615
+ if distributed_type in (DistributedType.NO, DistributedType.MULTI_GPU) and not use_cpu and not use_mps:
616
+ enable_cpu_affinity = _ask_field(
617
+ "Would you like to enable numa efficiency? (Currently only supported on NVIDIA hardware). [yes/NO]: ",
618
+ _convert_yes_no_to_bool,
619
+ default=False,
620
+ error_message="Please enter yes or no.",
621
+ )
622
+
623
+ fp8_config = None
624
+ if distributed_type == DistributedType.XLA:
625
+ mixed_precision = "no"
626
+ main_training_function = _ask_field(
627
+ "What is the name of the function in your script that should be launched in all parallel scripts? [main]: ",
628
+ default="main",
629
+ )
630
+ tpu_use_cluster = _ask_field(
631
+ "Are you using a TPU cluster? [yes/NO]: ",
632
+ _convert_yes_no_to_bool,
633
+ default=False,
634
+ error_message="Please enter yes or no.",
635
+ )
636
+ if tpu_use_cluster:
637
+ tpu_name = _ask_field(
638
+ "What is the name of your TPU cluster? ",
639
+ default=None,
640
+ error_message="Please enter the name of your TPU cluster.",
641
+ )
642
+ tpu_zone = _ask_field(
643
+ "What is the zone of your TPU cluster? ",
644
+ default=None,
645
+ error_message="Please enter the zone of your TPU cluster.",
646
+ )
647
+ tpu_use_sudo = _ask_field(
648
+ "To run a python script in a TPU pod, should `sudo` be used? [yes/NO]: ",
649
+ default=False,
650
+ error_message="Please enter yes or no.",
651
+ )
652
+ run_commands = _ask_field(
653
+ "Do you have code you wish to run on startup in each pod? [yes/NO]: ",
654
+ _convert_yes_no_to_bool,
655
+ default=False,
656
+ error_message="Please enter yes or no.",
657
+ )
658
+ if run_commands:
659
+ use_command_file = _ask_field(
660
+ "Is this code located in a bash script? [yes/NO]: ",
661
+ _convert_yes_no_to_bool,
662
+ default=False,
663
+ error_message="Please enter yes or no.",
664
+ )
665
+ if use_command_file:
666
+ tpu_command_file = _ask_field(
667
+ "What is the path to your bash script? ",
668
+ default=None,
669
+ error_message="Please enter the path to your bash script.",
670
+ )
671
+ tpu_command_file = os.path.abspath(tpu_command_file)
672
+ else:
673
+ print("Please enter each command seperately you wish to run on startup in each pod.")
674
+ tpu_commands = []
675
+ another_command = True
676
+ while another_command:
677
+ tpu_commands.append(
678
+ _ask_field(
679
+ "Please enter a single command to be ran ",
680
+ default=None,
681
+ error_message="Please enter the commands you wish to run on startup in each pod as a single string.",
682
+ )
683
+ )
684
+ another_command = _ask_field(
685
+ "Do you wish to add another command? [yes/NO]: ",
686
+ _convert_yes_no_to_bool,
687
+ default=False,
688
+ error_message="Please enter yes or no.",
689
+ )
690
+ tpu_vm = _ask_field(
691
+ "If not using an instance group, what are the names of the Compute VM instances to be used, seperated by a comma: ",
692
+ default="",
693
+ ).split(",")
694
+ tpu_env = _ask_field(
695
+ "What environment variables do you wish to set in each pod, seperated by a comma: ",
696
+ default="",
697
+ ).split(",")
698
+
699
+ else:
700
+ main_training_function = "main"
701
+ if distributed_type == DistributedType.DEEPSPEED and use_deepspeed_config:
702
+ mixed_precision = None
703
+ else:
704
+ mixed_precision = _ask_options(
705
+ "Do you wish to use mixed precision?",
706
+ ["no", "fp16", "bf16", "fp8"],
707
+ _convert_mixed_precision,
708
+ )
709
+ if mixed_precision == "fp8":
710
+ if not is_fp8_available():
711
+ raise ValueError("FP8 (either Transformer Engine or MSAMP) is not installed on this machine.")
712
+ fp8_config = {}
713
+ fp8_config["backend"] = _ask_options(
714
+ "Which FP8 backend do you want to use?",
715
+ ["te", "msamp"],
716
+ _convert_fp8_backend,
717
+ )
718
+ if fp8_config["backend"] == "TE":
719
+ if not is_transformer_engine_available():
720
+ raise ValueError("TransformersEngine was selected, but it is not installed on this machine.")
721
+ fp8_config["use_autocast_during_eval"] = _ask_field(
722
+ "Do you want to use FP8 autocast during eval mode? Generally better metrics are found when this is disabled [yes/NO]: ",
723
+ _convert_yes_no_to_bool,
724
+ default=False,
725
+ )
726
+ fp8_config["margin"] = _ask_field(
727
+ "What margin should be used for gradient scaling? [0]: ",
728
+ int,
729
+ default=0,
730
+ )
731
+ fp8_config["interval"] = _ask_field(
732
+ "What interval should be used for for how often the scaling factor is recomputed? [1]: ",
733
+ int,
734
+ default=1,
735
+ )
736
+ fp8_config["fp8_format"] = _ask_options(
737
+ "Which weight format should be used?",
738
+ ["HYBRID", "E4M3"],
739
+ lambda x: "HYBRID" if x == 0 else "E4M3",
740
+ default=0,
741
+ )
742
+ fp8_config["amax_history_length"] = _ask_field(
743
+ "What length of history should be used for the amax scaling factor computation? [1024]: ",
744
+ int,
745
+ default=1024,
746
+ )
747
+ fp8_config["amax_compute_algorithm"] = _ask_options(
748
+ "Which algorithm should be used for the amax scaling factor computation?",
749
+ ["max", "most_recent"],
750
+ lambda x: "max" if x == 0 else "most_recent",
751
+ default=0,
752
+ )
753
+ fp8_config["override_linear_precision"] = _ask_field(
754
+ "Do you want to to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision? [yes/NO]: ",
755
+ _convert_yes_no_to_bool,
756
+ default=False,
757
+ )
758
+ if fp8_config["override_linear_precision"]:
759
+ fprop = _ask_field(
760
+ "Should `fprop` be executed in higher precision? [yes/NO]: ",
761
+ _convert_yes_no_to_bool,
762
+ default=False,
763
+ )
764
+ dgrad = _ask_field(
765
+ "Should `dgrad` be executed in higher precision? [yes/NO]: ",
766
+ _convert_yes_no_to_bool,
767
+ default=False,
768
+ )
769
+ wgrad = _ask_field(
770
+ "Should `wgrad` be executed in higher precision? [yes/NO]: ",
771
+ _convert_yes_no_to_bool,
772
+ default=False,
773
+ )
774
+ fp8_config["override_linear_precision"] = (fprop, dgrad, wgrad)
775
+
776
+ elif fp8_config["backend"] == "MSAMP":
777
+ if not is_msamp_available():
778
+ raise ValueError("MSAMP was selected, but it is not installed on this machine.")
779
+ fp8_config["optimization_level"] = _ask_options(
780
+ "Which optimization level should be used?",
781
+ ["O1", "O2"],
782
+ lambda x: "O1" if x == 0 else "O2",
783
+ default=1,
784
+ )
785
+
786
+ if use_dynamo and mixed_precision == "no" and not use_cpu:
787
+ print(
788
+ "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts."
789
+ )
790
+
791
+ if distributed_type == DistributedType.XLA and mixed_precision == "bf16":
792
+ tpu_downcast_bf16 = _ask_field(
793
+ "Should `torch.float` be cast as `bfloat16` and `torch.double` remain `float32` on TPUs?", default="no"
794
+ )
795
+
796
+ return ClusterConfig(
797
+ compute_environment=ComputeEnvironment.LOCAL_MACHINE,
798
+ distributed_type=distributed_type,
799
+ num_processes=num_processes,
800
+ gpu_ids=gpu_ids,
801
+ mixed_precision=mixed_precision,
802
+ downcast_bf16=tpu_downcast_bf16,
803
+ machine_rank=machine_rank,
804
+ num_machines=num_machines,
805
+ main_process_ip=main_process_ip,
806
+ main_process_port=main_process_port,
807
+ main_training_function=main_training_function,
808
+ fp8_config=fp8_config,
809
+ deepspeed_config=deepspeed_config,
810
+ fsdp_config=fsdp_config,
811
+ megatron_lm_config=megatron_lm_config,
812
+ ipex_config=ipex_config,
813
+ mpirun_config=mpirun_config,
814
+ use_cpu=use_cpu,
815
+ rdzv_backend=rdzv_backend,
816
+ same_network=same_network,
817
+ commands=tpu_commands,
818
+ command_file=tpu_command_file,
819
+ tpu_env=tpu_env,
820
+ tpu_name=tpu_name,
821
+ tpu_vm=tpu_vm,
822
+ tpu_zone=tpu_zone,
823
+ tpu_use_sudo=tpu_use_sudo,
824
+ tpu_use_cluster=tpu_use_cluster,
825
+ dynamo_config=dynamo_config,
826
+ debug=debug,
827
+ enable_cpu_affinity=enable_cpu_affinity,
828
+ )
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import argparse
18
+ import os
19
+
20
+ from accelerate.utils import ComputeEnvironment
21
+
22
+ from .cluster import get_cluster_input
23
+ from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401
24
+ from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401
25
+ from .sagemaker import get_sagemaker_input
26
+
27
+
28
+ description = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine"
29
+
30
+
31
+ def get_user_input():
32
+ compute_environment = _ask_options(
33
+ "In which compute environment are you running?",
34
+ ["This machine", "AWS (Amazon SageMaker)"],
35
+ _convert_compute_environment,
36
+ )
37
+ if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
38
+ config = get_sagemaker_input()
39
+ else:
40
+ config = get_cluster_input()
41
+ return config
42
+
43
+
44
+ def config_command_parser(subparsers=None):
45
+ if subparsers is not None:
46
+ parser = subparsers.add_parser("config", description=description)
47
+ else:
48
+ parser = argparse.ArgumentParser("Accelerate config command", description=description)
49
+
50
+ parser.add_argument(
51
+ "--config_file",
52
+ default=None,
53
+ help=(
54
+ "The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
55
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
56
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
57
+ "with 'huggingface'."
58
+ ),
59
+ )
60
+
61
+ if subparsers is not None:
62
+ parser.set_defaults(func=config_command)
63
+ return parser
64
+
65
+
66
+ def config_command(args):
67
+ config = get_user_input()
68
+ if args.config_file is not None:
69
+ config_file = args.config_file
70
+ else:
71
+ if not os.path.isdir(cache_dir):
72
+ os.makedirs(cache_dir)
73
+ config_file = default_yaml_config_file
74
+
75
+ if config_file.endswith(".json"):
76
+ config.to_json_file(config_file)
77
+ else:
78
+ config.to_yaml_file(config_file)
79
+ print(f"accelerate configuration saved at {config_file}")
80
+
81
+
82
+ def main():
83
+ parser = config_command_parser()
84
+ args = parser.parse_args()
85
+ config_command(args)
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config_args.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import json
18
+ import os
19
+ from dataclasses import dataclass
20
+ from enum import Enum
21
+ from typing import List, Optional, Union
22
+
23
+ import yaml
24
+
25
+ from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
26
+ from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION
27
+
28
+
29
+ hf_cache_home = os.path.expanduser(
30
+ os.environ.get("HF_HOME", os.path.join(os.environ.get("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
31
+ )
32
+ cache_dir = os.path.join(hf_cache_home, "accelerate")
33
+ default_json_config_file = os.path.join(cache_dir, "default_config.yaml")
34
+ default_yaml_config_file = os.path.join(cache_dir, "default_config.yaml")
35
+
36
+ # For backward compatibility: the default config is the json one if it's the only existing file.
37
+ if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
38
+ default_config_file = default_yaml_config_file
39
+ else:
40
+ default_config_file = default_json_config_file
41
+
42
+
43
+ def load_config_from_file(config_file):
44
+ if config_file is not None:
45
+ if not os.path.isfile(config_file):
46
+ raise FileNotFoundError(
47
+ f"The passed configuration file `{config_file}` does not exist. "
48
+ "Please pass an existing file to `accelerate launch`, or use the default one "
49
+ "created through `accelerate config` and run `accelerate launch` "
50
+ "without the `--config_file` argument."
51
+ )
52
+ else:
53
+ config_file = default_config_file
54
+ with open(config_file, encoding="utf-8") as f:
55
+ if config_file.endswith(".json"):
56
+ if (
57
+ json.load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE)
58
+ == ComputeEnvironment.LOCAL_MACHINE
59
+ ):
60
+ config_class = ClusterConfig
61
+ else:
62
+ config_class = SageMakerConfig
63
+ return config_class.from_json_file(json_file=config_file)
64
+ else:
65
+ if (
66
+ yaml.safe_load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE)
67
+ == ComputeEnvironment.LOCAL_MACHINE
68
+ ):
69
+ config_class = ClusterConfig
70
+ else:
71
+ config_class = SageMakerConfig
72
+ return config_class.from_yaml_file(yaml_file=config_file)
73
+
74
+
75
+ @dataclass
76
+ class BaseConfig:
77
+ compute_environment: ComputeEnvironment
78
+ distributed_type: Union[DistributedType, SageMakerDistributedType]
79
+ mixed_precision: str
80
+ use_cpu: bool
81
+ debug: bool
82
+
83
+ def to_dict(self):
84
+ result = self.__dict__
85
+ # For serialization, it's best to convert Enums to strings (or their underlying value type).
86
+
87
+ def _convert_enums(value):
88
+ if isinstance(value, Enum):
89
+ return value.value
90
+ if isinstance(value, dict):
91
+ if not bool(value):
92
+ return None
93
+ for key1, value1 in value.items():
94
+ value[key1] = _convert_enums(value1)
95
+ return value
96
+
97
+ for key, value in result.items():
98
+ result[key] = _convert_enums(value)
99
+ result = {k: v for k, v in result.items() if v is not None}
100
+ return result
101
+
102
+ @staticmethod
103
+ def process_config(config_dict):
104
+ """
105
+ Processes `config_dict` and sets default values for any missing keys
106
+ """
107
+ if "compute_environment" not in config_dict:
108
+ config_dict["compute_environment"] = ComputeEnvironment.LOCAL_MACHINE
109
+ if "distributed_type" not in config_dict:
110
+ raise ValueError("A `distributed_type` must be specified in the config file.")
111
+ if "num_processes" not in config_dict and config_dict["distributed_type"] == DistributedType.NO:
112
+ config_dict["num_processes"] = 1
113
+ if "mixed_precision" not in config_dict:
114
+ config_dict["mixed_precision"] = "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
115
+ if "fp16" in config_dict: # Convert the config to the new format.
116
+ del config_dict["fp16"]
117
+ if "dynamo_backend" in config_dict: # Convert the config to the new format.
118
+ dynamo_backend = config_dict.pop("dynamo_backend")
119
+ config_dict["dynamo_config"] = {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
120
+ if "use_cpu" not in config_dict:
121
+ config_dict["use_cpu"] = False
122
+ if "debug" not in config_dict:
123
+ config_dict["debug"] = False
124
+ if "enable_cpu_affinity" not in config_dict:
125
+ config_dict["enable_cpu_affinity"] = False
126
+ return config_dict
127
+
128
+ @classmethod
129
+ def from_json_file(cls, json_file=None):
130
+ json_file = default_json_config_file if json_file is None else json_file
131
+ with open(json_file, encoding="utf-8") as f:
132
+ config_dict = json.load(f)
133
+ config_dict = cls.process_config(config_dict)
134
+ extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys()))
135
+ if len(extra_keys) > 0:
136
+ raise ValueError(
137
+ f"The config file at {json_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`"
138
+ " version or fix (and potentially remove) these keys from your config file."
139
+ )
140
+
141
+ return cls(**config_dict)
142
+
143
+ def to_json_file(self, json_file):
144
+ with open(json_file, "w", encoding="utf-8") as f:
145
+ content = json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
146
+ f.write(content)
147
+
148
+ @classmethod
149
+ def from_yaml_file(cls, yaml_file=None):
150
+ yaml_file = default_yaml_config_file if yaml_file is None else yaml_file
151
+ with open(yaml_file, encoding="utf-8") as f:
152
+ config_dict = yaml.safe_load(f)
153
+ config_dict = cls.process_config(config_dict)
154
+ extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys()))
155
+ if len(extra_keys) > 0:
156
+ raise ValueError(
157
+ f"The config file at {yaml_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`"
158
+ " version or fix (and potentially remove) these keys from your config file."
159
+ )
160
+ return cls(**config_dict)
161
+
162
+ def to_yaml_file(self, yaml_file):
163
+ with open(yaml_file, "w", encoding="utf-8") as f:
164
+ yaml.safe_dump(self.to_dict(), f)
165
+
166
+ def __post_init__(self):
167
+ if isinstance(self.compute_environment, str):
168
+ self.compute_environment = ComputeEnvironment(self.compute_environment)
169
+ if isinstance(self.distributed_type, str):
170
+ if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
171
+ self.distributed_type = SageMakerDistributedType(self.distributed_type)
172
+ else:
173
+ self.distributed_type = DistributedType(self.distributed_type)
174
+ if getattr(self, "dynamo_config", None) is None:
175
+ self.dynamo_config = {}
176
+
177
+
178
+ @dataclass
179
+ class ClusterConfig(BaseConfig):
180
+ num_processes: int = -1 # For instance if we use SLURM and the user manually passes it in
181
+ machine_rank: int = 0
182
+ num_machines: int = 1
183
+ gpu_ids: Optional[str] = None
184
+ main_process_ip: Optional[str] = None
185
+ main_process_port: Optional[int] = None
186
+ rdzv_backend: Optional[str] = "static"
187
+ same_network: Optional[bool] = False
188
+ main_training_function: str = "main"
189
+ enable_cpu_affinity: bool = False
190
+
191
+ # args for FP8 training
192
+ fp8_config: dict = None
193
+ # args for deepspeed_plugin
194
+ deepspeed_config: dict = None
195
+ # args for fsdp
196
+ fsdp_config: dict = None
197
+ # args for megatron_lm
198
+ megatron_lm_config: dict = None
199
+ # args for ipex
200
+ ipex_config: dict = None
201
+ # args for mpirun
202
+ mpirun_config: dict = None
203
+ # args for TPU
204
+ downcast_bf16: bool = False
205
+
206
+ # args for TPU pods
207
+ tpu_name: str = None
208
+ tpu_zone: str = None
209
+ tpu_use_cluster: bool = False
210
+ tpu_use_sudo: bool = False
211
+ command_file: str = None
212
+ commands: List[str] = None
213
+ tpu_vm: List[str] = None
214
+ tpu_env: List[str] = None
215
+
216
+ # args for dynamo
217
+ dynamo_config: dict = None
218
+
219
+ def __post_init__(self):
220
+ if self.deepspeed_config is None:
221
+ self.deepspeed_config = {}
222
+ if self.fsdp_config is None:
223
+ self.fsdp_config = {}
224
+ if self.megatron_lm_config is None:
225
+ self.megatron_lm_config = {}
226
+ if self.ipex_config is None:
227
+ self.ipex_config = {}
228
+ if self.mpirun_config is None:
229
+ self.mpirun_config = {}
230
+ if self.fp8_config is None:
231
+ self.fp8_config = {}
232
+ return super().__post_init__()
233
+
234
+
235
+ @dataclass
236
+ class SageMakerConfig(BaseConfig):
237
+ ec2_instance_type: str
238
+ iam_role_name: str
239
+ image_uri: Optional[str] = None
240
+ profile: Optional[str] = None
241
+ region: str = "us-east-1"
242
+ num_machines: int = 1
243
+ gpu_ids: str = "all"
244
+ base_job_name: str = f"accelerate-sagemaker-{num_machines}"
245
+ pytorch_version: str = SAGEMAKER_PYTORCH_VERSION
246
+ transformers_version: str = SAGEMAKER_TRANSFORMERS_VERSION
247
+ py_version: str = SAGEMAKER_PYTHON_VERSION
248
+ sagemaker_inputs_file: str = None
249
+ sagemaker_metrics_file: str = None
250
+ additional_args: dict = None
251
+ dynamo_config: dict = None
252
+ enable_cpu_affinity: bool = False
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config_utils.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import argparse
18
+
19
+ from ...utils.dataclasses import (
20
+ ComputeEnvironment,
21
+ DistributedType,
22
+ DynamoBackend,
23
+ FP8BackendType,
24
+ PrecisionType,
25
+ SageMakerDistributedType,
26
+ )
27
+ from ..menu import BulletMenu
28
+
29
+
30
+ DYNAMO_BACKENDS = [
31
+ "EAGER",
32
+ "AOT_EAGER",
33
+ "INDUCTOR",
34
+ "AOT_TS_NVFUSER",
35
+ "NVPRIMS_NVFUSER",
36
+ "CUDAGRAPHS",
37
+ "OFI",
38
+ "FX2TRT",
39
+ "ONNXRT",
40
+ "TENSORRT",
41
+ "AOT_TORCHXLA_TRACE_ONCE",
42
+ "TORHCHXLA_TRACE_ONCE",
43
+ "IPEX",
44
+ "TVM",
45
+ ]
46
+
47
+
48
+ def _ask_field(input_text, convert_value=None, default=None, error_message=None):
49
+ ask_again = True
50
+ while ask_again:
51
+ result = input(input_text)
52
+ try:
53
+ if default is not None and len(result) == 0:
54
+ return default
55
+ return convert_value(result) if convert_value is not None else result
56
+ except Exception:
57
+ if error_message is not None:
58
+ print(error_message)
59
+
60
+
61
+ def _ask_options(input_text, options=[], convert_value=None, default=0):
62
+ menu = BulletMenu(input_text, options)
63
+ result = menu.run(default_choice=default)
64
+ return convert_value(result) if convert_value is not None else result
65
+
66
+
67
+ def _convert_compute_environment(value):
68
+ value = int(value)
69
+ return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value])
70
+
71
+
72
+ def _convert_distributed_mode(value):
73
+ value = int(value)
74
+ return DistributedType(
75
+ ["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "MULTI_MLU", "MULTI_MUSA", "XLA"][value]
76
+ )
77
+
78
+
79
+ def _convert_dynamo_backend(value):
80
+ value = int(value)
81
+ return DynamoBackend(DYNAMO_BACKENDS[value]).value
82
+
83
+
84
+ def _convert_mixed_precision(value):
85
+ value = int(value)
86
+ return PrecisionType(["no", "fp16", "bf16", "fp8"][value])
87
+
88
+
89
+ def _convert_sagemaker_distributed_mode(value):
90
+ value = int(value)
91
+ return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value])
92
+
93
+
94
+ def _convert_fp8_backend(value):
95
+ value = int(value)
96
+ return FP8BackendType(["TE", "MSAMP"][value])
97
+
98
+
99
+ def _convert_yes_no_to_bool(value):
100
+ return {"yes": True, "no": False}[value.lower()]
101
+
102
+
103
+ class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter):
104
+ """
105
+ A custom formatter that will remove the usage line from the help message for subcommands.
106
+ """
107
+
108
+ def _format_usage(self, usage, actions, groups, prefix):
109
+ usage = super()._format_usage(usage, actions, groups, prefix)
110
+ usage = usage.replace("<command> [<args>] ", "")
111
+ return usage
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/default.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 pathlib import Path
18
+
19
+ import torch
20
+
21
+ from ...utils import is_mlu_available, is_musa_available, is_npu_available, is_xpu_available
22
+ from .config_args import ClusterConfig, default_json_config_file
23
+ from .config_utils import SubcommandHelpFormatter
24
+
25
+
26
+ description = "Create a default config file for Accelerate with only a few flags set."
27
+
28
+
29
+ def write_basic_config(mixed_precision="no", save_location: str = default_json_config_file, use_xpu: bool = False):
30
+ """
31
+ Creates and saves a basic cluster config to be used on a local machine with potentially multiple GPUs. Will also
32
+ set CPU if it is a CPU-only machine.
33
+
34
+ Args:
35
+ mixed_precision (`str`, *optional*, defaults to "no"):
36
+ Mixed Precision to use. Should be one of "no", "fp16", or "bf16"
37
+ save_location (`str`, *optional*, defaults to `default_json_config_file`):
38
+ Optional custom save location. Should be passed to `--config_file` when using `accelerate launch`. Default
39
+ location is inside the huggingface cache folder (`~/.cache/huggingface`) but can be overriden by setting
40
+ the `HF_HOME` environmental variable, followed by `accelerate/default_config.yaml`.
41
+ use_xpu (`bool`, *optional*, defaults to `False`):
42
+ Whether to use XPU if available.
43
+ """
44
+ path = Path(save_location)
45
+ path.parent.mkdir(parents=True, exist_ok=True)
46
+ if path.exists():
47
+ print(
48
+ f"Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`."
49
+ )
50
+ return False
51
+ mixed_precision = mixed_precision.lower()
52
+ if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
53
+ raise ValueError(
54
+ f"`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}"
55
+ )
56
+ config = {
57
+ "compute_environment": "LOCAL_MACHINE",
58
+ "mixed_precision": mixed_precision,
59
+ }
60
+ if is_mlu_available():
61
+ num_mlus = torch.mlu.device_count()
62
+ config["num_processes"] = num_mlus
63
+ config["use_cpu"] = False
64
+ if num_mlus > 1:
65
+ config["distributed_type"] = "MULTI_MLU"
66
+ else:
67
+ config["distributed_type"] = "NO"
68
+ elif is_musa_available():
69
+ num_musas = torch.musa.device_count()
70
+ config["num_processes"] = num_musas
71
+ config["use_cpu"] = False
72
+ if num_musas > 1:
73
+ config["distributed_type"] = "MULTI_MUSA"
74
+ else:
75
+ config["distributed_type"] = "NO"
76
+ elif torch.cuda.is_available():
77
+ num_gpus = torch.cuda.device_count()
78
+ config["num_processes"] = num_gpus
79
+ config["use_cpu"] = False
80
+ if num_gpus > 1:
81
+ config["distributed_type"] = "MULTI_GPU"
82
+ else:
83
+ config["distributed_type"] = "NO"
84
+ elif is_xpu_available() and use_xpu:
85
+ num_xpus = torch.xpu.device_count()
86
+ config["num_processes"] = num_xpus
87
+ config["use_cpu"] = False
88
+ if num_xpus > 1:
89
+ config["distributed_type"] = "MULTI_XPU"
90
+ else:
91
+ config["distributed_type"] = "NO"
92
+ elif is_npu_available():
93
+ num_npus = torch.npu.device_count()
94
+ config["num_processes"] = num_npus
95
+ config["use_cpu"] = False
96
+ if num_npus > 1:
97
+ config["distributed_type"] = "MULTI_NPU"
98
+ else:
99
+ config["distributed_type"] = "NO"
100
+ else:
101
+ num_xpus = 0
102
+ config["use_cpu"] = True
103
+ config["num_processes"] = 1
104
+ config["distributed_type"] = "NO"
105
+ config["debug"] = False
106
+ config["enable_cpu_affinity"] = False
107
+ config = ClusterConfig(**config)
108
+ config.to_json_file(path)
109
+ return path
110
+
111
+
112
+ def default_command_parser(parser, parents):
113
+ parser = parser.add_parser("default", parents=parents, help=description, formatter_class=SubcommandHelpFormatter)
114
+ parser.add_argument(
115
+ "--config_file",
116
+ default=default_json_config_file,
117
+ help=(
118
+ "The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
119
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
120
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
121
+ "with 'huggingface'."
122
+ ),
123
+ dest="save_location",
124
+ )
125
+
126
+ parser.add_argument(
127
+ "--mixed_precision",
128
+ choices=["no", "fp16", "bf16"],
129
+ type=str,
130
+ help="Whether or not to use mixed precision training. "
131
+ "Choose between FP16 and BF16 (bfloat16) training. "
132
+ "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.",
133
+ default="no",
134
+ )
135
+ parser.set_defaults(func=default_config_command)
136
+ return parser
137
+
138
+
139
+ def default_config_command(args):
140
+ config_file = write_basic_config(args.mixed_precision, args.save_location)
141
+ if config_file:
142
+ print(f"accelerate configuration saved at {config_file}")
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/sagemaker.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import json
17
+ import os
18
+
19
+ from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
20
+ from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
21
+ from ...utils.imports import is_boto3_available
22
+ from .config_args import SageMakerConfig
23
+ from .config_utils import (
24
+ DYNAMO_BACKENDS,
25
+ _ask_field,
26
+ _ask_options,
27
+ _convert_dynamo_backend,
28
+ _convert_mixed_precision,
29
+ _convert_sagemaker_distributed_mode,
30
+ _convert_yes_no_to_bool,
31
+ )
32
+
33
+
34
+ if is_boto3_available():
35
+ import boto3 # noqa: F401
36
+
37
+
38
+ def _create_iam_role_for_sagemaker(role_name):
39
+ iam_client = boto3.client("iam")
40
+
41
+ sagemaker_trust_policy = {
42
+ "Version": "2012-10-17",
43
+ "Statement": [
44
+ {"Effect": "Allow", "Principal": {"Service": "sagemaker.amazonaws.com"}, "Action": "sts:AssumeRole"}
45
+ ],
46
+ }
47
+ try:
48
+ # create the role, associated with the chosen trust policy
49
+ iam_client.create_role(
50
+ RoleName=role_name, AssumeRolePolicyDocument=json.dumps(sagemaker_trust_policy, indent=2)
51
+ )
52
+ policy_document = {
53
+ "Version": "2012-10-17",
54
+ "Statement": [
55
+ {
56
+ "Effect": "Allow",
57
+ "Action": [
58
+ "sagemaker:*",
59
+ "ecr:GetDownloadUrlForLayer",
60
+ "ecr:BatchGetImage",
61
+ "ecr:BatchCheckLayerAvailability",
62
+ "ecr:GetAuthorizationToken",
63
+ "cloudwatch:PutMetricData",
64
+ "cloudwatch:GetMetricData",
65
+ "cloudwatch:GetMetricStatistics",
66
+ "cloudwatch:ListMetrics",
67
+ "logs:CreateLogGroup",
68
+ "logs:CreateLogStream",
69
+ "logs:DescribeLogStreams",
70
+ "logs:PutLogEvents",
71
+ "logs:GetLogEvents",
72
+ "s3:CreateBucket",
73
+ "s3:ListBucket",
74
+ "s3:GetBucketLocation",
75
+ "s3:GetObject",
76
+ "s3:PutObject",
77
+ ],
78
+ "Resource": "*",
79
+ }
80
+ ],
81
+ }
82
+ # attach policy to role
83
+ iam_client.put_role_policy(
84
+ RoleName=role_name,
85
+ PolicyName=f"{role_name}_policy_permission",
86
+ PolicyDocument=json.dumps(policy_document, indent=2),
87
+ )
88
+ except iam_client.exceptions.EntityAlreadyExistsException:
89
+ print(f"role {role_name} already exists. Using existing one")
90
+
91
+
92
+ def _get_iam_role_arn(role_name):
93
+ iam_client = boto3.client("iam")
94
+ return iam_client.get_role(RoleName=role_name)["Role"]["Arn"]
95
+
96
+
97
+ def get_sagemaker_input():
98
+ credentials_configuration = _ask_options(
99
+ "How do you want to authorize?",
100
+ ["AWS Profile", "Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) "],
101
+ int,
102
+ )
103
+ aws_profile = None
104
+ if credentials_configuration == 0:
105
+ aws_profile = _ask_field("Enter your AWS Profile name: [default] ", default="default")
106
+ os.environ["AWS_PROFILE"] = aws_profile
107
+ else:
108
+ print(
109
+ "Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,"
110
+ "`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`"
111
+ )
112
+ aws_access_key_id = _ask_field("AWS Access Key ID: ")
113
+ os.environ["AWS_ACCESS_KEY_ID"] = aws_access_key_id
114
+
115
+ aws_secret_access_key = _ask_field("AWS Secret Access Key: ")
116
+ os.environ["AWS_SECRET_ACCESS_KEY"] = aws_secret_access_key
117
+
118
+ aws_region = _ask_field("Enter your AWS Region: [us-east-1]", default="us-east-1")
119
+ os.environ["AWS_DEFAULT_REGION"] = aws_region
120
+
121
+ role_management = _ask_options(
122
+ "Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?",
123
+ ["Provide IAM Role name", "Create new IAM role using credentials"],
124
+ int,
125
+ )
126
+ if role_management == 0:
127
+ iam_role_name = _ask_field("Enter your IAM role name: ")
128
+ else:
129
+ iam_role_name = "accelerate_sagemaker_execution_role"
130
+ print(f'Accelerate will create an iam role "{iam_role_name}" using the provided credentials')
131
+ _create_iam_role_for_sagemaker(iam_role_name)
132
+
133
+ is_custom_docker_image = _ask_field(
134
+ "Do you want to use custom Docker image? [yes/NO]: ",
135
+ _convert_yes_no_to_bool,
136
+ default=False,
137
+ error_message="Please enter yes or no.",
138
+ )
139
+ docker_image = None
140
+ if is_custom_docker_image:
141
+ docker_image = _ask_field("Enter your Docker image: ", lambda x: str(x).lower())
142
+
143
+ is_sagemaker_inputs_enabled = _ask_field(
144
+ "Do you want to provide SageMaker input channels with data locations? [yes/NO]: ",
145
+ _convert_yes_no_to_bool,
146
+ default=False,
147
+ error_message="Please enter yes or no.",
148
+ )
149
+ sagemaker_inputs_file = None
150
+ if is_sagemaker_inputs_enabled:
151
+ sagemaker_inputs_file = _ask_field(
152
+ "Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ",
153
+ lambda x: str(x).lower(),
154
+ )
155
+
156
+ is_sagemaker_metrics_enabled = _ask_field(
157
+ "Do you want to enable SageMaker metrics? [yes/NO]: ",
158
+ _convert_yes_no_to_bool,
159
+ default=False,
160
+ error_message="Please enter yes or no.",
161
+ )
162
+ sagemaker_metrics_file = None
163
+ if is_sagemaker_metrics_enabled:
164
+ sagemaker_metrics_file = _ask_field(
165
+ "Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ",
166
+ lambda x: str(x).lower(),
167
+ )
168
+
169
+ distributed_type = _ask_options(
170
+ "What is the distributed mode?",
171
+ ["No distributed training", "Data parallelism"],
172
+ _convert_sagemaker_distributed_mode,
173
+ )
174
+ dynamo_config = {}
175
+ use_dynamo = _ask_field(
176
+ "Do you wish to optimize your script with torch dynamo?[yes/NO]:",
177
+ _convert_yes_no_to_bool,
178
+ default=False,
179
+ error_message="Please enter yes or no.",
180
+ )
181
+ if use_dynamo:
182
+ prefix = "dynamo_"
183
+ dynamo_config[prefix + "backend"] = _ask_options(
184
+ "Which dynamo backend would you like to use?",
185
+ [x.lower() for x in DYNAMO_BACKENDS],
186
+ _convert_dynamo_backend,
187
+ default=2,
188
+ )
189
+ use_custom_options = _ask_field(
190
+ "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ",
191
+ _convert_yes_no_to_bool,
192
+ default=False,
193
+ error_message="Please enter yes or no.",
194
+ )
195
+
196
+ if use_custom_options:
197
+ dynamo_config[prefix + "mode"] = _ask_options(
198
+ "Which mode do you want to use?",
199
+ TORCH_DYNAMO_MODES,
200
+ lambda x: TORCH_DYNAMO_MODES[int(x)],
201
+ default="default",
202
+ )
203
+ dynamo_config[prefix + "use_fullgraph"] = _ask_field(
204
+ "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ",
205
+ _convert_yes_no_to_bool,
206
+ default=False,
207
+ error_message="Please enter yes or no.",
208
+ )
209
+ dynamo_config[prefix + "use_dynamic"] = _ask_field(
210
+ "Do you want to enable dynamic shape tracing? [yes/NO]: ",
211
+ _convert_yes_no_to_bool,
212
+ default=False,
213
+ error_message="Please enter yes or no.",
214
+ )
215
+ ec2_instance_query = "Which EC2 instance type you want to use for your training?"
216
+ if distributed_type != SageMakerDistributedType.NO:
217
+ ec2_instance_type = _ask_options(
218
+ ec2_instance_query, SAGEMAKER_PARALLEL_EC2_INSTANCES, lambda x: SAGEMAKER_PARALLEL_EC2_INSTANCES[int(x)]
219
+ )
220
+ else:
221
+ ec2_instance_query += "? [ml.p3.2xlarge]:"
222
+ ec2_instance_type = _ask_field(ec2_instance_query, lambda x: str(x).lower(), default="ml.p3.2xlarge")
223
+
224
+ debug = False
225
+ if distributed_type != SageMakerDistributedType.NO:
226
+ debug = _ask_field(
227
+ "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ",
228
+ _convert_yes_no_to_bool,
229
+ default=False,
230
+ error_message="Please enter yes or no.",
231
+ )
232
+
233
+ num_machines = 1
234
+ if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
235
+ num_machines = _ask_field(
236
+ "How many machines do you want use? [1]: ",
237
+ int,
238
+ default=1,
239
+ )
240
+
241
+ mixed_precision = _ask_options(
242
+ "Do you wish to use FP16 or BF16 (mixed precision)?",
243
+ ["no", "fp16", "bf16", "fp8"],
244
+ _convert_mixed_precision,
245
+ )
246
+
247
+ if use_dynamo and mixed_precision == "no":
248
+ print(
249
+ "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts."
250
+ )
251
+
252
+ return SageMakerConfig(
253
+ image_uri=docker_image,
254
+ compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER,
255
+ distributed_type=distributed_type,
256
+ use_cpu=False,
257
+ dynamo_config=dynamo_config,
258
+ ec2_instance_type=ec2_instance_type,
259
+ profile=aws_profile,
260
+ region=aws_region,
261
+ iam_role_name=iam_role_name,
262
+ mixed_precision=mixed_precision,
263
+ num_machines=num_machines,
264
+ sagemaker_inputs_file=sagemaker_inputs_file,
265
+ sagemaker_metrics_file=sagemaker_metrics_file,
266
+ debug=debug,
267
+ )
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/update.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2022 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 pathlib import Path
18
+
19
+ from .config_args import default_config_file, load_config_from_file
20
+ from .config_utils import SubcommandHelpFormatter
21
+
22
+
23
+ description = "Update an existing config file with the latest defaults while maintaining the old configuration."
24
+
25
+
26
+ def update_config(args):
27
+ """
28
+ Update an existing config file with the latest defaults while maintaining the old configuration.
29
+ """
30
+ config_file = args.config_file
31
+ if config_file is None and Path(default_config_file).exists():
32
+ config_file = default_config_file
33
+ elif not Path(config_file).exists():
34
+ raise ValueError(f"The passed config file located at {config_file} doesn't exist.")
35
+ config = load_config_from_file(config_file)
36
+
37
+ if config_file.endswith(".json"):
38
+ config.to_json_file(config_file)
39
+ else:
40
+ config.to_yaml_file(config_file)
41
+ return config_file
42
+
43
+
44
+ def update_command_parser(parser, parents):
45
+ parser = parser.add_parser("update", parents=parents, help=description, formatter_class=SubcommandHelpFormatter)
46
+ parser.add_argument(
47
+ "--config_file",
48
+ default=None,
49
+ help=(
50
+ "The path to the config file to update. Will default to a file named default_config.yaml in the cache "
51
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
52
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
53
+ "with 'huggingface'."
54
+ ),
55
+ )
56
+
57
+ parser.set_defaults(func=update_config_command)
58
+ return parser
59
+
60
+
61
+ def update_config_command(args):
62
+ config_file = update_config(args)
63
+ print(f"Sucessfully updated the configuration file at {config_file}.")
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/env.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2022 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
+ import argparse
18
+ import os
19
+ import platform
20
+ import subprocess
21
+
22
+ import numpy as np
23
+ import psutil
24
+ import torch
25
+
26
+ from accelerate import __version__ as version
27
+ from accelerate.commands.config import default_config_file, load_config_from_file
28
+
29
+ from ..utils import is_mlu_available, is_musa_available, is_npu_available, is_xpu_available
30
+
31
+
32
+ def env_command_parser(subparsers=None):
33
+ if subparsers is not None:
34
+ parser = subparsers.add_parser("env")
35
+ else:
36
+ parser = argparse.ArgumentParser("Accelerate env command")
37
+
38
+ parser.add_argument(
39
+ "--config_file", default=None, help="The config file to use for the default values in the launching script."
40
+ )
41
+
42
+ if subparsers is not None:
43
+ parser.set_defaults(func=env_command)
44
+ return parser
45
+
46
+
47
+ def env_command(args):
48
+ pt_version = torch.__version__
49
+ pt_cuda_available = torch.cuda.is_available()
50
+ pt_xpu_available = is_xpu_available()
51
+ pt_mlu_available = is_mlu_available()
52
+ pt_musa_available = is_musa_available()
53
+ pt_npu_available = is_npu_available()
54
+
55
+ accelerate_config = "Not found"
56
+ # Get the default from the config file.
57
+ if args.config_file is not None or os.path.isfile(default_config_file):
58
+ accelerate_config = load_config_from_file(args.config_file).to_dict()
59
+
60
+ # if we can run which, get it
61
+ command = None
62
+ bash_location = "Not found"
63
+ if os.name == "nt":
64
+ command = ["where", "accelerate"]
65
+ elif os.name == "posix":
66
+ command = ["which", "accelerate"]
67
+ if command is not None:
68
+ bash_location = subprocess.check_output(command, text=True, stderr=subprocess.STDOUT).strip()
69
+ info = {
70
+ "`Accelerate` version": version,
71
+ "Platform": platform.platform(),
72
+ "`accelerate` bash location": bash_location,
73
+ "Python version": platform.python_version(),
74
+ "Numpy version": np.__version__,
75
+ "PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})",
76
+ "PyTorch XPU available": str(pt_xpu_available),
77
+ "PyTorch NPU available": str(pt_npu_available),
78
+ "PyTorch MLU available": str(pt_mlu_available),
79
+ "PyTorch MUSA available": str(pt_musa_available),
80
+ "System RAM": f"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB",
81
+ }
82
+ if pt_cuda_available:
83
+ info["GPU type"] = torch.cuda.get_device_name()
84
+ if pt_mlu_available:
85
+ info["MLU type"] = torch.mlu.get_device_name()
86
+ if pt_npu_available:
87
+ info["CANN version"] = torch.version.cann
88
+
89
+ print("\nCopy-and-paste the text below in your GitHub issue\n")
90
+ print("\n".join([f"- {prop}: {val}" for prop, val in info.items()]))
91
+
92
+ print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:")
93
+ accelerate_config_str = (
94
+ "\n".join([f"\t- {prop}: {val}" for prop, val in accelerate_config.items()])
95
+ if isinstance(accelerate_config, dict)
96
+ else f"\t{accelerate_config}"
97
+ )
98
+ print(accelerate_config_str)
99
+
100
+ info["`Accelerate` configs"] = accelerate_config
101
+
102
+ return info
103
+
104
+
105
+ def main() -> int:
106
+ parser = env_command_parser()
107
+ args = parser.parse_args()
108
+ env_command(args)
109
+ return 0
110
+
111
+
112
+ if __name__ == "__main__":
113
+ raise SystemExit(main())
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/estimate.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2023 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
+ from huggingface_hub import model_info
17
+ from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
18
+
19
+ from accelerate import init_empty_weights
20
+ from accelerate.commands.utils import CustomArgumentParser
21
+ from accelerate.utils import (
22
+ calculate_maximum_sizes,
23
+ convert_bytes,
24
+ is_timm_available,
25
+ is_transformers_available,
26
+ )
27
+
28
+
29
+ if is_transformers_available():
30
+ import transformers
31
+ from transformers import AutoConfig, AutoModel
32
+
33
+ if is_timm_available():
34
+ import timm
35
+
36
+
37
+ def verify_on_hub(repo: str, token: str = None):
38
+ "Verifies that the model is on the hub and returns the model info."
39
+ try:
40
+ return model_info(repo, token=token)
41
+ except (OSError, GatedRepoError):
42
+ return "gated"
43
+ except RepositoryNotFoundError:
44
+ return "repo"
45
+
46
+
47
+ def check_has_model(error):
48
+ """
49
+ Checks what library spawned `error` when a model is not found
50
+ """
51
+ if is_timm_available() and isinstance(error, RuntimeError) and "Unknown model" in error.args[0]:
52
+ return "timm"
53
+ elif (
54
+ is_transformers_available()
55
+ and isinstance(error, OSError)
56
+ and "does not appear to have a file named" in error.args[0]
57
+ ):
58
+ return "transformers"
59
+ else:
60
+ return "unknown"
61
+
62
+
63
+ def create_empty_model(model_name: str, library_name: str, trust_remote_code: bool = False, access_token: str = None):
64
+ """
65
+ Creates an empty model from its parent library on the `Hub` to calculate the overall memory consumption.
66
+
67
+ Args:
68
+ model_name (`str`):
69
+ The model name on the Hub
70
+ library_name (`str`):
71
+ The library the model has an integration with, such as `transformers`. Will be used if `model_name` has no
72
+ metadata on the Hub to determine the library.
73
+ trust_remote_code (`bool`, `optional`, defaults to `False`):
74
+ Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
75
+ should only be set to `True` for repositories you trust and in which you have read the code, as it will
76
+ execute code present on the Hub on your local machine.
77
+ access_token (`str`, `optional`, defaults to `None`):
78
+ The access token to use to access private or gated models on the Hub. (for use on the Gradio app)
79
+
80
+ Returns:
81
+ `torch.nn.Module`: The torch model that has been initialized on the `meta` device.
82
+
83
+ """
84
+ model_info = verify_on_hub(model_name, access_token)
85
+ # Simplified errors
86
+ if model_info == "gated":
87
+ raise GatedRepoError(
88
+ f"Repo for model `{model_name}` is gated. You must be authenticated to access it. Please run `huggingface-cli login`."
89
+ )
90
+ elif model_info == "repo":
91
+ raise RepositoryNotFoundError(
92
+ f"Repo for model `{model_name}` does not exist on the Hub. If you are trying to access a private repo,"
93
+ " make sure you are authenticated via `huggingface-cli login` and have access."
94
+ )
95
+ if library_name is None:
96
+ library_name = getattr(model_info, "library_name", False)
97
+ if not library_name:
98
+ raise ValueError(
99
+ f"Model `{model_name}` does not have any library metadata on the Hub, please manually pass in a `--library_name` to use (such as `transformers`)"
100
+ )
101
+ if library_name == "transformers":
102
+ if not is_transformers_available():
103
+ raise ImportError(
104
+ f"To check `{model_name}`, `transformers` must be installed. Please install it via `pip install transformers`"
105
+ )
106
+ print(f"Loading pretrained config for `{model_name}` from `transformers`...")
107
+ if model_info.config is None:
108
+ raise RuntimeError(f"Tried to load `{model_name}` with `transformers` but it does not have any metadata.")
109
+
110
+ auto_map = model_info.config.get("auto_map", False)
111
+ config = AutoConfig.from_pretrained(model_name, trust_remote_code=trust_remote_code, token=access_token)
112
+ with init_empty_weights():
113
+ # remote code could specify a specific `AutoModel` class in the `auto_map`
114
+ constructor = AutoModel
115
+ if isinstance(auto_map, dict):
116
+ value = None
117
+ for key in auto_map.keys():
118
+ if key.startswith("AutoModelFor"):
119
+ value = key
120
+ break
121
+ if value is not None:
122
+ constructor = getattr(transformers, value)
123
+ model = constructor.from_config(config, trust_remote_code=trust_remote_code)
124
+ elif library_name == "timm":
125
+ if not is_timm_available():
126
+ raise ImportError(
127
+ f"To check `{model_name}`, `timm` must be installed. Please install it via `pip install timm`"
128
+ )
129
+ print(f"Loading pretrained config for `{model_name}` from `timm`...")
130
+ with init_empty_weights():
131
+ model = timm.create_model(model_name, pretrained=False)
132
+ else:
133
+ raise ValueError(
134
+ f"Library `{library_name}` is not supported yet, please open an issue on GitHub for us to add support."
135
+ )
136
+ return model
137
+
138
+
139
+ def create_ascii_table(headers: list, rows: list, title: str):
140
+ "Creates a pretty table from a list of rows, minimal version of `tabulate`."
141
+ sep_char, in_between = "│", "─"
142
+ column_widths = []
143
+ for i in range(len(headers)):
144
+ column_values = [row[i] for row in rows] + [headers[i]]
145
+ max_column_width = max(len(value) for value in column_values)
146
+ column_widths.append(max_column_width)
147
+
148
+ formats = [f"%{column_widths[i]}s" for i in range(len(rows[0]))]
149
+
150
+ pattern = f"{sep_char}{sep_char.join(formats)}{sep_char}"
151
+ diff = 0
152
+
153
+ def make_row(left_char, middle_char, right_char):
154
+ return f"{left_char}{middle_char.join([in_between * n for n in column_widths])}{in_between * diff}{right_char}"
155
+
156
+ separator = make_row("├", "┼", "┤")
157
+ if len(title) > sum(column_widths):
158
+ diff = abs(len(title) - len(separator))
159
+ column_widths[-1] += diff
160
+
161
+ # Update with diff
162
+ separator = make_row("├", "┼", "┤")
163
+ initial_rows = [
164
+ make_row("┌", in_between, "┐"),
165
+ f"{sep_char}{title.center(len(separator) - 2)}{sep_char}",
166
+ make_row("├", "┬", "┤"),
167
+ ]
168
+ table = "\n".join(initial_rows) + "\n"
169
+ column_widths[-1] += diff
170
+ centered_line = [text.center(column_widths[i]) for i, text in enumerate(headers)]
171
+ table += f"{pattern % tuple(centered_line)}\n{separator}\n"
172
+ for i, line in enumerate(rows):
173
+ centered_line = [t.center(column_widths[i]) for i, t in enumerate(line)]
174
+ table += f"{pattern % tuple(centered_line)}\n"
175
+ table += f'└{"┴".join([in_between * n for n in column_widths])}┘'
176
+
177
+ return table
178
+
179
+
180
+ def estimate_command_parser(subparsers=None):
181
+ if subparsers is not None:
182
+ parser = subparsers.add_parser("estimate-memory")
183
+ else:
184
+ parser = CustomArgumentParser(description="Model size estimator for fitting a model onto CUDA memory.")
185
+
186
+ parser.add_argument("model_name", type=str, help="The model name on the Hugging Face Hub.")
187
+ parser.add_argument(
188
+ "--library_name",
189
+ type=str,
190
+ help="The library the model has an integration with, such as `transformers`, needed only if this information is not stored on the Hub.",
191
+ choices=["timm", "transformers"],
192
+ )
193
+ parser.add_argument(
194
+ "--dtypes",
195
+ type=str,
196
+ nargs="+",
197
+ default=["float32", "float16", "int8", "int4"],
198
+ help="The dtypes to use for the model, must be one (or many) of `float32`, `float16`, `int8`, and `int4`",
199
+ choices=["float32", "float16", "int8", "int4"],
200
+ )
201
+ parser.add_argument(
202
+ "--trust_remote_code",
203
+ action="store_true",
204
+ help="""Whether or not to allow for custom models defined on the Hub in their own modeling files. This flag
205
+ should only be used for repositories you trust and in which you have read the code, as it will execute
206
+ code present on the Hub on your local machine.""",
207
+ default=False,
208
+ )
209
+
210
+ if subparsers is not None:
211
+ parser.set_defaults(func=estimate_command)
212
+ return parser
213
+
214
+
215
+ def estimate_training_usage(bytes: int, mixed_precision: str, msamp_config: str = None) -> dict:
216
+ """
217
+ Given an amount of `bytes` and `mixed_precision`, calculates how much training memory is needed for a batch size of
218
+ 1.
219
+
220
+ Args:
221
+ bytes (`int`):
222
+ The size of the model being trained.
223
+ mixed_precision (`str`):
224
+ The mixed precision that would be ran.
225
+ msamp_config (`str`):
226
+ The msamp config to estimate the training memory for if `mixed_precision` is set to `"fp8"`.
227
+ """
228
+ memory_sizes = {"model": -1, "optimizer": -1, "gradients": -1, "step": -1}
229
+ fp32_size = bytes
230
+ fp16_size = bytes // 2
231
+
232
+ if mixed_precision == "float32":
233
+ memory_sizes["model"] = fp32_size
234
+ memory_sizes["gradients"] = fp32_size
235
+ memory_sizes["optimizer"] = fp32_size * 2
236
+ memory_sizes["step"] = fp32_size * 4
237
+ elif mixed_precision in ("float16", "bfloat16") or (mixed_precision == "fp8" and msamp_config is None):
238
+ # With native `TransformersEngine`, there is no memory savings with FP8
239
+ # With mixed precision training, the model has weights stored
240
+ # in FP16 and FP32
241
+ memory_sizes["model"] = fp32_size
242
+ # 1.5 from weight gradient + computation (GEMM)
243
+ memory_sizes["gradients"] = fp32_size + fp16_size
244
+ # 2x from optimizer states
245
+ memory_sizes["optimizer"] = fp32_size * 2 # Optimizer states
246
+ memory_sizes["step"] = memory_sizes["optimizer"]
247
+ return memory_sizes
248
+
249
+
250
+ def gather_data(args):
251
+ "Creates an empty model and gathers the data for the sizes"
252
+ try:
253
+ model = create_empty_model(
254
+ args.model_name, library_name=args.library_name, trust_remote_code=args.trust_remote_code
255
+ )
256
+ except (RuntimeError, OSError) as e:
257
+ library = check_has_model(e)
258
+ if library != "unknown":
259
+ raise RuntimeError(
260
+ f"Tried to load `{args.model_name}` with `{library}` but a possible model to load was not found inside the repo."
261
+ )
262
+ raise e
263
+
264
+ total_size, largest_layer = calculate_maximum_sizes(model)
265
+
266
+ data = []
267
+
268
+ for dtype in args.dtypes:
269
+ dtype_total_size = total_size
270
+ dtype_largest_layer = largest_layer[0]
271
+ dtype_training_size = estimate_training_usage(dtype_total_size, dtype)
272
+ if dtype == "float16":
273
+ dtype_total_size /= 2
274
+ dtype_largest_layer /= 2
275
+ elif dtype == "int8":
276
+ dtype_total_size /= 4
277
+ dtype_largest_layer /= 4
278
+ elif dtype == "int4":
279
+ dtype_total_size /= 8
280
+ dtype_largest_layer /= 8
281
+ data.append([dtype, dtype_largest_layer, dtype_total_size, dtype_training_size])
282
+ return data
283
+
284
+
285
+ def estimate_command(args):
286
+ data = gather_data(args)
287
+ for row in data:
288
+ for i, item in enumerate(row):
289
+ if isinstance(item, (int, float)):
290
+ row[i] = convert_bytes(item)
291
+ elif isinstance(item, dict):
292
+ training_usage = max(item.values())
293
+ row[i] = convert_bytes(training_usage) if training_usage != -1 else "N/A"
294
+
295
+ headers = ["dtype", "Largest Layer", "Total Size", "Training using Adam"]
296
+
297
+ title = f"Memory Usage for loading `{args.model_name}`"
298
+ table = create_ascii_table(headers, data, title)
299
+ print(table)
300
+
301
+
302
+ def main():
303
+ parser = estimate_command_parser()
304
+ args = parser.parse_args()
305
+ estimate_command(args)
306
+
307
+
308
+ if __name__ == "__main__":
309
+ main()
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/launch.py ADDED
@@ -0,0 +1,1178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import argparse
18
+ import importlib
19
+ import logging
20
+ import os
21
+ import subprocess
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ import psutil
26
+ import torch
27
+
28
+ from accelerate.commands.config import default_config_file, load_config_from_file
29
+ from accelerate.commands.config.config_args import SageMakerConfig
30
+ from accelerate.commands.config.config_utils import DYNAMO_BACKENDS
31
+ from accelerate.commands.utils import CustomArgumentParser
32
+ from accelerate.state import get_int_from_env
33
+ from accelerate.utils import (
34
+ ComputeEnvironment,
35
+ DistributedType,
36
+ PrepareForLaunch,
37
+ _filter_args,
38
+ check_cuda_p2p_ib_support,
39
+ convert_dict_to_env_variables,
40
+ is_bf16_available,
41
+ is_deepspeed_available,
42
+ is_mlu_available,
43
+ is_musa_available,
44
+ is_npu_available,
45
+ is_rich_available,
46
+ is_sagemaker_available,
47
+ is_torch_version,
48
+ is_torch_xla_available,
49
+ is_xpu_available,
50
+ patch_environment,
51
+ prepare_deepspeed_cmd_env,
52
+ prepare_multi_gpu_env,
53
+ prepare_sagemager_args_inputs,
54
+ prepare_simple_launcher_cmd_env,
55
+ prepare_tpu,
56
+ str_to_bool,
57
+ )
58
+ from accelerate.utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS, TORCH_DYNAMO_MODES
59
+
60
+
61
+ if is_rich_available():
62
+ from rich import get_console
63
+ from rich.logging import RichHandler
64
+
65
+ FORMAT = "%(message)s"
66
+ logging.basicConfig(format=FORMAT, datefmt="[%X]", handlers=[RichHandler()])
67
+
68
+
69
+ logger = logging.getLogger(__name__)
70
+
71
+
72
+ options_to_group = {
73
+ "multi_gpu": "Distributed GPUs",
74
+ "tpu": "TPU",
75
+ "use_deepspeed": "DeepSpeed Arguments",
76
+ "use_fsdp": "FSDP Arguments",
77
+ "use_megatron_lm": "Megatron-LM Arguments",
78
+ "fp8_backend": "FP8 Arguments",
79
+ }
80
+
81
+
82
+ def clean_option(option):
83
+ "Finds all cases of - after the first two characters and changes them to _"
84
+ if "fp8_backend" in option:
85
+ option = "--fp8_backend"
86
+ if option.startswith("--"):
87
+ return option[2:].replace("-", "_")
88
+
89
+
90
+ class CustomHelpFormatter(argparse.HelpFormatter):
91
+ """
92
+ This is a custom help formatter that will hide all arguments that are not used in the command line when the help is
93
+ called. This is useful for the case where the user is using a specific platform and only wants to see the arguments
94
+ for that platform.
95
+ """
96
+
97
+ def __init__(self, *args, **kwargs):
98
+ super().__init__(*args, **kwargs)
99
+ self.titles = [
100
+ "Hardware Selection Arguments",
101
+ "Resource Selection Arguments",
102
+ "Training Paradigm Arguments",
103
+ "positional arguments",
104
+ "optional arguments",
105
+ ]
106
+
107
+ def add_argument(self, action: argparse.Action):
108
+ if "accelerate" in sys.argv[0] and "launch" in sys.argv[1:]:
109
+ args = sys.argv[2:]
110
+ else:
111
+ args = sys.argv[1:]
112
+
113
+ if len(args) > 1:
114
+ args = list(map(clean_option, args))
115
+ used_platforms = [arg for arg in args if arg in options_to_group.keys()]
116
+ used_titles = [options_to_group[o] for o in used_platforms]
117
+ if action.container.title not in self.titles + used_titles:
118
+ action.help = argparse.SUPPRESS
119
+ elif action.container.title == "Hardware Selection Arguments":
120
+ if set(action.option_strings).isdisjoint(set(args)):
121
+ action.help = argparse.SUPPRESS
122
+ else:
123
+ action.help = action.help + " (currently selected)"
124
+ elif action.container.title == "Training Paradigm Arguments":
125
+ if set(action.option_strings).isdisjoint(set(args)):
126
+ action.help = argparse.SUPPRESS
127
+ else:
128
+ action.help = action.help + " (currently selected)"
129
+
130
+ action.option_strings = [s for s in action.option_strings if "-" not in s[2:]]
131
+ super().add_argument(action)
132
+
133
+ def end_section(self):
134
+ if len(self._current_section.items) < 2:
135
+ self._current_section.items = []
136
+ self._current_section.heading = ""
137
+ super().end_section()
138
+
139
+
140
+ def launch_command_parser(subparsers=None):
141
+ description = "Launch a python script in a distributed scenario. Arguments can be passed in with either hyphens (`--num-processes=2`) or underscores (`--num_processes=2`)"
142
+ if subparsers is not None:
143
+ parser = subparsers.add_parser(
144
+ "launch", description=description, add_help=False, allow_abbrev=False, formatter_class=CustomHelpFormatter
145
+ )
146
+ else:
147
+ parser = CustomArgumentParser(
148
+ "Accelerate launch command",
149
+ description=description,
150
+ add_help=False,
151
+ allow_abbrev=False,
152
+ formatter_class=CustomHelpFormatter,
153
+ )
154
+
155
+ parser.add_argument("-h", "--help", action="help", help="Show this help message and exit.")
156
+
157
+ parser.add_argument(
158
+ "--config_file",
159
+ default=None,
160
+ help="The config file to use for the default values in the launching script.",
161
+ )
162
+ parser.add_argument(
163
+ "--quiet",
164
+ "-q",
165
+ action="store_true",
166
+ help="Silence subprocess errors from the launch stack trace and only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations)",
167
+ )
168
+ # Hardware selection arguments
169
+ hardware_args = parser.add_argument_group(
170
+ "Hardware Selection Arguments", "Arguments for selecting the hardware to be used."
171
+ )
172
+ hardware_args.add_argument(
173
+ "--cpu", default=False, action="store_true", help="Whether or not to force the training on the CPU."
174
+ )
175
+ hardware_args.add_argument(
176
+ "--multi_gpu",
177
+ default=False,
178
+ action="store_true",
179
+ help="Whether or not this should launch a distributed GPU training.",
180
+ )
181
+ hardware_args.add_argument(
182
+ "--tpu", default=False, action="store_true", help="Whether or not this should launch a TPU training."
183
+ )
184
+ hardware_args.add_argument(
185
+ "--ipex",
186
+ default=False,
187
+ action="store_true",
188
+ help="Whether or not this should launch a Intel PyTorch Extension (IPEX) training.",
189
+ )
190
+
191
+ # Resource selection arguments
192
+ resource_args = parser.add_argument_group(
193
+ "Resource Selection Arguments", "Arguments for fine-tuning how available hardware should be used."
194
+ )
195
+ resource_args.add_argument(
196
+ "--mixed_precision",
197
+ type=str,
198
+ choices=["no", "fp16", "bf16", "fp8"],
199
+ help="Whether or not to use mixed precision training. "
200
+ "Choose between FP16 and BF16 (bfloat16) training. "
201
+ "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.",
202
+ )
203
+ resource_args.add_argument(
204
+ "--num_processes", type=int, default=None, help="The total number of processes to be launched in parallel."
205
+ )
206
+ resource_args.add_argument(
207
+ "--num_machines", type=int, default=None, help="The total number of machines used in this training."
208
+ )
209
+ resource_args.add_argument(
210
+ "--num_cpu_threads_per_process",
211
+ type=int,
212
+ default=None,
213
+ help="The number of CPU threads per process. Can be tuned for optimal performance.",
214
+ )
215
+ resource_args.add_argument(
216
+ "--enable_cpu_affinity",
217
+ default=False,
218
+ action="store_true",
219
+ help="Whether or not CPU affinity and balancing should be enabled. Currently only supported on NVIDIA hardware.",
220
+ )
221
+ # Dynamo arguments
222
+ resource_args.add_argument(
223
+ "--dynamo_backend",
224
+ type=str,
225
+ choices=["no"] + [b.lower() for b in DYNAMO_BACKENDS],
226
+ help="Choose a backend to optimize your training with dynamo, see more at "
227
+ "https://github.com/pytorch/torchdynamo.",
228
+ )
229
+ resource_args.add_argument(
230
+ "--dynamo_mode",
231
+ type=str,
232
+ default="default",
233
+ choices=TORCH_DYNAMO_MODES,
234
+ help="Choose a mode to optimize your training with dynamo.",
235
+ )
236
+ resource_args.add_argument(
237
+ "--dynamo_use_fullgraph",
238
+ default=False,
239
+ action="store_true",
240
+ help="Whether to use full graph mode for dynamo or it is ok to break model into several subgraphs",
241
+ )
242
+ resource_args.add_argument(
243
+ "--dynamo_use_dynamic",
244
+ default=False,
245
+ action="store_true",
246
+ help="Whether to enable dynamic shape tracing.",
247
+ )
248
+
249
+ # Training Paradigm arguments
250
+ paradigm_args = parser.add_argument_group(
251
+ "Training Paradigm Arguments", "Arguments for selecting which training paradigm to be used."
252
+ )
253
+ paradigm_args.add_argument(
254
+ "--use_deepspeed",
255
+ default=False,
256
+ action="store_true",
257
+ help="Whether to use deepspeed.",
258
+ )
259
+ paradigm_args.add_argument(
260
+ "--use_fsdp",
261
+ default=False,
262
+ action="store_true",
263
+ help="Whether to use fsdp.",
264
+ )
265
+ paradigm_args.add_argument(
266
+ "--use_megatron_lm",
267
+ default=False,
268
+ action="store_true",
269
+ help="Whether to use Megatron-LM.",
270
+ )
271
+ paradigm_args.add_argument(
272
+ "--use_xpu",
273
+ default=False,
274
+ action="store_true",
275
+ help="Whether to use IPEX plugin to speed up training on XPU specifically.",
276
+ )
277
+
278
+ # distributed GPU training arguments
279
+ distributed_args = parser.add_argument_group("Distributed GPUs", "Arguments related to distributed GPU training.")
280
+ distributed_args.add_argument(
281
+ "--gpu_ids",
282
+ default=None,
283
+ help="What GPUs (by id) should be used for training on this machine as a comma-seperated list",
284
+ )
285
+ distributed_args.add_argument(
286
+ "--same_network",
287
+ default=False,
288
+ action="store_true",
289
+ help="Whether all machines used for multinode training exist on the same local network.",
290
+ )
291
+ distributed_args.add_argument(
292
+ "--machine_rank", type=int, default=None, help="The rank of the machine on which this script is launched."
293
+ )
294
+ distributed_args.add_argument(
295
+ "--main_process_ip", type=str, default=None, help="The IP address of the machine of rank 0."
296
+ )
297
+ distributed_args.add_argument(
298
+ "--main_process_port",
299
+ type=int,
300
+ default=None,
301
+ help="The port to use to communicate with the machine of rank 0.",
302
+ )
303
+ distributed_args.add_argument(
304
+ "-t",
305
+ "--tee",
306
+ default="0",
307
+ type=str,
308
+ help="Tee std streams into a log file and also to console.",
309
+ )
310
+ distributed_args.add_argument(
311
+ "--log_dir",
312
+ type=str,
313
+ default=None,
314
+ help=(
315
+ "Base directory to use for log files when using torchrun/torch.distributed.run as launcher. "
316
+ "Use with --tee to redirect std streams info log files."
317
+ ),
318
+ )
319
+ distributed_args.add_argument(
320
+ "--role",
321
+ type=str,
322
+ default="default",
323
+ help="User-defined role for the workers.",
324
+ )
325
+ # Rendezvous related arguments
326
+ distributed_args.add_argument(
327
+ "--rdzv_backend",
328
+ type=str,
329
+ default="static",
330
+ help="The rendezvous method to use, such as 'static' (the default) or 'c10d'",
331
+ )
332
+ distributed_args.add_argument(
333
+ "--rdzv_conf",
334
+ type=str,
335
+ default="",
336
+ help="Additional rendezvous configuration (<key1>=<value1>,<key2>=<value2>,...).",
337
+ )
338
+ distributed_args.add_argument(
339
+ "--max_restarts",
340
+ type=int,
341
+ default=0,
342
+ help="Maximum number of worker group restarts before failing.",
343
+ )
344
+ distributed_args.add_argument(
345
+ "--monitor_interval",
346
+ type=float,
347
+ default=0.1,
348
+ help="Interval, in seconds, to monitor the state of workers.",
349
+ )
350
+ parser.add_argument(
351
+ "-m",
352
+ "--module",
353
+ action="store_true",
354
+ help="Change each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'.",
355
+ )
356
+ parser.add_argument(
357
+ "--no_python",
358
+ action="store_true",
359
+ help="Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script.",
360
+ )
361
+
362
+ # TPU arguments
363
+ tpu_args = parser.add_argument_group("TPU", "Arguments related to TPU.")
364
+ tpu_args.add_argument(
365
+ "--tpu_cluster",
366
+ action="store_true",
367
+ dest="tpu_use_cluster",
368
+ help="Whether to use a GCP TPU pod for training.",
369
+ )
370
+ tpu_args.add_argument(
371
+ "--no_tpu_cluster",
372
+ action="store_false",
373
+ dest="tpu_use_cluster",
374
+ help="Should not be passed explicitly, this is for internal use only.",
375
+ )
376
+ tpu_args.add_argument(
377
+ "--tpu_use_sudo",
378
+ action="store_true",
379
+ help="Whether to use `sudo` when running the TPU training script in each pod.",
380
+ )
381
+ tpu_args.add_argument(
382
+ "--vm",
383
+ type=str,
384
+ action="append",
385
+ help=(
386
+ "List of single Compute VM instance names. "
387
+ "If not provided we assume usage of instance groups. For TPU pods."
388
+ ),
389
+ )
390
+ tpu_args.add_argument(
391
+ "--env",
392
+ type=str,
393
+ action="append",
394
+ help="List of environment variables to set on the Compute VM instances. For TPU pods.",
395
+ )
396
+ tpu_args.add_argument(
397
+ "--main_training_function",
398
+ type=str,
399
+ default=None,
400
+ help="The name of the main function to be executed in your script (only for TPU training).",
401
+ )
402
+ tpu_args.add_argument(
403
+ "--downcast_bf16",
404
+ action="store_true",
405
+ help="Whether when using bf16 precision on TPUs if both float and double tensors are cast to bfloat16 or if double tensors remain as float32.",
406
+ )
407
+
408
+ # DeepSpeed arguments
409
+ deepspeed_args = parser.add_argument_group("DeepSpeed Arguments", "Arguments related to DeepSpeed.")
410
+ deepspeed_args.add_argument(
411
+ "--deepspeed_config_file",
412
+ default=None,
413
+ type=str,
414
+ help="DeepSpeed config file.",
415
+ )
416
+ deepspeed_args.add_argument(
417
+ "--zero_stage",
418
+ default=None,
419
+ type=int,
420
+ help="DeepSpeed's ZeRO optimization stage (useful only when `use_deepspeed` flag is passed). "
421
+ "If unspecified, will default to `2`.",
422
+ )
423
+ deepspeed_args.add_argument(
424
+ "--offload_optimizer_device",
425
+ default=None,
426
+ type=str,
427
+ help="Decides where (none|cpu|nvme) to offload optimizer states (useful only when `use_deepspeed` flag is passed). "
428
+ "If unspecified, will default to 'none'.",
429
+ )
430
+ deepspeed_args.add_argument(
431
+ "--offload_param_device",
432
+ default=None,
433
+ type=str,
434
+ help="Decides where (none|cpu|nvme) to offload parameters (useful only when `use_deepspeed` flag is passed). "
435
+ "If unspecified, will default to 'none'.",
436
+ )
437
+ deepspeed_args.add_argument(
438
+ "--offload_optimizer_nvme_path",
439
+ default=None,
440
+ type=str,
441
+ help="Decides Nvme Path to offload optimizer states (useful only when `use_deepspeed` flag is passed). "
442
+ "If unspecified, will default to 'none'.",
443
+ )
444
+ deepspeed_args.add_argument(
445
+ "--offload_param_nvme_path",
446
+ default=None,
447
+ type=str,
448
+ help="Decides Nvme Path to offload parameters (useful only when `use_deepspeed` flag is passed). "
449
+ "If unspecified, will default to 'none'.",
450
+ )
451
+ deepspeed_args.add_argument(
452
+ "--gradient_accumulation_steps",
453
+ default=None,
454
+ type=int,
455
+ help="No of gradient_accumulation_steps used in your training script (useful only when `use_deepspeed` flag is passed). "
456
+ "If unspecified, will default to `1`.",
457
+ )
458
+ deepspeed_args.add_argument(
459
+ "--gradient_clipping",
460
+ default=None,
461
+ type=float,
462
+ help="gradient clipping value used in your training script (useful only when `use_deepspeed` flag is passed). "
463
+ "If unspecified, will default to `1.0`.",
464
+ )
465
+ deepspeed_args.add_argument(
466
+ "--zero3_init_flag",
467
+ default=None,
468
+ type=str,
469
+ help="Decides Whether (true|false) to enable `deepspeed.zero.Init` for constructing massive models. "
470
+ "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `true`.",
471
+ )
472
+ deepspeed_args.add_argument(
473
+ "--zero3_save_16bit_model",
474
+ default=None,
475
+ type=str,
476
+ help="Decides Whether (true|false) to save 16-bit model weights when using ZeRO Stage-3. "
477
+ "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `false`.",
478
+ )
479
+ deepspeed_args.add_argument(
480
+ "--deepspeed_hostfile",
481
+ default=None,
482
+ type=str,
483
+ help="DeepSpeed hostfile for configuring multi-node compute resources.",
484
+ )
485
+ deepspeed_args.add_argument(
486
+ "--deepspeed_exclusion_filter",
487
+ default=None,
488
+ type=str,
489
+ help="DeepSpeed exclusion filter string when using mutli-node setup.",
490
+ )
491
+ deepspeed_args.add_argument(
492
+ "--deepspeed_inclusion_filter",
493
+ default=None,
494
+ type=str,
495
+ help="DeepSpeed inclusion filter string when using mutli-node setup.",
496
+ )
497
+ deepspeed_args.add_argument(
498
+ "--deepspeed_multinode_launcher",
499
+ default=None,
500
+ type=str,
501
+ help="DeepSpeed multi-node launcher to use. If unspecified, will default to `pdsh`.",
502
+ )
503
+ deepspeed_args.add_argument(
504
+ "--deepspeed_moe_layer_cls_names",
505
+ default=None,
506
+ type=str,
507
+ help="comma-separated list of transformer MoE layer class names (case-sensitive) to wrap ,e.g, `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ..."
508
+ " (useful only when `use_deepspeed` flag is passed).",
509
+ )
510
+
511
+ # fsdp arguments
512
+ fsdp_args = parser.add_argument_group("FSDP Arguments", "Arguments related to Fully Shared Data Parallelism.")
513
+ fsdp_args.add_argument(
514
+ "--fsdp_offload_params",
515
+ default="false",
516
+ type=str,
517
+ help="Decides Whether (true|false) to offload parameters and gradients to CPU. (useful only when `use_fsdp` flag is passed).",
518
+ )
519
+ fsdp_args.add_argument(
520
+ "--fsdp_min_num_params",
521
+ type=int,
522
+ default=1e8,
523
+ help="FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `use_fsdp` flag is passed).",
524
+ )
525
+ fsdp_args.add_argument(
526
+ "--fsdp_sharding_strategy",
527
+ type=str,
528
+ default="FULL_SHARD",
529
+ help="FSDP's Sharding Strategy. (useful only when `use_fsdp` flag is passed).",
530
+ )
531
+ fsdp_args.add_argument(
532
+ "--fsdp_auto_wrap_policy",
533
+ type=str,
534
+ default=None,
535
+ help="FSDP's auto wrap policy. (useful only when `use_fsdp` flag is passed).",
536
+ )
537
+ fsdp_args.add_argument(
538
+ "--fsdp_transformer_layer_cls_to_wrap",
539
+ default=None,
540
+ type=str,
541
+ help="Transformer layer class name (case-sensitive) to wrap ,e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... "
542
+ "(useful only when `use_fsdp` flag is passed).",
543
+ )
544
+ fsdp_args.add_argument(
545
+ "--fsdp_backward_prefetch",
546
+ default=None,
547
+ type=str,
548
+ help="FSDP's backward prefetch policy. (useful only when `use_fsdp` flag is passed).",
549
+ )
550
+ fsdp_args.add_argument(
551
+ "--fsdp_state_dict_type",
552
+ default=None,
553
+ type=str,
554
+ help="FSDP's state dict type. (useful only when `use_fsdp` flag is passed).",
555
+ )
556
+ fsdp_args.add_argument(
557
+ "--fsdp_forward_prefetch",
558
+ default="false",
559
+ type=str,
560
+ help="If True, then FSDP explicitly prefetches the next upcoming "
561
+ "all-gather while executing in the forward pass (useful only when `use_fsdp` flag is passed).",
562
+ )
563
+ fsdp_args.add_argument(
564
+ "--fsdp_use_orig_params",
565
+ default="true",
566
+ type=str,
567
+ help="If True, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable paramteres."
568
+ " (useful only when `use_fsdp` flag is passed).",
569
+ )
570
+ fsdp_args.add_argument(
571
+ "--fsdp_cpu_ram_efficient_loading",
572
+ default="true",
573
+ type=str,
574
+ help="If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. "
575
+ "Only applicable for 🤗 Transformers. When using this, `--fsdp_sync_module_states` needs to True. "
576
+ "(useful only when `use_fsdp` flag is passed).",
577
+ )
578
+ fsdp_args.add_argument(
579
+ "--fsdp_sync_module_states",
580
+ default="true",
581
+ type=str,
582
+ help="If True, each individually wrapped FSDP unit will broadcast module parameters from rank 0."
583
+ " (useful only when `use_fsdp` flag is passed).",
584
+ )
585
+ fsdp_args.add_argument(
586
+ "--fsdp_activation_checkpointing",
587
+ default="false",
588
+ type=str,
589
+ help="Decides Whether (true|false) intermediate activations are freed during the forward pass, and a checkpoint is left as a placeholder. (useful only when `use_fsdp` flag is passed).",
590
+ )
591
+
592
+ # megatron_lm args
593
+ megatron_lm_args = parser.add_argument_group("Megatron-LM Arguments", "Arguments related to Megatron-LM.")
594
+ megatron_lm_args.add_argument(
595
+ "--megatron_lm_tp_degree",
596
+ type=int,
597
+ default=1,
598
+ help="Megatron-LM's Tensor Parallelism (TP) degree. (useful only when `use_megatron_lm` flag is passed).",
599
+ )
600
+ megatron_lm_args.add_argument(
601
+ "--megatron_lm_pp_degree",
602
+ type=int,
603
+ default=1,
604
+ help="Megatron-LM's Pipeline Parallelism (PP) degree. (useful only when `use_megatron_lm` flag is passed).",
605
+ )
606
+ megatron_lm_args.add_argument(
607
+ "--megatron_lm_num_micro_batches",
608
+ type=int,
609
+ default=None,
610
+ help="Megatron-LM's number of micro batches when PP degree > 1. (useful only when `use_megatron_lm` flag is passed).",
611
+ )
612
+ megatron_lm_args.add_argument(
613
+ "--megatron_lm_sequence_parallelism",
614
+ default=None,
615
+ type=str,
616
+ help="Decides Whether (true|false) to enable Sequence Parallelism when TP degree > 1. "
617
+ "(useful only when `use_megatron_lm` flag is passed).",
618
+ )
619
+ megatron_lm_args.add_argument(
620
+ "--megatron_lm_recompute_activations",
621
+ default=None,
622
+ type=str,
623
+ help="Decides Whether (true|false) to enable Selective Activation Recomputation. "
624
+ "(useful only when `use_megatron_lm` flag is passed).",
625
+ )
626
+ megatron_lm_args.add_argument(
627
+ "--megatron_lm_use_distributed_optimizer",
628
+ default=None,
629
+ type=str,
630
+ help="Decides Whether (true|false) to use distributed optimizer "
631
+ "which shards optimizer state and gradients across Data Pralellel (DP) ranks. "
632
+ "(useful only when `use_megatron_lm` flag is passed).",
633
+ )
634
+ megatron_lm_args.add_argument(
635
+ "--megatron_lm_gradient_clipping",
636
+ default=1.0,
637
+ type=float,
638
+ help="Megatron-LM's gradient clipping value based on global L2 Norm (0 to disable). "
639
+ "(useful only when `use_megatron_lm` flag is passed).",
640
+ )
641
+
642
+ # FP8 arguments
643
+ fp8_args = parser.add_argument_group(
644
+ "FP8 Arguments", "Arguments related to FP8 training (requires `--mixed_precision=fp8`)"
645
+ )
646
+ fp8_args.add_argument(
647
+ "--fp8_backend",
648
+ type=str,
649
+ choices=["te", "msamp"],
650
+ help="Choose a backend to train with FP8 (te: TransformerEngine, msamp: MS-AMP)",
651
+ )
652
+ fp8_args.add_argument(
653
+ "--fp8_use_autocast_during_eval",
654
+ default=False,
655
+ action="store_true",
656
+ help="Whether to use FP8 autocast during eval mode (useful only when `--fp8_backend=te` is passed). Generally better metrics are found when this is not passed.",
657
+ )
658
+ fp8_args.add_argument(
659
+ "--fp8_margin",
660
+ type=int,
661
+ default=0,
662
+ help="The margin to use for the gradient scaling (useful only when `--fp8_backend=te` is passed).",
663
+ )
664
+ fp8_args.add_argument(
665
+ "--fp8_interval",
666
+ type=int,
667
+ default=1,
668
+ help="The interval to use for how often the scaling factor is recomputed (useful only when `--fp8_backend=te` is passed).",
669
+ )
670
+ fp8_args.add_argument(
671
+ "--fp8_format",
672
+ type=str,
673
+ default="E4M3",
674
+ choices=["E4M3", "HYBRID"],
675
+ help="The format to use for the FP8 recipe (useful only when `--fp8_backend=te` is passed).",
676
+ )
677
+ fp8_args.add_argument(
678
+ "--fp8_amax_history_len",
679
+ type=int,
680
+ default=1024,
681
+ help="The length of the history to use for the scaling factor computation (useful only when `--fp8_backend=te` is passed).",
682
+ )
683
+ fp8_args.add_argument(
684
+ "--fp8_amax_compute_algo",
685
+ type=str,
686
+ default="most_recent",
687
+ choices=["max", "most_recent"],
688
+ help="The algorithm to use for the scaling factor computation. (useful only when `--fp8_backend=te` is passed).",
689
+ )
690
+ fp8_args.add_argument(
691
+ "--fp8_override_linear_precision",
692
+ type=lambda x: tuple(map(str_to_bool, x.split(","))),
693
+ default=(False, False, False),
694
+ help="Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. Should be passed in a comma-seperated string of booleans (useful only when `--fp8_backend=te` is passed).",
695
+ )
696
+ fp8_args.add_argument(
697
+ "--fp8_opt_level",
698
+ type=str,
699
+ default="O2",
700
+ choices=["O1", "O2"],
701
+ help="What level of 8-bit collective communication should be used with MS-AMP (useful only when `--fp8_backend=msamp` is passed).",
702
+ )
703
+
704
+ # AWS arguments
705
+ aws_args = parser.add_argument_group("AWS Arguments", "Arguments related to AWS.")
706
+ aws_args.add_argument(
707
+ "--aws_access_key_id",
708
+ type=str,
709
+ default=None,
710
+ help="The AWS_ACCESS_KEY_ID used to launch the Amazon SageMaker training job",
711
+ )
712
+ aws_args.add_argument(
713
+ "--aws_secret_access_key",
714
+ type=str,
715
+ default=None,
716
+ help="The AWS_SECRET_ACCESS_KEY used to launch the Amazon SageMaker training job.",
717
+ )
718
+ parser.add_argument(
719
+ "--debug",
720
+ action="store_true",
721
+ help="Whether to print out the torch.distributed stack trace when something fails.",
722
+ )
723
+ parser.add_argument(
724
+ "training_script",
725
+ type=str,
726
+ help=(
727
+ "The full path to the script to be launched in parallel, followed by all the arguments for the training "
728
+ "script."
729
+ ),
730
+ )
731
+
732
+ # MPI arguments
733
+ mpirun_args = parser.add_argument_group("MPI Arguments", "Arguments related to mpirun for Multi-CPU")
734
+ mpirun_args.add_argument(
735
+ "--mpirun_hostfile",
736
+ type=str,
737
+ default=None,
738
+ help="Location for a hostfile for using Accelerate to launch a multi-CPU training job with mpirun. This will "
739
+ "get passed to the MPI --hostfile or -f parameter, depending on which MPI program is installed.",
740
+ )
741
+ mpirun_args.add_argument(
742
+ "--mpirun_ccl",
743
+ type=int,
744
+ default=1,
745
+ help="The number of oneCCL worker threads when using Accelerate to launch multi-CPU training with mpirun.",
746
+ )
747
+
748
+ # Other arguments of the training scripts
749
+ parser.add_argument("training_script_args", nargs=argparse.REMAINDER, help="Arguments of the training script.")
750
+
751
+ if subparsers is not None:
752
+ parser.set_defaults(func=launch_command)
753
+ return parser
754
+
755
+
756
+ def simple_launcher(args):
757
+ cmd, current_env = prepare_simple_launcher_cmd_env(args)
758
+
759
+ process = subprocess.Popen(cmd, env=current_env)
760
+ process.wait()
761
+ if process.returncode != 0:
762
+ if not args.quiet:
763
+ raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd)
764
+ else:
765
+ sys.exit(1)
766
+
767
+
768
+ def multi_gpu_launcher(args):
769
+ import torch.distributed.run as distrib_run
770
+
771
+ current_env = prepare_multi_gpu_env(args)
772
+ if not check_cuda_p2p_ib_support():
773
+ message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled."
774
+ warn = False
775
+ if "NCCL_P2P_DISABLE" not in current_env:
776
+ current_env["NCCL_P2P_DISABLE"] = "1"
777
+ warn = True
778
+ if "NCCL_IB_DISABLE" not in current_env:
779
+ current_env["NCCL_IB_DISABLE"] = "1"
780
+ warn = True
781
+ if warn:
782
+ logger.warning(message)
783
+
784
+ debug = getattr(args, "debug", False)
785
+ args = _filter_args(
786
+ args,
787
+ distrib_run.get_args_parser(),
788
+ ["--training_script", args.training_script, "--training_script_args", args.training_script_args],
789
+ )
790
+
791
+ with patch_environment(**current_env):
792
+ try:
793
+ distrib_run.run(args)
794
+ except Exception:
795
+ if is_rich_available() and debug:
796
+ console = get_console()
797
+ console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]")
798
+ console.print_exception(suppress=[__file__], show_locals=False)
799
+ else:
800
+ raise
801
+
802
+
803
+ def deepspeed_launcher(args):
804
+ import torch.distributed.run as distrib_run
805
+
806
+ if not is_deepspeed_available():
807
+ raise ImportError("DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source.")
808
+ else:
809
+ from deepspeed.launcher.runner import DEEPSPEED_ENVIRONMENT_NAME
810
+
811
+ cmd, current_env = prepare_deepspeed_cmd_env(args)
812
+ if not check_cuda_p2p_ib_support():
813
+ message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled."
814
+ warn = False
815
+ if "NCCL_P2P_DISABLE" not in current_env:
816
+ current_env["NCCL_P2P_DISABLE"] = "1"
817
+ warn = True
818
+ if "NCCL_IB_DISABLE" not in current_env:
819
+ current_env["NCCL_IB_DISABLE"] = "1"
820
+ warn = True
821
+ if warn:
822
+ logger.warning(message)
823
+
824
+ if args.num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]:
825
+ with open(DEEPSPEED_ENVIRONMENT_NAME, "a") as f:
826
+ valid_env_items = convert_dict_to_env_variables(current_env)
827
+ if len(valid_env_items) > 1:
828
+ f.writelines(valid_env_items)
829
+
830
+ process = subprocess.Popen(cmd, env=current_env)
831
+ process.wait()
832
+ if process.returncode != 0:
833
+ if not args.quiet:
834
+ raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd)
835
+ else:
836
+ sys.exit(1)
837
+ else:
838
+ debug = getattr(args, "debug", False)
839
+ args = _filter_args(
840
+ args,
841
+ distrib_run.get_args_parser(),
842
+ ["--training_script", args.training_script, "--training_script_args", args.training_script_args],
843
+ )
844
+ with patch_environment(**current_env):
845
+ try:
846
+ distrib_run.run(args)
847
+ except Exception:
848
+ if is_rich_available() and debug:
849
+ console = get_console()
850
+ console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]")
851
+ console.print_exception(suppress=[__file__], show_locals=False)
852
+ else:
853
+ raise
854
+
855
+
856
+ def tpu_launcher(args):
857
+ import torch_xla.distributed.xla_multiprocessing as xmp
858
+
859
+ if args.no_python:
860
+ raise ValueError("--no_python cannot be used with TPU launcher")
861
+
862
+ args, current_env = prepare_tpu(args, {})
863
+
864
+ if args.module:
865
+ mod_name = args.training_script
866
+ else:
867
+ # Import training_script as a module
868
+ script_path = Path(args.training_script)
869
+ sys.path.append(str(script_path.parent.resolve()))
870
+ mod_name = script_path.stem
871
+
872
+ mod = importlib.import_module(mod_name)
873
+ if not hasattr(mod, args.main_training_function):
874
+ raise ValueError(
875
+ f"Your training script should have a function named {args.main_training_function}, or you should pass a "
876
+ "different value to `--main_training_function`."
877
+ )
878
+
879
+ # Patch sys.argv
880
+ sys.argv = [mod.__file__] + args.training_script_args
881
+
882
+ main_function = getattr(mod, args.main_training_function)
883
+ with patch_environment(**current_env):
884
+ xmp.spawn(PrepareForLaunch(main_function), args=(), nprocs=args.num_processes)
885
+
886
+
887
+ def tpu_pod_launcher(args):
888
+ from torch_xla.distributed import xla_dist
889
+
890
+ current_env = {}
891
+ args, current_env = prepare_tpu(args, current_env, True)
892
+ debug = getattr(args, "debug", False)
893
+
894
+ training_script = args.training_script
895
+ training_script_args = args.training_script_args
896
+ new_args = _filter_args(
897
+ args, xla_dist.get_args_parser(), ["--tpu", args.tpu_name, "--positional", "", "--restart-tpuvm-pod-server"]
898
+ )
899
+
900
+ if args.tpu_use_sudo:
901
+ new_cmd = ["sudo"]
902
+ else:
903
+ new_cmd = []
904
+
905
+ new_cmd += [
906
+ "accelerate-launch",
907
+ "--tpu",
908
+ "--no_tpu_cluster",
909
+ "--num_machines",
910
+ "1",
911
+ "--mixed_precision",
912
+ "no",
913
+ "--dynamo_backend",
914
+ "no",
915
+ "--num_processes",
916
+ str(args.num_processes),
917
+ "--main_training_function",
918
+ str(args.main_training_function),
919
+ training_script,
920
+ ] + training_script_args
921
+
922
+ new_args.positional = new_cmd
923
+ bad_flags = ""
924
+ for arg in vars(new_args):
925
+ if arg.startswith("docker_"):
926
+ value = getattr(new_args, arg)
927
+ if value != "" and value is not None:
928
+ bad_flags += f'{arg}="{value}"\n'
929
+ if bad_flags != "":
930
+ raise ValueError(
931
+ f"Docker containers are not supported for TPU pod launcher currently, please remove the following flags:\n{bad_flags}"
932
+ )
933
+ new_args.env = [f"{k}={v}" for k, v in current_env.items()]
934
+ new_args.env.append("ACCELERATE_IN_TPU_POD=1")
935
+ try:
936
+ xla_dist.resolve_and_execute(new_args)
937
+ except Exception:
938
+ if is_rich_available() and debug:
939
+ console = get_console()
940
+ console.print("\n[bold red]Using --debug, `torch_xla.xla_dist` Stack Trace:[/bold red]")
941
+ console.print_exception(suppress=[__file__], show_locals=False)
942
+ else:
943
+ raise
944
+
945
+
946
+ def sagemaker_launcher(sagemaker_config: SageMakerConfig, args):
947
+ if not is_sagemaker_available():
948
+ raise ImportError(
949
+ "Please install sagemaker to be able to launch training on Amazon SageMaker with `pip install accelerate[sagemaker]`"
950
+ )
951
+ if args.module or args.no_python:
952
+ raise ValueError(
953
+ "SageMaker requires a python training script file and cannot be used with --module or --no_python"
954
+ )
955
+
956
+ from sagemaker.huggingface import HuggingFace
957
+
958
+ args, sagemaker_inputs = prepare_sagemager_args_inputs(sagemaker_config, args)
959
+
960
+ huggingface_estimator = HuggingFace(**args)
961
+
962
+ huggingface_estimator.fit(inputs=sagemaker_inputs)
963
+ print(f"You can find your model data at: {huggingface_estimator.model_data}")
964
+
965
+
966
+ def _validate_launch_command(args):
967
+ # Sanity checks
968
+ if sum([args.multi_gpu, args.cpu, args.tpu, args.use_deepspeed, args.use_fsdp]) > 1:
969
+ raise ValueError(
970
+ "You can only use one of `--cpu`, `--multi_gpu`, `--tpu`, `--use_deepspeed`, `--use_fsdp` at a time."
971
+ )
972
+ if args.multi_gpu and (args.num_processes is not None) and (args.num_processes < 2):
973
+ raise ValueError("You need to use at least 2 processes to use `--multi_gpu`.")
974
+
975
+ defaults = None
976
+ warned = []
977
+ mp_from_config_flag = False
978
+ # Get the default from the config file.
979
+ if args.config_file is not None or os.path.isfile(default_config_file) and not args.cpu:
980
+ defaults = load_config_from_file(args.config_file)
981
+ if (
982
+ not args.multi_gpu
983
+ and not args.tpu
984
+ and not args.tpu_use_cluster
985
+ and not args.use_deepspeed
986
+ and not args.use_fsdp
987
+ and not args.use_megatron_lm
988
+ ):
989
+ args.use_deepspeed = defaults.distributed_type == DistributedType.DEEPSPEED
990
+ args.multi_gpu = (
991
+ True
992
+ if defaults.distributed_type
993
+ in (
994
+ DistributedType.MULTI_GPU,
995
+ DistributedType.MULTI_NPU,
996
+ DistributedType.MULTI_MLU,
997
+ DistributedType.MULTI_MUSA,
998
+ DistributedType.MULTI_XPU,
999
+ )
1000
+ else False
1001
+ )
1002
+ args.tpu = defaults.distributed_type == DistributedType.XLA
1003
+ args.use_fsdp = defaults.distributed_type == DistributedType.FSDP
1004
+ args.use_megatron_lm = defaults.distributed_type == DistributedType.MEGATRON_LM
1005
+ args.tpu_use_cluster = defaults.tpu_use_cluster if args.tpu else False
1006
+ if args.gpu_ids is None:
1007
+ if defaults.gpu_ids is not None:
1008
+ args.gpu_ids = defaults.gpu_ids
1009
+ else:
1010
+ args.gpu_ids = "all"
1011
+
1012
+ if args.multi_gpu and args.num_machines is None:
1013
+ args.num_machines = defaults.num_machines
1014
+
1015
+ if len(args.gpu_ids.split(",")) < 2 and (args.gpu_ids != "all") and args.multi_gpu and args.num_machines <= 1:
1016
+ raise ValueError(
1017
+ "Less than two GPU ids were configured and tried to run on on multiple GPUs. "
1018
+ "Please ensure at least two are specified for `--gpu_ids`, or use `--gpu_ids='all'`."
1019
+ )
1020
+ if defaults.compute_environment == ComputeEnvironment.LOCAL_MACHINE:
1021
+ # Update args with the defaults
1022
+ for name, attr in defaults.__dict__.items():
1023
+ if isinstance(attr, dict):
1024
+ for k in defaults.deepspeed_config:
1025
+ setattr(args, k, defaults.deepspeed_config[k])
1026
+ for k in defaults.fsdp_config:
1027
+ arg_to_set = k
1028
+ if "fsdp" not in arg_to_set:
1029
+ arg_to_set = "fsdp_" + arg_to_set
1030
+ setattr(args, arg_to_set, defaults.fsdp_config[k])
1031
+ for k in defaults.megatron_lm_config:
1032
+ setattr(args, k, defaults.megatron_lm_config[k])
1033
+ for k in defaults.dynamo_config:
1034
+ setattr(args, k, defaults.dynamo_config[k])
1035
+ for k in defaults.ipex_config:
1036
+ setattr(args, k, defaults.ipex_config[k])
1037
+ for k in defaults.mpirun_config:
1038
+ setattr(args, k, defaults.mpirun_config[k])
1039
+ continue
1040
+
1041
+ # Those args are handled separately
1042
+ if (
1043
+ name not in ["compute_environment", "mixed_precision", "distributed_type"]
1044
+ and getattr(args, name, None) is None
1045
+ ):
1046
+ setattr(args, name, attr)
1047
+ if not args.debug:
1048
+ args.debug = defaults.debug
1049
+
1050
+ if not args.mixed_precision:
1051
+ if defaults.mixed_precision is None:
1052
+ args.mixed_precision = "no"
1053
+ else:
1054
+ args.mixed_precision = defaults.mixed_precision
1055
+ mp_from_config_flag = True
1056
+ else:
1057
+ if args.use_cpu or (args.use_xpu and torch.xpu.is_available()):
1058
+ native_amp = is_torch_version(">=", "1.10")
1059
+ else:
1060
+ native_amp = is_bf16_available(True)
1061
+ if (
1062
+ args.mixed_precision == "bf16"
1063
+ and not native_amp
1064
+ and not (args.tpu and is_torch_xla_available(check_is_tpu=True))
1065
+ ):
1066
+ raise ValueError("bf16 mixed precision requires PyTorch >= 1.10 and a supported device.")
1067
+
1068
+ # Silently set the default here
1069
+ if args.dynamo_backend is None:
1070
+ args.dynamo_backend = "no"
1071
+ if args.num_processes == -1:
1072
+ raise ValueError("You need to manually pass in `--num_processes` using this config yaml.")
1073
+ else:
1074
+ if args.num_processes is None:
1075
+ if args.use_xpu and is_xpu_available():
1076
+ args.num_processes = torch.xpu.device_count()
1077
+ elif is_mlu_available():
1078
+ args.num_processes = torch.mlu.device_count()
1079
+ elif is_musa_available():
1080
+ args.num_processes = torch.musa.device_count()
1081
+ elif is_npu_available():
1082
+ args.num_processes = torch.npu.device_count()
1083
+ else:
1084
+ args.num_processes = torch.cuda.device_count()
1085
+ warned.append(f"\t`--num_processes` was set to a value of `{args.num_processes}`")
1086
+ if args.debug is None:
1087
+ args.debug = False
1088
+ if (
1089
+ not args.multi_gpu
1090
+ and args.num_processes > 1
1091
+ and (
1092
+ (args.use_xpu and is_xpu_available() and torch.xpu.device_count() > 1)
1093
+ or (is_mlu_available() and torch.mlu.device_count() > 1)
1094
+ or (is_musa_available() and torch.musa.device_count() > 1)
1095
+ or (is_npu_available() and torch.npu.device_count() > 1)
1096
+ or (torch.cuda.device_count() > 1)
1097
+ )
1098
+ ):
1099
+ warned.append(
1100
+ "\t\tMore than one GPU was found, enabling multi-GPU training.\n"
1101
+ "\t\tIf this was unintended please pass in `--num_processes=1`."
1102
+ )
1103
+ args.multi_gpu = True
1104
+ if args.num_machines is None:
1105
+ warned.append("\t`--num_machines` was set to a value of `1`")
1106
+ args.num_machines = 1
1107
+ if args.mixed_precision is None:
1108
+ warned.append("\t`--mixed_precision` was set to a value of `'no'`")
1109
+ args.mixed_precision = "no"
1110
+ if not hasattr(args, "use_cpu"):
1111
+ args.use_cpu = args.cpu
1112
+ if args.dynamo_backend is None:
1113
+ warned.append("\t`--dynamo_backend` was set to a value of `'no'`")
1114
+ args.dynamo_backend = "no"
1115
+ if args.debug:
1116
+ logger.debug("Running script in debug mode, expect distributed operations to be slightly slower.")
1117
+
1118
+ is_aws_env_disabled = defaults is None or (
1119
+ defaults is not None and defaults.compute_environment != ComputeEnvironment.AMAZON_SAGEMAKER
1120
+ )
1121
+ if is_aws_env_disabled and args.num_cpu_threads_per_process is None:
1122
+ args.num_cpu_threads_per_process = get_int_from_env(["OMP_NUM_THREADS"], 1)
1123
+ if args.use_cpu and args.num_processes >= 1 and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0:
1124
+ local_size = get_int_from_env(
1125
+ ["MPI_LOCALNRANKS", "OMPI_COMM_WORLD_LOCAL_SIZE", "MV2_COMM_WORLD_LOCAL_SIZE"],
1126
+ max(int(args.num_processes / args.num_machines), 1),
1127
+ )
1128
+ threads_per_process = int(psutil.cpu_count(logical=False) / local_size)
1129
+ if threads_per_process > 1:
1130
+ args.num_cpu_threads_per_process = threads_per_process
1131
+ warned.append(
1132
+ f"\t`--num_cpu_threads_per_process` was set to `{args.num_cpu_threads_per_process}` to improve out-of-box performance when training on CPUs"
1133
+ )
1134
+
1135
+ if any(warned):
1136
+ message = "The following values were not passed to `accelerate launch` and had defaults used instead:\n"
1137
+ message += "\n".join(warned)
1138
+ message += (
1139
+ "\nTo avoid this warning pass in values for each of the problematic parameters or run `accelerate config`."
1140
+ )
1141
+ logger.warning(message)
1142
+ return args, defaults, mp_from_config_flag
1143
+
1144
+
1145
+ def launch_command(args):
1146
+ args, defaults, mp_from_config_flag = _validate_launch_command(args)
1147
+ # Use the proper launcher
1148
+ if args.use_deepspeed and not args.cpu:
1149
+ args.deepspeed_fields_from_accelerate_config = list(defaults.deepspeed_config.keys()) if defaults else []
1150
+ if mp_from_config_flag:
1151
+ args.deepspeed_fields_from_accelerate_config.append("mixed_precision")
1152
+ args.deepspeed_fields_from_accelerate_config = ",".join(args.deepspeed_fields_from_accelerate_config)
1153
+ deepspeed_launcher(args)
1154
+ elif args.use_fsdp and not args.cpu:
1155
+ multi_gpu_launcher(args)
1156
+ elif args.use_megatron_lm and not args.cpu:
1157
+ multi_gpu_launcher(args)
1158
+ elif args.multi_gpu and not args.cpu:
1159
+ multi_gpu_launcher(args)
1160
+ elif args.tpu and not args.cpu:
1161
+ if args.tpu_use_cluster:
1162
+ tpu_pod_launcher(args)
1163
+ else:
1164
+ tpu_launcher(args)
1165
+ elif defaults is not None and defaults.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
1166
+ sagemaker_launcher(defaults, args)
1167
+ else:
1168
+ simple_launcher(args)
1169
+
1170
+
1171
+ def main():
1172
+ parser = launch_command_parser()
1173
+ args = parser.parse_args()
1174
+ launch_command(args)
1175
+
1176
+
1177
+ if __name__ == "__main__":
1178
+ main()
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from .selection_menu import BulletMenu
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/cursor.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team and Brian Chao. 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 utility for showing and hiding the terminal cursor on Windows and Linux, based on https://github.com/bchao1/bullet
17
+ """
18
+
19
+ import os
20
+ import sys
21
+ from contextlib import contextmanager
22
+
23
+
24
+ # Windows only
25
+ if os.name == "nt":
26
+ import ctypes
27
+ import msvcrt # noqa
28
+
29
+ class CursorInfo(ctypes.Structure):
30
+ # _fields is a specific attr expected by ctypes
31
+ _fields_ = [("size", ctypes.c_int), ("visible", ctypes.c_byte)]
32
+
33
+
34
+ def hide_cursor():
35
+ if os.name == "nt":
36
+ ci = CursorInfo()
37
+ handle = ctypes.windll.kernel32.GetStdHandle(-11)
38
+ ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
39
+ ci.visible = False
40
+ ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
41
+ elif os.name == "posix":
42
+ sys.stdout.write("\033[?25l")
43
+ sys.stdout.flush()
44
+
45
+
46
+ def show_cursor():
47
+ if os.name == "nt":
48
+ ci = CursorInfo()
49
+ handle = ctypes.windll.kernel32.GetStdHandle(-11)
50
+ ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
51
+ ci.visible = True
52
+ ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
53
+ elif os.name == "posix":
54
+ sys.stdout.write("\033[?25h")
55
+ sys.stdout.flush()
56
+
57
+
58
+ @contextmanager
59
+ def hide():
60
+ "Context manager to hide the terminal cursor"
61
+ try:
62
+ hide_cursor()
63
+ yield
64
+ finally:
65
+ show_cursor()
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/helpers.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team and Brian Chao. 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 variety of helper functions and constants when dealing with terminal menu choices, based on
17
+ https://github.com/bchao1/bullet
18
+ """
19
+
20
+ import enum
21
+ import shutil
22
+ import sys
23
+
24
+
25
+ TERMINAL_WIDTH, _ = shutil.get_terminal_size()
26
+
27
+ CURSOR_TO_CHAR = {"UP": "A", "DOWN": "B", "RIGHT": "C", "LEFT": "D"}
28
+
29
+
30
+ class Direction(enum.Enum):
31
+ UP = 0
32
+ DOWN = 1
33
+
34
+
35
+ def forceWrite(content, end=""):
36
+ sys.stdout.write(str(content) + end)
37
+ sys.stdout.flush()
38
+
39
+
40
+ def writeColor(content, color, end=""):
41
+ forceWrite(f"\u001b[{color}m{content}\u001b[0m", end)
42
+
43
+
44
+ def reset_cursor():
45
+ forceWrite("\r")
46
+
47
+
48
+ def move_cursor(num_lines: int, direction: str):
49
+ forceWrite(f"\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}")
50
+
51
+
52
+ def clear_line():
53
+ forceWrite(" " * TERMINAL_WIDTH)
54
+ reset_cursor()
55
+
56
+
57
+ def linebreak():
58
+ reset_cursor()
59
+ forceWrite("-" * TERMINAL_WIDTH)
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/input.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team and Brian Chao. 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
+ This file contains utilities for handling input from the user and registering specific keys to specific functions,
17
+ based on https://github.com/bchao1/bullet
18
+ """
19
+
20
+ from typing import List
21
+
22
+ from .keymap import KEYMAP, get_character
23
+
24
+
25
+ def mark(key: str):
26
+ """
27
+ Mark the function with the key code so it can be handled in the register
28
+ """
29
+
30
+ def decorator(func):
31
+ handle = getattr(func, "handle_key", [])
32
+ handle += [key]
33
+ func.handle_key = handle
34
+ return func
35
+
36
+ return decorator
37
+
38
+
39
+ def mark_multiple(*keys: List[str]):
40
+ """
41
+ Mark the function with the key codes so it can be handled in the register
42
+ """
43
+
44
+ def decorator(func):
45
+ handle = getattr(func, "handle_key", [])
46
+ handle += keys
47
+ func.handle_key = handle
48
+ return func
49
+
50
+ return decorator
51
+
52
+
53
+ class KeyHandler(type):
54
+ """
55
+ Metaclass that adds the key handlers to the class
56
+ """
57
+
58
+ def __new__(cls, name, bases, attrs):
59
+ new_cls = super().__new__(cls, name, bases, attrs)
60
+ if not hasattr(new_cls, "key_handler"):
61
+ new_cls.key_handler = {}
62
+ new_cls.handle_input = KeyHandler.handle_input
63
+
64
+ for value in attrs.values():
65
+ handled_keys = getattr(value, "handle_key", [])
66
+ for key in handled_keys:
67
+ new_cls.key_handler[key] = value
68
+ return new_cls
69
+
70
+ @staticmethod
71
+ def handle_input(cls):
72
+ "Finds and returns the selected character if it exists in the handler"
73
+ char = get_character()
74
+ if char != KEYMAP["undefined"]:
75
+ char = ord(char)
76
+ handler = cls.key_handler.get(char)
77
+ if handler:
78
+ cls.current_selection = char
79
+ return handler(cls)
80
+ else:
81
+ return None
82
+
83
+
84
+ def register(cls):
85
+ """Adds KeyHandler metaclass to the class"""
86
+ return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy())
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/keymap.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team and Brian Chao. 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
+ Utilities relating to parsing raw characters from the keyboard, based on https://github.com/bchao1/bullet
17
+ """
18
+
19
+ import os
20
+ import string
21
+ import sys
22
+
23
+
24
+ ARROW_KEY_FLAG = 1 << 8
25
+
26
+ KEYMAP = {
27
+ "tab": ord("\t"),
28
+ "newline": ord("\r"),
29
+ "esc": 27,
30
+ "up": 65 + ARROW_KEY_FLAG,
31
+ "down": 66 + ARROW_KEY_FLAG,
32
+ "right": 67 + ARROW_KEY_FLAG,
33
+ "left": 68 + ARROW_KEY_FLAG,
34
+ "mod_int": 91,
35
+ "undefined": sys.maxsize,
36
+ "interrupt": 3,
37
+ "insert": 50,
38
+ "delete": 51,
39
+ "pg_up": 53,
40
+ "pg_down": 54,
41
+ }
42
+
43
+ KEYMAP["arrow_begin"] = KEYMAP["up"]
44
+ KEYMAP["arrow_end"] = KEYMAP["left"]
45
+
46
+ if sys.platform == "win32":
47
+ WIN_CH_BUFFER = []
48
+ WIN_KEYMAP = {
49
+ b"\xe0H": KEYMAP["up"] - ARROW_KEY_FLAG,
50
+ b"\x00H": KEYMAP["up"] - ARROW_KEY_FLAG,
51
+ b"\xe0P": KEYMAP["down"] - ARROW_KEY_FLAG,
52
+ b"\x00P": KEYMAP["down"] - ARROW_KEY_FLAG,
53
+ b"\xe0M": KEYMAP["right"] - ARROW_KEY_FLAG,
54
+ b"\x00M": KEYMAP["right"] - ARROW_KEY_FLAG,
55
+ b"\xe0K": KEYMAP["left"] - ARROW_KEY_FLAG,
56
+ b"\x00K": KEYMAP["left"] - ARROW_KEY_FLAG,
57
+ }
58
+
59
+ for i in range(10):
60
+ KEYMAP[str(i)] = ord(str(i))
61
+
62
+
63
+ def get_raw_chars():
64
+ "Gets raw characters from inputs"
65
+ if os.name == "nt":
66
+ import msvcrt
67
+
68
+ encoding = "mbcs"
69
+ # Flush the keyboard buffer
70
+ while msvcrt.kbhit():
71
+ msvcrt.getch()
72
+ if len(WIN_CH_BUFFER) == 0:
73
+ # Read the keystroke
74
+ ch = msvcrt.getch()
75
+
76
+ # If it is a prefix char, get second part
77
+ if ch in (b"\x00", b"\xe0"):
78
+ ch2 = ch + msvcrt.getch()
79
+ # Translate actual Win chars to bullet char types
80
+ try:
81
+ chx = chr(WIN_KEYMAP[ch2])
82
+ WIN_CH_BUFFER.append(chr(KEYMAP["mod_int"]))
83
+ WIN_CH_BUFFER.append(chx)
84
+ if ord(chx) in (
85
+ KEYMAP["insert"] - 1 << 9,
86
+ KEYMAP["delete"] - 1 << 9,
87
+ KEYMAP["pg_up"] - 1 << 9,
88
+ KEYMAP["pg_down"] - 1 << 9,
89
+ ):
90
+ WIN_CH_BUFFER.append(chr(126))
91
+ ch = chr(KEYMAP["esc"])
92
+ except KeyError:
93
+ ch = ch2[1]
94
+ else:
95
+ ch = ch.decode(encoding)
96
+ else:
97
+ ch = WIN_CH_BUFFER.pop(0)
98
+ elif os.name == "posix":
99
+ import termios
100
+ import tty
101
+
102
+ fd = sys.stdin.fileno()
103
+ old_settings = termios.tcgetattr(fd)
104
+ try:
105
+ tty.setraw(fd)
106
+ ch = sys.stdin.read(1)
107
+ finally:
108
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
109
+ return ch
110
+
111
+
112
+ def get_character():
113
+ "Gets a character from the keyboard and returns the key code"
114
+ char = get_raw_chars()
115
+ if ord(char) in [KEYMAP["interrupt"], KEYMAP["newline"]]:
116
+ return char
117
+
118
+ elif ord(char) == KEYMAP["esc"]:
119
+ combo = get_raw_chars()
120
+ if ord(combo) == KEYMAP["mod_int"]:
121
+ key = get_raw_chars()
122
+ if ord(key) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(key) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG:
123
+ return chr(ord(key) + ARROW_KEY_FLAG)
124
+ else:
125
+ return KEYMAP["undefined"]
126
+ else:
127
+ return get_raw_chars()
128
+
129
+ else:
130
+ if char in string.printable:
131
+ return char
132
+ else:
133
+ return KEYMAP["undefined"]
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/selection_menu.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team and Brian Chao. 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
+ Main driver for the selection menu, based on https://github.com/bchao1/bullet
17
+ """
18
+
19
+ import builtins
20
+ import sys
21
+
22
+ from ...utils.imports import _is_package_available
23
+ from . import cursor, input
24
+ from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
25
+ from .keymap import KEYMAP
26
+
27
+
28
+ in_colab = False
29
+ try:
30
+ in_colab = _is_package_available("google.colab")
31
+ except ModuleNotFoundError:
32
+ pass
33
+
34
+
35
+ @input.register
36
+ class BulletMenu:
37
+ """
38
+ A CLI menu to select a choice from a list of choices using the keyboard.
39
+ """
40
+
41
+ def __init__(self, prompt: str = None, choices: list = []):
42
+ self.position = 0
43
+ self.choices = choices
44
+ self.prompt = prompt
45
+ if sys.platform == "win32":
46
+ self.arrow_char = "*"
47
+ else:
48
+ self.arrow_char = "➔ "
49
+
50
+ def write_choice(self, index, end: str = ""):
51
+ if sys.platform != "win32":
52
+ writeColor(self.choices[index], 32, end)
53
+ else:
54
+ forceWrite(self.choices[index], end)
55
+
56
+ def print_choice(self, index: int):
57
+ "Prints the choice at the given index"
58
+ if index == self.position:
59
+ forceWrite(f" {self.arrow_char} ")
60
+ self.write_choice(index)
61
+ else:
62
+ forceWrite(f" {self.choices[index]}")
63
+ reset_cursor()
64
+
65
+ def move_direction(self, direction: Direction, num_spaces: int = 1):
66
+ "Should not be directly called, used to move a direction of either up or down"
67
+ old_position = self.position
68
+ if direction == Direction.DOWN:
69
+ if self.position + 1 >= len(self.choices):
70
+ return
71
+ self.position += num_spaces
72
+ else:
73
+ if self.position - 1 < 0:
74
+ return
75
+ self.position -= num_spaces
76
+ clear_line()
77
+ self.print_choice(old_position)
78
+ move_cursor(num_spaces, direction.name)
79
+ self.print_choice(self.position)
80
+
81
+ @input.mark(KEYMAP["up"])
82
+ def move_up(self):
83
+ self.move_direction(Direction.UP)
84
+
85
+ @input.mark(KEYMAP["down"])
86
+ def move_down(self):
87
+ self.move_direction(Direction.DOWN)
88
+
89
+ @input.mark(KEYMAP["newline"])
90
+ def select(self):
91
+ move_cursor(len(self.choices) - self.position, "DOWN")
92
+ return self.position
93
+
94
+ @input.mark(KEYMAP["interrupt"])
95
+ def interrupt(self):
96
+ move_cursor(len(self.choices) - self.position, "DOWN")
97
+ raise KeyboardInterrupt
98
+
99
+ @input.mark_multiple(*[KEYMAP[str(number)] for number in range(10)])
100
+ def select_row(self):
101
+ index = int(chr(self.current_selection))
102
+ movement = index - self.position
103
+ if index == self.position:
104
+ return
105
+ if index < len(self.choices):
106
+ if self.position > index:
107
+ self.move_direction(Direction.UP, -movement)
108
+ elif self.position < index:
109
+ self.move_direction(Direction.DOWN, movement)
110
+ else:
111
+ return
112
+ else:
113
+ return
114
+
115
+ def run(self, default_choice: int = 0):
116
+ "Start the menu and return the selected choice"
117
+ if self.prompt:
118
+ linebreak()
119
+ forceWrite(self.prompt, "\n")
120
+ if in_colab:
121
+ forceWrite("Please input a choice index (starting from 0), and press enter", "\n")
122
+ else:
123
+ forceWrite("Please select a choice using the arrow or number keys, and selecting with enter", "\n")
124
+ self.position = default_choice
125
+ for i in range(len(self.choices)):
126
+ self.print_choice(i)
127
+ forceWrite("\n")
128
+ move_cursor(len(self.choices) - self.position, "UP")
129
+ with cursor.hide():
130
+ while True:
131
+ if in_colab:
132
+ try:
133
+ choice = int(builtins.input())
134
+ except ValueError:
135
+ choice = default_choice
136
+ else:
137
+ choice = self.handle_input()
138
+ if choice is not None:
139
+ reset_cursor()
140
+ for _ in range(len(self.choices) + 1):
141
+ move_cursor(1, "UP")
142
+ clear_line()
143
+ self.write_choice(choice, "\n")
144
+ return choice
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/merge.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 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
+ from accelerate.commands.utils import CustomArgumentParser
17
+ from accelerate.utils import merge_fsdp_weights
18
+
19
+
20
+ description = """Utility to merge the weights from multiple FSDP checkpoints into a single combined checkpoint. Should be used if
21
+ `SHARDED_STATE_DICT` was used for the model. Weights will be saved to `{output_path}`.
22
+
23
+ This is a CPU-bound process and requires enough RAM to load the entire model state dict."""
24
+
25
+
26
+ def merge_command(args):
27
+ merge_fsdp_weights(
28
+ args.checkpoint_directory, args.output_path, not args.unsafe_serialization, args.remove_checkpoint_dir
29
+ )
30
+
31
+
32
+ def merge_command_parser(subparsers=None):
33
+ if subparsers is not None:
34
+ parser = subparsers.add_parser("merge-weights", description=description)
35
+ else:
36
+ parser = CustomArgumentParser(description=description)
37
+
38
+ parser.add_argument("checkpoint_directory", type=str, help="A directory containing sharded weights saved by FSDP.")
39
+ parser.add_argument(
40
+ "output_path",
41
+ type=str,
42
+ help="The path to save the merged weights. Defaults to the current directory. ",
43
+ )
44
+ parser.add_argument(
45
+ "--unsafe_serialization",
46
+ action="store_false",
47
+ default=False,
48
+ help="Whether to save the merged weights as `.bin` rather than `.safetensors` (not recommended).",
49
+ )
50
+ parser.add_argument(
51
+ "--remove_checkpoint_dir",
52
+ action="store_true",
53
+ help="Whether to remove the checkpoint directory after merging.",
54
+ default=False,
55
+ )
56
+
57
+ if subparsers is not None:
58
+ parser.set_defaults(func=merge_command)
59
+ return parser
60
+
61
+
62
+ def main():
63
+ parser = merge_command_parser()
64
+ args = parser.parse_args()
65
+ merge_command(args)
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/test.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import argparse
18
+
19
+ from accelerate.test_utils import execute_subprocess_async, path_in_accelerate_package
20
+
21
+
22
+ def test_command_parser(subparsers=None):
23
+ if subparsers is not None:
24
+ parser = subparsers.add_parser("test")
25
+ else:
26
+ parser = argparse.ArgumentParser("Accelerate test command")
27
+
28
+ parser.add_argument(
29
+ "--config_file",
30
+ default=None,
31
+ help=(
32
+ "The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
33
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
34
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
35
+ "with 'huggingface'."
36
+ ),
37
+ )
38
+
39
+ if subparsers is not None:
40
+ parser.set_defaults(func=test_command)
41
+ return parser
42
+
43
+
44
+ def test_command(args):
45
+ script_name = path_in_accelerate_package("test_utils", "scripts", "test_script.py")
46
+
47
+ if args.config_file is None:
48
+ test_args = [script_name]
49
+ else:
50
+ test_args = f"--config_file={args.config_file} {script_name}".split()
51
+
52
+ cmd = ["accelerate-launch"] + test_args
53
+ result = execute_subprocess_async(cmd)
54
+ if result.returncode == 0:
55
+ print("Test is a success! You are ready for your distributed training!")
56
+
57
+
58
+ def main():
59
+ parser = test_command_parser()
60
+ args = parser.parse_args()
61
+ test_command(args)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/tpu.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2022 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
+ import argparse
18
+ import os
19
+ import subprocess
20
+
21
+ from packaging.version import Version, parse
22
+
23
+ from accelerate.commands.config.config_args import default_config_file, load_config_from_file
24
+
25
+
26
+ _description = "Run commands across TPU VMs for initial setup before running `accelerate launch`."
27
+
28
+
29
+ def tpu_command_parser(subparsers=None):
30
+ if subparsers is not None:
31
+ parser = subparsers.add_parser("tpu-config", description=_description)
32
+ else:
33
+ parser = argparse.ArgumentParser("Accelerate tpu-config command", description=_description)
34
+ # Core arguments
35
+ config_args = parser.add_argument_group(
36
+ "Config Arguments", "Arguments that can be configured through `accelerate config`."
37
+ )
38
+ config_args.add_argument(
39
+ "--config_file",
40
+ type=str,
41
+ default=None,
42
+ help="Path to the config file to use for accelerate.",
43
+ )
44
+ config_args.add_argument(
45
+ "--tpu_name",
46
+ default=None,
47
+ help="The name of the TPU to use. If not specified, will use the TPU specified in the config file.",
48
+ )
49
+ config_args.add_argument(
50
+ "--tpu_zone",
51
+ default=None,
52
+ help="The zone of the TPU to use. If not specified, will use the zone specified in the config file.",
53
+ )
54
+ pod_args = parser.add_argument_group("TPU Arguments", "Arguments for options ran inside the TPU.")
55
+ pod_args.add_argument(
56
+ "--use_alpha",
57
+ action="store_true",
58
+ help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.",
59
+ )
60
+ pod_args.add_argument(
61
+ "--command_file",
62
+ default=None,
63
+ help="The path to the file containing the commands to run on the pod on startup.",
64
+ )
65
+ pod_args.add_argument(
66
+ "--command",
67
+ action="append",
68
+ nargs="+",
69
+ help="A command to run on the pod. Can be passed multiple times.",
70
+ )
71
+ pod_args.add_argument(
72
+ "--install_accelerate",
73
+ action="store_true",
74
+ help="Whether to install accelerate on the pod. Defaults to False.",
75
+ )
76
+ pod_args.add_argument(
77
+ "--accelerate_version",
78
+ default="latest",
79
+ help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub.",
80
+ )
81
+ pod_args.add_argument(
82
+ "--debug", action="store_true", help="If set, will print the command that would be run instead of running it."
83
+ )
84
+
85
+ if subparsers is not None:
86
+ parser.set_defaults(func=tpu_command_launcher)
87
+ return parser
88
+
89
+
90
+ def tpu_command_launcher(args):
91
+ defaults = None
92
+
93
+ # Get the default from the config file if it exists.
94
+ if args.config_file is not None or os.path.isfile(default_config_file):
95
+ defaults = load_config_from_file(args.config_file)
96
+ if not args.command_file and defaults.command_file is not None and not args.command:
97
+ args.command_file = defaults.command_file
98
+ if not args.command and defaults.commands is not None:
99
+ args.command = defaults.commands
100
+ if not args.tpu_name:
101
+ args.tpu_name = defaults.tpu_name
102
+ if not args.tpu_zone:
103
+ args.tpu_zone = defaults.tpu_zone
104
+ if args.accelerate_version == "dev":
105
+ args.accelerate_version = "git+https://github.com/huggingface/accelerate.git"
106
+ elif args.accelerate_version == "latest":
107
+ args.accelerate_version = "accelerate -U"
108
+ elif isinstance(parse(args.accelerate_version), Version):
109
+ args.accelerate_version = f"accelerate=={args.accelerate_version}"
110
+
111
+ if not args.command_file and not args.command:
112
+ raise ValueError("You must specify either a command file or a command to run on the pod.")
113
+
114
+ if args.command_file:
115
+ with open(args.command_file) as f:
116
+ args.command = [f.read().splitlines()]
117
+
118
+ # To turn list of lists into list of strings
119
+ if isinstance(args.command[0], list):
120
+ args.command = [line for cmd in args.command for line in cmd]
121
+ # Default to the shared folder and install accelerate
122
+ new_cmd = ["cd /usr/share"]
123
+ if args.install_accelerate:
124
+ new_cmd += [f"pip install {args.accelerate_version}"]
125
+ new_cmd += args.command
126
+ args.command = "; ".join(new_cmd)
127
+
128
+ # Then send it to gcloud
129
+ # Eventually try to use google-api-core to do this instead of subprocess
130
+ cmd = ["gcloud"]
131
+ if args.use_alpha:
132
+ cmd += ["alpha"]
133
+ cmd += [
134
+ "compute",
135
+ "tpus",
136
+ "tpu-vm",
137
+ "ssh",
138
+ args.tpu_name,
139
+ "--zone",
140
+ args.tpu_zone,
141
+ "--command",
142
+ args.command,
143
+ "--worker",
144
+ "all",
145
+ ]
146
+ if args.debug:
147
+ print(f"Running {' '.join(cmd)}")
148
+ return
149
+ subprocess.run(cmd)
150
+ print("Successfully setup pod.")
151
+
152
+
153
+ def main():
154
+ parser = tpu_command_parser()
155
+ args = parser.parse_args()
156
+
157
+ tpu_command_launcher(args)
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/utils.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import argparse
16
+
17
+
18
+ class _StoreAction(argparse.Action):
19
+ """
20
+ Custom action that allows for `-` or `_` to be passed in for an argument.
21
+ """
22
+
23
+ def __init__(self, *args, **kwargs):
24
+ super().__init__(*args, **kwargs)
25
+ new_option_strings = []
26
+ for option_string in self.option_strings:
27
+ new_option_strings.append(option_string)
28
+ if "_" in option_string[2:]:
29
+ # Add `-` version to the option string
30
+ new_option_strings.append(option_string.replace("_", "-"))
31
+ self.option_strings = new_option_strings
32
+
33
+ def __call__(self, parser, namespace, values, option_string=None):
34
+ setattr(namespace, self.dest, values)
35
+
36
+
37
+ class _StoreConstAction(_StoreAction):
38
+ """
39
+ Same as `argparse._StoreConstAction` but uses the custom `_StoreAction`.
40
+ """
41
+
42
+ def __init__(self, option_strings, dest, const, default=None, required=False, help=None):
43
+ super().__init__(
44
+ option_strings=option_strings,
45
+ dest=dest,
46
+ nargs=0,
47
+ const=const,
48
+ default=default,
49
+ required=required,
50
+ help=help,
51
+ )
52
+
53
+ def __call__(self, parser, namespace, values, option_string=None):
54
+ setattr(namespace, self.dest, self.const)
55
+
56
+
57
+ class _StoreTrueAction(_StoreConstAction):
58
+ """
59
+ Same as `argparse._StoreTrueAction` but uses the custom `_StoreConstAction`.
60
+ """
61
+
62
+ def __init__(
63
+ self,
64
+ option_strings,
65
+ dest,
66
+ default=None,
67
+ required=False,
68
+ help=None,
69
+ ):
70
+ super().__init__(
71
+ option_strings=option_strings, dest=dest, const=True, default=default, required=required, help=help
72
+ )
73
+
74
+
75
+ class CustomArgumentGroup(argparse._ArgumentGroup):
76
+ """
77
+ Custom argument group that allows for the use of `-` or `_` in arguments passed and overrides the help for each
78
+ when applicable.
79
+ """
80
+
81
+ def _add_action(self, action):
82
+ args = vars(action)
83
+ if isinstance(action, argparse._StoreTrueAction):
84
+ action = _StoreTrueAction(
85
+ args["option_strings"], args["dest"], args["default"], args["required"], args["help"]
86
+ )
87
+ elif isinstance(action, argparse._StoreConstAction):
88
+ action = _StoreConstAction(
89
+ args["option_strings"],
90
+ args["dest"],
91
+ args["const"],
92
+ args["default"],
93
+ args["required"],
94
+ args["help"],
95
+ )
96
+ elif isinstance(action, argparse._StoreAction):
97
+ action = _StoreAction(**args)
98
+ action = super()._add_action(action)
99
+ return action
100
+
101
+
102
+ class CustomArgumentParser(argparse.ArgumentParser):
103
+ """
104
+ Custom argument parser that allows for the use of `-` or `_` in arguments passed and overrides the help for each
105
+ when applicable.
106
+ """
107
+
108
+ def add_argument(self, *args, **kwargs):
109
+ if "action" in kwargs:
110
+ # Translate action -> class
111
+ if kwargs["action"] == "store_true":
112
+ kwargs["action"] = _StoreTrueAction
113
+ else:
114
+ kwargs["action"] = _StoreAction
115
+ super().add_argument(*args, **kwargs)
116
+
117
+ def add_argument_group(self, *args, **kwargs):
118
+ group = CustomArgumentGroup(self, *args, **kwargs)
119
+ self._action_groups.append(group)
120
+ return group
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/data_loader.py ADDED
@@ -0,0 +1,1314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
16
+ from contextlib import suppress
17
+ from typing import Callable, List, Optional, Union
18
+
19
+ import torch
20
+ from torch.utils.data import BatchSampler, DataLoader, IterableDataset, RandomSampler
21
+
22
+ from .logging import get_logger
23
+ from .state import DistributedType, GradientState, PartialState, is_torch_xla_available
24
+ from .utils import (
25
+ RNGType,
26
+ broadcast,
27
+ broadcast_object_list,
28
+ concatenate,
29
+ find_batch_size,
30
+ get_data_structure,
31
+ initialize_tensors,
32
+ is_torch_version,
33
+ is_torchdata_stateful_dataloader_available,
34
+ send_to_device,
35
+ slice_tensors,
36
+ synchronize_rng_states,
37
+ )
38
+
39
+
40
+ logger = get_logger(__name__)
41
+
42
+ # kwargs of the DataLoader in min version 1.4.0.
43
+ _PYTORCH_DATALOADER_KWARGS = {
44
+ "batch_size": 1,
45
+ "shuffle": False,
46
+ "sampler": None,
47
+ "batch_sampler": None,
48
+ "num_workers": 0,
49
+ "collate_fn": None,
50
+ "pin_memory": False,
51
+ "drop_last": False,
52
+ "timeout": 0,
53
+ "worker_init_fn": None,
54
+ "multiprocessing_context": None,
55
+ "generator": None,
56
+ "prefetch_factor": 2,
57
+ "persistent_workers": False,
58
+ }
59
+
60
+ # kwargs added after by version
61
+ _PYTORCH_DATALOADER_ADDITIONAL_KWARGS = {}
62
+
63
+ for v, additional_kwargs in _PYTORCH_DATALOADER_ADDITIONAL_KWARGS.items():
64
+ if is_torch_version(">=", v):
65
+ _PYTORCH_DATALOADER_KWARGS.update(additional_kwargs)
66
+
67
+
68
+ class SeedableRandomSampler(RandomSampler):
69
+ """
70
+ Same as a random sampler, except that in `__iter__` a seed can be used.
71
+
72
+ Needed specifically in distributed cases, when the random generator for each GPU needs to start from the same seed
73
+ and be fully reproducable on multiple iterations.
74
+
75
+ If a custom `generator` is passed, it will rely on its initial seed as well as the current iteration it is on
76
+ (stored in `self.epoch`).
77
+ """
78
+
79
+ def __init__(self, *args, **kwargs):
80
+ super().__init__(*args, **kwargs)
81
+ self.epoch = 0
82
+ self.initial_seed = torch.random.initial_seed()
83
+
84
+ def __iter__(self):
85
+ if self.generator is None:
86
+ self.generator = torch.Generator()
87
+ self.generator.manual_seed(self.initial_seed)
88
+
89
+ # Allow `self.epoch` to modify the seed of the generator
90
+ seed = self.epoch + self.initial_seed
91
+ # print("Setting seed at epoch", self.epoch, seed)
92
+ self.generator.manual_seed(seed)
93
+ yield from super().__iter__()
94
+ self.set_epoch(self.epoch + 1)
95
+
96
+ def set_epoch(self, epoch: int):
97
+ "Sets the current iteration of the sampler."
98
+ self.epoch = epoch
99
+
100
+
101
+ class BatchSamplerShard(BatchSampler):
102
+ """
103
+ Wraps a PyTorch `BatchSampler` to generate batches for one of the processes only. Instances of this class will
104
+ always yield a number of batches that is a round multiple of `num_processes` and that all have the same size.
105
+ Depending on the value of the `drop_last` attribute of the batch sampler passed, it will either stop the iteration
106
+ at the first batch that would be too small / not present on all processes or loop with indices from the beginning.
107
+
108
+ Args:
109
+ batch_sampler (`torch.utils.data.sampler.BatchSampler`):
110
+ The batch sampler to split in several shards.
111
+ num_processes (`int`, *optional*, defaults to 1):
112
+ The number of processes running concurrently.
113
+ process_index (`int`, *optional*, defaults to 0):
114
+ The index of the current process.
115
+ split_batches (`bool`, *optional*, defaults to `False`):
116
+ Whether the shards should be created by splitting a batch to give a piece of it on each process, or by
117
+ yielding different full batches on each process.
118
+
119
+ On two processes with a sampler of `[[0, 1, 2, 3], [4, 5, 6, 7]]`, this will result in:
120
+
121
+ - the sampler on process 0 to yield `[0, 1, 2, 3]` and the sampler on process 1 to yield `[4, 5, 6, 7]` if
122
+ this argument is set to `False`.
123
+ - the sampler on process 0 to yield `[0, 1]` then `[4, 5]` and the sampler on process 1 to yield `[2, 3]`
124
+ then `[6, 7]` if this argument is set to `True`.
125
+ even_batches (`bool`, *optional*, defaults to `True`):
126
+ Whether or not to loop back at the beginning of the sampler when the number of samples is not a round
127
+ multiple of (original batch size / number of processes).
128
+
129
+ <Tip warning={true}>
130
+
131
+ `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`
132
+ equal to `False`
133
+
134
+ </Tip>"""
135
+
136
+ def __init__(
137
+ self,
138
+ batch_sampler: BatchSampler,
139
+ num_processes: int = 1,
140
+ process_index: int = 0,
141
+ split_batches: bool = False,
142
+ even_batches: bool = True,
143
+ ):
144
+ if split_batches and batch_sampler.batch_size % num_processes != 0:
145
+ raise ValueError(
146
+ f"To use `BatchSamplerShard` in `split_batches` mode, the batch size ({batch_sampler.batch_size}) "
147
+ f"needs to be a round multiple of the number of processes ({num_processes})."
148
+ )
149
+ self.batch_sampler = batch_sampler
150
+ self.num_processes = num_processes
151
+ self.process_index = process_index
152
+ self.split_batches = split_batches
153
+ self.even_batches = even_batches
154
+ self.batch_size = getattr(batch_sampler, "batch_size", None)
155
+ self.drop_last = getattr(batch_sampler, "drop_last", False)
156
+ if self.batch_size is None and self.even_batches:
157
+ raise ValueError(
158
+ "You need to use `even_batches=False` when the batch sampler has no batch size. If you "
159
+ "are not calling this method directly, set `accelerator.even_batches=False` instead."
160
+ )
161
+
162
+ @property
163
+ def total_length(self):
164
+ return len(self.batch_sampler)
165
+
166
+ def __len__(self):
167
+ if self.split_batches:
168
+ # Split batches does not change the length of the batch sampler
169
+ return len(self.batch_sampler)
170
+ if len(self.batch_sampler) % self.num_processes == 0:
171
+ # If the length is a round multiple of the number of processes, it's easy.
172
+ return len(self.batch_sampler) // self.num_processes
173
+ length = len(self.batch_sampler) // self.num_processes
174
+ if self.drop_last:
175
+ # Same if we drop the remainder.
176
+ return length
177
+ elif self.even_batches:
178
+ # When we even batches we always get +1
179
+ return length + 1
180
+ else:
181
+ # Otherwise it depends on the process index.
182
+ return length + 1 if self.process_index < len(self.batch_sampler) % self.num_processes else length
183
+
184
+ def __iter__(self):
185
+ return self._iter_with_split() if self.split_batches else self._iter_with_no_split()
186
+
187
+ def _iter_with_split(self):
188
+ initial_data = []
189
+ batch_length = self.batch_sampler.batch_size // self.num_processes
190
+ for idx, batch in enumerate(self.batch_sampler):
191
+ if idx == 0:
192
+ initial_data = batch
193
+ if len(batch) == self.batch_size:
194
+ # If the batch is full, we yield the part of it this process is responsible of.
195
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
196
+
197
+ # If drop_last is True of the last batch was full, iteration is over, otherwise...
198
+ if not self.drop_last and len(initial_data) > 0 and len(batch) < self.batch_size:
199
+ if not self.even_batches:
200
+ if len(batch) > batch_length * self.process_index:
201
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
202
+ else:
203
+ # For degenerate cases where the dataset has less than num_process * batch_size samples
204
+ while len(initial_data) < self.batch_size:
205
+ initial_data += initial_data
206
+ batch = batch + initial_data
207
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
208
+
209
+ def _iter_with_no_split(self):
210
+ initial_data = []
211
+ batch_to_yield = []
212
+ for idx, batch in enumerate(self.batch_sampler):
213
+ # We gather the initial indices in case we need to circle back at the end.
214
+ if not self.drop_last and idx < self.num_processes:
215
+ initial_data += batch
216
+ # We identify the batch to yield but wait until we ar sure every process gets a full batch before actually
217
+ # yielding it.
218
+ if idx % self.num_processes == self.process_index:
219
+ batch_to_yield = batch
220
+ if idx % self.num_processes == self.num_processes - 1 and (
221
+ self.batch_size is None or len(batch) == self.batch_size
222
+ ):
223
+ yield batch_to_yield
224
+ batch_to_yield = []
225
+
226
+ # If drop_last is True, iteration is over, otherwise...
227
+ if not self.drop_last and len(initial_data) > 0:
228
+ if not self.even_batches:
229
+ if len(batch_to_yield) > 0:
230
+ yield batch_to_yield
231
+ else:
232
+ # ... we yield the complete batch we had saved before if it has the proper length
233
+ if len(batch_to_yield) == self.batch_size:
234
+ yield batch_to_yield
235
+
236
+ # For degenerate cases where the dataset has less than num_process * batch_size samples
237
+ while len(initial_data) < self.num_processes * self.batch_size:
238
+ initial_data += initial_data
239
+
240
+ # If the last batch seen was of the proper size, it has been yielded by its process so we move to the next
241
+ if len(batch) == self.batch_size:
242
+ batch = []
243
+ idx += 1
244
+
245
+ # Make sure we yield a multiple of self.num_processes batches
246
+ cycle_index = 0
247
+ while idx % self.num_processes != 0 or len(batch) > 0:
248
+ end_index = cycle_index + self.batch_size - len(batch)
249
+ batch += initial_data[cycle_index:end_index]
250
+ if idx % self.num_processes == self.process_index:
251
+ yield batch
252
+ cycle_index = end_index
253
+ batch = []
254
+ idx += 1
255
+
256
+
257
+ class IterableDatasetShard(IterableDataset):
258
+ """
259
+ Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will
260
+ always yield a number of samples that is a round multiple of the actual batch size (depending of the value of
261
+ `split_batches`, this is either `batch_size` or `batch_size x num_processes`). Depending on the value of the
262
+ `drop_last` attribute of the batch sampler passed, it will either stop the iteration at the first batch that would
263
+ be too small or loop with indices from the beginning.
264
+
265
+ Args:
266
+ dataset (`torch.utils.data.dataset.IterableDataset`):
267
+ The batch sampler to split in several shards.
268
+ batch_size (`int`, *optional*, defaults to 1):
269
+ The size of the batches per shard (if `split_batches=False`) or the size of the batches (if
270
+ `split_batches=True`).
271
+ drop_last (`bool`, *optional*, defaults to `False`):
272
+ Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the
273
+ beginning.
274
+ num_processes (`int`, *optional*, defaults to 1):
275
+ The number of processes running concurrently.
276
+ process_index (`int`, *optional*, defaults to 0):
277
+ The index of the current process.
278
+ split_batches (`bool`, *optional*, defaults to `False`):
279
+ Whether the shards should be created by splitting a batch to give a piece of it on each process, or by
280
+ yielding different full batches on each process.
281
+
282
+ On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7]`, this will result in:
283
+
284
+ - the shard on process 0 to yield `[0, 1, 2, 3]` and the shard on process 1 to yield `[4, 5, 6, 7]` if this
285
+ argument is set to `False`.
286
+ - the shard on process 0 to yield `[0, 1, 4, 5]` and the sampler on process 1 to yield `[2, 3, 6, 7]` if
287
+ this argument is set to `True`.
288
+ """
289
+
290
+ def __init__(
291
+ self,
292
+ dataset: IterableDataset,
293
+ batch_size: int = 1,
294
+ drop_last: bool = False,
295
+ num_processes: int = 1,
296
+ process_index: int = 0,
297
+ split_batches: bool = False,
298
+ ):
299
+ if split_batches and batch_size > 1 and batch_size % num_processes != 0:
300
+ raise ValueError(
301
+ f"To use `IterableDatasetShard` in `split_batches` mode, the batch size ({batch_size}) "
302
+ f"needs to be a round multiple of the number of processes ({num_processes})."
303
+ )
304
+ self.dataset = dataset
305
+ self.batch_size = batch_size
306
+ self.drop_last = drop_last
307
+ self.num_processes = num_processes
308
+ self.process_index = process_index
309
+ self.split_batches = split_batches
310
+
311
+ def set_epoch(self, epoch):
312
+ self.epoch = epoch
313
+ if hasattr(self.dataset, "set_epoch"):
314
+ self.dataset.set_epoch(epoch)
315
+
316
+ def __len__(self):
317
+ # We will just raise the downstream error if the underlying dataset is not sized
318
+ if self.drop_last:
319
+ return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size
320
+ else:
321
+ return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size
322
+
323
+ def __iter__(self):
324
+ if (
325
+ not hasattr(self.dataset, "set_epoch")
326
+ and hasattr(self.dataset, "generator")
327
+ and isinstance(self.dataset.generator, torch.Generator)
328
+ ):
329
+ self.dataset.generator.manual_seed(self.epoch)
330
+ real_batch_size = self.batch_size if self.split_batches else (self.batch_size * self.num_processes)
331
+ process_batch_size = (self.batch_size // self.num_processes) if self.split_batches else self.batch_size
332
+ process_slice = range(self.process_index * process_batch_size, (self.process_index + 1) * process_batch_size)
333
+
334
+ first_batch = None
335
+ current_batch = []
336
+ for element in self.dataset:
337
+ current_batch.append(element)
338
+ # Wait to have a full batch before yielding elements.
339
+ if len(current_batch) == real_batch_size:
340
+ for i in process_slice:
341
+ yield current_batch[i]
342
+ if first_batch is None:
343
+ first_batch = current_batch.copy()
344
+ current_batch = []
345
+
346
+ # Finished if drop_last is True, otherwise complete the last batch with elements from the beginning.
347
+ if not self.drop_last and len(current_batch) > 0:
348
+ if first_batch is None:
349
+ first_batch = current_batch.copy()
350
+ while len(current_batch) < real_batch_size:
351
+ current_batch += first_batch
352
+ for i in process_slice:
353
+ yield current_batch[i]
354
+
355
+
356
+ class DataLoaderStateMixin:
357
+ """
358
+ Mixin class that adds a state to a `DataLoader` to keep track of the status inside the dataloader such as at the
359
+ end of the iteration, the number of items in the dataset in the last batch relative to the batch size, and other
360
+ useful information that might be needed.
361
+
362
+ **Available attributes:**
363
+
364
+ - **end_of_dataloader** (`bool`) -- Whether at the last iteration or batch
365
+ - **remainder** (`int`) -- The number of items that are remaining in the last batch, relative to the total
366
+ batch size
367
+
368
+ <Tip warning={true}>
369
+
370
+ Inheriters of this class should ensure that the class creates a `GradientState()` instance, stored in
371
+ `self.gradient_state`.
372
+
373
+ </Tip>
374
+
375
+ """
376
+
377
+ def __init_subclass__(cls, **kwargs):
378
+ cls.end_of_dataloader = False
379
+ cls.remainder = -1
380
+
381
+ def reset(self):
382
+ self.end_of_dataloader = False
383
+ self.remainder = -1
384
+
385
+ def begin(self):
386
+ "Prepares the gradient state for the current dataloader"
387
+ self.reset()
388
+ with suppress(Exception):
389
+ if not self._drop_last:
390
+ length = getattr(self.dataset, "total_dataset_length", len(self.dataset))
391
+ self.remainder = length % self.total_batch_size
392
+ self.gradient_state._add_dataloader(self)
393
+
394
+ def end(self):
395
+ "Cleans up the gradient state after exiting the dataloader"
396
+ self.gradient_state._remove_dataloader(self)
397
+
398
+
399
+ class DataLoaderAdapter:
400
+ """
401
+ A class which wraps around a PyTorch `DataLoader` (or variants of it) to be used with the `Accelerator`. For
402
+ compatability reasons, this class inherits from the class it wraps around, so it can be used as a drop-in.
403
+ """
404
+
405
+ def __init__(self, dataset, use_stateful_dataloader=False, batch_sampler=None, **kwargs):
406
+ self.use_stateful_dataloader = use_stateful_dataloader
407
+ if is_torchdata_stateful_dataloader_available():
408
+ from torchdata.stateful_dataloader import StatefulDataLoader
409
+
410
+ if use_stateful_dataloader and not is_torchdata_stateful_dataloader_available():
411
+ raise ImportError(
412
+ "StatefulDataLoader is not available. Please install torchdata version 0.8.0 or higher to use it."
413
+ )
414
+ if use_stateful_dataloader:
415
+ self.base_dataloader = StatefulDataLoader(dataset, batch_sampler=batch_sampler, **kwargs)
416
+ else:
417
+ self.base_dataloader = DataLoader(dataset, batch_sampler=batch_sampler, **kwargs)
418
+
419
+ if hasattr(self.base_dataloader, "state_dict"):
420
+ self.dl_state_dict = self.base_dataloader.state_dict()
421
+
422
+ def __getattr__(self, name):
423
+ # Avoid infinite recursion if we try to access a nonexistent base_dataloader attribute.
424
+ if name == "base_dataloader":
425
+ raise AttributeError()
426
+ # Delegate attribute access to the internal dataloader
427
+ return getattr(self.base_dataloader, name)
428
+
429
+ def state_dict(self):
430
+ return self.dl_state_dict
431
+
432
+ def load_state_dict(self, state_dict):
433
+ self.base_dataloader.load_state_dict(state_dict)
434
+
435
+ @property
436
+ def __class__(self):
437
+ """
438
+ In order to maintain backwards compatability with other code, we need to ensure `isinstance(obj, DataLoader)`
439
+ returs true. This is because some downstream code assumes that the `DataLoader` is the base class of the
440
+ object.
441
+ """
442
+ return self.base_dataloader.__class__
443
+
444
+ def __len__(self):
445
+ return len(self.base_dataloader)
446
+
447
+ def adjust_state_dict_for_prefetch(self):
448
+ """
449
+ Adjusts the state dict for prefetching. Natively, this will adjust all of the iters yielded keys in
450
+ `self.dl_state_dict` by a factor of `num_processes - 1`, however if a custom correction is needed, this can be
451
+ overridden.
452
+
453
+ This should modify `self.dl_state_dict` directly
454
+ """
455
+ # The state dict will be off by a factor of `n-1` batch too many during DDP,
456
+ # so we need to adjust it here
457
+ if PartialState().distributed_type != DistributedType.NO:
458
+ factor = PartialState().num_processes - 1
459
+ if self.dl_state_dict["_sampler_iter_yielded"] > 0:
460
+ self.dl_state_dict["_sampler_iter_yielded"] -= factor
461
+ if self.dl_state_dict["_num_yielded"] > 0:
462
+ self.dl_state_dict["_num_yielded"] -= factor
463
+ if self.dl_state_dict["_index_sampler_state"] is not None:
464
+ if (
465
+ "samples_yielded" in self.dl_state_dict["_index_sampler_state"]
466
+ and self.dl_state_dict["_index_sampler_state"]["samples_yielded"] > 0
467
+ ):
468
+ self.dl_state_dict["_index_sampler_state"]["samples_yielded"] -= self.batch_size * factor
469
+
470
+ def _update_state_dict(self):
471
+ # The state_dict of the underlying base_dataloader may be ahead of what is currently being yielded.
472
+ # E.g. the implementation of DataLoaderShard involves having an underlying iterator 1 element ahead of
473
+ # what it wants to yield.
474
+ #
475
+ # _update_state_dict is called to snapshot the state_dict that would properly recover the DataLoaderAdapter.
476
+ if hasattr(self.base_dataloader, "state_dict"):
477
+ self.dl_state_dict = self.base_dataloader.state_dict()
478
+ # Potentially modify the state_dict to adjust for prefetching
479
+ self.adjust_state_dict_for_prefetch()
480
+ # Then tag if we are at the end of the dataloader
481
+ self.dl_state_dict["_iterator_finished"] = self.end_of_dataloader
482
+
483
+
484
+ class DataLoaderShard(DataLoaderAdapter, DataLoaderStateMixin):
485
+ """
486
+ Subclass of `DataLoaderAdapter` that will deal with device placement and current distributed setup.
487
+
488
+ Args:
489
+ dataset (`torch.utils.data.dataset.Dataset`):
490
+ The dataset to use to build this dataloader.
491
+ device (`torch.device`, *optional*):
492
+ If passed, the device to put all batches on.
493
+ rng_types (list of `str` or [`~utils.RNGType`]):
494
+ The list of random number generators to synchronize at the beginning of each iteration. Should be one or
495
+ several of:
496
+
497
+ - `"torch"`: the base torch random number generator
498
+ - `"cuda"`: the CUDA random number generator (GPU only)
499
+ - `"xla"`: the XLA random number generator (TPU only)
500
+ - `"generator"`: an optional `torch.Generator`
501
+ synchronized_generator (`torch.Generator`, *optional*):
502
+ A random number generator to keep synchronized across processes.
503
+ skip_batches (`int`, *optional*, defaults to 0):
504
+ The number of batches to skip at the beginning.
505
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
506
+ Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`.
507
+ **kwargs (additional keyword arguments, *optional*):
508
+ All other keyword arguments to pass to the regular `DataLoader` initialization.
509
+
510
+ **Available attributes:**
511
+
512
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
513
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
514
+ number of processes
515
+
516
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
517
+ """
518
+
519
+ def __init__(
520
+ self,
521
+ dataset,
522
+ device=None,
523
+ rng_types=None,
524
+ synchronized_generator=None,
525
+ skip_batches=0,
526
+ use_stateful_dataloader=False,
527
+ _drop_last: bool = False,
528
+ _non_blocking: bool = False,
529
+ **kwargs,
530
+ ):
531
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
532
+ self.device = device
533
+ self.rng_types = rng_types
534
+ self.synchronized_generator = synchronized_generator
535
+ self.skip_batches = skip_batches
536
+ self.gradient_state = GradientState()
537
+ self._drop_last = _drop_last
538
+ self._non_blocking = _non_blocking
539
+ self.iteration = 0
540
+
541
+ def __iter__(self):
542
+ if self.rng_types is not None:
543
+ synchronize_rng_states(self.rng_types, self.synchronized_generator)
544
+ self.begin()
545
+
546
+ self.set_epoch(self.iteration)
547
+ dataloader_iter = self.base_dataloader.__iter__()
548
+ # We iterate one batch ahead to check when we are at the end
549
+ try:
550
+ current_batch = next(dataloader_iter)
551
+ except StopIteration:
552
+ yield
553
+
554
+ batch_index = 0
555
+ while True:
556
+ try:
557
+ # But we still move it to the device so it is done before `StopIteration` is reached
558
+ if self.device is not None:
559
+ current_batch = send_to_device(current_batch, self.device, non_blocking=self._non_blocking)
560
+ self._update_state_dict()
561
+ next_batch = next(dataloader_iter)
562
+ if batch_index >= self.skip_batches:
563
+ yield current_batch
564
+ batch_index += 1
565
+ current_batch = next_batch
566
+ except StopIteration:
567
+ self.end_of_dataloader = True
568
+ self._update_state_dict()
569
+ if batch_index >= self.skip_batches:
570
+ yield current_batch
571
+ break
572
+
573
+ self.iteration += 1
574
+ self.end()
575
+
576
+ def __reduce__(self):
577
+ """
578
+ Define the `__reduce__` method to ensure a `DataLoaderShard` can be pickled and unpickled. This needs to be
579
+ explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
580
+ `__class__` member.
581
+ """
582
+ args = super().__reduce__()
583
+ return (DataLoaderShard, *args[1:])
584
+
585
+ def set_epoch(self, epoch: int):
586
+ # In case it is manually passed in, the user can set it to what they like
587
+ if self.iteration != epoch:
588
+ self.iteration = epoch
589
+ if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"):
590
+ self.batch_sampler.sampler.set_epoch(epoch)
591
+ # We support if a custom `Dataset` implementation has `set_epoch`
592
+ # or in general HF datasets `Datasets`
593
+ elif hasattr(self.dataset, "set_epoch"):
594
+ self.dataset.set_epoch(epoch)
595
+
596
+ @property
597
+ def total_batch_size(self):
598
+ batch_sampler = self.sampler if isinstance(self.sampler, BatchSampler) else self.batch_sampler
599
+ return (
600
+ batch_sampler.batch_size
601
+ if getattr(batch_sampler, "split_batches", False)
602
+ else (batch_sampler.batch_size * getattr(batch_sampler, "num_processes", 1))
603
+ )
604
+
605
+ @property
606
+ def total_dataset_length(self):
607
+ if hasattr(self.dataset, "total_length"):
608
+ return self.dataset.total_length
609
+ else:
610
+ return len(self.dataset)
611
+
612
+ def get_sampler(self):
613
+ return get_sampler(self)
614
+
615
+ def set_sampler(self, sampler):
616
+ sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler)
617
+ if sampler_is_batch_sampler:
618
+ self.sampler.sampler = sampler
619
+ else:
620
+ self.batch_sampler.sampler = sampler
621
+ if hasattr(self.batch_sampler, "batch_sampler"):
622
+ self.batch_sampler.batch_sampler.sampler = sampler
623
+
624
+
625
+ if is_torch_xla_available():
626
+ import torch_xla.distributed.parallel_loader as xpl
627
+
628
+ class MpDeviceLoaderWrapper(xpl.MpDeviceLoader):
629
+ """
630
+ Wrapper for the xpl.MpDeviceLoader class that knows the total batch size.
631
+
632
+ XLA preloading threads will all call DataLoaderShard's __iter__(). Remove rng_types from DataLoaderShard to
633
+ prevent it from using the XLA device in the preloading threads, and synchronize the RNG once from the main
634
+ thread only.
635
+
636
+ **Available attributes:**
637
+
638
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
639
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
640
+ number of processes
641
+
642
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
643
+ """
644
+
645
+ def __init__(self, dataloader: DataLoaderShard, device: torch.device):
646
+ super().__init__(dataloader, device)
647
+ self._rng_types = self._loader.rng_types
648
+ self._loader.rng_types = None
649
+ self.device = device
650
+
651
+ def __iter__(self):
652
+ if self._rng_types is not None:
653
+ synchronize_rng_states(self._rng_types, self._loader.synchronized_generator)
654
+
655
+ return super().__iter__()
656
+
657
+ def set_epoch(self, epoch: int):
658
+ if hasattr(self.dataloader, "set_epoch"):
659
+ self.dataloader.set_epoch(epoch)
660
+
661
+ @property
662
+ def total_batch_size(self):
663
+ return self._loader.total_batch_size
664
+
665
+ @property
666
+ def total_dataset_length(self):
667
+ return self._loader.total_dataset_length
668
+
669
+ @property
670
+ def batch_sampler(self):
671
+ return self._loader.batch_sampler
672
+
673
+ @property
674
+ def dataloader(self):
675
+ return self._loader
676
+
677
+
678
+ class DataLoaderDispatcher(DataLoaderAdapter, DataLoaderStateMixin):
679
+ """
680
+ Subclass of `DataLoaderAdapter` that will iterate and preprocess on process 0 only, then dispatch on each process
681
+ their part of the batch.
682
+
683
+ Args:
684
+ split_batches (`bool`, *optional*, defaults to `False`):
685
+ Whether the resulting `DataLoader` should split the batches of the original data loader across devices or
686
+ yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of
687
+ `num_processes` batches at each iteration). Another way to see this is that the observed batch size will be
688
+ the same as the initial `dataloader` if this option is set to `True`, the batch size of the initial
689
+ `dataloader` multiplied by `num_processes` otherwise. Setting this option to `True` requires that the batch
690
+ size of the `dataloader` is a round multiple of `batch_size`.
691
+ skip_batches (`int`, *optional*, defaults to 0):
692
+ The number of batches to skip at the beginning of an iteration.
693
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
694
+ Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`.
695
+
696
+ **Available attributes:**
697
+
698
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
699
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
700
+ number of processes
701
+
702
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
703
+ """
704
+
705
+ def __init__(
706
+ self,
707
+ dataset,
708
+ split_batches: bool = False,
709
+ skip_batches=0,
710
+ use_stateful_dataloader=False,
711
+ _drop_last: bool = False,
712
+ _non_blocking: bool = False,
713
+ slice_fn=None,
714
+ **kwargs,
715
+ ):
716
+ shuffle = False
717
+ if is_torch_version(">=", "1.11.0"):
718
+ from torch.utils.data.datapipes.iter.combinatorics import ShufflerIterDataPipe
719
+
720
+ # We need to save the shuffling state of the DataPipe
721
+ if isinstance(dataset, ShufflerIterDataPipe):
722
+ shuffle = dataset._shuffle_enabled
723
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
724
+ self.split_batches = split_batches
725
+ if shuffle:
726
+ torch.utils.data.graph_settings.apply_shuffle_settings(dataset, shuffle=shuffle)
727
+
728
+ self.gradient_state = GradientState()
729
+ self.state = PartialState()
730
+ self._drop_last = _drop_last
731
+ self._non_blocking = _non_blocking
732
+ self.skip_batches = skip_batches
733
+
734
+ self.slice_fn = slice_tensors if slice_fn is None else slice_fn
735
+ self.iteration = 0
736
+
737
+ def _fetch_batches(self, iterator):
738
+ batches, batch = None, None
739
+ # On process 0, we gather the batch to dispatch.
740
+ if self.state.process_index == 0:
741
+ try:
742
+ if self.split_batches:
743
+ # One batch of the main iterator is dispatched and split.
744
+ self._update_state_dict()
745
+ batch = next(iterator)
746
+ else:
747
+ # num_processes batches of the main iterator are concatenated then dispatched and split.
748
+ # We add the batches one by one so we have the remainder available when drop_last=False.
749
+ batches = []
750
+ for _ in range(self.state.num_processes):
751
+ self._update_state_dict()
752
+ batches.append(next(iterator))
753
+ try:
754
+ batch = concatenate(batches, dim=0)
755
+ except RuntimeError as e:
756
+ raise RuntimeError(
757
+ "You can't use batches of different size with `dispatch_batches=True` or when using an `IterableDataset`."
758
+ "either pass `dispatch_batches=False` and have each process fetch its own batch "
759
+ " or pass `split_batches=True`. By doing so, the main process will fetch a full batch and "
760
+ "slice it into `num_processes` batches for each process."
761
+ ) from e
762
+ # In both cases, we need to get the structure of the batch that we will broadcast on other
763
+ # processes to initialize the tensors with the right shape.
764
+ # data_structure, stop_iteration
765
+ batch_info = [get_data_structure(batch), False]
766
+ except StopIteration:
767
+ batch_info = [None, True]
768
+ else:
769
+ batch_info = [None, self._stop_iteration]
770
+ # This is inplace, so after this instruction, every process has the same `batch_info` as process 0.
771
+ broadcast_object_list(batch_info)
772
+ self._stop_iteration = batch_info[1]
773
+ if self._stop_iteration:
774
+ # If drop_last is False and split_batches is False, we may have a remainder to take care of.
775
+ if not self.split_batches and not self._drop_last:
776
+ if self.state.process_index == 0 and len(batches) > 0:
777
+ batch = concatenate(batches, dim=0)
778
+ batch_info = [get_data_structure(batch), False]
779
+ else:
780
+ batch_info = [None, True]
781
+ broadcast_object_list(batch_info)
782
+ return batch, batch_info
783
+
784
+ def __iter__(self):
785
+ self.begin()
786
+ self.set_epoch(self.iteration)
787
+ main_iterator = None
788
+ if is_torch_version(">=", "2.0.1"):
789
+ # NOTE PyTorch DataLoader adds forward compatibilities for DataPipes, which broadcasts
790
+ # shared seed to all dist processes. Thus, we need to create iterator for all dist processes.
791
+ # But, we only iterate through the DataLoader on process 0.
792
+ main_iterator = self.base_dataloader.__iter__()
793
+ elif self.state.process_index == 0:
794
+ main_iterator = self.base_dataloader.__iter__()
795
+ stop_iteration = False
796
+ self._stop_iteration = False
797
+ first_batch = None
798
+ next_batch, next_batch_info = self._fetch_batches(main_iterator)
799
+ batch_index = 0
800
+ while not stop_iteration:
801
+ batch, batch_info = next_batch, next_batch_info
802
+
803
+ if self.state.process_index != 0:
804
+ # Initialize tensors on other processes than process 0.
805
+ batch = initialize_tensors(batch_info[0])
806
+ batch = send_to_device(batch, self.state.device, non_blocking=self._non_blocking)
807
+ # Broadcast the batch before splitting it.
808
+ batch = broadcast(batch, from_process=0)
809
+
810
+ if not self._drop_last and first_batch is None:
811
+ # We keep at least num processes elements of the first batch to be able to complete the last batch
812
+ first_batch = self.slice_fn(
813
+ batch,
814
+ slice(0, self.state.num_processes),
815
+ process_index=self.state.process_index,
816
+ num_processes=self.state.num_processes,
817
+ )
818
+
819
+ if batch is None:
820
+ raise ValueError(
821
+ f"Batch does not contain any data (`{batch}`). At the end of all iterable data available before expected stop iteration."
822
+ )
823
+
824
+ observed_batch_size = find_batch_size(batch)
825
+ batch_size = observed_batch_size // self.state.num_processes
826
+
827
+ stop_iteration = self._stop_iteration
828
+ if not stop_iteration:
829
+ # We may still be at the end of the dataloader without knowing it yet: if there is nothing left in
830
+ # the dataloader since the number of batches is a round multiple of the number of processes.
831
+ next_batch, next_batch_info = self._fetch_batches(main_iterator)
832
+ # next_batch_info[0] is None when there are no more batches, otherwise we still need to process them.
833
+ if self._stop_iteration and next_batch_info[0] is None:
834
+ stop_iteration = True
835
+
836
+ if not self._drop_last and stop_iteration and observed_batch_size % self.state.num_processes != 0:
837
+ # If the last batch is not complete, let's add the first batch to it.
838
+ batch = concatenate([batch, first_batch], dim=0)
839
+ # Batch size computation above is wrong, it's off by 1 so we fix it.
840
+ batch_size += 1
841
+
842
+ data_slice = slice(self.state.process_index * batch_size, (self.state.process_index + 1) * batch_size)
843
+ batch = self.slice_fn(
844
+ batch,
845
+ data_slice,
846
+ process_index=self.state.process_index,
847
+ num_processes=self.state.num_processes,
848
+ )
849
+
850
+ if stop_iteration:
851
+ self.end_of_dataloader = True
852
+ self._update_state_dict()
853
+ self.remainder = observed_batch_size
854
+ if batch_index >= self.skip_batches:
855
+ yield batch
856
+ batch_index += 1
857
+ self.iteration += 1
858
+ self.end()
859
+
860
+ def set_epoch(self, epoch: int):
861
+ # In case it is manually passed in, the user can set it to what they like
862
+ if self.iteration != epoch:
863
+ self.iteration = epoch
864
+ if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"):
865
+ self.batch_sampler.sampler.set_epoch(epoch)
866
+ elif hasattr(self.dataset, "set_epoch"):
867
+ self.dataset.set_epoch(epoch)
868
+
869
+ def __len__(self):
870
+ whole_length = len(self.base_dataloader)
871
+ if self.split_batches:
872
+ return whole_length
873
+ elif self._drop_last:
874
+ return whole_length // self.state.num_processes
875
+ else:
876
+ return math.ceil(whole_length / self.state.num_processes)
877
+
878
+ def __reduce__(self):
879
+ """
880
+ Define the `__reduce__` method to ensure a `DataLoaderDispatcher` can be pickled and unpickled. This needs to
881
+ be explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
882
+ `__class__` member.
883
+ """
884
+ args = super().__reduce__()
885
+ return (DataLoaderDispatcher, *args[1:])
886
+
887
+ @property
888
+ def total_batch_size(self):
889
+ return (
890
+ self.dataset.batch_size if self.split_batches else (self.dataset.batch_size * self.dataset.num_processes)
891
+ )
892
+
893
+ @property
894
+ def total_dataset_length(self):
895
+ return len(self.dataset)
896
+
897
+ def get_sampler(self):
898
+ return get_sampler(self)
899
+
900
+ def set_sampler(self, sampler):
901
+ sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler)
902
+ if sampler_is_batch_sampler:
903
+ self.sampler.sampler = sampler
904
+ else:
905
+ self.batch_sampler.sampler = sampler
906
+ if hasattr(self.batch_sampler, "batch_sampler"):
907
+ self.batch_sampler.batch_sampler.sampler = sampler
908
+
909
+
910
+ def get_sampler(dataloader):
911
+ """
912
+ Get the sampler associated to the dataloader
913
+
914
+ Args:
915
+ dataloader (`torch.utils.data.dataloader.DataLoader`):
916
+ The data loader to split across several devices.
917
+ Returns:
918
+ `torch.utils.data.Sampler`: The sampler associated to the dataloader
919
+ """
920
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
921
+ if sampler_is_batch_sampler:
922
+ sampler = getattr(dataloader.sampler, "sampler", None)
923
+ else:
924
+ sampler = getattr(dataloader.batch_sampler, "sampler", None)
925
+ return sampler
926
+
927
+
928
+ def prepare_data_loader(
929
+ dataloader: DataLoader,
930
+ device: Optional[torch.device] = None,
931
+ num_processes: Optional[int] = None,
932
+ process_index: Optional[int] = None,
933
+ split_batches: bool = False,
934
+ put_on_device: bool = False,
935
+ rng_types: Optional[List[Union[str, RNGType]]] = None,
936
+ dispatch_batches: Optional[bool] = None,
937
+ even_batches: bool = True,
938
+ slice_fn_for_dispatch: Optional[Callable] = None,
939
+ use_seedable_sampler: bool = False,
940
+ non_blocking: bool = False,
941
+ use_stateful_dataloader: bool = False,
942
+ ) -> DataLoader:
943
+ """
944
+ Wraps a PyTorch `DataLoader` to generate batches for one of the processes only.
945
+
946
+ Depending on the value of the `drop_last` attribute of the `dataloader` passed, it will either stop the iteration
947
+ at the first batch that would be too small / not present on all processes or loop with indices from the beginning.
948
+
949
+ Args:
950
+ dataloader (`torch.utils.data.dataloader.DataLoader`):
951
+ The data loader to split across several devices.
952
+ device (`torch.device`):
953
+ The target device for the returned `DataLoader`.
954
+ num_processes (`int`, *optional*):
955
+ The number of processes running concurrently. Will default to the value given by [`~state.PartialState`].
956
+ process_index (`int`, *optional*):
957
+ The index of the current process. Will default to the value given by [`~state.PartialState`].
958
+ split_batches (`bool`, *optional*, defaults to `False`):
959
+ Whether the resulting `DataLoader` should split the batches of the original data loader across devices or
960
+ yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of
961
+ `num_processes` batches at each iteration).
962
+
963
+ Another way to see this is that the observed batch size will be the same as the initial `dataloader` if
964
+ this option is set to `True`, the batch size of the initial `dataloader` multiplied by `num_processes`
965
+ otherwise.
966
+
967
+ Setting this option to `True` requires that the batch size of the `dataloader` is a round multiple of
968
+ `batch_size`.
969
+ put_on_device (`bool`, *optional*, defaults to `False`):
970
+ Whether or not to put the batches on `device` (only works if the batches are nested list, tuples or
971
+ dictionaries of tensors).
972
+ rng_types (list of `str` or [`~utils.RNGType`]):
973
+ The list of random number generators to synchronize at the beginning of each iteration. Should be one or
974
+ several of:
975
+
976
+ - `"torch"`: the base torch random number generator
977
+ - `"cuda"`: the CUDA random number generator (GPU only)
978
+ - `"xla"`: the XLA random number generator (TPU only)
979
+ - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your
980
+ dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type.
981
+
982
+ dispatch_batches (`bool`, *optional*):
983
+ If set to `True`, the dataloader prepared is only iterated through on the main process and then the batches
984
+ are split and broadcast to each process. Will default to `True` when the underlying dataset is an
985
+ `IterableDataset`, `False` otherwise.
986
+ even_batches (`bool`, *optional*, defaults to `True`):
987
+ If set to `True`, in cases where the total batch size across all processes does not exactly divide the
988
+ dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among
989
+ all workers.
990
+ slice_fn_for_dispatch (`Callable`, *optional*`):
991
+ If passed, this function will be used to slice tensors across `num_processes`. Will default to
992
+ [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will be
993
+ ignored otherwise.
994
+ use_seedable_sampler (`bool`, *optional*, defaults to `False`):
995
+ Whether to use the [`~data_loader.SeedableRandomSampler`] instead of a `RandomSampler` for better
996
+ reproducability. Comes at a cost of potentially different performances due to different shuffling
997
+ algorithms but ensures results will be the *exact* same. Should be paired with `set_seed()` at every
998
+ `self.set_epoch`
999
+ non_blocking (`bool`, *optional*, defaults to `False`):
1000
+ If set to `True`, dataloader will utilize non-blocking host-to-device transfers. If the dataloader has
1001
+ `pin_memory` set to `True`, this will help to increase overlap between data transfer and computations.
1002
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
1003
+ "If set to true, the dataloader prepared by the Accelerator will be backed by "
1004
+ "[torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader).
1005
+ This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed."
1006
+
1007
+
1008
+ Returns:
1009
+ `torch.utils.data.dataloader.DataLoader`: A new data loader that will yield the portion of the batches
1010
+
1011
+ <Tip warning={true}>
1012
+
1013
+ `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`
1014
+ equal to `False`
1015
+
1016
+ </Tip>
1017
+ """
1018
+ if dispatch_batches is None:
1019
+ if not put_on_device:
1020
+ dispatch_batches = False
1021
+ else:
1022
+ dispatch_batches = isinstance(dataloader.dataset, IterableDataset)
1023
+
1024
+ if dispatch_batches and not put_on_device:
1025
+ raise ValueError("Using `dispatch_batches=True` requires `put_on_device=True`.")
1026
+ # Grab defaults from PartialState
1027
+ state = PartialState()
1028
+ if num_processes is None:
1029
+ num_processes = state.num_processes
1030
+ if process_index is None:
1031
+ process_index = state.process_index
1032
+
1033
+ # Sanity check
1034
+ if split_batches:
1035
+ if dataloader.batch_size is not None:
1036
+ batch_size_for_check = dataloader.batch_size
1037
+ else:
1038
+ # For custom batch_sampler
1039
+ if hasattr(dataloader.batch_sampler, "batch_size"):
1040
+ batch_size_for_check = dataloader.batch_sampler.batch_size
1041
+ else:
1042
+ raise ValueError(
1043
+ "In order to use `split_batches==True` you must have a `batch_size` attribute either in the passed "
1044
+ "`dataloader` or `dataloader.batch_sampler` objects, and it has to return a natural number. "
1045
+ "Your `dataloader.batch_size` is None and `dataloader.batch_sampler` "
1046
+ f"(`{type(dataloader.batch_sampler)}`) does not have the `batch_size` attribute set."
1047
+ )
1048
+
1049
+ if batch_size_for_check > 1 and batch_size_for_check % num_processes != 0:
1050
+ raise ValueError(
1051
+ f"To use a `DataLoader` in `split_batches` mode, the batch size ({dataloader.batch_size}) "
1052
+ f"needs to be a round multiple of the number of processes ({num_processes})."
1053
+ )
1054
+
1055
+ new_dataset = dataloader.dataset
1056
+ # Iterable dataset doesn't like batch_sampler, but data_loader creates a default one for it
1057
+ new_batch_sampler = dataloader.batch_sampler if not isinstance(new_dataset, IterableDataset) else None
1058
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
1059
+ synchronized_generator = None
1060
+
1061
+ sampler = get_sampler(dataloader)
1062
+ if isinstance(sampler, RandomSampler) and use_seedable_sampler:
1063
+ # When iterating through the dataloader during distributed processes
1064
+ # we want to ensure that on each process we are iterating through the same
1065
+ # samples in the same order if a seed is set. This requires a tweak
1066
+ # to the `torch.utils.data.RandomSampler` class (if used).
1067
+ sampler = SeedableRandomSampler(
1068
+ data_source=sampler.data_source,
1069
+ replacement=sampler.replacement,
1070
+ num_samples=sampler._num_samples,
1071
+ generator=getattr(sampler, "generator", torch.Generator()),
1072
+ )
1073
+
1074
+ if isinstance(dataloader.sampler, RandomSampler) and state.distributed_type == DistributedType.XLA:
1075
+ # isinstance(dataloader.sampler, RandomSampler) indicates the original dataloader has `shuffle` enabled.
1076
+ generator = torch.Generator().manual_seed(42)
1077
+ dataloader.generator = generator
1078
+ dataloader.sampler.generator = generator
1079
+ # No change if no multiprocess
1080
+ if (num_processes != 1 or state.distributed_type == DistributedType.MEGATRON_LM) and not dispatch_batches:
1081
+ if isinstance(new_dataset, IterableDataset):
1082
+ if getattr(dataloader.dataset, "generator", None) is not None:
1083
+ synchronized_generator = dataloader.dataset.generator
1084
+ new_dataset = IterableDatasetShard(
1085
+ new_dataset,
1086
+ batch_size=dataloader.batch_size,
1087
+ drop_last=dataloader.drop_last,
1088
+ num_processes=num_processes,
1089
+ process_index=process_index,
1090
+ split_batches=split_batches,
1091
+ )
1092
+ else:
1093
+ if not use_seedable_sampler and hasattr(sampler, "generator"):
1094
+ if sampler.generator is None:
1095
+ sampler.generator = torch.Generator()
1096
+ synchronized_generator = sampler.generator
1097
+ batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler
1098
+ new_batch_sampler = BatchSamplerShard(
1099
+ batch_sampler,
1100
+ num_processes=num_processes,
1101
+ process_index=process_index,
1102
+ split_batches=split_batches,
1103
+ even_batches=even_batches,
1104
+ )
1105
+
1106
+ # We ignore all of those since they are all dealt with by our new_batch_sampler
1107
+ ignore_kwargs = [
1108
+ "batch_size",
1109
+ "shuffle",
1110
+ "sampler",
1111
+ "batch_sampler",
1112
+ "drop_last",
1113
+ ]
1114
+
1115
+ if rng_types is not None and synchronized_generator is None and "generator" in rng_types:
1116
+ rng_types.remove("generator")
1117
+
1118
+ kwargs = {
1119
+ k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])
1120
+ for k in _PYTORCH_DATALOADER_KWARGS
1121
+ if k not in ignore_kwargs
1122
+ }
1123
+
1124
+ # Need to provide batch_size as batch_sampler is None for Iterable dataset
1125
+ if new_batch_sampler is None:
1126
+ kwargs["drop_last"] = dataloader.drop_last
1127
+ kwargs["batch_size"] = (
1128
+ dataloader.batch_size // num_processes if split_batches and not dispatch_batches else dataloader.batch_size
1129
+ )
1130
+ if dispatch_batches:
1131
+ kwargs.pop("generator")
1132
+ dataloader = DataLoaderDispatcher(
1133
+ new_dataset,
1134
+ split_batches=split_batches,
1135
+ batch_sampler=new_batch_sampler,
1136
+ _drop_last=dataloader.drop_last,
1137
+ _non_blocking=non_blocking,
1138
+ slice_fn=slice_fn_for_dispatch,
1139
+ use_stateful_dataloader=use_stateful_dataloader,
1140
+ **kwargs,
1141
+ )
1142
+ elif sampler_is_batch_sampler:
1143
+ dataloader = DataLoaderShard(
1144
+ new_dataset,
1145
+ device=device if put_on_device and state.distributed_type != DistributedType.XLA else None,
1146
+ sampler=new_batch_sampler,
1147
+ batch_size=dataloader.batch_size,
1148
+ rng_types=rng_types,
1149
+ _drop_last=dataloader.drop_last,
1150
+ _non_blocking=non_blocking,
1151
+ synchronized_generator=synchronized_generator,
1152
+ use_stateful_dataloader=use_stateful_dataloader,
1153
+ **kwargs,
1154
+ )
1155
+ else:
1156
+ dataloader = DataLoaderShard(
1157
+ new_dataset,
1158
+ device=device if put_on_device and state.distributed_type != DistributedType.XLA else None,
1159
+ batch_sampler=new_batch_sampler,
1160
+ rng_types=rng_types,
1161
+ synchronized_generator=synchronized_generator,
1162
+ _drop_last=dataloader.drop_last,
1163
+ _non_blocking=non_blocking,
1164
+ use_stateful_dataloader=use_stateful_dataloader,
1165
+ **kwargs,
1166
+ )
1167
+
1168
+ if isinstance(sampler, SeedableRandomSampler) and use_seedable_sampler:
1169
+ dataloader.set_sampler(sampler)
1170
+ if state.distributed_type == DistributedType.XLA:
1171
+ return MpDeviceLoaderWrapper(dataloader, device)
1172
+ return dataloader
1173
+
1174
+
1175
+ class SkipBatchSampler(BatchSampler):
1176
+ """
1177
+ A `torch.utils.data.BatchSampler` that skips the first `n` batches of another `torch.utils.data.BatchSampler`.
1178
+ Should not be used if the original dataloader is a `StatefulDataLoader`.
1179
+ """
1180
+
1181
+ def __init__(self, batch_sampler, skip_batches=0):
1182
+ self.batch_sampler = batch_sampler
1183
+ self.skip_batches = skip_batches
1184
+
1185
+ def __iter__(self):
1186
+ for index, samples in enumerate(self.batch_sampler):
1187
+ if index >= self.skip_batches:
1188
+ yield samples
1189
+
1190
+ @property
1191
+ def total_length(self):
1192
+ return len(self.batch_sampler)
1193
+
1194
+ def __len__(self):
1195
+ return len(self.batch_sampler) - self.skip_batches
1196
+
1197
+
1198
+ class SkipDataLoader(DataLoaderAdapter, DataLoaderStateMixin):
1199
+ """
1200
+ Subclass of a PyTorch `DataLoader` that will skip the first batches. Generally it's preferable to use
1201
+ `skip_first_batches`/`torchdata.StatefulDataLoader` instead of this class.
1202
+
1203
+ Args:
1204
+ dataset (`torch.utils.data.dataset.Dataset`):
1205
+ The dataset to use to build this dataloader.
1206
+ skip_batches (`int`, *optional*, defaults to 0):
1207
+ The number of batches to skip at the beginning.
1208
+ kwargs:
1209
+ All other keyword arguments to pass to the regular `DataLoader` initialization.
1210
+ """
1211
+
1212
+ def __init__(self, dataset, skip_batches=0, use_stateful_dataloader=False, **kwargs):
1213
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
1214
+ self.skip_batches = skip_batches
1215
+ self.gradient_state = GradientState()
1216
+
1217
+ def __iter__(self):
1218
+ self.begin()
1219
+ for index, batch in enumerate(self.base_dataloader.__iter__()):
1220
+ if index >= self.skip_batches:
1221
+ self._update_state_dict()
1222
+ yield batch
1223
+ self.end()
1224
+
1225
+ def __len__(self):
1226
+ return len(self.base_dataloader) - self.skip_batches
1227
+
1228
+ def __reduce__(self):
1229
+ """
1230
+ Define the `__reduce__` method to ensure a `SkipDataLoader` can be pickled and unpickled. This needs to be
1231
+ explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
1232
+ `__class__` member.
1233
+ """
1234
+ args = super().__reduce__()
1235
+ return (SkipDataLoader, *args[1:])
1236
+
1237
+
1238
+ def skip_first_batches(dataloader, num_batches=0):
1239
+ """
1240
+ Creates a `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`. Should not be used if
1241
+ the original dataloader is a `StatefulDataLoader`.
1242
+ """
1243
+ state = PartialState()
1244
+ if state.distributed_type == DistributedType.XLA:
1245
+ device = dataloader.device
1246
+ dataloader = dataloader.dataloader
1247
+
1248
+ dataset = dataloader.dataset
1249
+ sampler_is_batch_sampler = False
1250
+ if isinstance(dataset, IterableDataset):
1251
+ new_batch_sampler = None
1252
+ else:
1253
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
1254
+ batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler
1255
+ new_batch_sampler = SkipBatchSampler(batch_sampler, skip_batches=num_batches)
1256
+
1257
+ # We ignore all of those since they are all dealt with by our new_batch_sampler
1258
+ ignore_kwargs = [
1259
+ "batch_size",
1260
+ "shuffle",
1261
+ "sampler",
1262
+ "batch_sampler",
1263
+ "drop_last",
1264
+ ]
1265
+
1266
+ kwargs = {
1267
+ k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])
1268
+ for k in _PYTORCH_DATALOADER_KWARGS
1269
+ if k not in ignore_kwargs
1270
+ }
1271
+
1272
+ # Need to provide batch_size as batch_sampler is None for Iterable dataset
1273
+ if new_batch_sampler is None:
1274
+ kwargs["drop_last"] = dataloader.drop_last
1275
+ kwargs["batch_size"] = dataloader.batch_size
1276
+
1277
+ if isinstance(dataloader, DataLoaderDispatcher):
1278
+ if new_batch_sampler is None:
1279
+ # Need to manually skip batches in the dataloader
1280
+ kwargs["skip_batches"] = num_batches
1281
+ dataloader = DataLoaderDispatcher(
1282
+ dataset,
1283
+ split_batches=dataloader.split_batches,
1284
+ batch_sampler=new_batch_sampler,
1285
+ _drop_last=dataloader._drop_last,
1286
+ **kwargs,
1287
+ )
1288
+ elif isinstance(dataloader, DataLoaderShard):
1289
+ if new_batch_sampler is None:
1290
+ # Need to manually skip batches in the dataloader
1291
+ kwargs["skip_batches"] = num_batches
1292
+ elif sampler_is_batch_sampler:
1293
+ kwargs["sampler"] = new_batch_sampler
1294
+ kwargs["batch_size"] = dataloader.batch_size
1295
+ else:
1296
+ kwargs["batch_sampler"] = new_batch_sampler
1297
+ dataloader = DataLoaderShard(
1298
+ dataset,
1299
+ device=dataloader.device,
1300
+ rng_types=dataloader.rng_types,
1301
+ synchronized_generator=dataloader.synchronized_generator,
1302
+ **kwargs,
1303
+ )
1304
+ else:
1305
+ if new_batch_sampler is None:
1306
+ # Need to manually skip batches in the dataloader
1307
+ dataloader = SkipDataLoader(dataset, skip_batches=num_batches, **kwargs)
1308
+ else:
1309
+ dataloader = DataLoader(dataset, batch_sampler=new_batch_sampler, **kwargs)
1310
+
1311
+ if state.distributed_type == DistributedType.XLA:
1312
+ dataloader = MpDeviceLoaderWrapper(dataloader, device)
1313
+
1314
+ return dataloader
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/hooks.py ADDED
@@ -0,0 +1,720 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 functools
16
+ from typing import Dict, List, Mapping, Optional, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from .state import PartialState
22
+ from .utils import (
23
+ PrefixedDataset,
24
+ find_device,
25
+ named_module_tensors,
26
+ send_to_device,
27
+ set_module_tensor_to_device,
28
+ )
29
+ from .utils.memory import clear_device_cache
30
+ from .utils.modeling import get_non_persistent_buffers
31
+ from .utils.other import recursive_getattr
32
+
33
+
34
+ _accelerate_added_attributes = ["to", "cuda", "npu", "xpu", "mlu", "musa"]
35
+
36
+
37
+ class ModelHook:
38
+ """
39
+ A hook that contains callbacks to be executed just before and after the forward method of a model. The difference
40
+ with PyTorch existing hooks is that they get passed along the kwargs.
41
+
42
+ Class attribute:
43
+ - **no_grad** (`bool`, *optional*, defaults to `False`) -- Whether or not to execute the actual forward pass under
44
+ the `torch.no_grad()` context manager.
45
+ """
46
+
47
+ no_grad = False
48
+
49
+ def init_hook(self, module):
50
+ """
51
+ To be executed when the hook is attached to the module.
52
+
53
+ Args:
54
+ module (`torch.nn.Module`): The module attached to this hook.
55
+ """
56
+ return module
57
+
58
+ def pre_forward(self, module, *args, **kwargs):
59
+ """
60
+ To be executed just before the forward method of the model.
61
+
62
+ Args:
63
+ module (`torch.nn.Module`): The module whose forward pass will be executed just after this event.
64
+ args (`Tuple[Any]`): The positional arguments passed to the module.
65
+ kwargs (`Dict[Str, Any]`): The keyword arguments passed to the module.
66
+
67
+ Returns:
68
+ `Tuple[Tuple[Any], Dict[Str, Any]]`: A tuple with the treated `args` and `kwargs`.
69
+ """
70
+ return args, kwargs
71
+
72
+ def post_forward(self, module, output):
73
+ """
74
+ To be executed just after the forward method of the model.
75
+
76
+ Args:
77
+ module (`torch.nn.Module`): The module whose forward pass been executed just before this event.
78
+ output (`Any`): The output of the module.
79
+
80
+ Returns:
81
+ `Any`: The processed `output`.
82
+ """
83
+ return output
84
+
85
+ def detach_hook(self, module):
86
+ """
87
+ To be executed when the hook is detached from a module.
88
+
89
+ Args:
90
+ module (`torch.nn.Module`): The module detached from this hook.
91
+ """
92
+ return module
93
+
94
+
95
+ class SequentialHook(ModelHook):
96
+ """
97
+ A hook that can contain several hooks and iterates through them at each event.
98
+ """
99
+
100
+ def __init__(self, *hooks):
101
+ self.hooks = hooks
102
+
103
+ def init_hook(self, module):
104
+ for hook in self.hooks:
105
+ module = hook.init_hook(module)
106
+ return module
107
+
108
+ def pre_forward(self, module, *args, **kwargs):
109
+ for hook in self.hooks:
110
+ args, kwargs = hook.pre_forward(module, *args, **kwargs)
111
+ return args, kwargs
112
+
113
+ def post_forward(self, module, output):
114
+ for hook in self.hooks:
115
+ output = hook.post_forward(module, output)
116
+ return output
117
+
118
+ def detach_hook(self, module):
119
+ for hook in self.hooks:
120
+ module = hook.detach_hook(module)
121
+ return module
122
+
123
+
124
+ def add_hook_to_module(module: nn.Module, hook: ModelHook, append: bool = False):
125
+ """
126
+ Adds a hook to a given module. This will rewrite the `forward` method of the module to include the hook, to remove
127
+ this behavior and restore the original `forward` method, use `remove_hook_from_module`.
128
+
129
+ <Tip warning={true}>
130
+
131
+ If the module already contains a hook, this will replace it with the new hook passed by default. To chain two hooks
132
+ together, pass `append=True`, so it chains the current and new hook into an instance of the `SequentialHook` class.
133
+
134
+ </Tip>
135
+
136
+ Args:
137
+ module (`torch.nn.Module`):
138
+ The module to attach a hook to.
139
+ hook (`ModelHook`):
140
+ The hook to attach.
141
+ append (`bool`, *optional*, defaults to `False`):
142
+ Whether the hook should be chained with an existing one (if module already contains a hook) or not.
143
+
144
+ Returns:
145
+ `torch.nn.Module`: The same module, with the hook attached (the module is modified in place, so the result can
146
+ be discarded).
147
+ """
148
+
149
+ if append and (getattr(module, "_hf_hook", None) is not None):
150
+ old_hook = module._hf_hook
151
+ remove_hook_from_module(module)
152
+ hook = SequentialHook(old_hook, hook)
153
+
154
+ if hasattr(module, "_hf_hook") and hasattr(module, "_old_forward"):
155
+ # If we already put some hook on this module, we replace it with the new one.
156
+ old_forward = module._old_forward
157
+ else:
158
+ old_forward = module.forward
159
+ module._old_forward = old_forward
160
+
161
+ module = hook.init_hook(module)
162
+ module._hf_hook = hook
163
+
164
+ def new_forward(module, *args, **kwargs):
165
+ args, kwargs = module._hf_hook.pre_forward(module, *args, **kwargs)
166
+ if module._hf_hook.no_grad:
167
+ with torch.no_grad():
168
+ output = module._old_forward(*args, **kwargs)
169
+ else:
170
+ output = module._old_forward(*args, **kwargs)
171
+ return module._hf_hook.post_forward(module, output)
172
+
173
+ # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail.
174
+ # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409
175
+ if "GraphModuleImpl" in str(type(module)):
176
+ module.__class__.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward)
177
+ else:
178
+ module.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward)
179
+
180
+ return module
181
+
182
+
183
+ def remove_hook_from_module(module: nn.Module, recurse=False):
184
+ """
185
+ Removes any hook attached to a module via `add_hook_to_module`.
186
+
187
+ Args:
188
+ module (`torch.nn.Module`): The module to attach a hook to.
189
+ recurse (`bool`, **optional**): Whether to remove the hooks recursively
190
+
191
+ Returns:
192
+ `torch.nn.Module`: The same module, with the hook detached (the module is modified in place, so the result can
193
+ be discarded).
194
+ """
195
+
196
+ if hasattr(module, "_hf_hook"):
197
+ module._hf_hook.detach_hook(module)
198
+ delattr(module, "_hf_hook")
199
+
200
+ if hasattr(module, "_old_forward"):
201
+ # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail.
202
+ # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409
203
+ if "GraphModuleImpl" in str(type(module)):
204
+ module.__class__.forward = module._old_forward
205
+ else:
206
+ module.forward = module._old_forward
207
+ delattr(module, "_old_forward")
208
+
209
+ # Remove accelerate added warning hooks from dispatch_model
210
+ for attr in _accelerate_added_attributes:
211
+ module.__dict__.pop(attr, None)
212
+
213
+ if recurse:
214
+ for child in module.children():
215
+ remove_hook_from_module(child, recurse)
216
+
217
+ return module
218
+
219
+
220
+ class AlignDevicesHook(ModelHook):
221
+ """
222
+ A generic `ModelHook` that ensures inputs and model weights are on the same device for the forward pass of the
223
+ associated module, potentially offloading the weights after the forward pass.
224
+
225
+ Args:
226
+ execution_device (`torch.device`, *optional*):
227
+ The device on which inputs and model weights should be placed before the forward pass.
228
+ offload (`bool`, *optional*, defaults to `False`):
229
+ Whether or not the weights should be offloaded after the forward pass.
230
+ io_same_device (`bool`, *optional*, defaults to `False`):
231
+ Whether or not the output should be placed on the same device as the input was.
232
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
233
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
234
+ offload_buffers (`bool`, *optional*, defaults to `False`):
235
+ Whether or not to include the associated module's buffers when offloading.
236
+ place_submodules (`bool`, *optional*, defaults to `False`):
237
+ Whether to place the submodules on `execution_device` during the `init_hook` event.
238
+ """
239
+
240
+ def __init__(
241
+ self,
242
+ execution_device: Optional[Union[int, str, torch.device]] = None,
243
+ offload: bool = False,
244
+ io_same_device: bool = False,
245
+ weights_map: Optional[Mapping] = None,
246
+ offload_buffers: bool = False,
247
+ place_submodules: bool = False,
248
+ skip_keys: Optional[Union[str, List[str]]] = None,
249
+ tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None,
250
+ ):
251
+ self.execution_device = execution_device
252
+ self.offload = offload
253
+ self.io_same_device = io_same_device
254
+ self.weights_map = weights_map
255
+ self.offload_buffers = offload_buffers
256
+ self.place_submodules = place_submodules
257
+ self.skip_keys = skip_keys
258
+
259
+ # Will contain the input device when `io_same_device=True`.
260
+ self.input_device = None
261
+ self.param_original_devices = {}
262
+ self.buffer_original_devices = {}
263
+ self.tied_params_names = set()
264
+
265
+ # The hook pre_forward/post_forward need to have knowledge of this dictionary, as with offloading we want to avoid duplicating memory
266
+ # for tied weights already loaded on the target execution device.
267
+ self.tied_params_map = tied_params_map
268
+
269
+ def __repr__(self):
270
+ return (
271
+ f"AlignDevicesHook(execution_device={self.execution_device}, offload={self.offload}, "
272
+ f"io_same_device={self.io_same_device}, offload_buffers={self.offload_buffers}, "
273
+ f"place_submodules={self.place_submodules}, skip_keys={repr(self.skip_keys)})"
274
+ )
275
+
276
+ def init_hook(self, module):
277
+ # In case the AlignDevicesHook is on meta device, ignore tied weights as data_ptr() is then always zero.
278
+ if self.execution_device == "meta" or self.execution_device == torch.device("meta"):
279
+ self.tied_params_map = None
280
+
281
+ if not self.offload and self.execution_device is not None:
282
+ for name, _ in named_module_tensors(module, recurse=self.place_submodules):
283
+ set_module_tensor_to_device(module, name, self.execution_device, tied_params_map=self.tied_params_map)
284
+ elif self.offload:
285
+ self.original_devices = {
286
+ name: param.device for name, param in named_module_tensors(module, recurse=self.place_submodules)
287
+ }
288
+ if self.weights_map is None:
289
+ self.weights_map = {
290
+ name: param.to("cpu")
291
+ for name, param in named_module_tensors(
292
+ module, include_buffers=self.offload_buffers, recurse=self.place_submodules
293
+ )
294
+ }
295
+ for name, _ in named_module_tensors(
296
+ module, include_buffers=self.offload_buffers, recurse=self.place_submodules, remove_non_persistent=True
297
+ ):
298
+ # When using disk offloading, we can not rely on `weights_map[name].data_ptr()` as the reference pointer,
299
+ # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
300
+ # As we have no reliable way to track the shared data pointer of tied weights in this case, we use tied_params_names: List[str]
301
+ # to add on the fly pointers to `tied_params_map` in the pre_forward call.
302
+ if (
303
+ self.tied_params_map is not None
304
+ and recursive_getattr(module, name).data_ptr() in self.tied_params_map
305
+ ):
306
+ self.tied_params_names.add(name)
307
+
308
+ set_module_tensor_to_device(module, name, "meta")
309
+
310
+ if not self.offload_buffers and self.execution_device is not None:
311
+ for name, _ in module.named_buffers(recurse=self.place_submodules):
312
+ set_module_tensor_to_device(
313
+ module, name, self.execution_device, tied_params_map=self.tied_params_map
314
+ )
315
+ elif self.offload_buffers and self.execution_device is not None:
316
+ for name in get_non_persistent_buffers(module, recurse=self.place_submodules):
317
+ set_module_tensor_to_device(
318
+ module, name, self.execution_device, tied_params_map=self.tied_params_map
319
+ )
320
+
321
+ return module
322
+
323
+ def pre_forward(self, module, *args, **kwargs):
324
+ if self.io_same_device:
325
+ self.input_device = find_device([args, kwargs])
326
+ if self.offload:
327
+ self.tied_pointers_to_remove = set()
328
+
329
+ for name, _ in named_module_tensors(
330
+ module,
331
+ include_buffers=self.offload_buffers,
332
+ recurse=self.place_submodules,
333
+ remove_non_persistent=True,
334
+ ):
335
+ fp16_statistics = None
336
+ value = self.weights_map[name]
337
+ if "weight" in name and name.replace("weight", "SCB") in self.weights_map.keys():
338
+ if value.dtype == torch.int8:
339
+ fp16_statistics = self.weights_map[name.replace("weight", "SCB")]
340
+
341
+ # In case we are using offloading with tied weights, we need to keep track of the offloaded weights
342
+ # that are loaded on device at this point, as we will need to remove them as well from the dictionary
343
+ # self.tied_params_map in order to allow to free memory.
344
+ if name in self.tied_params_names and value.data_ptr() not in self.tied_params_map:
345
+ self.tied_params_map[value.data_ptr()] = {}
346
+
347
+ if (
348
+ value is not None
349
+ and self.tied_params_map is not None
350
+ and value.data_ptr() in self.tied_params_map
351
+ and self.execution_device not in self.tied_params_map[value.data_ptr()]
352
+ ):
353
+ self.tied_pointers_to_remove.add((value.data_ptr(), self.execution_device))
354
+
355
+ set_module_tensor_to_device(
356
+ module,
357
+ name,
358
+ self.execution_device,
359
+ value=value,
360
+ fp16_statistics=fp16_statistics,
361
+ tied_params_map=self.tied_params_map,
362
+ )
363
+
364
+ return send_to_device(args, self.execution_device), send_to_device(
365
+ kwargs, self.execution_device, skip_keys=self.skip_keys
366
+ )
367
+
368
+ def post_forward(self, module, output):
369
+ if self.offload:
370
+ for name, _ in named_module_tensors(
371
+ module,
372
+ include_buffers=self.offload_buffers,
373
+ recurse=self.place_submodules,
374
+ remove_non_persistent=True,
375
+ ):
376
+ set_module_tensor_to_device(module, name, "meta")
377
+ if type(module).__name__ == "Linear8bitLt":
378
+ module.state.SCB = None
379
+ module.state.CxB = None
380
+
381
+ # We may have loaded tied weights into self.tied_params_map (avoiding to load them several times in e.g. submodules): remove them from
382
+ # this dictionary to allow the garbage collector to do its job.
383
+ for value_pointer, device in self.tied_pointers_to_remove:
384
+ del self.tied_params_map[value_pointer][device]
385
+ self.tied_pointers_to_remove = set()
386
+
387
+ if self.io_same_device and self.input_device is not None:
388
+ output = send_to_device(output, self.input_device, skip_keys=self.skip_keys)
389
+
390
+ return output
391
+
392
+ def detach_hook(self, module):
393
+ if self.offload:
394
+ for name, device in self.original_devices.items():
395
+ if device != torch.device("meta"):
396
+ set_module_tensor_to_device(module, name, device, value=self.weights_map.get(name, None))
397
+ return module
398
+
399
+
400
+ def attach_execution_device_hook(
401
+ module: torch.nn.Module,
402
+ execution_device: Union[int, str, torch.device],
403
+ skip_keys: Optional[Union[str, List[str]]] = None,
404
+ preload_module_classes: Optional[List[str]] = None,
405
+ tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None,
406
+ ):
407
+ """
408
+ Recursively attaches `AlignDevicesHook` to all submodules of a given model to make sure they have the right
409
+ execution device
410
+
411
+ Args:
412
+ module (`torch.nn.Module`):
413
+ The module where we want to attach the hooks.
414
+ execution_device (`int`, `str` or `torch.device`):
415
+ The device on which inputs and model weights should be placed before the forward pass.
416
+ skip_keys (`str` or `List[str]`, *optional*):
417
+ A list of keys to ignore when moving inputs or outputs between devices.
418
+ preload_module_classes (`List[str]`, *optional*):
419
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
420
+ of the forward. This should only be used for classes that have submodules which are registered but not
421
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
422
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
423
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
424
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
425
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
426
+ instead of duplicating memory.
427
+ """
428
+ if not hasattr(module, "_hf_hook") and len(module.state_dict()) > 0:
429
+ add_hook_to_module(
430
+ module,
431
+ AlignDevicesHook(execution_device, skip_keys=skip_keys, tied_params_map=tied_params_map),
432
+ )
433
+
434
+ # Break the recursion if we get to a preload module.
435
+ if preload_module_classes is not None and module.__class__.__name__ in preload_module_classes:
436
+ return
437
+
438
+ for child in module.children():
439
+ attach_execution_device_hook(child, execution_device, skip_keys=skip_keys, tied_params_map=tied_params_map)
440
+
441
+
442
+ def attach_align_device_hook(
443
+ module: torch.nn.Module,
444
+ execution_device: Optional[torch.device] = None,
445
+ offload: bool = False,
446
+ weights_map: Optional[Mapping] = None,
447
+ offload_buffers: bool = False,
448
+ module_name: str = "",
449
+ skip_keys: Optional[Union[str, List[str]]] = None,
450
+ preload_module_classes: Optional[List[str]] = None,
451
+ tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None,
452
+ ):
453
+ """
454
+ Recursively attaches `AlignDevicesHook` to all submodules of a given model that have direct parameters and/or
455
+ buffers.
456
+
457
+ Args:
458
+ module (`torch.nn.Module`):
459
+ The module where we want to attach the hooks.
460
+ execution_device (`torch.device`, *optional*):
461
+ The device on which inputs and model weights should be placed before the forward pass.
462
+ offload (`bool`, *optional*, defaults to `False`):
463
+ Whether or not the weights should be offloaded after the forward pass.
464
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
465
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
466
+ offload_buffers (`bool`, *optional*, defaults to `False`):
467
+ Whether or not to include the associated module's buffers when offloading.
468
+ module_name (`str`, *optional*, defaults to `""`):
469
+ The name of the module.
470
+ skip_keys (`str` or `List[str]`, *optional*):
471
+ A list of keys to ignore when moving inputs or outputs between devices.
472
+ preload_module_classes (`List[str]`, *optional*):
473
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
474
+ of the forward. This should only be used for classes that have submodules which are registered but not
475
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
476
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
477
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
478
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
479
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
480
+ instead of duplicating memory.
481
+ """
482
+ # Attach the hook on this module if it has any direct tensor.
483
+ directs = named_module_tensors(module)
484
+ full_offload = (
485
+ offload and preload_module_classes is not None and module.__class__.__name__ in preload_module_classes
486
+ )
487
+
488
+ if len(list(directs)) > 0 or full_offload:
489
+ if weights_map is not None:
490
+ prefix = f"{module_name}." if len(module_name) > 0 else ""
491
+ prefixed_weights_map = PrefixedDataset(weights_map, prefix)
492
+ else:
493
+ prefixed_weights_map = None
494
+ hook = AlignDevicesHook(
495
+ execution_device=execution_device,
496
+ offload=offload,
497
+ weights_map=prefixed_weights_map,
498
+ offload_buffers=offload_buffers,
499
+ place_submodules=full_offload,
500
+ skip_keys=skip_keys,
501
+ tied_params_map=tied_params_map,
502
+ )
503
+ add_hook_to_module(module, hook, append=True)
504
+
505
+ # We stop the recursion in case we hit the full offload.
506
+ if full_offload:
507
+ return
508
+
509
+ # Recurse on all children of the module.
510
+ for child_name, child in module.named_children():
511
+ child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name
512
+ attach_align_device_hook(
513
+ child,
514
+ execution_device=execution_device,
515
+ offload=offload,
516
+ weights_map=weights_map,
517
+ offload_buffers=offload_buffers,
518
+ module_name=child_name,
519
+ preload_module_classes=preload_module_classes,
520
+ skip_keys=skip_keys,
521
+ tied_params_map=tied_params_map,
522
+ )
523
+
524
+
525
+ def remove_hook_from_submodules(module: nn.Module):
526
+ """
527
+ Recursively removes all hooks attached on the submodules of a given model.
528
+
529
+ Args:
530
+ module (`torch.nn.Module`): The module on which to remove all hooks.
531
+ """
532
+ remove_hook_from_module(module)
533
+ for child in module.children():
534
+ remove_hook_from_submodules(child)
535
+
536
+
537
+ def attach_align_device_hook_on_blocks(
538
+ module: nn.Module,
539
+ execution_device: Optional[Union[torch.device, Dict[str, torch.device]]] = None,
540
+ offload: Union[bool, Dict[str, bool]] = False,
541
+ weights_map: Mapping = None,
542
+ offload_buffers: bool = False,
543
+ module_name: str = "",
544
+ skip_keys: Optional[Union[str, List[str]]] = None,
545
+ preload_module_classes: Optional[List[str]] = None,
546
+ tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None,
547
+ ):
548
+ """
549
+ Attaches `AlignDevicesHook` to all blocks of a given model as needed.
550
+
551
+ Args:
552
+ module (`torch.nn.Module`):
553
+ The module where we want to attach the hooks.
554
+ execution_device (`torch.device` or `Dict[str, torch.device]`, *optional*):
555
+ The device on which inputs and model weights should be placed before the forward pass. It can be one device
556
+ for the whole module, or a dictionary mapping module name to device.
557
+ offload (`bool`, *optional*, defaults to `False`):
558
+ Whether or not the weights should be offloaded after the forward pass. It can be one boolean for the whole
559
+ module, or a dictionary mapping module name to boolean.
560
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
561
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
562
+ offload_buffers (`bool`, *optional*, defaults to `False`):
563
+ Whether or not to include the associated module's buffers when offloading.
564
+ module_name (`str`, *optional*, defaults to `""`):
565
+ The name of the module.
566
+ skip_keys (`str` or `List[str]`, *optional*):
567
+ A list of keys to ignore when moving inputs or outputs between devices.
568
+ preload_module_classes (`List[str]`, *optional*):
569
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
570
+ of the forward. This should only be used for classes that have submodules which are registered but not
571
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
572
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
573
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
574
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
575
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
576
+ instead of duplicating memory.
577
+ """
578
+ # If one device and one offload, we've got one hook.
579
+ if not isinstance(execution_device, Mapping) and not isinstance(offload, dict):
580
+ if not offload:
581
+ hook = AlignDevicesHook(
582
+ execution_device=execution_device,
583
+ io_same_device=True,
584
+ skip_keys=skip_keys,
585
+ place_submodules=True,
586
+ tied_params_map=tied_params_map,
587
+ )
588
+ add_hook_to_module(module, hook)
589
+ else:
590
+ attach_align_device_hook(
591
+ module,
592
+ execution_device=execution_device,
593
+ offload=True,
594
+ weights_map=weights_map,
595
+ offload_buffers=offload_buffers,
596
+ module_name=module_name,
597
+ skip_keys=skip_keys,
598
+ tied_params_map=tied_params_map,
599
+ )
600
+ return
601
+
602
+ if not isinstance(execution_device, Mapping):
603
+ execution_device = {key: execution_device for key in offload.keys()}
604
+ if not isinstance(offload, Mapping):
605
+ offload = {key: offload for key in execution_device.keys()}
606
+
607
+ if module_name in execution_device and module_name in offload and not offload[module_name]:
608
+ hook = AlignDevicesHook(
609
+ execution_device=execution_device[module_name],
610
+ offload_buffers=offload_buffers,
611
+ io_same_device=(module_name == ""),
612
+ place_submodules=True,
613
+ skip_keys=skip_keys,
614
+ tied_params_map=tied_params_map,
615
+ )
616
+ add_hook_to_module(module, hook)
617
+ attach_execution_device_hook(
618
+ module, execution_device[module_name], skip_keys=skip_keys, tied_params_map=tied_params_map
619
+ )
620
+ elif module_name in execution_device and module_name in offload:
621
+ attach_align_device_hook(
622
+ module,
623
+ execution_device=execution_device[module_name],
624
+ offload=True,
625
+ weights_map=weights_map,
626
+ offload_buffers=offload_buffers,
627
+ module_name=module_name,
628
+ skip_keys=skip_keys,
629
+ preload_module_classes=preload_module_classes,
630
+ tied_params_map=tied_params_map,
631
+ )
632
+ if not hasattr(module, "_hf_hook"):
633
+ hook = AlignDevicesHook(
634
+ execution_device=execution_device[module_name],
635
+ io_same_device=(module_name == ""),
636
+ skip_keys=skip_keys,
637
+ tied_params_map=tied_params_map,
638
+ )
639
+ add_hook_to_module(module, hook)
640
+ attach_execution_device_hook(
641
+ module,
642
+ execution_device[module_name],
643
+ preload_module_classes=preload_module_classes,
644
+ skip_keys=skip_keys,
645
+ tied_params_map=tied_params_map,
646
+ )
647
+ elif module_name == "":
648
+ hook = AlignDevicesHook(
649
+ execution_device=execution_device.get(""),
650
+ io_same_device=True,
651
+ skip_keys=skip_keys,
652
+ tied_params_map=tied_params_map,
653
+ )
654
+ add_hook_to_module(module, hook)
655
+
656
+ for child_name, child in module.named_children():
657
+ child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name
658
+ attach_align_device_hook_on_blocks(
659
+ child,
660
+ execution_device=execution_device,
661
+ offload=offload,
662
+ weights_map=weights_map,
663
+ offload_buffers=offload_buffers,
664
+ module_name=child_name,
665
+ preload_module_classes=preload_module_classes,
666
+ skip_keys=skip_keys,
667
+ tied_params_map=tied_params_map,
668
+ )
669
+
670
+
671
+ class CpuOffload(ModelHook):
672
+ """
673
+ Offloads a model on the CPU until its forward pass is called. The model will not be offloaded back to the CPU after
674
+ the forward, the user needs to call the `init_hook` method again for this.
675
+
676
+ Args:
677
+ execution_device(`str`, `int` or `torch.device`, *optional*):
678
+ The device on which the model should be executed. Will default to the MPS device if it's available, then
679
+ GPU 0 if there is a GPU, and finally to the CPU.
680
+ prev_module_hook (`UserCpuOffloadHook`, *optional*):
681
+ The hook sent back by [`cpu_offload_with_hook`] for a previous model in the pipeline you are running. If
682
+ passed, its offload method will be called just before the forward of the model to which this hook is
683
+ attached.
684
+ """
685
+
686
+ def __init__(
687
+ self,
688
+ execution_device: Optional[Union[str, int, torch.device]] = None,
689
+ prev_module_hook: Optional["UserCpuOffloadHook"] = None,
690
+ ):
691
+ self.prev_module_hook = prev_module_hook
692
+
693
+ self.execution_device = execution_device if execution_device is not None else PartialState().default_device
694
+
695
+ def init_hook(self, module):
696
+ return module.to("cpu")
697
+
698
+ def pre_forward(self, module, *args, **kwargs):
699
+ if self.prev_module_hook is not None:
700
+ self.prev_module_hook.offload()
701
+ clear_device_cache()
702
+ module.to(self.execution_device)
703
+ return send_to_device(args, self.execution_device), send_to_device(kwargs, self.execution_device)
704
+
705
+
706
+ class UserCpuOffloadHook:
707
+ """
708
+ A simple hook grouping a model and a `ModelHook`, which provides easy APIs for to call the init method of the hook
709
+ or remove it entirely.
710
+ """
711
+
712
+ def __init__(self, model, hook):
713
+ self.model = model
714
+ self.hook = hook
715
+
716
+ def offload(self):
717
+ self.hook.init_hook(self.model)
718
+
719
+ def remove(self):
720
+ remove_hook_from_module(self.model)
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/inference.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 math
15
+ from types import MethodType
16
+ from typing import Any, Dict, List, Optional, Tuple, Union
17
+
18
+ from .state import PartialState
19
+ from .utils import (
20
+ calculate_maximum_sizes,
21
+ convert_bytes,
22
+ copy_tensor_to_devices,
23
+ ignorant_find_batch_size,
24
+ infer_auto_device_map,
25
+ is_pippy_available,
26
+ pad_input_tensors,
27
+ send_to_device,
28
+ )
29
+
30
+
31
+ def generate_device_map(model, num_processes: int = 1, no_split_module_classes=None, max_memory: dict = None):
32
+ """
33
+ Calculates the device map for `model` with an offset for PiPPy
34
+ """
35
+ if num_processes == 1:
36
+ return infer_auto_device_map(model, no_split_module_classes=no_split_module_classes, clean_result=False)
37
+ if max_memory is None:
38
+ model_size, shared = calculate_maximum_sizes(model)
39
+
40
+ # Split into `n` chunks for each GPU
41
+ memory = (model_size + shared[0]) / num_processes
42
+ memory = convert_bytes(memory)
43
+ value, ending = memory.split(" ")
44
+
45
+ # Add a chunk to deal with potential extra shared memory instances
46
+ memory = math.ceil(float(value)) * 1.1
47
+ memory = f"{memory} {ending}"
48
+ max_memory = {i: memory for i in range(num_processes)}
49
+ device_map = infer_auto_device_map(
50
+ model,
51
+ max_memory=max_memory,
52
+ no_split_module_classes=no_split_module_classes,
53
+ clean_result=False,
54
+ )
55
+ return device_map
56
+
57
+
58
+ def find_pippy_batch_size(args, kwargs):
59
+ found_batch_size = None
60
+ if args is not None:
61
+ for arg in args:
62
+ found_batch_size = ignorant_find_batch_size(arg)
63
+ if found_batch_size is not None:
64
+ break
65
+ if kwargs is not None and found_batch_size is None:
66
+ for kwarg in kwargs.values():
67
+ found_batch_size = ignorant_find_batch_size(kwarg)
68
+ if found_batch_size is not None:
69
+ break
70
+ return found_batch_size
71
+
72
+
73
+ def build_pipeline(model, split_points, args, kwargs, num_chunks):
74
+ """
75
+ Attaches the split points to the model based on `self.device_map` and generates a `PipelineStage`. Requires passing
76
+ in needed `args` and `kwargs` as the model needs on the CPU.
77
+
78
+ Users can pass in custom `num_chunks` as an optional hyper-parameter. By default will use
79
+ `AcceleratorState.num_processes`
80
+ """
81
+ # Note: We import here to reduce import time from general modules, and isolate outside dependencies
82
+ from torch.distributed.pipelining import ScheduleGPipe, SplitPoint, pipeline
83
+
84
+ # We need to annotate the split points in the model for PiPPy
85
+ state = PartialState()
86
+ split_spec = {split_point: SplitPoint.BEGINNING for split_point in split_points}
87
+ pipe = pipeline(
88
+ model,
89
+ mb_args=args,
90
+ mb_kwargs=kwargs,
91
+ split_spec=split_spec,
92
+ )
93
+ stage = pipe.build_stage(state.local_process_index, device=state.device)
94
+ schedule = ScheduleGPipe(stage, num_chunks)
95
+
96
+ return schedule
97
+
98
+
99
+ def pippy_forward(forward, num_chunks, gather_output, *args, **kwargs):
100
+ state = PartialState()
101
+ output = None
102
+
103
+ if state.num_processes == 1:
104
+ output = forward(*args, **kwargs)
105
+ elif state.is_local_main_process:
106
+ found_batch_size = find_pippy_batch_size(args, kwargs)
107
+ if found_batch_size is None:
108
+ raise ValueError("Could not find batch size from args or kwargs")
109
+ else:
110
+ if found_batch_size != num_chunks:
111
+ args = pad_input_tensors(args, found_batch_size, num_chunks)
112
+ kwargs = pad_input_tensors(kwargs, found_batch_size, num_chunks)
113
+ forward(*args, **kwargs)
114
+ elif state.is_last_process:
115
+ output = forward()
116
+ else:
117
+ forward()
118
+ if gather_output:
119
+ # Each node will get a copy of the full output which is only on the last GPU
120
+ output = copy_tensor_to_devices(output)
121
+ return output
122
+
123
+
124
+ def prepare_pippy(
125
+ model,
126
+ split_points: Optional[Union[str, List[str]]] = "auto",
127
+ no_split_module_classes: Optional[List[str]] = None,
128
+ example_args: Optional[Tuple[Any]] = (),
129
+ example_kwargs: Optional[Dict[str, Any]] = None,
130
+ num_chunks: Optional[int] = None,
131
+ gather_output: Optional[bool] = False,
132
+ ):
133
+ """
134
+ Wraps `model` for pipeline parallel inference.
135
+
136
+ Args:
137
+ model (`torch.nn.Module`):
138
+ A model we want to split for pipeline-parallel inference
139
+ split_points (`str` or `List[str]`, defaults to 'auto'):
140
+ How to generate the split points and chunk the model across each GPU. 'auto' will find the best balanced
141
+ split given any model. Should be a list of layer names in the model to split by otherwise.
142
+ no_split_module_classes (`List[str]`):
143
+ A list of class names for layers we don't want to be split.
144
+ example_args (tuple of model inputs):
145
+ The expected inputs for the model that uses order-based inputs for a *single process*. Recommended to use
146
+ this method if possible.
147
+ example_kwargs (dict of model inputs)
148
+ The expected inputs for the model that uses dictionary-based inputs for a *single process*. This is a
149
+ *highly* limiting structure that requires the same keys be present at *all* inference calls. Not
150
+ recommended unless the prior condition is true for all cases.
151
+ num_chunks (`int`, defaults to the number of available GPUs):
152
+ The number of different stages the Pipeline will have. By default it will assign one chunk per GPU, but
153
+ this can be tuned and played with. In general one should have num_chunks >= num_gpus.
154
+ gather_output (`bool`, defaults to `False`):
155
+ If `True`, the output from the last GPU (which holds the true outputs) is sent across to all GPUs.
156
+ """
157
+ if not is_pippy_available():
158
+ raise ImportError("Using `torch.distributed.pipelining` requires PyTorch 2.4.0 or later.")
159
+ state = PartialState()
160
+ example_args = send_to_device(example_args, "cpu")
161
+ example_kwargs = send_to_device(example_kwargs, "cpu")
162
+ if num_chunks is None:
163
+ num_chunks = state.num_processes
164
+ if split_points == "auto":
165
+ device_map = generate_device_map(model, num_chunks, no_split_module_classes=no_split_module_classes)
166
+ split_points = []
167
+ for i in range(1, num_chunks):
168
+ split_points.append(next(k for k, v in device_map.items() if v == i))
169
+ model.hf_split_points = split_points
170
+ stage = build_pipeline(model, split_points, example_args, example_kwargs, num_chunks)
171
+ model._original_forward = model.forward
172
+ model._original_call = model.__call__
173
+ model.pippy_stage = stage
174
+ model.hf_split_points = split_points
175
+
176
+ def forward(*args, **kwargs):
177
+ return pippy_forward(stage.step, num_chunks, gather_output, *args, **kwargs)
178
+
179
+ # To act like a decorator so that it can be popped when doing `extract_model_from_parallel`
180
+ # Note: creates an infinite recursion loop with `generate`
181
+ model_forward = MethodType(forward, model)
182
+ forward.__wrapped__ = model_forward
183
+ model.forward = forward
184
+ return model
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/launchers.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 tempfile
18
+
19
+ import torch
20
+
21
+ from .state import AcceleratorState, PartialState
22
+ from .utils import (
23
+ PrecisionType,
24
+ PrepareForLaunch,
25
+ are_libraries_initialized,
26
+ check_cuda_p2p_ib_support,
27
+ get_gpu_info,
28
+ is_mps_available,
29
+ is_torch_version,
30
+ patch_environment,
31
+ )
32
+ from .utils.constants import ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION
33
+
34
+
35
+ def test_launch():
36
+ "Verify a `PartialState` can be initialized."
37
+ _ = PartialState()
38
+
39
+
40
+ def notebook_launcher(
41
+ function,
42
+ args=(),
43
+ num_processes=None,
44
+ mixed_precision="no",
45
+ use_port="29500",
46
+ master_addr="127.0.0.1",
47
+ node_rank=0,
48
+ num_nodes=1,
49
+ rdzv_backend="static",
50
+ rdzv_endpoint="",
51
+ rdzv_conf=None,
52
+ rdzv_id="none",
53
+ max_restarts=0,
54
+ monitor_interval=0.1,
55
+ log_line_prefix_template=None,
56
+ ):
57
+ """
58
+ Launches a training function, using several processes or multiple nodes if it's possible in the current environment
59
+ (TPU with multiple cores for instance).
60
+
61
+ <Tip warning={true}>
62
+
63
+ To use this function absolutely zero calls to a CUDA device must be made in the notebook session before calling. If
64
+ any have been made, you will need to restart the notebook and make sure no cells use any CUDA capability.
65
+
66
+ Setting `ACCELERATE_DEBUG_MODE="1"` in your environment will run a test before truly launching to ensure that none
67
+ of those calls have been made.
68
+
69
+ </Tip>
70
+
71
+ Args:
72
+ function (`Callable`):
73
+ The training function to execute. If it accepts arguments, the first argument should be the index of the
74
+ process run.
75
+ args (`Tuple`):
76
+ Tuple of arguments to pass to the function (it will receive `*args`).
77
+ num_processes (`int`, *optional*):
78
+ The number of processes to use for training. Will default to 8 in Colab/Kaggle if a TPU is available, to
79
+ the number of GPUs available otherwise.
80
+ mixed_precision (`str`, *optional*, defaults to `"no"`):
81
+ If `fp16` or `bf16`, will use mixed precision training on multi-GPU.
82
+ use_port (`str`, *optional*, defaults to `"29500"`):
83
+ The port to use to communicate between processes when launching a multi-GPU training.
84
+ master_addr (`str`, *optional*, defaults to `"127.0.0.1"`):
85
+ The address to use for communication between processes.
86
+ node_rank (`int`, *optional*, defaults to 0):
87
+ The rank of the current node.
88
+ num_nodes (`int`, *optional*, defaults to 1):
89
+ The number of nodes to use for training.
90
+ rdzv_backend (`str`, *optional*, defaults to `"static"`):
91
+ The rendezvous method to use, such as 'static' (the default) or 'c10d'
92
+ rdzv_endpoint (`str`, *optional*, defaults to `""`):
93
+ The endpoint of the rdzv sync. storage.
94
+ rdzv_conf (`Dict`, *optional*, defaults to `None`):
95
+ Additional rendezvous configuration.
96
+ rdzv_id (`str`, *optional*, defaults to `"none"`):
97
+ The unique run id of the job.
98
+ max_restarts (`int`, *optional*, defaults to 0):
99
+ The maximum amount of restarts that elastic agent will conduct on workers before failure.
100
+ monitor_interval (`float`, *optional*, defaults to 0.1):
101
+ The interval in seconds that is used by the elastic_agent as a period of monitoring workers.
102
+ log_line_prefix_template (`str`, *optional*, defaults to `None`):
103
+ The prefix template for elastic launch logging. Available from PyTorch 2.2.0.
104
+
105
+ Example:
106
+
107
+ ```python
108
+ # Assume this is defined in a Jupyter Notebook on an instance with two GPUs
109
+ from accelerate import notebook_launcher
110
+
111
+
112
+ def train(*args):
113
+ # Your training function here
114
+ ...
115
+
116
+
117
+ notebook_launcher(train, args=(arg1, arg2), num_processes=2, mixed_precision="fp16")
118
+ ```
119
+ """
120
+ # Are we in a google colab or a Kaggle Kernel?
121
+ in_colab = False
122
+ in_kaggle = False
123
+ if any(key.startswith("KAGGLE") for key in os.environ.keys()):
124
+ in_kaggle = True
125
+ elif "IPython" in sys.modules:
126
+ in_colab = "google.colab" in str(sys.modules["IPython"].get_ipython())
127
+
128
+ try:
129
+ mixed_precision = PrecisionType(mixed_precision.lower())
130
+ except ValueError:
131
+ raise ValueError(
132
+ f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}."
133
+ )
134
+
135
+ if (in_colab or in_kaggle) and (os.environ.get("TPU_NAME", None) is not None):
136
+ # TPU launch
137
+ import torch_xla.distributed.xla_multiprocessing as xmp
138
+
139
+ if len(AcceleratorState._shared_state) > 0:
140
+ raise ValueError(
141
+ "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside "
142
+ "your training function. Restart your notebook and make sure no cells initializes an "
143
+ "`Accelerator`."
144
+ )
145
+ if num_processes is None:
146
+ num_processes = 8
147
+
148
+ launcher = PrepareForLaunch(function, distributed_type="XLA")
149
+ print(f"Launching a training on {num_processes} TPU cores.")
150
+ xmp.spawn(launcher, args=args, nprocs=num_processes, start_method="fork")
151
+ elif in_colab and get_gpu_info()[1] < 2:
152
+ # No need for a distributed launch otherwise as it's either CPU or one GPU.
153
+ if torch.cuda.is_available():
154
+ print("Launching training on one GPU.")
155
+ else:
156
+ print("Launching training on one CPU.")
157
+ function(*args)
158
+ else:
159
+ if num_processes is None:
160
+ raise ValueError(
161
+ "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call."
162
+ )
163
+ if node_rank >= num_nodes:
164
+ raise ValueError("The node_rank must be less than the number of nodes.")
165
+ if num_processes > 1:
166
+ # Multi-GPU launch
167
+ from torch.distributed.launcher.api import LaunchConfig, elastic_launch
168
+ from torch.multiprocessing import start_processes
169
+ from torch.multiprocessing.spawn import ProcessRaisedException
170
+
171
+ if len(AcceleratorState._shared_state) > 0:
172
+ raise ValueError(
173
+ "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized "
174
+ "inside your training function. Restart your notebook and make sure no cells initializes an "
175
+ "`Accelerator`."
176
+ )
177
+ # Check for specific libraries known to initialize CUDA that users constantly use
178
+ problematic_imports = are_libraries_initialized("bitsandbytes")
179
+ if len(problematic_imports) > 0:
180
+ err = (
181
+ "Could not start distributed process. Libraries known to initialize CUDA upon import have been "
182
+ "imported already. Please keep these imports inside your training function to try and help with this:"
183
+ )
184
+ for lib_name in problematic_imports:
185
+ err += f"\n\t* `{lib_name}`"
186
+ raise RuntimeError(err)
187
+
188
+ patched_env = dict(
189
+ nproc=num_processes,
190
+ node_rank=node_rank,
191
+ world_size=num_nodes * num_processes,
192
+ master_addr=master_addr,
193
+ master_port=use_port,
194
+ mixed_precision=mixed_precision,
195
+ )
196
+
197
+ # Check for CUDA P2P and IB issues
198
+ if not check_cuda_p2p_ib_support():
199
+ patched_env["nccl_p2p_disable"] = "1"
200
+ patched_env["nccl_ib_disable"] = "1"
201
+
202
+ # torch.distributed will expect a few environment variable to be here. We set the ones common to each
203
+ # process here (the other ones will be set be the launcher).
204
+ with patch_environment(**patched_env):
205
+ # First dummy launch
206
+ if os.environ.get("ACCELERATE_DEBUG_MODE", "false").lower() == "true":
207
+ launcher = PrepareForLaunch(test_launch, distributed_type="MULTI_GPU")
208
+ try:
209
+ start_processes(launcher, args=(), nprocs=num_processes, start_method="fork")
210
+ except ProcessRaisedException as e:
211
+ err = "An issue was found when verifying a stable environment for the notebook launcher."
212
+ if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
213
+ raise RuntimeError(
214
+ f"{err}"
215
+ "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
216
+ "Please review your imports and test them when running the `notebook_launcher()` to identify "
217
+ "which one is problematic and causing CUDA to be initialized."
218
+ ) from e
219
+ else:
220
+ raise RuntimeError(f"{err} The following error was raised: {e}") from e
221
+ # Now the actual launch
222
+ launcher = PrepareForLaunch(function, distributed_type="MULTI_GPU")
223
+ print(f"Launching training on {num_processes} GPUs.")
224
+ try:
225
+ if rdzv_conf is None:
226
+ rdzv_conf = {}
227
+ if rdzv_backend == "static":
228
+ rdzv_conf["rank"] = node_rank
229
+ if not rdzv_endpoint:
230
+ rdzv_endpoint = f"{master_addr}:{use_port}"
231
+ launch_config_kwargs = dict(
232
+ min_nodes=num_nodes,
233
+ max_nodes=num_nodes,
234
+ nproc_per_node=num_processes,
235
+ run_id=rdzv_id,
236
+ rdzv_endpoint=rdzv_endpoint,
237
+ rdzv_backend=rdzv_backend,
238
+ rdzv_configs=rdzv_conf,
239
+ max_restarts=max_restarts,
240
+ monitor_interval=monitor_interval,
241
+ start_method="fork",
242
+ )
243
+ if is_torch_version(">=", ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION):
244
+ launch_config_kwargs["log_line_prefix_template"] = log_line_prefix_template
245
+ elastic_launch(config=LaunchConfig(**launch_config_kwargs), entrypoint=function)(*args)
246
+ except ProcessRaisedException as e:
247
+ if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
248
+ raise RuntimeError(
249
+ "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. "
250
+ "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
251
+ "Please review your imports and test them when running the `notebook_launcher()` to identify "
252
+ "which one is problematic and causing CUDA to be initialized."
253
+ ) from e
254
+ else:
255
+ raise RuntimeError(f"An issue was found when launching the training: {e}") from e
256
+
257
+ else:
258
+ # No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
259
+ if is_mps_available():
260
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
261
+ print("Launching training on MPS.")
262
+ elif torch.cuda.is_available():
263
+ print("Launching training on one GPU.")
264
+ else:
265
+ print("Launching training on CPU.")
266
+ function(*args)
267
+
268
+
269
+ def debug_launcher(function, args=(), num_processes=2):
270
+ """
271
+ Launches a training function using several processes on CPU for debugging purposes.
272
+
273
+ <Tip warning={true}>
274
+
275
+ This function is provided for internal testing and debugging, but it's not intended for real trainings. It will
276
+ only use the CPU.
277
+
278
+ </Tip>
279
+
280
+ Args:
281
+ function (`Callable`):
282
+ The training function to execute.
283
+ args (`Tuple`):
284
+ Tuple of arguments to pass to the function (it will receive `*args`).
285
+ num_processes (`int`, *optional*, defaults to 2):
286
+ The number of processes to use for training.
287
+ """
288
+ from torch.multiprocessing import start_processes
289
+
290
+ with tempfile.NamedTemporaryFile() as tmp_file:
291
+ # torch.distributed will expect a few environment variable to be here. We set the ones common to each
292
+ # process here (the other ones will be set be the launcher).
293
+ with patch_environment(
294
+ world_size=num_processes,
295
+ master_addr="127.0.0.1",
296
+ master_port="29500",
297
+ accelerate_mixed_precision="no",
298
+ accelerate_debug_rdv_file=tmp_file.name,
299
+ accelerate_use_cpu="yes",
300
+ ):
301
+ launcher = PrepareForLaunch(function, debug=True)
302
+ start_processes(launcher, args=args, nprocs=num_processes, start_method="fork")
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/local_sgd.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 torch
15
+
16
+ from accelerate import Accelerator, DistributedType
17
+
18
+
19
+ class LocalSGD:
20
+ """
21
+ A helper class to support local SGD on top of Accelerator. It simply runs a given number of updates independently
22
+ on each device, and averages model weights every K synchronization step.
23
+
24
+ It should be used only in the multi-GPU (or multi-CPU) setup without extensions such as DeepSpeed. In particular,
25
+ this is a simple implementation that cannot support scenarios such as model parallelism.
26
+
27
+
28
+ Although we are not aware of the true origins of this simple approach, the idea of local SGD is quite old and goes
29
+ back to at least:
30
+
31
+ Zhang, J., De Sa, C., Mitliagkas, I., & Ré, C. (2016). [Parallel SGD: When does averaging help?. arXiv preprint
32
+ arXiv:1606.07365.](https://arxiv.org/abs/1606.07365)
33
+
34
+ We credit the term Local SGD to the following paper (but there might be earlier references we are not aware of).
35
+
36
+ Stich, Sebastian Urban. ["Local SGD Converges Fast and Communicates Little." ICLR 2019-International Conference on
37
+ Learning Representations. No. CONF. 2019.](https://arxiv.org/abs/1805.09767)
38
+
39
+ """
40
+
41
+ def __enter__(self):
42
+ if self.enabled:
43
+ self.model_sync_obj = self.model.no_sync()
44
+ self.model_sync_obj.__enter__()
45
+
46
+ return self
47
+
48
+ def __exit__(self, type, value, tb):
49
+ if self.enabled:
50
+ # Average all models on exit
51
+ self._sync_and_avg_model_params()
52
+ self.model_sync_obj.__exit__(type, value, tb)
53
+
54
+ def __init__(self, accelerator: Accelerator, model: torch.nn.Module, local_sgd_steps: int, enabled: bool = True):
55
+ """
56
+ Constructor.
57
+
58
+ Args:
59
+ model (`torch.nn.Module):
60
+ The model whose parameters we need to average.
61
+ accelerator (`Accelerator`):
62
+ Accelerator object.
63
+ local_sgd_steps (`int`):
64
+ A number of local SGD steps (before model parameters are synchronized).
65
+ enabled (`bool):
66
+ Local SGD is disabled if this parameter set to `False`.
67
+ """
68
+ if accelerator.distributed_type not in [
69
+ DistributedType.NO,
70
+ DistributedType.MULTI_CPU,
71
+ DistributedType.MULTI_GPU,
72
+ DistributedType.MULTI_MLU,
73
+ DistributedType.MULTI_MUSA,
74
+ DistributedType.MULTI_NPU,
75
+ ]:
76
+ raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)")
77
+ self.enabled = enabled and accelerator.distributed_type != DistributedType.NO
78
+ self.num_steps = 0
79
+ if self.enabled:
80
+ self.accelerator = accelerator
81
+ self.model = model
82
+ self.local_sgd_steps = local_sgd_steps
83
+
84
+ def step(self):
85
+ """
86
+ This function makes a "step" and synchronizes model parameters if necessary.
87
+ """
88
+ self.num_steps += 1
89
+ if not self.enabled:
90
+ return
91
+
92
+ if self.num_steps % self.local_sgd_steps == 0:
93
+ self._sync_and_avg_model_params()
94
+
95
+ def _sync_and_avg_model_params(self):
96
+ """
97
+ Synchronize + Average model parameters across all GPUs
98
+ """
99
+
100
+ self.accelerator.wait_for_everyone()
101
+ with self.accelerator.autocast():
102
+ for param in self.model.parameters():
103
+ param.data = self.accelerator.reduce(param.data, reduction="mean")
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/logging.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 functools
16
+ import logging
17
+ import os
18
+
19
+ from .state import PartialState
20
+
21
+
22
+ class MultiProcessAdapter(logging.LoggerAdapter):
23
+ """
24
+ An adapter to assist with logging in multiprocess.
25
+
26
+ `log` takes in an additional `main_process_only` kwarg, which dictates whether it should be called on all processes
27
+ or only the main executed one. Default is `main_process_only=True`.
28
+
29
+ Does not require an `Accelerator` object to be created first.
30
+ """
31
+
32
+ @staticmethod
33
+ def _should_log(main_process_only):
34
+ "Check if log should be performed"
35
+ state = PartialState()
36
+ return not main_process_only or (main_process_only and state.is_main_process)
37
+
38
+ def log(self, level, msg, *args, **kwargs):
39
+ """
40
+ Delegates logger call after checking if we should log.
41
+
42
+ Accepts a new kwarg of `main_process_only`, which will dictate whether it will be logged across all processes
43
+ or only the main executed one. Default is `True` if not passed
44
+
45
+ Also accepts "in_order", which if `True` makes the processes log one by one, in order. This is much easier to
46
+ read, but comes at the cost of sometimes needing to wait for the other processes. Default is `False` to not
47
+ break with the previous behavior.
48
+
49
+ `in_order` is ignored if `main_process_only` is passed.
50
+ """
51
+ if PartialState._shared_state == {}:
52
+ raise RuntimeError(
53
+ "You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility."
54
+ )
55
+ main_process_only = kwargs.pop("main_process_only", True)
56
+ in_order = kwargs.pop("in_order", False)
57
+ # set `stacklevel` to exclude ourself in `Logger.findCaller()` while respecting user's choice
58
+ kwargs.setdefault("stacklevel", 2)
59
+
60
+ if self.isEnabledFor(level):
61
+ if self._should_log(main_process_only):
62
+ msg, kwargs = self.process(msg, kwargs)
63
+ self.logger.log(level, msg, *args, **kwargs)
64
+
65
+ elif in_order:
66
+ state = PartialState()
67
+ for i in range(state.num_processes):
68
+ if i == state.process_index:
69
+ msg, kwargs = self.process(msg, kwargs)
70
+ self.logger.log(level, msg, *args, **kwargs)
71
+ state.wait_for_everyone()
72
+
73
+ @functools.lru_cache(None)
74
+ def warning_once(self, *args, **kwargs):
75
+ """
76
+ This method is identical to `logger.warning()`, but will emit the warning with the same message only once
77
+
78
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the
79
+ cache. The assumption here is that all warning messages are unique across the code. If they aren't then need to
80
+ switch to another type of cache that includes the caller frame information in the hashing function.
81
+ """
82
+ self.warning(*args, **kwargs)
83
+
84
+
85
+ def get_logger(name: str, log_level: str = None):
86
+ """
87
+ Returns a `logging.Logger` for `name` that can handle multiprocessing.
88
+
89
+ If a log should be called on all processes, pass `main_process_only=False` If a log should be called on all
90
+ processes and in order, also pass `in_order=True`
91
+
92
+ Args:
93
+ name (`str`):
94
+ The name for the logger, such as `__file__`
95
+ log_level (`str`, *optional*):
96
+ The log level to use. If not passed, will default to the `LOG_LEVEL` environment variable, or `INFO` if not
97
+
98
+ Example:
99
+
100
+ ```python
101
+ >>> from accelerate.logging import get_logger
102
+ >>> from accelerate import Accelerator
103
+
104
+ >>> logger = get_logger(__name__)
105
+
106
+ >>> accelerator = Accelerator()
107
+ >>> logger.info("My log", main_process_only=False)
108
+ >>> logger.debug("My log", main_process_only=True)
109
+
110
+ >>> logger = get_logger(__name__, log_level="DEBUG")
111
+ >>> logger.info("My log")
112
+ >>> logger.debug("My second log")
113
+
114
+ >>> array = ["a", "b", "c", "d"]
115
+ >>> letter_at_rank = array[accelerator.process_index]
116
+ >>> logger.info(letter_at_rank, in_order=True)
117
+ ```
118
+ """
119
+ if log_level is None:
120
+ log_level = os.environ.get("ACCELERATE_LOG_LEVEL", None)
121
+ logger = logging.getLogger(name)
122
+ if log_level is not None:
123
+ logger.setLevel(log_level.upper())
124
+ logger.root.setLevel(log_level.upper())
125
+ return MultiProcessAdapter(logger, {})
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/memory_utils.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 warnings
16
+
17
+
18
+ warnings.warn(
19
+ "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: "
20
+ "`from accelerate import find_executable_batch_size` to avoid this warning.",
21
+ FutureWarning,
22
+ )
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/optimizer.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 inspect
16
+
17
+ import torch
18
+
19
+ from .state import AcceleratorState, GradientState
20
+ from .utils import DistributedType, honor_type, is_lomo_available, is_torch_xla_available
21
+
22
+
23
+ if is_torch_xla_available():
24
+ import torch_xla.core.xla_model as xm
25
+
26
+
27
+ def move_to_device(state, device):
28
+ if isinstance(state, (list, tuple)):
29
+ return honor_type(state, (move_to_device(t, device) for t in state))
30
+ elif isinstance(state, dict):
31
+ return type(state)({k: move_to_device(v, device) for k, v in state.items()})
32
+ elif isinstance(state, torch.Tensor):
33
+ return state.to(device)
34
+ return state
35
+
36
+
37
+ class AcceleratedOptimizer(torch.optim.Optimizer):
38
+ """
39
+ Internal wrapper around a torch optimizer.
40
+
41
+ Conditionally will perform `step` and `zero_grad` if gradients should be synchronized when performing gradient
42
+ accumulation.
43
+
44
+ Args:
45
+ optimizer (`torch.optim.optimizer.Optimizer`):
46
+ The optimizer to wrap.
47
+ device_placement (`bool`, *optional*, defaults to `True`):
48
+ Whether or not the optimizer should handle device placement. If so, it will place the state dictionary of
49
+ `optimizer` on the right device.
50
+ scaler (`torch.cuda.amp.grad_scaler.GradScaler`, *optional*):
51
+ The scaler to use in the step function if training with mixed precision.
52
+ """
53
+
54
+ def __init__(self, optimizer, device_placement=True, scaler=None):
55
+ self.optimizer = optimizer
56
+ self.scaler = scaler
57
+ self.accelerator_state = AcceleratorState()
58
+ self.gradient_state = GradientState()
59
+ self.device_placement = device_placement
60
+ self._is_overflow = False
61
+
62
+ if self.scaler is not None:
63
+ self._accelerate_step_called = False
64
+ self._optimizer_original_step_method = self.optimizer.step
65
+ self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step)
66
+
67
+ # Handle device placement
68
+ if device_placement:
69
+ state_dict = self.optimizer.state_dict()
70
+ if self.accelerator_state.distributed_type == DistributedType.XLA:
71
+ xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device)
72
+ else:
73
+ state_dict = move_to_device(state_dict, self.accelerator_state.device)
74
+ self.optimizer.load_state_dict(state_dict)
75
+
76
+ @property
77
+ def state(self):
78
+ return self.optimizer.state
79
+
80
+ @state.setter
81
+ def state(self, state):
82
+ self.optimizer.state = state
83
+
84
+ @property
85
+ def param_groups(self):
86
+ return self.optimizer.param_groups
87
+
88
+ @param_groups.setter
89
+ def param_groups(self, param_groups):
90
+ self.optimizer.param_groups = param_groups
91
+
92
+ @property
93
+ def defaults(self):
94
+ return self.optimizer.defaults
95
+
96
+ @defaults.setter
97
+ def defaults(self, defaults):
98
+ self.optimizer.defaults = defaults
99
+
100
+ def add_param_group(self, param_group):
101
+ self.optimizer.add_param_group(param_group)
102
+
103
+ def load_state_dict(self, state_dict):
104
+ if self.accelerator_state.distributed_type == DistributedType.XLA and self.device_placement:
105
+ xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device)
106
+ self.optimizer.load_state_dict(state_dict)
107
+
108
+ def state_dict(self):
109
+ return self.optimizer.state_dict()
110
+
111
+ def zero_grad(self, set_to_none=None):
112
+ if self.gradient_state.sync_gradients:
113
+ accept_arg = "set_to_none" in inspect.signature(self.optimizer.zero_grad).parameters
114
+ if accept_arg:
115
+ if set_to_none is None:
116
+ set_to_none = True
117
+ self.optimizer.zero_grad(set_to_none=set_to_none)
118
+ else:
119
+ if set_to_none is not None:
120
+ raise ValueError("`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer.")
121
+ self.optimizer.zero_grad()
122
+
123
+ def train(self):
124
+ """
125
+ Sets the optimizer to "train" mode. Useful for optimizers like `schedule_free`
126
+ """
127
+ if hasattr(self.optimizer, "train") and callable(self.optimizer.train):
128
+ self.optimizer.train()
129
+
130
+ def eval(self):
131
+ """
132
+ Sets the optimizer to "eval" mode. Useful for optimizers like `schedule_free`
133
+ """
134
+ if hasattr(self.optimizer, "eval") and callable(self.optimizer.eval):
135
+ self.optimizer.eval()
136
+
137
+ def step(self, closure=None):
138
+ if is_lomo_available():
139
+ from lomo_optim import AdaLomo, Lomo
140
+
141
+ if (
142
+ not self.gradient_state.is_xla_gradients_synced
143
+ and self.accelerator_state.distributed_type == DistributedType.XLA
144
+ ):
145
+ gradients = xm._fetch_gradients(self.optimizer)
146
+ xm.all_reduce("sum", gradients, scale=1.0 / xm.xrt_world_size())
147
+ self.gradient_state.is_xla_gradients_synced = True
148
+
149
+ if is_lomo_available():
150
+ # `step` should be a no-op for LOMO optimizers.
151
+ if isinstance(self.optimizer, (Lomo, AdaLomo)):
152
+ return
153
+
154
+ if self.gradient_state.sync_gradients:
155
+ if self.scaler is not None:
156
+ self.optimizer.step = self._optimizer_patched_step_method
157
+
158
+ self.scaler.step(self.optimizer, closure)
159
+ self.scaler.update()
160
+
161
+ if not self._accelerate_step_called:
162
+ # If the optimizer step was skipped, gradient overflow was detected.
163
+ self._is_overflow = True
164
+ else:
165
+ self._is_overflow = False
166
+ # Reset the step method to the original one
167
+ self.optimizer.step = self._optimizer_original_step_method
168
+ # Reset the indicator
169
+ self._accelerate_step_called = False
170
+ else:
171
+ self.optimizer.step(closure)
172
+ if self.accelerator_state.distributed_type == DistributedType.XLA:
173
+ self.gradient_state.is_xla_gradients_synced = False
174
+
175
+ def _switch_parameters(self, parameters_map):
176
+ for param_group in self.optimizer.param_groups:
177
+ param_group["params"] = [parameters_map.get(p, p) for p in param_group["params"]]
178
+
179
+ @property
180
+ def step_was_skipped(self):
181
+ """Whether or not the optimizer step was skipped."""
182
+ return self._is_overflow
183
+
184
+ def __getstate__(self):
185
+ _ignored_keys = [
186
+ "_accelerate_step_called",
187
+ "_optimizer_original_step_method",
188
+ "_optimizer_patched_step_method",
189
+ ]
190
+ return {k: v for k, v in self.__dict__.items() if k not in _ignored_keys}
191
+
192
+ def __setstate__(self, state):
193
+ self.__dict__.update(state)
194
+ if self.scaler is not None:
195
+ self._accelerate_step_called = False
196
+ self._optimizer_original_step_method = self.optimizer.step
197
+ self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step)
198
+
199
+
200
+ def patch_optimizer_step(accelerated_optimizer: AcceleratedOptimizer, method):
201
+ def patched_step(*args, **kwargs):
202
+ accelerated_optimizer._accelerate_step_called = True
203
+ return method(*args, **kwargs)
204
+
205
+ return patched_step
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/scheduler.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation
16
+
17
+ import warnings
18
+
19
+ from .state import AcceleratorState, GradientState
20
+
21
+
22
+ warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler")
23
+
24
+
25
+ class AcceleratedScheduler:
26
+ """
27
+ A wrapper around a learning rate scheduler that will only step when the optimizer(s) have a training step. Useful
28
+ to avoid making a scheduler step too fast when gradients went overflow and there was no training step (in mixed
29
+ precision training)
30
+
31
+ When performing gradient accumulation scheduler lengths should not be changed accordingly, Accelerate will always
32
+ step the scheduler to account for it.
33
+
34
+ Args:
35
+ scheduler (`torch.optim.lr_scheduler._LRScheduler`):
36
+ The scheduler to wrap.
37
+ optimizers (one or a list of `torch.optim.Optimizer`):
38
+ The optimizers used.
39
+ step_with_optimizer (`bool`, *optional*, defaults to `True`):
40
+ Whether or not the scheduler should be stepped at each optimizer step.
41
+ split_batches (`bool`, *optional*, defaults to `False`):
42
+ Whether or not the dataloaders split one batch across the different processes (so batch size is the same
43
+ regardless of the number of processes) or create batches on each process (so batch size is the original
44
+ batch size multiplied by the number of processes).
45
+ """
46
+
47
+ def __init__(self, scheduler, optimizers, step_with_optimizer: bool = True, split_batches: bool = False):
48
+ self.scheduler = scheduler
49
+ self.optimizers = optimizers if isinstance(optimizers, (list, tuple)) else [optimizers]
50
+ self.split_batches = split_batches
51
+ self.step_with_optimizer = step_with_optimizer
52
+ self.gradient_state = GradientState()
53
+
54
+ def step(self, *args, **kwargs):
55
+ if not self.step_with_optimizer:
56
+ # No link between scheduler and optimizer -> just step
57
+ self.scheduler.step(*args, **kwargs)
58
+ return
59
+
60
+ # Otherwise, first make sure the optimizer was stepped.
61
+ if not self.gradient_state.sync_gradients:
62
+ if self.gradient_state.adjust_scheduler:
63
+ self.scheduler._step_count += 1
64
+ return
65
+
66
+ for opt in self.optimizers:
67
+ if opt.step_was_skipped:
68
+ return
69
+ if self.split_batches:
70
+ # Split batches -> the training dataloader batch size is not changed so one step per training step
71
+ self.scheduler.step(*args, **kwargs)
72
+ else:
73
+ # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do
74
+ # num_processes steps per training step
75
+ num_processes = AcceleratorState().num_processes
76
+ for _ in range(num_processes):
77
+ # Special case when using OneCycle and `drop_last` was not used
78
+ if hasattr(self.scheduler, "total_steps"):
79
+ if self.scheduler._step_count <= self.scheduler.total_steps:
80
+ self.scheduler.step(*args, **kwargs)
81
+ else:
82
+ self.scheduler.step(*args, **kwargs)
83
+
84
+ # Passthroughs
85
+ def get_last_lr(self):
86
+ return self.scheduler.get_last_lr()
87
+
88
+ def state_dict(self):
89
+ return self.scheduler.state_dict()
90
+
91
+ def load_state_dict(self, state_dict):
92
+ self.scheduler.load_state_dict(state_dict)
93
+
94
+ def get_lr(self):
95
+ return self.scheduler.get_lr()
96
+
97
+ def print_lr(self, *args, **kwargs):
98
+ return self.scheduler.print_lr(*args, **kwargs)
tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/state.py ADDED
@@ -0,0 +1,1257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 __future__ import annotations
16
+
17
+ import logging
18
+ import os
19
+ import threading
20
+ import warnings
21
+ from contextlib import contextmanager
22
+ from functools import partial
23
+ from typing import Any, Callable, Optional
24
+
25
+ import torch
26
+
27
+ from .utils import (
28
+ DistributedType,
29
+ DynamoBackend,
30
+ GradientAccumulationPlugin,
31
+ check_cuda_p2p_ib_support,
32
+ check_fp8_capability,
33
+ deepspeed_required,
34
+ get_ccl_version,
35
+ get_cpu_distributed_information,
36
+ get_int_from_env,
37
+ is_ccl_available,
38
+ is_datasets_available,
39
+ is_deepspeed_available,
40
+ is_fp8_available,
41
+ is_ipex_available,
42
+ is_mlu_available,
43
+ is_mps_available,
44
+ is_musa_available,
45
+ is_npu_available,
46
+ is_torch_xla_available,
47
+ is_xpu_available,
48
+ parse_choice_from_env,
49
+ parse_flag_from_env,
50
+ set_numa_affinity,
51
+ )
52
+ from .utils.dataclasses import SageMakerDistributedType
53
+
54
+
55
+ if is_torch_xla_available():
56
+ import torch_xla.core.xla_model as xm
57
+
58
+ if is_mlu_available(check_device=False):
59
+ import torch_mlu # noqa: F401
60
+
61
+ if is_musa_available(check_device=False):
62
+ import torch_musa # noqa: F401
63
+
64
+ if is_npu_available(check_device=False):
65
+ import torch_npu # noqa: F401
66
+
67
+ logger = logging.getLogger(__name__)
68
+
69
+
70
+ def is_initialized() -> bool:
71
+ """
72
+ Checks if the `AcceleratorState` has been initialized from `Accelerator`. Same as `AcceleratorState.initialized`,
73
+ but works as a module method.
74
+ """
75
+ return AcceleratorState._shared_state != {}
76
+
77
+
78
+ # Lambda function that does nothing
79
+ def do_nothing(*args, **kwargs):
80
+ return None
81
+
82
+
83
+ class ThreadLocalSharedDict(threading.local):
84
+ """
85
+ Descriptor that holds a dict shared between instances of a class in the same thread.
86
+
87
+ Note: Descriptors have slightly different semantics than just a dict field on its own.
88
+ `PartialState(...)._shared_state` and `PartialState._shared_state` (instance vs class) give the same value: the
89
+ underlying _storage dict. Likewise, `PartialState(...)._shared_state = {...}` overrides the _storage dict inside
90
+ the descriptor as you would expect. However, `PartialState._shared_state = {}` actually replaces the descriptor
91
+ object with a dict instead Thus, you should modify the _storage dict in-place (e.g. `_shared_state.clear()`).
92
+
93
+ See Python documentation for an explanation of descriptors: https://docs.python.org/3/howto/descriptor.html
94
+
95
+ This is required for using PyTorch/XLA with PJRT in multithreaded mode (required for TPU v2 and v3).
96
+
97
+ See https://github.com/pytorch/xla/blob/r2.0/docs/pjrt.md#multithreading-on-tpu-v2v3
98
+ """
99
+
100
+ def __init__(self, thread_local: bool = False):
101
+ self._storage = {}
102
+
103
+ def __get__(self, obj, objtype=None):
104
+ return self._storage
105
+
106
+ def __set__(self, obj, value):
107
+ self._storage = value
108
+
109
+
110
+ # Prefer global shared dictionary, except when using TPU.
111
+ SharedDict = dict if not is_torch_xla_available() else ThreadLocalSharedDict
112
+
113
+
114
+ # Inspired by Alex Martelli's 'Borg'.
115
+ class PartialState:
116
+ """
117
+ Singleton class that has information about the current training environment and functions to help with process
118
+ control. Designed to be used when only process control and device execution states are needed. Does *not* need to
119
+ be initialized from `Accelerator`.
120
+
121
+ Args:
122
+ cpu (`bool`, *optional*):
123
+ Whether or not to force the script to execute on CPU. Will ignore any accelerators available if set to
124
+ `True` and force the execution on the CPU.
125
+ kwargs (additional keyword arguments, *optional*):
126
+ Additional keyword arguments to pass to the relevent `init_process_group` function. Valid `kwargs` can be
127
+ found in [`utils.InitProcessGroupKwargs`]. See the example section for detailed usage.
128
+
129
+ **Available attributes:**
130
+
131
+ - **device** (`torch.device`) -- The device to use.
132
+ - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently
133
+ in use.
134
+ - **local_process_index** (`int`) -- The index of the current process on the current server.
135
+ - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type
136
+ of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8').
137
+ - **num_processes** (`int`) -- The number of processes currently launched in parallel.
138
+ - **process_index** (`int`) -- The index of the current process.
139
+ - **is_last_process** (`bool`) -- Whether or not the current process is the last one.
140
+ - **is_main_process** (`bool`) -- Whether or not the current process is the main one.
141
+ - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node.
142
+ - **debug** (`bool`) -- Whether or not the current script is being run in debug mode.
143
+
144
+ Example:
145
+ ```python
146
+ from accelerate.utils import InitProcessGroupKwargs
147
+
148
+ # To include `InitProcessGroupKwargs`, init then call `.to_kwargs()`
149
+ kwargs = InitProcessGroupKwargs(...).to_kwargs()
150
+ state = PartialState(**kwargs)
151
+ ```
152
+ """
153
+
154
+ _shared_state = SharedDict()
155
+ _known_attrs = [
156
+ "_cpu",
157
+ "_mixed_precision",
158
+ "_shared_state",
159
+ "backend",
160
+ "debug",
161
+ "device",
162
+ "distributed_type",
163
+ "fork_launched",
164
+ "local_process_index",
165
+ "num_processes",
166
+ "process_index",
167
+ ]
168
+
169
+ def __init__(self, cpu: bool = False, **kwargs):
170
+ self.__dict__ = self._shared_state
171
+ if not self.initialized:
172
+ self._cpu = cpu
173
+ self.backend = None
174
+ env_device = os.environ.get("ACCELERATE_TORCH_DEVICE", None)
175
+ self.device = torch.device(env_device) if env_device is not None else None
176
+ self.debug = parse_flag_from_env("ACCELERATE_DEBUG_MODE")
177
+ use_sagemaker_dp = kwargs.pop("_use_sagemaker_dp", None)
178
+ dist_information = None
179
+ if use_sagemaker_dp is None:
180
+ use_sagemaker_dp = (
181
+ os.environ.get("ACCELERATE_USE_SAGEMAKER", "false") == "true"
182
+ and os.environ.get("ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE") != SageMakerDistributedType.NO
183
+ )
184
+
185
+ # Sets up self.backend + imports
186
+ original_backend = kwargs.pop("backend", None)
187
+ backend, distributed_type = self._prepare_backend(cpu, use_sagemaker_dp, original_backend)
188
+ if original_backend is not None and backend != original_backend:
189
+ raise ValueError(f"Your assigned backend {original_backend} is not avaliable, please use {backend}")
190
+ self.backend = backend
191
+ self.distributed_type = distributed_type
192
+ use_deepspeed = False
193
+ if not cpu and self.backend != "xla":
194
+ if int(os.environ.get("LOCAL_RANK", -1)) != -1:
195
+ # Deal with spawning deepspeed
196
+ if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true":
197
+ if not is_deepspeed_available():
198
+ raise ImportError(
199
+ "DeepSpeed is not available => install it using `pip3 install deepspeed` or build it from source"
200
+ )
201
+ from deepspeed import comm as dist
202
+
203
+ if not dist.is_initialized():
204
+ dist.init_distributed(dist_backend=self.backend, auto_mpi_discovery=False, **kwargs)
205
+ # We need to flag to `use_deepspeed` to be True to override `distributed_type` later
206
+ use_deepspeed = True
207
+ # Deal with all other backends but XPU and CPU, that gets handled special later
208
+ elif (
209
+ self.distributed_type not in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU)
210
+ and not torch.distributed.is_initialized()
211
+ ):
212
+ torch.distributed.init_process_group(backend=self.backend, **kwargs)
213
+ # XPU and CPU require special env configs to be set
214
+ if self.distributed_type in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU):
215
+ dist_information = get_cpu_distributed_information()
216
+ os.environ["RANK"] = str(dist_information.rank)
217
+ os.environ["WORLD_SIZE"] = str(dist_information.world_size)
218
+ os.environ["LOCAL_RANK"] = str(dist_information.local_rank)
219
+ os.environ["LOCAL_WORLD_SIZE"] = str(dist_information.local_world_size)
220
+ if not os.environ.get("MASTER_PORT", None):
221
+ os.environ["MASTER_PORT"] = "29500"
222
+ if (
223
+ not os.environ.get("MASTER_ADDR", None)
224
+ and dist_information.local_world_size != dist_information.world_size
225
+ and self.backend != "mpi"
226
+ ):
227
+ raise ValueError(
228
+ "Tried to launch on distributed with multinode, but `MASTER_ADDR` env was not set, "
229
+ "please try exporting rank 0's hostname as `MASTER_ADDR`"
230
+ )
231
+ kwargs["rank"] = dist_information.rank
232
+ kwargs["world_size"] = dist_information.world_size
233
+
234
+ if (
235
+ self.distributed_type == DistributedType.MULTI_CPU
236
+ and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0
237
+ ):
238
+ import psutil
239
+
240
+ num_cpu_threads_per_process = int(
241
+ psutil.cpu_count(logical=False) / dist_information.local_world_size
242
+ )
243
+ if num_cpu_threads_per_process == 0:
244
+ num_cpu_threads_per_process = 1
245
+ torch.set_num_threads(num_cpu_threads_per_process)
246
+ warnings.warn(
247
+ f"OMP_NUM_THREADS/MKL_NUM_THREADS unset, we set it at {num_cpu_threads_per_process} to improve oob"
248
+ " performance."
249
+ )
250
+
251
+ if not torch.distributed.is_initialized():
252
+ torch.distributed.init_process_group(backend=self.backend, **kwargs)
253
+
254
+ # No backend == no distributed training
255
+ if self.backend is None:
256
+ self.distributed_type = DistributedType.NO
257
+ self.num_processes = 1
258
+ self.process_index = 0
259
+ self.local_process_index = 0
260
+ elif self.backend == "xla":
261
+ # XLA needs device setting first for `set_replication`
262
+ self.set_device()
263
+ xm.set_replication(self.device, xm.get_xla_supported_devices())
264
+ self.num_processes = xm.xrt_world_size()
265
+ self.process_index = xm.get_ordinal()
266
+ if is_torch_xla_available(check_is_tpu=True):
267
+ self.local_process_index = xm.get_local_ordinal()
268
+ else:
269
+ self.local_process_index = int(os.environ.get("LOCAL_RANK", -1))
270
+ else:
271
+ self.num_processes = torch.distributed.get_world_size()
272
+ self.process_index = torch.distributed.get_rank()
273
+ self.local_process_index = (
274
+ int(os.environ.get("LOCAL_RANK", -1)) if dist_information is None else dist_information.local_rank
275
+ )
276
+ self.set_device()
277
+ # Now we can change to deepseed
278
+ if use_deepspeed:
279
+ self.distributed_type = DistributedType.DEEPSPEED
280
+
281
+ # Set CPU affinity if enabled
282
+ if parse_flag_from_env("ACCELERATE_CPU_AFFINITY", False):
283
+ set_numa_affinity(self.local_process_index)
284
+
285
+ # Check for old RTX 4000's that can't use P2P or IB and are on old drivers
286
+ if self.device.type == "cuda" and not check_cuda_p2p_ib_support():
287
+ if "NCCL_P2P_DISABLE" not in os.environ or "NCCL_IB_DISABLE" not in os.environ:
288
+ raise NotImplementedError(
289
+ "Using RTX 4000 series doesn't support faster communication broadband via P2P or IB. "
290
+ 'Please set `NCCL_P2P_DISABLE="1"` and `NCCL_IB_DISABLE="1" or use `accelerate launch` which '
291
+ "will do this automatically."
292
+ )
293
+ # Important: This should be the *only* code outside of `self.initialized!`
294
+ self.fork_launched = parse_flag_from_env("FORK_LAUNCHED", 0)
295
+
296
+ def __repr__(self) -> str:
297
+ return (
298
+ f"Distributed environment: {self.distributed_type}{(' Backend: ' + self.backend) if self.backend else ''}\n"
299
+ f"Num processes: {self.num_processes}\n"
300
+ f"Process index: {self.process_index}\n"
301
+ f"Local process index: {self.local_process_index}\n"
302
+ f"Device: {self.device}\n"
303
+ )
304
+
305
+ @staticmethod
306
+ def _reset_state():
307
+ "Resets `_shared_state`, is used internally and should not be called"
308
+ PartialState._shared_state.clear()
309
+
310
+ @property
311
+ def initialized(self) -> bool:
312
+ "Returns whether the `PartialState` has been initialized"
313
+ return self._shared_state != {}
314
+
315
+ @property
316
+ def use_distributed(self):
317
+ """
318
+ Whether the Accelerator is configured for distributed training
319
+ """
320
+ return self.distributed_type != DistributedType.NO and self.num_processes > 1
321
+
322
+ @property
323
+ def is_last_process(self) -> bool:
324
+ "Returns whether the current process is the last one"
325
+ return self.process_index == self.num_processes - 1
326
+
327
+ @property
328
+ def is_main_process(self) -> bool:
329
+ "Returns whether the current process is the main process"
330
+ return (
331
+ self.process_index == 0 if self.distributed_type != DistributedType.MEGATRON_LM else self.is_last_process
332
+ )
333
+
334
+ @property
335
+ def is_local_main_process(self) -> bool:
336
+ "Returns whether the current process is the main process on the local node"
337
+ return (
338
+ self.local_process_index == 0
339
+ if self.distributed_type != DistributedType.MEGATRON_LM
340
+ else self.is_last_process
341
+ )
342
+
343
+ def wait_for_everyone(self):
344
+ """
345
+ Will stop the execution of the current process until every other process has reached that point (so this does
346
+ nothing when the script is only run in one process). Useful to do before saving a model.
347
+
348
+ Example:
349
+
350
+ ```python
351
+ >>> # Assuming two GPU processes
352
+ >>> import time
353
+ >>> from accelerate.state import PartialState
354
+
355
+ >>> state = PartialState()
356
+ >>> if state.is_main_process:
357
+ ... time.sleep(2)
358
+ >>> else:
359
+ ... print("I'm waiting for the main process to finish its sleep...")
360
+ >>> state.wait_for_everyone()
361
+ >>> # Should print on every process at the same time
362
+ >>> print("Everyone is here")
363
+ ```
364
+ """
365
+ if self.distributed_type in (
366
+ DistributedType.MULTI_GPU,
367
+ DistributedType.MULTI_MLU,
368
+ DistributedType.MULTI_MUSA,
369
+ DistributedType.MULTI_NPU,
370
+ DistributedType.MULTI_XPU,
371
+ DistributedType.MULTI_CPU,
372
+ DistributedType.DEEPSPEED,
373
+ DistributedType.FSDP,
374
+ ):
375
+ torch.distributed.barrier()
376
+ elif self.distributed_type == DistributedType.XLA:
377
+ xm.rendezvous("accelerate.utils.wait_for_everyone")
378
+
379
+ def _goes_first(self, is_main: bool):
380
+ if not is_main:
381
+ self.wait_for_everyone()
382
+
383
+ yield
384
+
385
+ if is_main:
386
+ self.wait_for_everyone()
387
+
388
+ @contextmanager
389
+ def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False):
390
+ """
391
+ Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
392
+ distributed inference, such as with different prompts.
393
+
394
+ Note that when using a `dict`, all keys need to have the same number of elements.
395
+
396
+ Args:
397
+ inputs (`list`, `tuple`, `torch.Tensor`, `dict` of `list`/`tuple`/`torch.Tensor`, or `datasets.Dataset`):
398
+ The input to split between processes.
399
+ apply_padding (`bool`, `optional`, defaults to `False`):
400
+ Whether to apply padding by repeating the last element of the input so that all processes have the same
401
+ number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing
402
+ in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.
403
+
404
+
405
+ Example:
406
+
407
+ ```python
408
+ # Assume there are two processes
409
+ from accelerate import PartialState
410
+
411
+ state = PartialState()
412
+ with state.split_between_processes(["A", "B", "C"]) as inputs:
413
+ print(inputs)
414
+ # Process 0
415
+ ["A", "B"]
416
+ # Process 1
417
+ ["C"]
418
+
419
+ with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
420
+ print(inputs)
421
+ # Process 0
422
+ ["A", "B"]
423
+ # Process 1
424
+ ["C", "C"]
425
+ ```
426
+ """
427
+ if self.num_processes == 1:
428
+ yield inputs
429
+ return
430
+ length = len(inputs)
431
+ # Nested dictionary of any types
432
+ if isinstance(inputs, dict):
433
+ length = len(inputs[list(inputs.keys())[0]])
434
+ if not all(len(v) == length for v in inputs.values()):
435
+ raise ValueError("All values in the dictionary must have the same length")
436
+ num_samples_per_process, num_extras = divmod(length, self.num_processes)
437
+ start_index = self.process_index * num_samples_per_process + min(self.process_index, num_extras)
438
+ end_index = start_index + num_samples_per_process + (1 if self.process_index < num_extras else 0)
439
+
440
+ def _split_values(inputs, start_index, end_index):
441
+ if isinstance(inputs, (list, tuple, torch.Tensor)):
442
+ if start_index >= len(inputs):
443
+ result = inputs[-1:]
444
+ else:
445
+ result = inputs[start_index:end_index]
446
+ if apply_padding:
447
+ if isinstance(result, torch.Tensor):
448
+ from accelerate.utils import pad_across_processes, send_to_device
449
+
450
+ # The tensor needs to be on the device before we can pad it
451
+ tensorized_result = send_to_device(result, self.device)
452
+ result = pad_across_processes(tensorized_result, pad_index=inputs[-1])
453
+ else:
454
+ result += [result[-1]] * (num_samples_per_process + 1 - len(result))
455
+ return result
456
+ elif isinstance(inputs, dict):
457
+ for key in inputs.keys():
458
+ inputs[key] = _split_values(inputs[key], start_index, end_index)
459
+ return inputs
460
+ else:
461
+ if is_datasets_available():
462
+ from datasets import Dataset
463
+
464
+ if isinstance(inputs, Dataset):
465
+ if start_index >= len(inputs):
466
+ start_index = len(inputs) - 1
467
+ if end_index > len(inputs):
468
+ end_index = len(inputs)
469
+ result_idcs = list(range(start_index, end_index))
470
+ if apply_padding:
471
+ result_idcs += [end_index - 1] * (num_samples_per_process + 1 - len(result_idcs))
472
+ return inputs.select(result_idcs)
473
+ return inputs
474
+
475
+ yield _split_values(inputs, start_index, end_index)
476
+
477
+ @contextmanager
478
+ def main_process_first(self):
479
+ """
480
+ Lets the main process go first inside a with block.
481
+
482
+ The other processes will enter the with block after the main process exits.
483
+
484
+ Example:
485
+
486
+ ```python
487
+ >>> from accelerate import Accelerator
488
+
489
+ >>> accelerator = Accelerator()
490
+ >>> with accelerator.main_process_first():
491
+ ... # This will be printed first by process 0 then in a seemingly
492
+ ... # random order by the other processes.
493
+ ... print(f"This will be printed by process {accelerator.process_index}")
494
+ ```
495
+ """
496
+ yield from self._goes_first(self.is_main_process)
497
+
498
+ @contextmanager
499
+ def local_main_process_first(self):
500
+ """
501
+ Lets the local main process go inside a with block.
502
+
503
+ The other processes will enter the with block after the main process exits.
504
+
505
+ Example:
506
+
507
+ ```python
508
+ >>> from accelerate.state import PartialState
509
+
510
+ >>> state = PartialState()
511
+ >>> with state.local_main_process_first():
512
+ ... # This will be printed first by local process 0 then in a seemingly
513
+ ... # random order by the other processes.
514
+ ... print(f"This will be printed by process {state.local_process_index}")
515
+ ```
516
+ """
517
+ yield from self._goes_first(self.is_local_main_process)
518
+
519
+ def on_main_process(self, function: Callable[..., Any] = None):
520
+ """
521
+ Decorator that only runs the decorated function on the main process.
522
+
523
+ Args:
524
+ function (`Callable`): The function to decorate.
525
+
526
+ Example:
527
+
528
+ ```python
529
+ >>> from accelerate.state import PartialState
530
+
531
+ >>> state = PartialState()
532
+
533
+
534
+ >>> @state.on_main_process
535
+ ... def print_something():
536
+ ... print("This will be printed by process 0 only.")
537
+
538
+
539
+ >>> print_something()
540
+ "This will be printed by process 0 only"
541
+ ```
542
+ """
543
+ if not self.initialized:
544
+ raise ValueError("The `PartialState` or `Accelerator` must be initialized before calling this function.")
545
+ if self.is_main_process or not self.use_distributed:
546
+ return function
547
+ return do_nothing
548
+
549
+ def on_local_main_process(self, function: Callable[..., Any] = None):
550
+ """
551
+ Decorator that only runs the decorated function on the local main process.
552
+
553
+ Args:
554
+ function (`Callable`): The function to decorate.
555
+
556
+ Example:
557
+ ```python
558
+ # Assume we have 2 servers with 4 processes each.
559
+ from accelerate.state import PartialState
560
+
561
+ state = PartialState()
562
+
563
+
564
+ @state.on_local_main_process
565
+ def print_something():
566
+ print("This will be printed by process 0 only on each server.")
567
+
568
+
569
+ print_something()
570
+ # On server 1:
571
+ "This will be printed by process 0 only"
572
+ # On server 2:
573
+ "This will be printed by process 0 only"
574
+ ```
575
+ """
576
+ if self.is_local_main_process or not self.use_distributed:
577
+ return function
578
+ return do_nothing
579
+
580
+ def on_last_process(self, function: Callable[..., Any]):
581
+ """
582
+ Decorator that only runs the decorated function on the last process.
583
+
584
+ Args:
585
+ function (`Callable`): The function to decorate.
586
+
587
+ Example:
588
+ ```python
589
+ # Assume we have 4 processes.
590
+ from accelerate.state import PartialState
591
+
592
+ state = PartialState()
593
+
594
+
595
+ @state.on_last_process
596
+ def print_something():
597
+ print(f"Printed on process {state.process_index}")
598
+
599
+
600
+ print_something()
601
+ "Printed on process 3"
602
+ ```
603
+ """
604
+ if self.is_last_process or not self.use_distributed:
605
+ return function
606
+ return do_nothing
607
+
608
+ def on_process(self, function: Callable[..., Any] = None, process_index: int = None):
609
+ """
610
+ Decorator that only runs the decorated function on the process with the given index.
611
+
612
+ Args:
613
+ function (`Callable`, `optional`):
614
+ The function to decorate.
615
+ process_index (`int`, `optional`):
616
+ The index of the process on which to run the function.
617
+
618
+ Example:
619
+ ```python
620
+ # Assume we have 4 processes.
621
+ from accelerate.state import PartialState
622
+
623
+ state = PartialState()
624
+
625
+
626
+ @state.on_process(process_index=2)
627
+ def print_something():
628
+ print(f"Printed on process {state.process_index}")
629
+
630
+
631
+ print_something()
632
+ "Printed on process 2"
633
+ ```
634
+ """
635
+ if function is None:
636
+ return partial(self.on_process, process_index=process_index)
637
+ if (self.process_index == process_index) or (not self.use_distributed):
638
+ return function
639
+ return do_nothing
640
+
641
+ def on_local_process(self, function: Callable[..., Any] = None, local_process_index: int = None):
642
+ """
643
+ Decorator that only runs the decorated function on the process with the given index on the current node.
644
+
645
+ Args:
646
+ function (`Callable`, *optional*):
647
+ The function to decorate.
648
+ local_process_index (`int`, *optional*):
649
+ The index of the local process on which to run the function.
650
+
651
+ Example:
652
+ ```python
653
+ # Assume we have 2 servers with 4 processes each.
654
+ from accelerate import Accelerator
655
+
656
+ accelerator = Accelerator()
657
+
658
+
659
+ @accelerator.on_local_process(local_process_index=2)
660
+ def print_something():
661
+ print(f"Printed on process {accelerator.local_process_index}")
662
+
663
+
664
+ print_something()
665
+ # On server 1:
666
+ "Printed on process 2"
667
+ # On server 2:
668
+ "Printed on process 2"
669
+ ```
670
+ """
671
+ if function is None:
672
+ return partial(self.on_local_process, local_process_index=local_process_index)
673
+ if (self.local_process_index == local_process_index) or (not self.use_distributed):
674
+ return function
675
+ return do_nothing
676
+
677
+ def print(self, *args, **kwargs):
678
+ if self.is_local_main_process:
679
+ print(*args, **kwargs)
680
+
681
+ @property
682
+ def default_device(self) -> torch.device:
683
+ """
684
+ Returns the default device which is:
685
+ - MPS if `torch.backends.mps.is_available()` and `torch.backends.mps.is_built()` both return True.
686
+ - CUDA if `torch.cuda.is_available()`
687
+ - MLU if `is_mlu_available()`
688
+ - MUSA if `is_musa_available()`
689
+ - NPU if `is_npu_available()`
690
+ - CPU otherwise
691
+ """
692
+ if is_mps_available():
693
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
694
+ return torch.device("mps")
695
+ elif is_mlu_available():
696
+ return torch.device("mlu")
697
+ elif is_musa_available():
698
+ return torch.device("musa")
699
+ # NPU should be checked before CUDA when using `transfer_to_npu`
700
+ # See issue #3020: https://github.com/huggingface/accelerate/issues/3020
701
+ elif is_npu_available():
702
+ return torch.device("npu")
703
+ elif torch.cuda.is_available():
704
+ return torch.device("cuda")
705
+ elif is_xpu_available():
706
+ return torch.device("xpu")
707
+ else:
708
+ return torch.device("cpu")
709
+
710
+ def _prepare_backend(
711
+ self, cpu: bool = False, sagemaker_dp=False, backend: str = None
712
+ ) -> tuple[str, DistributedType]:
713
+ "Prepares any imports needed before initializing the distributed backend and sets `self.backend` properly"
714
+ distributed_type = None
715
+ if sagemaker_dp:
716
+ import smdistributed.dataparallel.torch.torch_smddp # noqa
717
+
718
+ backend = "smddp"
719
+ distributed_type = DistributedType.MULTI_GPU
720
+ elif is_torch_xla_available():
721
+ backend = "xla"
722
+ distributed_type = DistributedType.XLA
723
+ elif int(os.environ.get("LOCAL_RANK", -1)) != -1 and not cpu:
724
+ if is_mlu_available():
725
+ backend = "cncl"
726
+ distributed_type = DistributedType.MULTI_MLU
727
+ elif is_musa_available():
728
+ backend = "mccl"
729
+ distributed_type = DistributedType.MULTI_MUSA
730
+ # NPU should be checked before CUDA when using `transfer_to_npu`
731
+ # See issue #3020: https://github.com/huggingface/accelerate/issues/3020
732
+ elif is_npu_available():
733
+ backend = "hccl"
734
+ distributed_type = DistributedType.MULTI_NPU
735
+ elif torch.cuda.is_available():
736
+ if backend is None:
737
+ backend = "nccl"
738
+ distributed_type = DistributedType.MULTI_GPU
739
+
740
+ if distributed_type is None and (
741
+ int(os.environ.get("LOCAL_RANK", -1)) != -1
742
+ or get_int_from_env(["PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "MV2_COMM_WORLD_SIZE", "WORLD_SIZE"], 1) > 1
743
+ ):
744
+ if not cpu and is_xpu_available():
745
+ distributed_type = DistributedType.MULTI_XPU
746
+ else:
747
+ distributed_type = DistributedType.MULTI_CPU
748
+
749
+ if (
750
+ backend in (None, "ccl")
751
+ and is_ccl_available()
752
+ and (get_int_from_env(["CCL_WORKER_COUNT"], 0) > 0 or distributed_type == DistributedType.MULTI_XPU)
753
+ ):
754
+ if get_ccl_version() >= "1.12":
755
+ import oneccl_bindings_for_pytorch # noqa: F401
756
+ else:
757
+ import torch_ccl # noqa: F401
758
+
759
+ backend = "ccl"
760
+ elif backend in (None, "mpi") and torch.distributed.is_mpi_available():
761
+ backend = "mpi"
762
+ else:
763
+ backend = "gloo"
764
+ if distributed_type is None:
765
+ distributed_type = DistributedType.NO
766
+
767
+ return backend, distributed_type
768
+
769
+ def set_device(self):
770
+ """
771
+ Sets the device in `self.device` to the current distributed environment.
772
+ """
773
+ if self.device is not None:
774
+ return
775
+ if self.distributed_type == DistributedType.NO:
776
+ self.device = torch.device("cpu") if self._cpu else self.default_device
777
+ return
778
+ device = str(self.distributed_type).split(".")[-1].replace("MULTI_", "").lower()
779
+ if device not in ("cpu", "gpu", "mlu", "musa", "npu", "xpu", "xla"):
780
+ raise ValueError(
781
+ f"Can't set device for {self.distributed_type} ({device}), verify we should be calling `_set_device()` for it!"
782
+ )
783
+ if device == "xla":
784
+ self.device = xm.xla_device()
785
+ else:
786
+ if device == "gpu":
787
+ device = "cuda"
788
+ device_module = getattr(torch, device)
789
+ device_index = self.local_process_index % device_module.device_count()
790
+ self.device = torch.device(device, device_index)
791
+ device_module.set_device(self.device)
792
+
793
+ def destroy_process_group(self, group=None):
794
+ """
795
+ Destroys the process group. If one is not specified, the default process group is destroyed.
796
+ """
797
+ if self.fork_launched and group is None:
798
+ return
799
+ # needed when using torch.distributed.init_process_group
800
+ if torch.distributed.is_initialized():
801
+ torch.distributed.destroy_process_group(group)
802
+
803
+ def __getattr__(self, name: str):
804
+ # By this point we know that no attributes of `self` contain `name`,
805
+ # so we just modify the error message
806
+ if name in self._known_attrs:
807
+ raise AttributeError(
808
+ f"`PartialState` object has no attribute `{name}`. "
809
+ "This happens if `PartialState._reset_state()` was called and "
810
+ "an `Accelerator` or `PartialState` was not reinitialized."
811
+ )
812
+ # Raise a typical AttributeError
813
+ raise AttributeError(f"'PartialState' object has no attribute '{name}'")
814
+
815
+
816
+ class AcceleratorState:
817
+ """
818
+ Singleton class that has information about the current training environment.
819
+
820
+ **Available attributes:**
821
+
822
+ - **device** (`torch.device`) -- The device to use.
823
+ - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently
824
+ in use.
825
+ - **initialized** (`bool`) -- Whether or not the `AcceleratorState` has been initialized from `Accelerator`.
826
+ - **local_process_index** (`int`) -- The index of the current process on the current server.
827
+ - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type
828
+ of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8').
829
+ - **num_processes** (`int`) -- The number of processes currently launched in parallel.
830
+ - **process_index** (`int`) -- The index of the current process.
831
+ - **is_last_process** (`bool`) -- Whether or not the current process is the last one.
832
+ - **is_main_process** (`bool`) -- Whether or not the current process is the main one.
833
+ - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node.
834
+ - **debug** (`bool`) -- Whether or not the current script is being run in debug mode.
835
+ """
836
+
837
+ _shared_state = SharedDict()
838
+ _known_attrs = PartialState._known_attrs + [
839
+ "deepspeed_plugin",
840
+ "use_ipex",
841
+ "fsdp_plugin",
842
+ "megatron_lm_plugin",
843
+ "dynamo_plugin",
844
+ ]
845
+
846
+ def __init__(
847
+ self,
848
+ mixed_precision: str = None,
849
+ cpu: bool = False,
850
+ dynamo_plugin=None,
851
+ deepspeed_plugin=None,
852
+ fsdp_plugin=None,
853
+ megatron_lm_plugin=None,
854
+ _from_accelerator: bool = False,
855
+ **kwargs,
856
+ ):
857
+ self.__dict__ = self._shared_state
858
+ if parse_flag_from_env("ACCELERATE_USE_CPU"):
859
+ cpu = True
860
+ if PartialState._shared_state == {}:
861
+ PartialState(cpu, **kwargs)
862
+ self.__dict__.update(PartialState._shared_state)
863
+ self._check_initialized(mixed_precision, cpu)
864
+ if not self.initialized:
865
+ self.deepspeed_plugins = None
866
+ self.use_ipex = None
867
+ mixed_precision = (
868
+ parse_choice_from_env("ACCELERATE_MIXED_PRECISION", "no")
869
+ if mixed_precision is None
870
+ else mixed_precision.lower()
871
+ )
872
+ if mixed_precision == "fp8":
873
+ if not is_fp8_available():
874
+ raise ValueError(
875
+ "Using `fp8` precision requires `transformer_engine` or `MS-AMP` to be installed."
876
+ )
877
+ elif not check_fp8_capability():
878
+ logger.warning(
879
+ f"The current device has compute capability of {torch.cuda.get_device_capability()} which is "
880
+ "insufficient for FP8 mixed precision training (requires a GPU Hopper/Ada Lovelace "
881
+ "or higher, compute capability of 8.9 or higher). Will use FP16 instead."
882
+ )
883
+ mixed_precision = "fp16"
884
+
885
+ self.dynamo_plugin = dynamo_plugin
886
+ if not _from_accelerator:
887
+ raise ValueError(
888
+ "Please make sure to properly initialize your accelerator via `accelerator = Accelerator()` "
889
+ "before using any functionality from the `accelerate` library."
890
+ )
891
+ # deepspeed handles mixed_precision using deepspeed_config
892
+ self._mixed_precision = "no" if self.distributed_type == DistributedType.DEEPSPEED else mixed_precision
893
+ if self.distributed_type == DistributedType.XLA and is_torch_xla_available(check_is_tpu=True):
894
+ if mixed_precision == "bf16":
895
+ if os.environ.get("ACCELERATE_DOWNCAST_BF16"):
896
+ os.environ["XLA_USE_BF16"] = str(0)
897
+ os.environ["XLA_DOWNCAST_BF16"] = str(1)
898
+ self.downcast_bfloat = True
899
+ else:
900
+ os.environ["XLA_USE_BF16"] = str(1)
901
+ os.environ["XLA_DOWNCAST_BF16"] = str(0)
902
+ self.downcast_bfloat = False
903
+ elif os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true" and not cpu:
904
+ self.deepspeed_plugins = deepspeed_plugin
905
+ self.distributed_type = DistributedType.DEEPSPEED
906
+ elif self.distributed_type in [
907
+ DistributedType.MULTI_GPU,
908
+ DistributedType.MULTI_MLU,
909
+ DistributedType.MULTI_MUSA,
910
+ DistributedType.MULTI_NPU,
911
+ DistributedType.MULTI_XPU,
912
+ ]:
913
+ if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true" or fsdp_plugin is not None:
914
+ self.distributed_type = DistributedType.FSDP
915
+ if self._mixed_precision != "no":
916
+ fsdp_plugin.set_mixed_precision(self._mixed_precision)
917
+ self.fsdp_plugin = fsdp_plugin
918
+ if os.environ.get("ACCELERATE_USE_MEGATRON_LM", "false") == "true" and self.distributed_type not in [
919
+ DistributedType.MULTI_XPU,
920
+ ]:
921
+ self.distributed_type = DistributedType.MEGATRON_LM
922
+ megatron_lm_plugin.set_mixed_precision(self._mixed_precision)
923
+ self.megatron_lm_plugin = megatron_lm_plugin
924
+ elif self.distributed_type in [DistributedType.MULTI_CPU, DistributedType.MULTI_XPU, DistributedType.NO]:
925
+ if is_ipex_available():
926
+ # check if user disables it explicitly
927
+ self.use_ipex = parse_flag_from_env("ACCELERATE_USE_IPEX", default=True)
928
+ else:
929
+ self.use_ipex = False
930
+ if (
931
+ self.dynamo_plugin.backend != DynamoBackend.NO
932
+ and self._mixed_precision == "no"
933
+ and self.device.type == "cuda"
934
+ ):
935
+ torch.backends.cuda.matmul.allow_tf32 = True
936
+ if (
937
+ self.dynamo_plugin.backend != DynamoBackend.NO
938
+ and self._mixed_precision == "no"
939
+ and self.device.type == "musa"
940
+ ):
941
+ torch.backends.musa.matmul.allow_tf32 = True
942
+ PartialState._shared_state["distributed_type"] = self.distributed_type
943
+
944
+ @property
945
+ def initialized(self) -> bool:
946
+ return self._shared_state != PartialState._shared_state
947
+
948
+ def __repr__(self):
949
+ repr = PartialState().__repr__() + f"\nMixed precision type: {self.mixed_precision}\n"
950
+ if self.distributed_type == DistributedType.DEEPSPEED:
951
+ repr += f"ds_config: {self.deepspeed_plugin.deepspeed_config}\n"
952
+ return repr
953
+
954
+ def _check_initialized(self, mixed_precision=None, cpu=None):
955
+ "Checks if a modification is trying to be made and the `AcceleratorState` has already been initialized"
956
+ if self.initialized:
957
+ err = "AcceleratorState has already been initialized and cannot be changed, restart your runtime completely and pass `{flag}` to `Accelerator()`."
958
+ if cpu and self.device.type != "cpu":
959
+ raise ValueError(err.format(flag="cpu=True"))
960
+ if (
961
+ mixed_precision is not None
962
+ and mixed_precision != self._mixed_precision
963
+ and self.distributed_type != DistributedType.DEEPSPEED
964
+ ):
965
+ raise ValueError(err.format(flag=f"mixed_precision='{mixed_precision}'"))
966
+
967
+ @property
968
+ def mixed_precision(self):
969
+ if self.distributed_type == DistributedType.DEEPSPEED:
970
+ config = self.deepspeed_plugin.deepspeed_config
971
+ if config.get("fp16", {}).get("enabled", False):
972
+ mixed_precision = "fp16"
973
+ elif config.get("bf16", {}).get("enabled", False):
974
+ mixed_precision = "bf16"
975
+ else:
976
+ mixed_precision = "no"
977
+ else:
978
+ mixed_precision = self._mixed_precision
979
+ return mixed_precision
980
+
981
+ @staticmethod
982
+ def _reset_state(reset_partial_state: bool = False):
983
+ "Resets `_shared_state`, is used internally and should not be called"
984
+ AcceleratorState._shared_state.clear()
985
+ if reset_partial_state:
986
+ PartialState._reset_state()
987
+
988
+ def destroy_process_group(self, group=None):
989
+ """
990
+ Destroys the process group. If one is not specified, the default process group is destroyed.
991
+
992
+ If `self.fork_lauched` is `True` and `group` is `None`, nothing happens.
993
+ """
994
+ PartialState().destroy_process_group(group)
995
+
996
+ @property
997
+ def fork_launched(self):
998
+ return PartialState().fork_launched
999
+
1000
+ @property
1001
+ def use_distributed(self):
1002
+ """
1003
+ Whether the Accelerator is configured for distributed training
1004
+ """
1005
+ return PartialState().use_distributed
1006
+
1007
+ @property
1008
+ def is_last_process(self) -> bool:
1009
+ "Returns whether the current process is the last one"
1010
+ return PartialState().is_last_process
1011
+
1012
+ @property
1013
+ def is_main_process(self) -> bool:
1014
+ "Returns whether the current process is the main process"
1015
+ return PartialState().is_main_process
1016
+
1017
+ @property
1018
+ def is_local_main_process(self) -> bool:
1019
+ "Returns whether the current process is the main process on the local node"
1020
+ return PartialState().is_local_main_process
1021
+
1022
+ def wait_for_everyone(self):
1023
+ PartialState().wait_for_everyone()
1024
+
1025
+ @contextmanager
1026
+ def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False):
1027
+ """
1028
+ Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
1029
+ distributed inference, such as with different prompts.
1030
+
1031
+ Note that when using a `dict`, all keys need to have the same number of elements.
1032
+
1033
+ Args:
1034
+ inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`):
1035
+ The input to split between processes.
1036
+ apply_padding (`bool`, `optional`, defaults to `False`):
1037
+ Whether to apply padding by repeating the last element of the input so that all processes have the same
1038
+ number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing
1039
+ in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.
1040
+
1041
+
1042
+ Example:
1043
+
1044
+ ```python
1045
+ # Assume there are two processes
1046
+ from accelerate.state import AcceleratorState
1047
+
1048
+ state = AcceleratorState()
1049
+ with state.split_between_processes(["A", "B", "C"]) as inputs:
1050
+ print(inputs)
1051
+ # Process 0
1052
+ ["A", "B"]
1053
+ # Process 1
1054
+ ["C"]
1055
+
1056
+ with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
1057
+ print(inputs)
1058
+ # Process 0
1059
+ ["A", "B"]
1060
+ # Process 1
1061
+ ["C", "C"]
1062
+ ```
1063
+ """
1064
+ with PartialState().split_between_processes(inputs, apply_padding=apply_padding) as inputs:
1065
+ yield inputs
1066
+
1067
+ @contextmanager
1068
+ def main_process_first(self):
1069
+ """
1070
+ Lets the main process go first inside a with block.
1071
+
1072
+ The other processes will enter the with block after the main process exits.
1073
+ """
1074
+ with PartialState().main_process_first():
1075
+ yield
1076
+
1077
+ @contextmanager
1078
+ def local_main_process_first(self):
1079
+ """
1080
+ Lets the local main process go inside a with block.
1081
+
1082
+ The other processes will enter the with block after the main process exits.
1083
+ """
1084
+ with PartialState().local_main_process_first():
1085
+ yield
1086
+
1087
+ @property
1088
+ def deepspeed_plugin(self):
1089
+ """
1090
+ Returns the currently active DeepSpeedPlugin.
1091
+
1092
+ If not using deepspeed, returns `None`.
1093
+ """
1094
+ # To maintain original behavior, return None if not using deepspeed.
1095
+ if self.distributed_type != DistributedType.DEEPSPEED:
1096
+ return None
1097
+ from accelerate.utils.deepspeed import get_active_deepspeed_plugin
1098
+
1099
+ return get_active_deepspeed_plugin(self)
1100
+
1101
+ @deepspeed_required
1102
+ def get_deepspeed_plugin(self, name: str):
1103
+ """
1104
+ Returns the DeepSpeedPlugin with the given plugin_key.
1105
+ """
1106
+ return self.deepspeed_plugins[name]
1107
+
1108
+ @deepspeed_required
1109
+ def select_deepspeed_plugin(self, name: str = None):
1110
+ """
1111
+ Activates the DeepSpeedPlugin with the given `name`, and will disable all other plugins.
1112
+ """
1113
+ for key, plugin in self.deepspeed_plugins.items():
1114
+ if key != name:
1115
+ plugin._unselect()
1116
+ self.deepspeed_plugins[name].select(_from_accelerator_state=True)
1117
+
1118
+ def print(self, *args, **kwargs):
1119
+ PartialState().print(*args, **kwargs)
1120
+
1121
+ def __getattr__(self, name: str):
1122
+ # By this point we know that no attributes of `self` contain `name`,
1123
+ # so we just modify the error message
1124
+ if name in self._known_attrs:
1125
+ raise AttributeError(
1126
+ f"`AcceleratorState` object has no attribute `{name}`. "
1127
+ "This happens if `AcceleratorState._reset_state()` was called and "
1128
+ "an `Accelerator` or `PartialState` was not reinitialized."
1129
+ )
1130
+ # Raise a typical AttributeError
1131
+ raise AttributeError(f"'AcceleratorState' object has no attribute '{name}'")
1132
+
1133
+
1134
+ class GradientState:
1135
+ """
1136
+ Singleton class that has information related to gradient synchronization for gradient accumulation
1137
+
1138
+ **Available attributes:**
1139
+
1140
+ - **end_of_dataloader** (`bool`) -- Whether we have reached the end the current dataloader
1141
+ - **remainder** (`int`) -- The number of extra samples that were added from padding the dataloader
1142
+ - **sync_gradients** (`bool`) -- Whether the gradients should be synced across all devices
1143
+ - **active_dataloader** (`Optional[DataLoader]`) -- The dataloader that is currently being iterated over
1144
+ - **dataloader_references** (`List[Optional[DataLoader]]`) -- A list of references to the dataloaders that are
1145
+ being iterated over
1146
+ - **num_steps** (`int`) -- The number of steps to accumulate over
1147
+ - **adjust_scheduler** (`bool`) -- Whether the scheduler should be adjusted to account for the gradient
1148
+ accumulation
1149
+ - **sync_with_dataloader** (`bool`) -- Whether the gradients should be synced at the end of the dataloader
1150
+ iteration and the number of total steps reset
1151
+ - **is_xla_gradients_synced** (`bool`) -- Whether the XLA gradients have been synchronized. It is initialized
1152
+ as false. Once gradients have been reduced before the optimizer step, this flag is set to true. Subsequently,
1153
+ after each step, the flag is reset to false. FSDP will always synchronize the gradients, hence
1154
+ is_xla_gradients_synced is always true.
1155
+ """
1156
+
1157
+ _shared_state = SharedDict()
1158
+
1159
+ def __init__(self, gradient_accumulation_plugin: Optional[GradientAccumulationPlugin] = None):
1160
+ self.__dict__ = self._shared_state
1161
+ if not self.initialized:
1162
+ self.sync_gradients = True
1163
+ self.active_dataloader = None
1164
+ self.dataloader_references = [None]
1165
+ self.plugin_kwargs = (
1166
+ gradient_accumulation_plugin.to_kwargs() if gradient_accumulation_plugin is not None else {}
1167
+ )
1168
+ self._is_xla_gradients_synced = False
1169
+
1170
+ # Plugin args are different and can be updated
1171
+ if gradient_accumulation_plugin is not None and self.plugin_kwargs != gradient_accumulation_plugin.to_kwargs():
1172
+ self.plugin_kwargs = gradient_accumulation_plugin.to_kwargs()
1173
+
1174
+ @property
1175
+ def num_steps(self) -> int:
1176
+ "Returns the number of steps to accumulate over"
1177
+ return self.plugin_kwargs.get("num_steps", 1)
1178
+
1179
+ @property
1180
+ def adjust_scheduler(self) -> bool:
1181
+ "Returns whether the scheduler should be adjusted"
1182
+ return self.plugin_kwargs.get("adjust_scheduler", False)
1183
+
1184
+ @property
1185
+ def sync_with_dataloader(self) -> bool:
1186
+ "Returns whether the gradients should be synced at the end of the dataloader iteration and the number of total steps reset"
1187
+ return self.plugin_kwargs.get("sync_with_dataloader", True)
1188
+
1189
+ @property
1190
+ def initialized(self) -> bool:
1191
+ "Returns whether the `GradientState` has been initialized"
1192
+ return GradientState._shared_state != {}
1193
+
1194
+ @property
1195
+ def end_of_dataloader(self) -> bool:
1196
+ "Returns whether we have reached the end of the current dataloader"
1197
+ if not self.in_dataloader:
1198
+ return False
1199
+ return self.active_dataloader.end_of_dataloader
1200
+
1201
+ @property
1202
+ def remainder(self) -> int:
1203
+ "Returns the number of extra samples that were added from padding the dataloader"
1204
+ if not self.in_dataloader:
1205
+ return -1
1206
+ return self.active_dataloader.remainder
1207
+
1208
+ def __repr__(self):
1209
+ return (
1210
+ f"Sync Gradients: {self.sync_gradients}\n"
1211
+ f"At end of current dataloader: {self.end_of_dataloader}\n"
1212
+ f"Extra samples added: {self.remainder}\n"
1213
+ f"Gradient accumulation plugin: {self.plugin_kwargs}\n"
1214
+ )
1215
+
1216
+ @property
1217
+ def is_xla_gradients_synced(self):
1218
+ "Returns the value of is_xla_gradients_synced. FSDP will always synchronize the gradients, hence is_xla_gradients_synced is always true."
1219
+ if parse_flag_from_env("ACCELERATE_USE_FSDP", default=False):
1220
+ return True
1221
+ return self._is_xla_gradients_synced
1222
+
1223
+ @is_xla_gradients_synced.setter
1224
+ def is_xla_gradients_synced(self, is_synced):
1225
+ "Set the _is_xla_gradients_synced attribute."
1226
+ self._is_xla_gradients_synced = is_synced
1227
+
1228
+ def _set_sync_gradients(self, sync_gradients):
1229
+ "Private function that sets whether gradients should be synchronized. Users should not have to call this."
1230
+ self.sync_gradients = sync_gradients
1231
+ # Allow grad-sync to automatically work on TPUs
1232
+ if (
1233
+ self.sync_gradients
1234
+ and is_torch_xla_available(check_is_tpu=True)
1235
+ and PartialState().distributed_type == DistributedType.XLA
1236
+ ):
1237
+ xm.mark_step()
1238
+
1239
+ def _add_dataloader(self, dataloader):
1240
+ "Private function that adds a dataloader to `self.dataloader_references` and sets `in_dataloader` to `True`. Users should not have to call this."
1241
+ self.active_dataloader = dataloader
1242
+ self.dataloader_references.append(self.active_dataloader)
1243
+
1244
+ def _remove_dataloader(self, dataloader):
1245
+ "Private function that removes a dataloader from `self.dataloader_references` and sets `in_dataloader` to `False` if there are no more dataloaders. Users should not have to call this."
1246
+ self.dataloader_references.remove(dataloader)
1247
+ self.active_dataloader = self.dataloader_references[-1]
1248
+
1249
+ @property
1250
+ def in_dataloader(self) -> bool:
1251
+ "Returns whether the current process is in a dataloader"
1252
+ return self.active_dataloader is not None
1253
+
1254
+ @staticmethod
1255
+ def _reset_state():
1256
+ "Resets `_shared_state`, is used internally and should not be called"
1257
+ GradientState._shared_state.clear()