diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_3.py b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_3.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ba20c4b523ab773949030aafb1c9fd0e0822a7f
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_3.py
@@ -0,0 +1,158 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from manim import *
+
+class Stage3(Scene):
+ def construct(self):
+ mem = Rectangle(height=0.5,width=0.5)
+ meta_mem = Rectangle(height=0.25,width=0.25)
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
+
+ cpu_left_col_base = [mem.copy() for i in range(6)]
+ cpu_right_col_base = [mem.copy() for i in range(6)]
+ cpu_left_col = VGroup(*cpu_left_col_base).arrange(UP, buff=0)
+ cpu_right_col = VGroup(*cpu_right_col_base).arrange(UP, buff=0)
+ cpu_rects = VGroup(cpu_left_col,cpu_right_col).arrange(RIGHT, buff=0)
+ cpu_text = Text("CPU", font_size=24)
+ cpu = Group(cpu_rects,cpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ cpu.move_to([-2.5,-.5,0])
+ self.add(cpu)
+
+ gpu_base = [mem.copy() for i in range(4)]
+ gpu_rect = VGroup(*gpu_base).arrange(UP,buff=0)
+ gpu_text = Text("GPU", font_size=24)
+ gpu = Group(gpu_rect,gpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ gpu.move_to([-1,-1,0])
+ self.add(gpu)
+
+ model_base = [mem.copy() for i in range(6)]
+ model_rect = VGroup(*model_base).arrange(RIGHT,buff=0)
+
+ model_text = Text("Model", font_size=24)
+ model = Group(model_rect,model_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ model.move_to([3, -1., 0])
+ self.add(model)
+
+ model_arr = []
+ model_cpu_arr = []
+ model_meta_arr = []
+
+ for i,rect in enumerate(model_base):
+ rect.set_stroke(YELLOW)
+
+ cpu_target = Rectangle(height=0.46/4,width=0.46/3).set_stroke(width=0.).set_fill(YELLOW, opacity=0.7)
+
+ if i == 0:
+ cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN+LEFT), buff=0.02, direction=UP)
+ cpu_target.set_x(cpu_target.get_x()+0.1)
+ elif i == 3:
+ cpu_target.next_to(model_cpu_arr[0], direction=UP, buff=0.)
+ else:
+ cpu_target.next_to(model_cpu_arr[i-1], direction=RIGHT, buff=0.)
+ self.add(cpu_target)
+ model_cpu_arr.append(cpu_target)
+
+ self.add(*model_arr, *model_cpu_arr, *model_meta_arr)
+
+ checkpoint_base = [mem.copy() for i in range(6)]
+ checkpoint_rect = VGroup(*checkpoint_base).arrange(RIGHT,buff=0)
+
+ checkpoint_text = Text("Loaded Checkpoint", font_size=24)
+ checkpoint = Group(checkpoint_rect,checkpoint_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ checkpoint.move_to([3, .5, 0])
+
+ self.add(checkpoint)
+
+ ckpt_arr = []
+ ckpt_cpu_arr = []
+
+ for i,rect in enumerate(checkpoint_base):
+ target = fill.copy().set_fill(BLUE, opacity=0.7)
+ target.move_to(rect)
+ ckpt_arr.append(target)
+
+ cpu_target = target.copy()
+ if i < 5:
+ cpu_target.move_to(cpu_left_col_base[i+1])
+ else:
+ cpu_target.move_to(cpu_right_col_base[i-5])
+ ckpt_cpu_arr.append(cpu_target)
+ self.add(*ckpt_arr, *ckpt_cpu_arr)
+
+ key = Square(side_length=2.2)
+ key.move_to([-5, 2, 0])
+
+ key_text = MarkupText(
+ f"Key:\n\n● Empty Model",
+ font_size=18,
+ )
+
+ key_text.move_to([-5, 2.4, 0])
+
+ self.add(key_text, key)
+
+ blue_text = MarkupText(
+ f"● Checkpoint",
+ font_size=18,
+ )
+
+ blue_text.next_to(key_text, DOWN*2.4, aligned_edge=key_text.get_left())
+ self.add(blue_text)
+
+ step_3 = MarkupText(
+ f'Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.',
+ font_size=24
+ )
+ step_3.move_to([2, 2, 0])
+
+ disk_left_col_base = [meta_mem.copy() for i in range(6)]
+ disk_right_col_base = [meta_mem.copy() for i in range(6)]
+ disk_left_col = VGroup(*disk_left_col_base).arrange(UP, buff=0)
+ disk_right_col = VGroup(*disk_right_col_base).arrange(UP, buff=0)
+ disk_rects = VGroup(disk_left_col,disk_right_col).arrange(RIGHT, buff=0)
+ disk_text = Text("Disk", font_size=24)
+ disk = Group(disk_rects,disk_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ disk.move_to([-4.,-1.25,0])
+ self.play(
+ Write(step_3, run_time=3),
+ Write(disk_text, run_time=1),
+ Create(disk_rects, run_time=1)
+ )
+
+ animations = []
+ for i,rect in enumerate(ckpt_cpu_arr):
+ target = rect.copy()
+ target.generate_target()
+ target.target.move_to(disk_left_col_base[i]).scale(0.5)
+ animations.append(MoveToTarget(target, run_time=1.5))
+ self.play(*animations)
+
+ self.play(FadeOut(step_3))
+
+ step_4 = MarkupText(
+ f'Then, the checkpoint is removed from memory\nthrough garbage collection.',
+ font_size=24
+ )
+ step_4.move_to([2, 2, 0])
+
+ self.play(
+ Write(step_4, run_time=3)
+ )
+
+ self.play(
+ FadeOut(checkpoint_rect, checkpoint_text, *ckpt_arr, *ckpt_cpu_arr),
+ )
+
+ self.wait()
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_4.py b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_4.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a79ad97cb1fa6cc029d25f88581bf3525baeefb
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_4.py
@@ -0,0 +1,156 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from manim import *
+
+class Stage4(Scene):
+ def construct(self):
+ mem = Rectangle(height=0.5,width=0.5)
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
+ meta_mem = Rectangle(height=0.25,width=0.25)
+
+ cpu_left_col_base = [mem.copy() for i in range(6)]
+ cpu_right_col_base = [mem.copy() for i in range(6)]
+ cpu_left_col = VGroup(*cpu_left_col_base).arrange(UP, buff=0)
+ cpu_right_col = VGroup(*cpu_right_col_base).arrange(UP, buff=0)
+ cpu_rects = VGroup(cpu_left_col,cpu_right_col).arrange(RIGHT, buff=0)
+ cpu_text = Text("CPU", font_size=24)
+ cpu = Group(cpu_rects,cpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ cpu.move_to([-2.5,-.5,0])
+ self.add(cpu)
+
+ gpu_base = [mem.copy() for i in range(4)]
+ gpu_rect = VGroup(*gpu_base).arrange(UP,buff=0)
+ gpu_text = Text("GPU", font_size=24)
+ gpu = Group(gpu_rect,gpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ gpu.move_to([-1,-1,0])
+ self.add(gpu)
+
+ model_base = [mem.copy() for i in range(6)]
+ model_rect = VGroup(*model_base).arrange(RIGHT,buff=0)
+
+ model_text = Text("Model", font_size=24)
+ model = Group(model_rect,model_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ model.move_to([3, -1., 0])
+ self.add(model)
+
+ model_cpu_arr = []
+ model_meta_arr = []
+
+ for i,rect in enumerate(model_base):
+ rect.set_stroke(YELLOW)
+
+ cpu_target = Rectangle(height=0.46/4,width=0.46/3).set_stroke(width=0.).set_fill(YELLOW, opacity=0.7)
+
+ if i == 0:
+ cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN+LEFT), buff=0.02, direction=UP)
+ cpu_target.set_x(cpu_target.get_x()+0.1)
+ elif i == 3:
+ cpu_target.next_to(model_cpu_arr[0], direction=UP, buff=0.)
+ else:
+ cpu_target.next_to(model_cpu_arr[i-1], direction=RIGHT, buff=0.)
+ self.add(cpu_target)
+ model_cpu_arr.append(cpu_target)
+
+ self.add(*model_cpu_arr, *model_meta_arr)
+
+ disk_left_col_base = [meta_mem.copy() for i in range(6)]
+ disk_right_col_base = [meta_mem.copy() for i in range(6)]
+ disk_left_col = VGroup(*disk_left_col_base).arrange(UP, buff=0)
+ disk_right_col = VGroup(*disk_right_col_base).arrange(UP, buff=0)
+ disk_rects = VGroup(disk_left_col,disk_right_col).arrange(RIGHT, buff=0)
+ disk_text = Text("Disk", font_size=24)
+ disk = Group(disk_rects,disk_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ disk.move_to([-4.,-1.25,0])
+ self.add(disk_text, disk_rects)
+
+ cpu_disk_arr = []
+
+ for i in range(6):
+ target = fill.copy().set_fill(BLUE, opacity=0.8)
+ target.move_to(disk_left_col_base[i]).scale(0.5)
+ cpu_disk_arr.append(target)
+
+ self.add(*cpu_disk_arr)
+
+ key = Square(side_length=2.2)
+ key.move_to([-5, 2, 0])
+
+ key_text = MarkupText(
+ f"Key:\n\n● Empty Model",
+ font_size=18,
+ )
+
+ key_text.move_to([-5, 2.4, 0])
+
+ self.add(key_text, key)
+
+ blue_text = MarkupText(
+ f"● Checkpoint",
+ font_size=18,
+ )
+
+ blue_text.next_to(key_text, DOWN*2.4, aligned_edge=key_text.get_left())
+ self.add(blue_text)
+
+ step_5 = MarkupText(
+ f'The offloaded weights are all sent to the CPU.',
+ font_size=24
+ )
+ step_5.move_to([2, 2, 0])
+
+ self.play(Write(step_5, run_time=3))
+
+ for i in range(6):
+ rect = cpu_disk_arr[i]
+ cp2 = rect.copy().set_fill(BLUE, opacity=0.8).scale(2.0)
+ cp2.generate_target()
+ cp2.target.move_to(model_base[i])
+
+ if i == 0:
+ rect.set_fill(BLUE, opacity=0.8)
+ rect.generate_target()
+ rect.target.move_to(cpu_left_col_base[0]).scale(2.0)
+
+ self.remove(*model_meta_arr,
+ *model_cpu_arr,
+ )
+
+ else:
+ rect.generate_target()
+ rect.target.move_to(cpu_left_col_base[i]).scale(2.0)
+ self.play(
+ MoveToTarget(rect),
+ MoveToTarget(cp2),
+ model_base[i].animate.set_stroke(WHITE)
+ )
+ self.play(FadeOut(step_5))
+
+ step_5 = MarkupText(
+ 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.',
+ font_size=24
+ )
+ step_5.move_to([2, 2, 0])
+
+ self.play(Write(step_5, run_time=3))
+
+ arrows = []
+ animations = []
+ for i in range(6):
+ a = Arrow(start=UP, end=DOWN, color=RED, buff=.5)
+ a.next_to(model_base[i].get_left(), UP, buff=0.2)
+ arrows.append(a)
+ animations.append(Write(a))
+ self.play(*animations)
+ self.wait()
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_5.py b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_5.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b2ff33577ead0d32f54818998427c845d3cfb63
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/big_model_inference/stage_5.py
@@ -0,0 +1,221 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from manim import *
+
+class Stage5(Scene):
+ def construct(self):
+ mem = Rectangle(height=0.5,width=0.5)
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
+
+ meta_mem = Rectangle(height=0.25,width=0.25)
+
+ cpu_left_col_base = [mem.copy() for i in range(6)]
+ cpu_right_col_base = [mem.copy() for i in range(6)]
+ cpu_left_col = VGroup(*cpu_left_col_base).arrange(UP, buff=0)
+ cpu_right_col = VGroup(*cpu_right_col_base).arrange(UP, buff=0)
+ cpu_rects = VGroup(cpu_left_col,cpu_right_col).arrange(RIGHT, buff=0)
+ cpu_text = Text("CPU", font_size=24)
+ cpu = Group(cpu_rects,cpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ cpu.move_to([-2.5,-.5,0])
+ self.add(cpu)
+
+ gpu_base = [mem.copy() for i in range(4)]
+ gpu_rect = VGroup(*gpu_base).arrange(UP,buff=0)
+ gpu_text = Text("GPU", font_size=24)
+ gpu = Group(gpu_rect,gpu_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ gpu.move_to([-1,-1,0])
+ self.add(gpu)
+
+ model_base = [mem.copy() for i in range(6)]
+ model_rect = VGroup(*model_base).arrange(RIGHT,buff=0)
+
+ model_text = Text("Model", font_size=24)
+ model = Group(model_rect,model_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ model.move_to([3, -1., 0])
+ self.add(model)
+
+ model_arr = []
+ model_cpu_arr = []
+
+ for i,rect in enumerate(model_base):
+ target = fill.copy().set_fill(BLUE, opacity=0.8)
+ target.move_to(rect)
+ model_arr.append(target)
+
+ cpu_target = Rectangle(height=0.46,width=0.46).set_stroke(width=0.).set_fill(BLUE, opacity=0.8)
+ cpu_target.move_to(cpu_left_col_base[i])
+ model_cpu_arr.append(cpu_target)
+
+ self.add(*model_arr, *model_cpu_arr)
+
+ disk_left_col_base = [meta_mem.copy() for i in range(6)]
+ disk_right_col_base = [meta_mem.copy() for i in range(6)]
+ disk_left_col = VGroup(*disk_left_col_base).arrange(UP, buff=0)
+ disk_right_col = VGroup(*disk_right_col_base).arrange(UP, buff=0)
+ disk_rects = VGroup(disk_left_col,disk_right_col).arrange(RIGHT, buff=0)
+ disk_text = Text("Disk", font_size=24)
+ disk = Group(disk_rects,disk_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ disk.move_to([-4,-1.25,0])
+ self.add(disk_text, disk_rects)
+
+ key = Square(side_length=2.2)
+ key.move_to([-5, 2, 0])
+
+ key_text = MarkupText(
+ f"Key:\n\n● Empty Model",
+ font_size=18,
+ )
+
+ key_text.move_to([-5, 2.4, 0])
+
+ self.add(key_text, key)
+
+ blue_text = MarkupText(
+ f"● Checkpoint",
+ font_size=18,
+ )
+
+ blue_text.next_to(key_text, DOWN*2.4, aligned_edge=key_text.get_left())
+ self.add(blue_text)
+
+ step_6 = MarkupText(
+ f'Now watch as an input is passed through the model\nand how the memory is utilized and handled.',
+ font_size=24
+ )
+ step_6.move_to([2, 2, 0])
+
+ self.play(Write(step_6))
+
+ input = Square(0.3)
+ input.set_fill(RED, opacity=1.)
+ input.set_stroke(width=0.)
+ input.next_to(model_base[0], LEFT, buff=.5)
+
+ self.play(Write(input))
+
+ input.generate_target()
+ input.target.next_to(model_arr[0], direction=LEFT, buff=0.02)
+ self.play(MoveToTarget(input))
+
+ self.play(FadeOut(step_6))
+
+
+ a = Arrow(start=UP, end=DOWN, color=RED, buff=.5)
+ a.next_to(model_arr[0].get_left(), UP, buff=0.2)
+
+ model_cpu_arr[0].generate_target()
+ model_cpu_arr[0].target.move_to(gpu_rect[0])
+
+ step_7 = MarkupText(
+ f'As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.',
+ font_size=24
+ )
+ step_7.move_to([2, 2, 0])
+
+ self.play(Write(step_7, run_time=3))
+
+ circ_kwargs = {"run_time":1, "fade_in":True, "fade_out":True, "buff":0.02}
+
+ self.play(
+ Write(a),
+ Circumscribe(model_arr[0], color=ORANGE, **circ_kwargs),
+ Circumscribe(model_cpu_arr[0], color=ORANGE, **circ_kwargs),
+ Circumscribe(gpu_rect[0], color=ORANGE, **circ_kwargs),
+ )
+ self.play(
+ MoveToTarget(model_cpu_arr[0])
+ )
+
+ a_c = a.copy()
+ for i in range(6):
+ a_c.next_to(model_arr[i].get_right()+0.02, UP, buff=0.2)
+
+ input.generate_target()
+ input.target.move_to(model_arr[i].get_right()+0.02)
+
+ grp = AnimationGroup(
+ FadeOut(a, run_time=.5),
+ MoveToTarget(input, run_time=.5),
+ FadeIn(a_c, run_time=.5),
+ lag_ratio=0.2
+ )
+
+ self.play(grp)
+
+
+ model_cpu_arr[i].generate_target()
+ model_cpu_arr[i].target.move_to(cpu_left_col_base[i])
+
+
+ if i < 5:
+ model_cpu_arr[i+1].generate_target()
+ model_cpu_arr[i+1].target.move_to(gpu_rect[0])
+ if i >= 1:
+ circ_kwargs["run_time"] = .7
+
+ self.play(
+ Circumscribe(model_arr[i], **circ_kwargs),
+ Circumscribe(cpu_left_col_base[i], **circ_kwargs),
+ Circumscribe(cpu_left_col_base[i+1], color=ORANGE, **circ_kwargs),
+ Circumscribe(gpu_rect[0], color=ORANGE, **circ_kwargs),
+ Circumscribe(model_arr[i+1], color=ORANGE, **circ_kwargs),
+ )
+ if i < 1:
+ self.play(
+ MoveToTarget(model_cpu_arr[i]),
+ MoveToTarget(model_cpu_arr[i+1]),
+ )
+ else:
+ self.play(
+ MoveToTarget(model_cpu_arr[i], run_time=.7),
+ MoveToTarget(model_cpu_arr[i+1], run_time=.7),
+ )
+ else:
+ model_cpu_arr[i].generate_target()
+ model_cpu_arr[i].target.move_to(cpu_left_col_base[-1])
+ input.generate_target()
+ input.target.next_to(model_arr[-1].get_right(), RIGHT+0.02, buff=0.2)
+
+ self.play(
+ Circumscribe(model_arr[-1], color=ORANGE, **circ_kwargs),
+ Circumscribe(cpu_left_col_base[-1], color=ORANGE, **circ_kwargs),
+ Circumscribe(gpu_rect[0], color=ORANGE, **circ_kwargs),
+ )
+
+ self.play(
+ MoveToTarget(model_cpu_arr[i])
+ )
+
+ a = a_c
+ a_c = a_c.copy()
+
+ input.generate_target()
+ input.target.next_to(model_base[-1], RIGHT+0.02, buff=.5)
+ self.play(
+ FadeOut(step_7),
+ FadeOut(a, run_time=.5),
+ )
+
+ step_8 = MarkupText(
+ f'Inference on a model too large for GPU memory\nis successfully completed.', font_size=24
+ )
+ step_8.move_to([2, 2, 0])
+
+ self.play(
+ Write(step_8, run_time=3),
+ MoveToTarget(input)
+ )
+
+ self.wait()
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_0.py b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_0.py
new file mode 100644
index 0000000000000000000000000000000000000000..0128fddc5f4eb7642d70e18617d7dffe8d0bf37c
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_0.py
@@ -0,0 +1,32 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from manim import *
+
+
+class Stage0(Scene):
+ def construct(self):
+ mascot = ImageMobject("mascot_bookie.png")
+ mascot.scale(.35)
+ mascot.move_to([-3.75,-1,0])
+ text = Paragraph(
+ "Distributed Training,\nHugging Face Accelerate,\nand PyTorch DataLoaders\n\nHow do they all interact?",
+ font_size=36,
+ line_spacing=1,
+ alignment="center",
+ weight=BOLD,
+ )
+ text.move_to([1.75,.5,0])
+ self.add(mascot)
+ self.add(text)
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_1.py b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_1.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aea2085be30eeb6f7921bb3039babf73bc7e3d3
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_1.py
@@ -0,0 +1,31 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from manim import *
+
+class Stage01(Scene):
+ def construct(self):
+ mascot = ImageMobject("mascot_bookie.png")
+ mascot.scale(.35)
+ mascot.move_to([-3.75,-1,0])
+ text = Paragraph(
+ "Distributed Training,\nHugging Face Accelerate,\nand PyTorch DataLoaders\n\nHow do they all interact?",
+ font_size=36,
+ line_spacing=1,
+ alignment="center",
+ weight=BOLD,
+ )
+ text.move_to([1.75,.5,0])
+ self.add(mascot)
+ self.add(text)
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_2.py b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c09884600ca7a4fe32eeff9754d180d566809d1
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_2.py
@@ -0,0 +1,176 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from manim import *
+
+
+class Stage2(Scene):
+ def construct(self):
+ # The dataset items
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
+ columns = [
+ VGroup(*[Rectangle(height=0.25,width=0.25,color="green") for i in range(8)]).arrange(RIGHT,buff=0)
+ for j in range(4)
+ ]
+ dataset_recs = VGroup(*columns).arrange(UP, buff=0)
+ dataset_text = Text("Dataset", font_size=24)
+ dataset = Group(dataset_recs,dataset_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ dataset.move_to([-2,0,0])
+ self.add(dataset)
+
+ code = Code(
+ code="dataloader = DataLoader(...)\nfor batch in dataloader():\n\t...",
+ tab_width=4,
+ background="window",
+ language="Python",
+ font="Monospace",
+ font_size=14,
+ corner_radius=.2,
+ insert_line_no=False,
+ line_spacing=.75,
+ style=Code.styles_list[1],
+ )
+ code.move_to([-3.5, 2.5, 0])
+ self.add(code)
+
+ # The dataloader itself
+ dataloader = Group(
+ Rectangle(color="red", height=2, width=2),
+ Text("DataLoader", font_size=24)
+ ).arrange(DOWN, buff=.5, aligned_edge=DOWN)
+
+ sampler = Group(
+ Rectangle(color="blue", height=1, width=1),
+ Text("Sampler", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ dataloader.move_to([1, 0, 0])
+ sampler.move_to([.75,.25,0])
+ self.add(dataloader)
+ self.add(sampler)
+
+ gpu_1 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("GPU 1", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4, 2, 0])
+ gpu_2 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("GPU 2", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4, .5, 0])
+ gpu_3 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("GPU 3", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4, -1, 0])
+ gpu_4 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("GPU 4", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4, -2.5, 0])
+ gpus = [gpu_1[0], gpu_2[0], gpu_3[0], gpu_4[0]]
+ self.add(gpu_1, gpu_2, gpu_3, gpu_4)
+
+ # Animate their existence
+ self.play(
+ Create(gpu_1[0], run_time=0.5),
+ Create(gpu_2[0], run_time=0.5),
+ Create(gpu_3[0], run_time=0.5),
+ Create(gpu_4[0], run_time=0.5),
+ Create(dataset_recs, run_time=1),
+ Create(sampler[0], run_time=1),
+ Create(dataloader[0], run_time=1)
+ )
+
+ step_1 = MarkupText(
+ f"Without any special care, \nthe same data is sent though each sampler, \nand the same samples are spit out on each GPU",
+ font_size=18
+ )
+ step_1.move_to([0, -2.5, 0])
+ self.play(
+ Write(step_1, run_time=4),
+ )
+
+ first_animations = []
+ second_animations = []
+
+
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
+ current_color = colors[0]
+ buff = 0
+ lr_buff = .25
+ old_target = None
+ new_datasets = []
+ for i,data in enumerate(dataset_recs[-1]):
+ if i % 2 == 0:
+ # current_color = colors[i//2]
+ current_color = "BLUE_E"
+ dataset_target = Rectangle(height=0.46/2,width=0.46/2).set_stroke(width=0.).set_fill(current_color, opacity=0.7)
+ dataset_target.move_to(data)
+ dataset_target.generate_target()
+ aligned_edge = ORIGIN
+ if i % 2 == 0:
+ old_target = dataset_target.target
+ buff -= .25
+ aligned_edge = LEFT
+ dataset_target.target.next_to(
+ sampler, buff=buff, direction=UP,
+ aligned_edge=LEFT
+ )
+ else:
+ dataset_target.target.next_to(
+ old_target, direction=RIGHT, buff=0.01,
+ )
+ new_datasets.append(dataset_target)
+ first_animations.append(data.animate(run_time=0.5).set_stroke(current_color))
+ second_animations.append(MoveToTarget(dataset_target, run_time=1.5))
+ self.play(*first_animations)
+ self.play(*second_animations)
+ self.wait()
+
+ move_animation = []
+
+ for j,gpu in enumerate(gpus):
+ buff = 0
+ for i,data in enumerate(new_datasets):
+ if i % 2 == 0:
+ current_color = colors[i//2]
+ if j != 3:
+ data = data.copy()
+ data.generate_target()
+ aligned_edge = ORIGIN
+ if i % 2 == 0:
+ old_target = data.target
+ buff -= .25
+ aligned_edge = LEFT
+ data.target.next_to(
+ gpu, buff=buff, direction=UP,
+ aligned_edge=LEFT
+ )
+ else:
+ data.target.next_to(
+ old_target, direction=RIGHT, buff=0.01,
+ )
+ move_animation.append(MoveToTarget(data, run_time=1.5))
+
+
+ self.play(*move_animation)
+
+ self.remove(step_1)
+ step_2 = MarkupText(
+ f"This behavior is undesireable, because we want\neach GPU to see different data for efficient training.",
+ font_size=18
+ )
+ step_2.move_to([0, -2.5, 0])
+
+ self.play(
+ Write(step_2, run_time=2.5),
+ )
+ self.wait()
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_3.py b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_3.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a561c03dc49ee4b694114dad9deff790b8c0f26
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_3.py
@@ -0,0 +1,34 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from manim import *
+
+class Stage3(Scene):
+ def construct(self):
+ step_1 = MarkupText(
+ f"To combat this, Accelerate employs one of two different\nSampler wrapper methods depending on the scenario:",
+ font_size=24
+ )
+ step_1.move_to([0, 1.5, 0])
+ self.add(step_1)
+ step_2 = MarkupText(
+ f"1. Sharding the dataset before drawing:\n\t● IterableDatasetShard\n\t● BatchSamplerShard",
+ font_size=24,
+ ).next_to(step_1, direction=DOWN, aligned_edge=LEFT)
+ self.add(step_2)
+ step_3 = MarkupText(
+ f"\n\n2. Splitting the batch after drawing:\n\t● DataLoaderDispatcher",
+ font_size=24,
+ ).next_to(step_2, direction=DOWN, aligned_edge=LEFT)
+ self.add(step_3)
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_4.py b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_4.py
new file mode 100644
index 0000000000000000000000000000000000000000..18fd8b58da39d3b522daa69cc51293ad74138a0c
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_4.py
@@ -0,0 +1,52 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from manim import *
+
+class Stage4(Scene):
+ def construct(self):
+
+ step_1 = MarkupText(
+ f"To understand the next part fully, let's define two terms,\n`batch_size` and `global_batch_size`:",
+ font_size=18
+ )
+ step_1.move_to([0, 1.5, 0])
+ # ●
+ step_2 = MarkupText(
+ f"\n\n● `batch_size`: \n\tThis will be defined as the batch size seen on a given\n\t*individual* GPU",
+ font_size=18,
+ ).next_to(step_1, direction=DOWN, aligned_edge=LEFT)
+
+ step_3 = MarkupText(
+ f"\n\n● `global_batch_size`:\n\tThis will be defined as the *total* number of\n\tdifferent items seen in the dataset, across all GPUs",
+ font_size=18,
+ ).next_to(step_2, direction=DOWN, aligned_edge=LEFT)
+
+ step_4 = MarkupText(
+ 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",
+ font_size=18,
+ ).next_to(step_3, direction=DOWN, aligned_edge=LEFT)
+ self.play(
+ Write(step_1, run_time=4),
+ )
+ self.play(
+ Write(step_2, run_time=4)
+ )
+ self.play(
+ Write(step_3, run_time=4)
+ )
+ self.play(
+ Write(step_4, run_time=6)
+ )
+ self.wait()
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_5.py b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_5.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c78286c5dbfb44721b0d3ea9a25c911fe7a19b6
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_5.py
@@ -0,0 +1,203 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from manim import *
+
+class Stage5(Scene):
+ def construct(self):
+ # The dataset items
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
+ columns = [
+ VGroup(*[Rectangle(height=0.25,width=0.25,color=colors[j]) for i in range(8)]).arrange(RIGHT,buff=0)
+ for j in range(4)
+ ]
+ dataset_recs = VGroup(*columns).arrange(UP, buff=0)
+ dataset_text = Text("Dataset", font_size=24)
+ dataset = Group(dataset_recs,dataset_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ dataset.move_to([-2,0,0])
+ self.add(dataset)
+ code = Code(
+ code="# We enable this by default\naccelerator = Accelerator()\ndataloader = DataLoader(...)\ndataloader = accelerator.prepare(dataloader)\nfor batch in dataloader:\n\t...",
+ tab_width=4,
+ background="window",
+ language="Python",
+ font="Monospace",
+ font_size=14,
+ corner_radius=.2,
+ insert_line_no=False,
+ line_spacing=.75,
+ style=Code.styles_list[1],
+ )
+ code.move_to([-3.5, 2.5, 0])
+ self.add(code)
+
+ # The dataloader itself
+
+ sampler_1 = Group(
+ Rectangle(color="blue", height=1, width=1),
+ Text("Sampler GPU 1", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_2 = Group(
+ Rectangle(color="blue", height=1, width=1),
+ Text("Sampler GPU 2", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_3 = Group(
+ Rectangle(color="blue", height=1, width=1),
+ Text("Sampler GPU 3", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_4 = Group(
+ Rectangle(color="blue", height=1, width=1),
+ Text("Sampler GPU 4", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_1.move_to([2,2,0])
+ sampler_2.move_to([2,.5,0])
+ sampler_3.move_to([2,-1.,0])
+ sampler_4.move_to([2,-2.5,0])
+ self.add(sampler_1, sampler_2, sampler_3, sampler_4)
+ samplers = [sampler_1[0], sampler_2[0], sampler_3[0], sampler_4[0]]
+
+ gpu_1 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("Output GPU 1", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, 2, 0])
+ gpu_2 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("Output GPU 2", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, .5, 0])
+ gpu_3 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("Output GPU 3", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -1, 0])
+ gpu_4 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("Output GPU 4", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -2.5, 0])
+ gpus = [gpu_1[0], gpu_2[0], gpu_3[0], gpu_4[0]]
+ self.add(gpu_1, gpu_2, gpu_3, gpu_4)
+
+ # Animate their existence
+ self.play(
+ Create(gpu_1[0], run_time=1),
+ Create(gpu_2[0], run_time=1),
+ Create(gpu_3[0], run_time=1),
+ Create(gpu_4[0], run_time=1),
+ Create(dataset_recs, run_time=1),
+ Create(sampler_1[0], run_time=1),
+ Create(sampler_2[0], run_time=1),
+ Create(sampler_3[0], run_time=1),
+ Create(sampler_4[0], run_time=1),
+ )
+
+ first_animations = []
+ second_animations = []
+
+
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
+ current_color = colors[0]
+ buff = 0
+ lr_buff = .25
+ old_target = None
+ new_datasets = []
+ for i,row_data in enumerate(dataset_recs):
+ new_row = []
+ current_color = colors[i]
+ if i == 0:
+ idx = -3
+ elif i == 1:
+ idx = -2
+ elif i == 2:
+ idx = -1
+ elif i == 3:
+ idx = 0
+ for j,indiv_data in enumerate(row_data):
+ dataset_target = Rectangle(height=0.46/2,width=0.46/2).set_stroke(width=0.).set_fill(current_color, opacity=0.7)
+ dataset_target.move_to(indiv_data)
+ dataset_target.generate_target()
+ aligned_edge = ORIGIN
+ if j % 8 == 0:
+ aligned_edge = LEFT
+ dataset_target.target.next_to(
+ samplers[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
+ )
+ dataset_target.target.set_x(dataset_target.target.get_x())
+ elif j % 4 == 0:
+ old_target = dataset_target.target
+ dataset_target.target.next_to(
+ samplers[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
+ )
+ dataset_target.target.set_x(dataset_target.target.get_x())
+ dataset_target.target.set_y(dataset_target.target.get_y()-.25)
+ else:
+ dataset_target.target.next_to(
+ old_target, direction=RIGHT, buff=0.02,
+ )
+ old_target = dataset_target.target
+ new_row.append(dataset_target)
+ first_animations.append(indiv_data.animate(run_time=0.5).set_stroke(current_color))
+ second_animations.append(MoveToTarget(dataset_target, run_time=1.5))
+
+ new_datasets.append(new_row)
+ step_1 = MarkupText(
+ 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.",
+ font_size=18
+ )
+ step_1.move_to([-2.5, -2, 0])
+
+ self.play(
+ Write(step_1, run_time=3),
+ )
+ self.play(
+ *first_animations,
+ )
+ self.play(*second_animations)
+ self.wait(duration=.5)
+
+ move_animation = []
+ import random
+ for i,row in enumerate(new_datasets):
+ # row = [row[k] for k in random.sample(range(8), 8)]
+ current_color = colors[i]
+ if i == 0:
+ idx = -3
+ elif i == 1:
+ idx = -2
+ elif i == 2:
+ idx = -1
+ elif i == 3:
+ idx = 0
+ for j,indiv_data in enumerate(row):
+ indiv_data.generate_target()
+ aligned_edge = ORIGIN
+ if j % 8 == 0:
+ aligned_edge = LEFT
+ indiv_data.target.next_to(
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
+ )
+ indiv_data.target.set_x(indiv_data.target.get_x())
+ elif j % 4 == 0:
+ indiv_data.target.next_to(
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
+ )
+ indiv_data.target.set_x(indiv_data.target.get_x())
+ indiv_data.target.set_y(indiv_data.target.get_y()-.25)
+ else:
+ indiv_data.target.next_to(
+ old_target, direction=RIGHT, buff=0.02,
+ )
+ old_target = indiv_data.target
+ move_animation.append(MoveToTarget(indiv_data, run_time=1.5))
+
+ self.play(*move_animation)
+ self.wait()
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_6.py b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_6.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ac5d3904ffaf9e1b6e2ffb12d6254727aca422e
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_6.py
@@ -0,0 +1,193 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from manim import *
+
+
+class Stage6(Scene):
+ def construct(self):
+ # The dataset items
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
+ columns = [
+ VGroup(*[Rectangle(height=0.25,width=0.25,color=colors[j]) for i in range(8)]).arrange(RIGHT,buff=0)
+ for j in range(4)
+ ]
+ dataset_recs = VGroup(*columns).arrange(UP, buff=0)
+ dataset_text = Text("Dataset", font_size=24)
+ dataset = Group(dataset_recs,dataset_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ dataset.move_to([-2,0,0])
+ self.add(dataset)
+ code = Code(
+ code="# We enable this by default\naccelerator = Accelerator()\ndataloader = DataLoader(..., shuffle=True)\ndataloader = accelerator.prepare(dataloader)\nfor batch in dataloader:\n\t...",
+ tab_width=4,
+ background="window",
+ language="Python",
+ font="Monospace",
+ font_size=14,
+ corner_radius=.2,
+ insert_line_no=False,
+ line_spacing=.75,
+ style=Code.styles_list[1],
+ )
+ code.move_to([-3.5, 2.5, 0])
+ self.add(code)
+
+ # The dataloader itself
+
+ sampler_1 = Group(
+ Rectangle(color="blue", height=1, width=1),
+ Text("Sampler GPU 1", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_2 = Group(
+ Rectangle(color="blue", height=1, width=1),
+ Text("Sampler GPU 2", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_3 = Group(
+ Rectangle(color="blue", height=1, width=1),
+ Text("Sampler GPU 3", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_4 = Group(
+ Rectangle(color="blue", height=1, width=1),
+ Text("Sampler GPU 4", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_1.move_to([2,2,0])
+ sampler_2.move_to([2,.5,0])
+ sampler_3.move_to([2,-1.,0])
+ sampler_4.move_to([2,-2.5,0])
+ self.add(sampler_1, sampler_2, sampler_3, sampler_4)
+ samplers = [sampler_1[0], sampler_2[0], sampler_3[0], sampler_4[0]]
+
+ gpu_1 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("Output GPU 1", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, 2, 0])
+ gpu_2 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("Output GPU 2", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, .5, 0])
+ gpu_3 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("Output GPU 3", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -1, 0])
+ gpu_4 = Group(
+ Rectangle(color="white", height=1, width=1),
+ Text("Output GPU 4", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -2.5, 0])
+ gpus = [gpu_1[0], gpu_2[0], gpu_3[0], gpu_4[0]]
+ self.add(gpu_1, gpu_2, gpu_3, gpu_4)
+
+
+ first_animations = []
+ second_animations = []
+
+
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
+ current_color = colors[0]
+ buff = 0
+ lr_buff = .25
+ old_target = None
+ new_datasets = []
+ for i,row_data in enumerate(dataset_recs):
+ new_row = []
+ current_color = colors[i]
+ if i == 0:
+ idx = -3
+ elif i == 1:
+ idx = -2
+ elif i == 2:
+ idx = -1
+ elif i == 3:
+ idx = 0
+ for j,indiv_data in enumerate(row_data):
+ dataset_target = Rectangle(height=0.46/2,width=0.46/2).set_stroke(width=0.).set_fill(current_color, opacity=0.7)
+ dataset_target.move_to(indiv_data)
+ dataset_target.generate_target()
+ aligned_edge = ORIGIN
+ if j % 8 == 0:
+ aligned_edge = LEFT
+ old_target = dataset_target.target
+ dataset_target.target.next_to(
+ samplers[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
+ )
+ dataset_target.target.set_x(dataset_target.target.get_x())
+ elif j % 4 == 0:
+ old_target = dataset_target.target
+ dataset_target.target.next_to(
+ samplers[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
+ )
+ dataset_target.target.set_x(dataset_target.target.get_x())
+ dataset_target.target.set_y(dataset_target.target.get_y()-.25)
+ else:
+ dataset_target.target.next_to(
+ old_target, direction=RIGHT, buff=0.02,
+ )
+ old_target = dataset_target.target
+ new_row.append(dataset_target)
+ first_animations.append(indiv_data.animate(run_time=0.5).set_stroke(current_color))
+ second_animations.append(MoveToTarget(dataset_target, run_time=1.5))
+
+ new_datasets.append(new_row)
+ step_1 = MarkupText(
+ f"During shuffling, each mini-batch's\noutput order will be modified",
+ font_size=18
+ )
+ step_1.move_to([-1.5, -2, 0])
+
+ self.play(
+ Write(step_1, run_time=3),
+ )
+ self.play(
+ *first_animations,
+ )
+ self.play(*second_animations)
+ self.wait(duration=.5)
+
+ move_animation = []
+ import random
+ for i,row in enumerate(new_datasets):
+ row = [row[k] for k in random.sample(range(8), 8)]
+ current_color = colors[i]
+ if i == 0:
+ idx = -3
+ elif i == 1:
+ idx = -2
+ elif i == 2:
+ idx = -1
+ elif i == 3:
+ idx = 0
+ for j,indiv_data in enumerate(row):
+ indiv_data.generate_target()
+ aligned_edge = ORIGIN
+ if j % 8 == 0:
+ aligned_edge = LEFT
+ indiv_data.target.next_to(
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
+ )
+ indiv_data.target.set_x(indiv_data.target.get_x())
+ elif j % 4 == 0:
+ indiv_data.target.next_to(
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.02, direction=RIGHT+DOWN,
+ )
+ indiv_data.target.set_x(indiv_data.target.get_x())
+ indiv_data.target.set_y(indiv_data.target.get_y()-.25)
+ else:
+ indiv_data.target.next_to(
+ old_target, direction=RIGHT, buff=0.02,
+ )
+ old_target = indiv_data.target
+ move_animation.append(MoveToTarget(indiv_data, run_time=1.5))
+
+ self.play(*move_animation)
+ self.wait()
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_7.py b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_7.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec1b952a9360c0a94f500746fa1ade38d065eb45
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/manim_animations/dataloaders/stage_7.py
@@ -0,0 +1,182 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from manim import *
+
+class Stage7(Scene):
+ def construct(self):
+ # The dataset items
+ code = Code(
+ code="accelerator = Accelerator(dispatch_batches=True)\ndataloader = DataLoader(...)\ndataloader = accelerator.prepare(dataloader)\nfor batch in dataloader:\n\t...",
+ tab_width=4,
+ background="window",
+ language="Python",
+ font="Monospace",
+ font_size=14,
+ corner_radius=.2,
+ insert_line_no=False,
+ line_spacing=.75,
+ style=Code.styles_list[1],
+ )
+ code.move_to([-3.5, 2.5, 0])
+ self.add(code)
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
+ fill = Rectangle(height=0.46,width=0.46).set_stroke(width=0)
+ columns = [
+ VGroup(*[Rectangle(height=0.25,width=0.25,color=colors[j]) for i in range(8)]).arrange(RIGHT,buff=0)
+ for j in range(4)
+ ]
+ dataset_recs = VGroup(*columns).arrange(UP, buff=0)
+ dataset_text = Text("Dataset", font_size=24)
+ dataset = Group(dataset_recs,dataset_text).arrange(DOWN, buff=0.5, aligned_edge=DOWN)
+ dataset.move_to([-2,0,0])
+ self.add(dataset)
+
+ # The dataloader itself
+
+ sampler_1 = Group(
+ Rectangle(color="blue", height=1.02, width=1.02),
+ Text("Sampler GPU 1", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_2 = Group(
+ Rectangle(color="blue", height=1.02, width=1.02),
+ Text("Sampler GPU 2", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_3 = Group(
+ Rectangle(color="blue", height=1.02, width=1.02),
+ Text("Sampler GPU 3", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_4 = Group(
+ Rectangle(color="blue", height=1.02, width=1.02),
+ Text("Sampler GPU 4", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN)
+ sampler_1.move_to([2,2,0])
+ sampler_2.move_to([2,.5,0])
+ sampler_3.move_to([2,-1.,0])
+ sampler_4.move_to([2,-2.5,0])
+ self.add(sampler_1, sampler_2, sampler_3, sampler_4)
+ samplers = [sampler_1[0], sampler_2[0], sampler_3[0], sampler_4[0]]
+
+ gpu_1 = Group(
+ Rectangle(color="white", height=1.02, width=.98),
+ Text("Output GPU 1", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, 2, 0])
+ gpu_2 = Group(
+ Rectangle(color="white", height=1.02, width=.98),
+ Text("Output GPU 2", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, .5, 0])
+ gpu_3 = Group(
+ Rectangle(color="white", height=1.02, width=.98),
+ Text("Output GPU 3", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -1, 0])
+ gpu_4 = Group(
+ Rectangle(color="white", height=1.02, width=.98),
+ Text("Output GPU 4", font_size=12)
+ ).arrange(DOWN, buff=.25, aligned_edge=DOWN).move_to([4.5, -2.5, 0])
+ gpus = [gpu_1[0], gpu_2[0], gpu_3[0], gpu_4[0]]
+ self.add(gpu_1, gpu_2, gpu_3, gpu_4)
+
+ step_1 = MarkupText(
+ 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.",
+ font_size=18
+ )
+ step_1.move_to([-2.5, -2, 0])
+
+ self.play(
+ Write(step_1, run_time=3.5),
+ )
+
+ first_animations = []
+ second_animations = []
+
+
+ colors = ["BLUE_E", "DARK_BROWN", "GOLD_E", "GRAY_A"]
+ current_color = colors[0]
+ ud_buff = 0.01
+ lr_buff = 0.01
+ old_target = None
+ new_datasets = []
+ for i,row_data in enumerate(dataset_recs):
+ new_row = []
+ current_color = colors[i]
+
+ for j,indiv_data in enumerate(row_data):
+ dataset_target = Rectangle(height=0.46/4,width=0.46/2).set_stroke(width=0.).set_fill(current_color, opacity=0.7)
+ dataset_target.move_to(indiv_data)
+ dataset_target.generate_target()
+ aligned_edge = ORIGIN
+ if j % 8 == 0:
+ aligned_edge = LEFT
+ dataset_target.target.next_to(
+ samplers[0].get_corner(DOWN+LEFT), buff=0.0125, direction=RIGHT+UP,
+ )
+ dataset_target.target.set_x(dataset_target.target.get_x())
+ dataset_target.target.set_y(dataset_target.target.get_y() + (.25 * i))
+ elif j % 4 == 0:
+ old_target = dataset_target.target
+ dataset_target.target.next_to(
+ samplers[0].get_corner(DOWN+LEFT), buff=0.0125, direction=RIGHT+UP,
+ )
+ dataset_target.target.set_x(dataset_target.target.get_x())
+ dataset_target.target.set_y(dataset_target.target.get_y()+.125 + (.25 * i))
+ else:
+ dataset_target.target.next_to(
+ old_target, direction=RIGHT, buff=0.0125,
+ )
+ old_target = dataset_target.target
+ new_row.append(dataset_target)
+ first_animations.append(indiv_data.animate(run_time=0.5).set_stroke(current_color))
+ second_animations.append(MoveToTarget(dataset_target, run_time=1.5))
+
+ new_datasets.append(new_row)
+ self.play(
+ *first_animations,
+ )
+ self.play(*second_animations)
+ move_animation = []
+ for i,row in enumerate(new_datasets):
+ current_color = colors[i]
+ if i == 0:
+ idx = -3
+ elif i == 1:
+ idx = -2
+ elif i == 2:
+ idx = -1
+ elif i == 3:
+ idx = 0
+ for j,indiv_data in enumerate(row):
+ indiv_data.generate_target()
+ indiv_data.animate.stretch_to_fit_height(0.46/2)
+ aligned_edge = ORIGIN
+ if j % 8 == 0:
+ aligned_edge = LEFT
+ indiv_data.target.next_to(
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.01, direction=RIGHT+DOWN,
+ )
+ indiv_data.target.set_x(indiv_data.target.get_x())
+ indiv_data.target.set_y(indiv_data.target.get_y()-.25)
+ elif j % 4 == 0:
+ indiv_data.target.next_to(
+ gpus[abs(idx)].get_corner(UP+LEFT), buff=.01, direction=RIGHT+DOWN,
+ )
+ indiv_data.target.set_x(indiv_data.target.get_x())
+ else:
+ indiv_data.target.next_to(
+ old_target, direction=RIGHT, buff=0.01,
+ )
+ old_target = indiv_data.target
+ move_animation.append(MoveToTarget(indiv_data, run_time=1.5))
+
+ self.play(*move_animation)
+ self.wait()
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/pyproject.toml b/tasks/tasksmith-5db757e91a6e/tests/source/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..96d5ffb5ef7dda491bb7bcfad5264de07cfa7681
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/pyproject.toml
@@ -0,0 +1,43 @@
+[tool.ruff]
+line-length = 119
+target-version = "py38"
+
+[tool.ruff.lint]
+preview = true
+extend-select = [
+ "B009", # static getattr
+ "B010", # static setattr
+ "CPY", # Copyright
+ "E", # PEP8 errors
+ "F", # PEP8 formatting
+ "I", # Import sorting
+ "TID251", # Banned API
+ "UP", # Pyupgrade
+ "W", # PEP8 warnings
+]
+ignore = [
+ "E501", # Line length (handled by ruff-format)
+ "E741", # Ambiguous variable name
+ "W605", # Invalid escape sequence
+ "UP007", # X | Y type annotations
+]
+
+[tool.ruff.lint.per-file-ignores]
+"__init__.py" = [
+ "F401", # Ignore seemingly unused imports (they're meant for re-export)
+]
+"manim_animations/*" = ["ALL"]
+
+[tool.ruff.lint.isort]
+lines-after-imports = 2
+known-first-party = ["accelerate"]
+
+[tool.ruff.format]
+exclude = [
+ "manim_animations/*"
+]
+
+[tool.ruff.lint.flake8-tidy-imports.banned-api]
+"os.getenv".msg = "Use os.environ instead"
+"os.putenv".msg = "Use os.environ instead"
+"os.unsetenv".msg = "Use os.environ instead"
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/setup.py b/tasks/tasksmith-5db757e91a6e/tests/source/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8c666e9367a33b670a22f04acd6eb1f247b0a0f
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/setup.py
@@ -0,0 +1,122 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from setuptools import find_packages, setup
+
+
+extras = {}
+extras["quality"] = [
+ "black ~= 23.1", # hf-doc-builder has a hidden dependency on `black`
+ "hf-doc-builder >= 0.3.0",
+ "ruff ~= 0.6.4",
+]
+extras["docs"] = []
+extras["test_prod"] = ["pytest>=7.2.0,<=8.0.0", "pytest-xdist", "pytest-subtests", "parameterized"]
+extras["test_dev"] = [
+ "datasets",
+ "diffusers",
+ "evaluate",
+ "torchdata>=0.8.0",
+ "torchpippy>=0.2.0",
+ "transformers",
+ "scipy",
+ "scikit-learn",
+ "tqdm",
+ "bitsandbytes",
+ "timm",
+]
+extras["testing"] = extras["test_prod"] + extras["test_dev"]
+extras["deepspeed"] = ["deepspeed"]
+extras["rich"] = ["rich"]
+
+extras["test_trackers"] = ["wandb", "comet-ml", "tensorboard", "dvclive"]
+extras["dev"] = extras["quality"] + extras["testing"] + extras["rich"]
+
+extras["sagemaker"] = [
+ "sagemaker", # boto3 is a required package in sagemaker
+]
+
+setup(
+ name="accelerate",
+ version="0.35.0.dev0",
+ description="Accelerate",
+ long_description=open("README.md", encoding="utf-8").read(),
+ long_description_content_type="text/markdown",
+ keywords="deep learning",
+ license="Apache",
+ author="The HuggingFace team",
+ author_email="zach.mueller@huggingface.co",
+ url="https://github.com/huggingface/accelerate",
+ package_dir={"": "src"},
+ packages=find_packages("src"),
+ entry_points={
+ "console_scripts": [
+ "accelerate=accelerate.commands.accelerate_cli:main",
+ "accelerate-config=accelerate.commands.config:main",
+ "accelerate-estimate-memory=accelerate.commands.estimate:main",
+ "accelerate-launch=accelerate.commands.launch:main",
+ "accelerate-merge-weights=accelerate.commands.merge:main",
+ ]
+ },
+ python_requires=">=3.8.0",
+ install_requires=[
+ "numpy>=1.17,<3.0.0",
+ "packaging>=20.0",
+ "psutil",
+ "pyyaml",
+ "torch>=1.10.0",
+ "huggingface_hub>=0.21.0",
+ "safetensors>=0.4.3",
+ ],
+ extras_require=extras,
+ classifiers=[
+ "Development Status :: 5 - Production/Stable",
+ "Intended Audience :: Developers",
+ "Intended Audience :: Education",
+ "Intended Audience :: Science/Research",
+ "License :: OSI Approved :: Apache Software License",
+ "Operating System :: OS Independent",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.8",
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
+ ],
+)
+
+# Release checklist
+# 1. Checkout the release branch (for a patch the current release branch, for a new minor version, create one):
+# git checkout -b vXX.xx-release
+# The -b is only necessary for creation (so remove it when doing a patch)
+# 2. Change the version in __init__.py and setup.py to the proper value.
+# 3. Commit these changes with the message: "Release: v"
+# 4. Add a tag in git to mark the release:
+# git tag v -m 'Adds tag v for pypi'
+# Push the tag and release commit to git: git push --tags origin vXX.xx-release
+# 5. Run the following commands in the top-level directory:
+# rm -rf dist
+# rm -rf build
+# python setup.py bdist_wheel
+# python setup.py sdist
+# 6. Upload the package to the pypi test server first:
+# twine upload dist/* -r testpypi
+# 7. Check that you can install it in a virtualenv by running:
+# pip install accelerate
+# pip uninstall accelerate
+# pip install -i https://testpypi.python.org/pypi accelerate
+# accelerate env
+# accelerate test
+# 8. Upload the final version to actual pypi:
+# twine upload dist/* -r pypi
+# 9. Add release notes to the tag in github once everything is looking hunky-dory.
+# 10. Go back to the main branch and update the version in __init__.py, setup.py to the new version ".dev" and push to
+# main.
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/__init__.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc36acf7fec37d74e62e37fd0edda2d01b300488
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/__init__.py
@@ -0,0 +1,50 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+__version__ = "0.35.0.dev0"
+
+from .accelerator import Accelerator
+from .big_modeling import (
+ cpu_offload,
+ cpu_offload_with_hook,
+ disk_offload,
+ dispatch_model,
+ init_empty_weights,
+ init_on_device,
+ load_checkpoint_and_dispatch,
+)
+from .data_loader import skip_first_batches
+from .inference import prepare_pippy
+from .launchers import debug_launcher, notebook_launcher
+from .state import PartialState
+from .utils import (
+ AutocastKwargs,
+ DataLoaderConfiguration,
+ DDPCommunicationHookType,
+ DeepSpeedPlugin,
+ DistributedDataParallelKwargs,
+ DistributedType,
+ FullyShardedDataParallelPlugin,
+ GradScalerKwargs,
+ InitProcessGroupKwargs,
+ ProfileKwargs,
+ find_executable_batch_size,
+ infer_auto_device_map,
+ is_rich_available,
+ load_checkpoint_in_model,
+ synchronize_rng_states,
+)
+
+
+if is_rich_available():
+ from .utils import rich
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/accelerator.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/accelerator.py
new file mode 100644
index 0000000000000000000000000000000000000000..de0ce0f374dff17a66c3fe4224148e498b1f8982
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/accelerator.py
@@ -0,0 +1,3609 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import contextlib
+import functools
+import json
+import math
+import os
+import re
+import shutil
+import sys
+import warnings
+from collections import OrderedDict
+from contextlib import contextmanager
+from functools import partial
+from types import MethodType
+from typing import Any, Callable, Union
+
+import torch
+import torch.utils.hooks as hooks
+from huggingface_hub import split_torch_state_dict_into_shards
+from packaging import version
+
+from .checkpointing import load_accelerator_state, load_custom_state, save_accelerator_state, save_custom_state
+from .data_loader import DataLoaderDispatcher, prepare_data_loader, skip_first_batches
+from .hooks import AlignDevicesHook
+from .logging import get_logger
+from .optimizer import AcceleratedOptimizer
+from .scheduler import AcceleratedScheduler
+from .state import AcceleratorState, GradientState, PartialState
+from .tracking import LOGGER_TYPE_TO_CLASS, GeneralTracker, filter_trackers
+from .utils import (
+ MODEL_NAME,
+ SAFE_WEIGHTS_INDEX_NAME,
+ SAFE_WEIGHTS_NAME,
+ SAFE_WEIGHTS_PATTERN_NAME,
+ WEIGHTS_INDEX_NAME,
+ WEIGHTS_NAME,
+ WEIGHTS_PATTERN_NAME,
+ AutocastKwargs,
+ DataLoaderConfiguration,
+ DeepSpeedPlugin,
+ DistributedDataParallelKwargs,
+ DistributedType,
+ DynamoBackend,
+ FP8RecipeKwargs,
+ FullyShardedDataParallelPlugin,
+ GradientAccumulationPlugin,
+ GradScalerKwargs,
+ InitProcessGroupKwargs,
+ KwargsHandler,
+ LoggerType,
+ MegatronLMPlugin,
+ PrecisionType,
+ ProfileKwargs,
+ ProjectConfiguration,
+ RNGType,
+ TorchDynamoPlugin,
+ apply_fp8_autowrap,
+ check_os_kernel,
+ clean_state_dict_for_safetensors,
+ compare_versions,
+ convert_model,
+ convert_outputs_to_fp32,
+ extract_model_from_parallel,
+ gather,
+ gather_object,
+ get_mixed_precision_context_manager,
+ get_pretty_name,
+ is_bf16_available,
+ is_bitsandbytes_multi_backend_available,
+ is_deepspeed_available,
+ is_ipex_available,
+ is_lomo_available,
+ is_megatron_lm_available,
+ is_mlu_available,
+ is_msamp_available,
+ is_musa_available,
+ is_npu_available,
+ is_torch_version,
+ is_torch_xla_available,
+ is_transformer_engine_available,
+ is_xpu_available,
+ load_fsdp_model,
+ load_fsdp_optimizer,
+ pad_across_processes,
+ parse_choice_from_env,
+ recursively_apply,
+ reduce,
+ release_memory,
+ save,
+ save_fsdp_model,
+ save_fsdp_optimizer,
+ wait_for_everyone,
+)
+from .utils.constants import FSDP_PYTORCH_VERSION, PROFILE_PATTERN_NAME
+from .utils.modeling import get_state_dict_offloaded_model
+from .utils.other import is_compiled_module
+
+
+if is_deepspeed_available():
+ from .utils import (
+ DeepSpeedEngineWrapper,
+ DeepSpeedOptimizerWrapper,
+ DeepSpeedSchedulerWrapper,
+ DummyOptim,
+ DummyScheduler,
+ )
+
+if is_megatron_lm_available():
+ from .utils import (
+ MegatronEngine,
+ MegatronLMDummyDataLoader,
+ MegatronLMDummyScheduler,
+ MegatronLMOptimizerWrapper,
+ MegatronLMSchedulerWrapper,
+ megatron_lm_initialize,
+ megatron_lm_prepare_data_loader,
+ megatron_lm_prepare_model_optimizer_scheduler,
+ )
+
+from torch.distributed.algorithms.join import Join
+
+
+if is_torch_xla_available():
+ import torch_xla.amp as xamp
+ import torch_xla.core.xla_model as xm
+ import torch_xla.distributed.xla_multiprocessing as xmp
+
+
+if is_npu_available(check_device=False):
+ import torch_npu # noqa: F401
+
+
+try:
+ from torch.optim.lr_scheduler import LRScheduler
+except ImportError:
+ from torch.optim.lr_scheduler import _LRScheduler as LRScheduler
+
+logger = get_logger(__name__)
+
+# Sentinel values for defaults
+_split_batches = object()
+_dispatch_batches = object()
+_even_batches = object()
+_use_seedable_sampler = object()
+
+
+class Accelerator:
+ """
+ Creates an instance of an accelerator for distributed training (on multi-GPU, TPU) or mixed precision training.
+
+ Args:
+ device_placement (`bool`, *optional*, defaults to `True`):
+ Whether or not the accelerator should put objects on device (tensors yielded by the dataloader, model,
+ etc...).
+ mixed_precision (`str`, *optional*):
+ Whether or not to use mixed precision training. Choose from 'no','fp16','bf16' or 'fp8'. Will default to
+ the value in the environment variable `ACCELERATE_MIXED_PRECISION`, which will use the default value in the
+ accelerate config of the current system or the flag passed with the `accelerate.launch` command. 'fp8'
+ requires the installation of transformers-engine.
+ gradient_accumulation_steps (`int`, *optional*, default to 1):
+ The number of steps that should pass before gradients are accumulated. A number > 1 should be combined with
+ `Accelerator.accumulate`. If not passed, will default to the value in the environment variable
+ `ACCELERATE_GRADIENT_ACCUMULATION_STEPS`. Can also be configured through a `GradientAccumulationPlugin`.
+ cpu (`bool`, *optional*):
+ Whether or not to force the script to execute on CPU. Will ignore GPU available if set to `True` and force
+ the execution on one process only.
+ dataloader_config (`DataLoaderConfiguration`, *optional*):
+ A configuration for how the dataloaders should be handled in distributed scenarios.
+ deepspeed_plugin ([`~utils.DeepSpeedPlugin`] or dict of `str`: [`~utils.DeepSpeedPlugin`], *optional*):
+ Tweak your DeepSpeed related args using this argument. This argument is optional and can be configured
+ directly using *accelerate config*. If using multiple plugins, use the configured `key` property of each
+ plugin to access them from `accelerator.state.get_deepspeed_plugin(key)`. Alias for `deepspeed_plugins`.
+ fsdp_plugin ([`~utils.FullyShardedDataParallelPlugin`], *optional*):
+ Tweak your FSDP related args using this argument. This argument is optional and can be configured directly
+ using *accelerate config*
+ megatron_lm_plugin ([`~utils.MegatronLMPlugin`], *optional*):
+ Tweak your MegatronLM related args using this argument. This argument is optional and can be configured
+ directly using *accelerate config*
+ rng_types (list of `str` or [`~utils.RNGType`]):
+ The list of random number generators to synchronize at the beginning of each iteration in your prepared
+ dataloaders. Should be one or several of:
+
+ - `"torch"`: the base torch random number generator
+ - `"cuda"`: the CUDA random number generator (GPU only)
+ - `"xla"`: the XLA random number generator (TPU only)
+ - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your
+ dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type.
+
+ Will default to `["torch"]` for PyTorch versions <=1.5.1 and `["generator"]` for PyTorch versions >= 1.6.
+ log_with (list of `str`, [`~utils.LoggerType`] or [`~tracking.GeneralTracker`], *optional*):
+ A list of loggers to be setup for experiment tracking. Should be one or several of:
+
+ - `"all"`
+ - `"tensorboard"`
+ - `"wandb"`
+ - `"comet_ml"`
+ If `"all"` is selected, will pick up all available trackers in the environment and initialize them. Can
+ also accept implementations of `GeneralTracker` for custom trackers, and can be combined with `"all"`.
+ project_config ([`~utils.ProjectConfiguration`], *optional*):
+ A configuration for how saving the state can be handled.
+ project_dir (`str`, `os.PathLike`, *optional*):
+ A path to a directory for storing data such as logs of locally-compatible loggers and potentially saved
+ checkpoints.
+ step_scheduler_with_optimizer (`bool`, *optional*, defaults to `True`):
+ Set `True` if the learning rate scheduler is stepped at the same time as the optimizer, `False` if only
+ done under certain circumstances (at the end of each epoch, for instance).
+ kwargs_handlers (list of [`~utils.KwargsHandler`], *optional*)
+ A list of [`~utils.KwargsHandler`] to customize how the objects related to distributed training, profiling
+ or mixed precision are created. See [kwargs](kwargs) for more information.
+ dynamo_backend (`str` or [`~utils.DynamoBackend`], *optional*, defaults to `"no"`):
+ Set to one of the possible dynamo backends to optimize your training with torch dynamo.
+ gradient_accumulation_plugin ([`~utils.GradientAccumulationPlugin`], *optional*):
+ A configuration for how gradient accumulation should be handled, if more tweaking than just the
+ `gradient_accumulation_steps` is needed.
+
+ **Available attributes:**
+
+ - **device** (`torch.device`) -- The device to use.
+ - **distributed_type** ([`~utils.DistributedType`]) -- The distributed training configuration.
+ - **local_process_index** (`int`) -- The process index on the current machine.
+ - **mixed_precision** (`str`) -- The configured mixed precision mode.
+ - **num_processes** (`int`) -- The total number of processes used for training.
+ - **optimizer_step_was_skipped** (`bool`) -- Whether or not the optimizer update was skipped (because of
+ gradient overflow in mixed precision), in which
+ case the learning rate should not be changed.
+ - **process_index** (`int`) -- The overall index of the current process among all processes.
+ - **state** ([`~state.AcceleratorState`]) -- The distributed setup state.
+ - **sync_gradients** (`bool`) -- Whether the gradients are currently being synced across all processes.
+ - **use_distributed** (`bool`) -- Whether the current configuration is for distributed training.
+ """
+
+ def __init__(
+ self,
+ device_placement: bool = True,
+ split_batches: bool = _split_batches,
+ mixed_precision: PrecisionType | str | None = None,
+ gradient_accumulation_steps: int = 1,
+ cpu: bool = False,
+ dataloader_config: DataLoaderConfiguration | None = None,
+ deepspeed_plugin: DeepSpeedPlugin | dict[str, DeepSpeedPlugin] | None = None,
+ fsdp_plugin: FullyShardedDataParallelPlugin | None = None,
+ megatron_lm_plugin: MegatronLMPlugin | None = None,
+ rng_types: list[str | RNGType] | None = None,
+ log_with: str | LoggerType | GeneralTracker | list[str | LoggerType | GeneralTracker] | None = None,
+ project_dir: str | os.PathLike | None = None,
+ project_config: ProjectConfiguration | None = None,
+ gradient_accumulation_plugin: GradientAccumulationPlugin | None = None,
+ step_scheduler_with_optimizer: bool = True,
+ kwargs_handlers: list[KwargsHandler] | None = None,
+ dynamo_backend: DynamoBackend | str | None = None,
+ deepspeed_plugins: DeepSpeedPlugin | dict[str, DeepSpeedPlugin] | None = None,
+ ):
+ self.trackers = []
+ if project_config is not None:
+ self.project_configuration = project_config
+ else:
+ self.project_configuration = ProjectConfiguration(project_dir=project_dir)
+ if project_dir is not None and self.project_dir is None:
+ self.project_configuration.set_directories(project_dir)
+ if mixed_precision is not None:
+ mixed_precision = str(mixed_precision)
+ if mixed_precision not in PrecisionType:
+ raise ValueError(
+ f"Unknown mixed_precision mode: {mixed_precision}. Choose between {PrecisionType.list()}"
+ )
+
+ dynamo_plugin = TorchDynamoPlugin() if dynamo_backend is None else TorchDynamoPlugin(backend=dynamo_backend)
+
+ if deepspeed_plugins is not None and deepspeed_plugin is not None:
+ raise ValueError("You cannot pass in both `deepspeed_plugins` and `deepspeed_plugin`.")
+ elif deepspeed_plugin is not None:
+ deepspeed_plugins = deepspeed_plugin
+
+ if deepspeed_plugins is None:
+ # First check if we're creating another `Accelerator` w/o setting `deepspeed_plugin`
+ if PartialState._shared_state != {} and PartialState().distributed_type == DistributedType.DEEPSPEED:
+ deepspeed_plugins = AcceleratorState().deepspeed_plugins
+ else:
+ # init from env variables
+ deepspeed_plugins = (
+ DeepSpeedPlugin() if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true" else None
+ )
+ else:
+ # If we're creating a second `Accelerator`, users shouldn't be passing in a `deepspeed_plugin`
+ if (
+ PartialState().distributed_type == DistributedType.DEEPSPEED
+ and AcceleratorState._shared_state != {}
+ and AcceleratorState().deepspeed_plugins is not None
+ ):
+ raise NotImplementedError(
+ "You cannot pass in a `deepspeed_plugin` when creating a second `Accelerator`. "
+ "Please make sure the first `Accelerator` is initialized with all the plugins you want to use."
+ )
+ if isinstance(deepspeed_plugins, dict):
+ for plugin in deepspeed_plugins.values():
+ if not isinstance(plugin, DeepSpeedPlugin):
+ raise TypeError("`deepspeed_plugin` must be a DeepSpeedPlugin object.")
+
+ if deepspeed_plugins is not None:
+ os.environ["ACCELERATE_USE_DEEPSPEED"] = "true" # use DeepSpeed if plugin is provided
+ if not is_deepspeed_available():
+ raise ImportError("DeepSpeed is not installed => run `pip install deepspeed` or build it from source.")
+ if is_mlu_available():
+ if compare_versions("deepspeed-mlu", "<", "0.10.1"):
+ raise ImportError("DeepSpeed MLU version must be >= 0.10.1. Please update DeepSpeed MLU.")
+ elif is_musa_available():
+ if compare_versions("deepspeed", ">", "0.14.3"):
+ raise ImportError("DeepSpeed MUSA version must be <= 0.14.3. Please downgrade DeepSpeed.")
+ elif compare_versions("deepspeed", "<", "0.9.3"):
+ raise ImportError("DeepSpeed version must be >= 0.9.3. Please update DeepSpeed.")
+
+ mixed_precision = (
+ os.environ.get("ACCELERATE_MIXED_PRECISION", "no") if mixed_precision is None else mixed_precision
+ )
+ if not isinstance(deepspeed_plugins, dict):
+ deepspeed_plugins.set_mixed_precision(mixed_precision)
+ deepspeed_plugins.select(_from_accelerator_state=True)
+ else:
+ for plugin in deepspeed_plugins.values():
+ plugin.set_mixed_precision(mixed_precision)
+ # The first plugin passed in is always the active one
+ first_plugin = next(iter(deepspeed_plugins.values()))
+ first_plugin.select(_from_accelerator_state=True)
+ self.deepspeed_engine_wrapped = None
+
+ if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true" or isinstance(
+ fsdp_plugin, FullyShardedDataParallelPlugin
+ ):
+ if not is_torch_version(">=", FSDP_PYTORCH_VERSION):
+ raise ValueError(f"FSDP requires PyTorch >= {FSDP_PYTORCH_VERSION}")
+
+ if fsdp_plugin is None: # init from env variables
+ fsdp_plugin = (
+ FullyShardedDataParallelPlugin() if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true" else None
+ )
+ else:
+ if not isinstance(fsdp_plugin, FullyShardedDataParallelPlugin):
+ raise TypeError("`fsdp_plugin` must be a FullyShardedDataParallelPlugin object.")
+ os.environ["ACCELERATE_USE_FSDP"] = "true" # use FSDP if plugin is provided
+
+ if megatron_lm_plugin is None: # init from env variables
+ megatron_lm_plugin = (
+ MegatronLMPlugin() if os.environ.get("ACCELERATE_USE_MEGATRON_LM", "false") == "true" else None
+ )
+ else:
+ if not isinstance(megatron_lm_plugin, MegatronLMPlugin):
+ raise TypeError("`megatron_lm_plugin` must be a MegatronLMPlugin object.")
+ os.environ["ACCELERATE_USE_MEGATRON_LM"] = "true" # use MegatronLM if plugin is provided
+
+ if megatron_lm_plugin:
+ if not is_megatron_lm_available():
+ raise ImportError("Megatron is not installed. please build it from source.")
+
+ # Kwargs handlers
+ self.ddp_handler = None
+ self.scaler_handler = None
+ self.init_handler = None
+ self.fp8_recipe_handler = None
+ self.autocast_handler = None
+ self.profile_handler = None
+ self.has_lomo_optimizer = False
+
+ if kwargs_handlers is not None:
+ for handler in kwargs_handlers:
+ assert isinstance(
+ handler, KwargsHandler
+ ), f"Unsupported kwargs handler passed: {handler}, must be one that inherits `accelerate.utils.KwargsHandler`."
+ if isinstance(handler, DistributedDataParallelKwargs):
+ if self.ddp_handler is not None:
+ raise ValueError("You can only pass one `DistributedDataParallelKwargs` in `kwargs_handler`.")
+ else:
+ self.ddp_handler = handler
+ elif isinstance(handler, GradScalerKwargs):
+ if self.scaler_handler is not None:
+ raise ValueError("You can only pass one `GradScalerKwargs` in `kwargs_handler`.")
+ else:
+ self.scaler_handler = handler
+ elif isinstance(handler, InitProcessGroupKwargs):
+ if self.init_handler is not None:
+ raise ValueError("You can only pass one `InitProcessGroupKwargs` in `kwargs_handler`.")
+ else:
+ self.init_handler = handler
+ elif isinstance(handler, FP8RecipeKwargs):
+ if self.fp8_recipe_handler is not None:
+ raise ValueError("You can only pass one `FP8RecipeKwargs` in `kwargs_handler`.")
+ else:
+ self.fp8_recipe_handler = handler
+ elif isinstance(handler, AutocastKwargs):
+ if self.autocast_handler is not None:
+ raise ValueError("You can only pass one `AutocastKwargs` in `kwargs_handler`.")
+ else:
+ self.autocast_handler = handler
+ elif isinstance(handler, ProfileKwargs):
+ if self.profile_handler is not None:
+ raise ValueError("You can only pass one `ProfileKwargs` in `kwargs_handler`.")
+ else:
+ self.profile_handler = handler
+
+ kwargs = self.init_handler.to_kwargs() if self.init_handler is not None else {}
+ self.state = AcceleratorState(
+ mixed_precision=mixed_precision,
+ cpu=cpu,
+ dynamo_plugin=dynamo_plugin,
+ deepspeed_plugin=deepspeed_plugins,
+ fsdp_plugin=fsdp_plugin,
+ megatron_lm_plugin=megatron_lm_plugin,
+ _from_accelerator=True,
+ **kwargs,
+ )
+
+ if self.state.mixed_precision == "fp8" and self.fp8_recipe_handler is None:
+ self.fp8_recipe_handler = FP8RecipeKwargs()
+
+ self.delayed_fp8_autocast = False
+ if self.fp8_recipe_handler is not None:
+ # We already check if FP8 is available during `self.state`
+ if self.state.mixed_precision != "fp8" and (
+ self.distributed_type not in (DistributedType.FSDP, DistributedType.DEEPSPEED)
+ ):
+ raise ValueError("Passing in a `FP8RecipeKwargs` object requires setting `mixed_precision='fp8'`.")
+ self.delayed_fp8_autocast = self.fp8_recipe_handler.backend == "TE" and self.distributed_type in (
+ DistributedType.MULTI_GPU,
+ DistributedType.FSDP,
+ )
+
+ trackers = filter_trackers(log_with, self.logging_dir)
+ if len(trackers) < 1 and log_with is not None:
+ warnings.warn(f"`log_with={log_with}` was passed but no supported trackers are currently installed.")
+ self.log_with = trackers
+
+ if (
+ (mixed_precision != "bf16")
+ and getattr(self.state, "downcast_bfloat", False)
+ and (self.state.distributedType != DistributedType.XLA)
+ ):
+ raise ValueError("Can only use `downcast_bf16` when using `mixed_precision='bf16'` and on a TPU")
+
+ if gradient_accumulation_plugin is not None:
+ if gradient_accumulation_steps != 1:
+ raise ValueError(
+ "You can only pass one of `gradient_accumulation_steps` and `gradient_accumulation_plugin`. Please only pass in the created `GradientAccumulationPlugin` object."
+ )
+ else:
+ gradient_accumulation_steps = int(
+ parse_choice_from_env("ACCELERATE_GRADIENT_ACCUMULATION_STEPS", gradient_accumulation_steps)
+ )
+ gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=gradient_accumulation_steps)
+ self.gradient_state = GradientState(
+ gradient_accumulation_plugin=gradient_accumulation_plugin,
+ )
+
+ self.device_placement = device_placement
+ if dataloader_config is None:
+ dataloader_config = DataLoaderConfiguration()
+ self.dataloader_config = dataloader_config
+ self.step_scheduler_with_optimizer = step_scheduler_with_optimizer
+
+ # Mixed precision attributes
+ self.scaler = None
+ self.native_amp = False
+ if (
+ self.state.mixed_precision == "fp16"
+ and self.device.type != "cpu"
+ and self.distributed_type not in (DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM)
+ ):
+ self.native_amp = True
+ if self.device.type not in ("xpu", "cuda", "npu", "xla", "mlu", "musa") or is_torch_xla_available(
+ check_is_tpu=True
+ ):
+ raise ValueError(f"fp16 mixed precision requires a GPU (not {self.device.type!r}).")
+ kwargs = self.scaler_handler.to_kwargs() if self.scaler_handler is not None else {}
+ if self.distributed_type == DistributedType.FSDP:
+ from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler
+
+ self.scaler = ShardedGradScaler(**kwargs)
+ elif is_torch_xla_available(check_is_gpu=True):
+ self.scaler = xamp.GradScaler(**kwargs)
+ elif is_mlu_available():
+ self.scaler = torch.mlu.amp.GradScaler(**kwargs)
+ elif is_musa_available():
+ self.scaler = torch.musa.amp.GradScaler(**kwargs)
+ elif is_npu_available():
+ self.scaler = torch.npu.amp.GradScaler(**kwargs)
+ elif is_xpu_available():
+ self.scaler = torch.amp.GradScaler("xpu", **kwargs)
+ else:
+ if version.parse(torch.__version__) > version.parse("2.3"):
+ self.scaler = torch.amp.GradScaler("cuda", **kwargs)
+ else:
+ self.scaler = torch.cuda.amp.GradScaler(**kwargs)
+
+ elif self.state.mixed_precision == "bf16" and self.distributed_type not in (
+ DistributedType.DEEPSPEED,
+ DistributedType.MEGATRON_LM,
+ ):
+ if self.device.type in ["cpu", "xpu"]:
+ self.native_amp = True
+ else:
+ self.native_amp = is_bf16_available(True)
+ if mixed_precision == "bf16" and not self.native_amp and not is_torch_xla_available():
+ raise ValueError("bf16 mixed precision requires PyTorch >= 1.10 and a supported device.")
+
+ elif self.state.mixed_precision == "fp8":
+ # We always enable `native_amp` for FP8
+ self.native_amp = True
+ if self.fp8_backend == "MSAMP":
+ if self.distributed_type == DistributedType.FSDP:
+ raise NotImplementedError(
+ "`accelerate` + `MS-AMP` + `FSDP` is not supported at this time. "
+ "Please consider using deepspeed, which is supported."
+ )
+ elif self.distributed_type != DistributedType.DEEPSPEED:
+ # MS-AMP requires `GradScaler` even with bf16 autocast w/ single GPU or DDP:
+ if version.parse(torch.__version__) > version.parse("2.3"):
+ self.scaler = torch.amp.GradScaler("cuda")
+ else:
+ self.scaler = torch.cuda.amp.GradScaler()
+
+ # Start of internal step tracking
+ self.step = 0
+
+ # Internal references to the training objects
+ self._optimizers = []
+ self._models = []
+ self._schedulers = []
+ self._dataloaders = []
+ self._custom_objects = []
+
+ # Hooks
+ self._load_model_state_pre_hook = OrderedDict()
+ self._save_model_state_pre_hook = OrderedDict()
+
+ # RNG Types
+ self.rng_types = rng_types
+ if self.rng_types is None:
+ self.rng_types = ["generator"]
+
+ # Set a flag tensor for early stopping and other breakpoints
+ self.flag_tensor = None
+
+ check_os_kernel()
+
+ @property
+ def deepspeed_plugin(self):
+ """
+ Returns the currently active DeepSpeedPlugin.
+
+ If using multiple plugins, the first one will be the active one by default. Manually call
+ `accelerator.state.select_deepspeed_plugin(key)` to activate a different plugin.
+
+ If deepspeed is not enabled, this will return `None`.
+ """
+ return self.state.deepspeed_plugin
+
+ @property
+ def use_distributed(self):
+ """
+ Whether the Accelerator is configured for distributed training
+ """
+ return self.state.use_distributed
+
+ @property
+ def distributed_type(self):
+ return self.state.distributed_type
+
+ @property
+ def num_processes(self):
+ return self.state.num_processes
+
+ @property
+ def process_index(self):
+ return self.state.process_index
+
+ @property
+ def local_process_index(self):
+ return self.state.local_process_index
+
+ @property
+ def device(self):
+ return self.state.device
+
+ @property
+ def split_batches(self):
+ return self.dataloader_config.split_batches
+
+ @property
+ def dispatch_batches(self):
+ return self.dataloader_config.dispatch_batches
+
+ @property
+ def even_batches(self):
+ return self.dataloader_config.even_batches
+
+ @even_batches.setter
+ def even_batches(self, value: bool):
+ self.dataloader_config.even_batches = value
+
+ @property
+ def use_seedable_sampler(self):
+ return self.dataloader_config.use_seedable_sampler
+
+ @property
+ def non_blocking(self):
+ return self.dataloader_config.non_blocking
+
+ @property
+ def use_stateful_dataloader(self):
+ if hasattr(self.dataloader_config, "use_stateful_dataloader"):
+ return self.dataloader_config.use_stateful_dataloader
+ return False
+
+ @property
+ def project_dir(self):
+ return self.project_configuration.project_dir
+
+ @property
+ def logging_dir(self):
+ return self.project_configuration.logging_dir
+
+ @property
+ def save_iteration(self):
+ return self.project_configuration.iteration
+
+ @property
+ def is_main_process(self):
+ """True for one process only."""
+ return self.state.is_main_process
+
+ @property
+ def is_local_main_process(self):
+ """True for one process per server."""
+ return self.state.is_local_main_process
+
+ @property
+ def is_last_process(self):
+ return self.process_index == self.num_processes - 1
+
+ @property
+ def mixed_precision(self):
+ return self.state.mixed_precision
+
+ @contextmanager
+ def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False):
+ """
+ Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
+ distributed inference, such as with different prompts.
+
+ Note that when using a `dict`, all keys need to have the same number of elements.
+
+ Args:
+ inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`):
+ The input to split between processes.
+ apply_padding (`bool`, `optional`, defaults to `False`):
+ Whether to apply padding by repeating the last element of the input so that all processes have the same
+ number of elements. Useful when trying to perform actions such as `Accelerator.gather()` on the outputs
+ or passing in less inputs than there are processes. If so, just remember to drop the padded elements
+ afterwards.
+
+ Example:
+
+ ```python
+ # Assume there are two processes
+ from accelerate import Accelerator
+
+ accelerator = Accelerator()
+ with accelerator.split_between_processes(["A", "B", "C"]) as inputs:
+ print(inputs)
+ # Process 0
+ ["A", "B"]
+ # Process 1
+ ["C"]
+
+ with accelerator.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
+ print(inputs)
+ # Process 0
+ ["A", "B"]
+ # Process 1
+ ["C", "C"]
+ ```
+ """
+ with PartialState().split_between_processes(inputs, apply_padding=apply_padding) as inputs:
+ yield inputs
+
+ def on_main_process(self, function: Callable[..., Any] = None):
+ """
+ A decorator that will run the decorated function on the main process only. Can also be called using the
+ `PartialState` class.
+
+ Args:
+ function (`Callable`): The function to decorate.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+
+
+ >>> @accelerator.on_main_process
+ ... def print_something():
+ ... print("This will be printed by process 0 only.")
+
+
+ >>> print_something()
+ "This will be printed by process 0 only"
+ ```
+ """
+ # For times when the `Accelerator` object itself utilizes this decorator.
+ if function is None:
+ if "Accelerator." in self.__qualname__:
+ function = self
+ else:
+ raise ValueError(
+ "The `on_main_process` decorator must be called with a function on an instantiated `Accelerator` object."
+ )
+
+ def _inner(*args, **kwargs):
+ return PartialState().on_main_process(function)(*args, **kwargs)
+
+ return _inner
+
+ def on_local_main_process(self, function: Callable[..., Any] = None):
+ """
+ A decorator that will run the decorated function on the local main process only. Can also be called using the
+ `PartialState` class.
+
+ Args:
+ function (`Callable`): The function to decorate.
+
+ Example:
+ ```python
+ # Assume we have 2 servers with 4 processes each.
+ from accelerate import Accelerator
+
+ accelerator = Accelerator()
+
+
+ @accelerator.on_local_main_process
+ def print_something():
+ print("This will be printed by process 0 only on each server.")
+
+
+ print_something()
+ # On server 1:
+ "This will be printed by process 0 only"
+ # On server 2:
+ "This will be printed by process 0 only"
+ ```
+ """
+ # For times when the `Accelerator` object itself utilizes this decorator.
+ if function is None:
+ if "Accelerator." in self.__qualname__:
+ function = self
+ else:
+ raise ValueError(
+ "The `on_local_main_process` decorator must be called with a function on an instantiated `Accelerator` object."
+ )
+
+ def _inner(*args, **kwargs):
+ return PartialState().on_local_main_process(function)(*args, **kwargs)
+
+ return _inner
+
+ def on_last_process(self, function: Callable[..., Any]):
+ """
+ A decorator that will run the decorated function on the last process only. Can also be called using the
+ `PartialState` class.
+
+ Args:
+ function (`Callable`): The function to decorate.
+
+ Example:
+ ```python
+ # Assume we have 4 processes.
+ from accelerate import Accelerator
+
+ accelerator = Accelerator()
+
+
+ @accelerator.on_last_process
+ def print_something():
+ print(f"Printed on process {accelerator.process_index}")
+
+
+ print_something()
+ "Printed on process 3"
+ ```
+ """
+ # For times when the `Accelerator` object itself utilizes this decorator.
+ if function is None:
+ if "Accelerator." in self.__qualname__:
+ function = self
+ else:
+ raise ValueError(
+ "The `on_last_process` decorator must be called with a function on an instantiated `Accelerator` object."
+ )
+
+ def _inner(*args, **kwargs):
+ return PartialState().on_last_process(function)(*args, **kwargs)
+
+ return _inner
+
+ def on_process(self, function: Callable[..., Any] = None, process_index: int = None):
+ """
+ A decorator that will run the decorated function on a given process index only. Can also be called using the
+ `PartialState` class.
+
+ Args:
+ function (`Callable`, `optional`):
+ The function to decorate.
+ process_index (`int`, `optional`):
+ The index of the process on which to run the function.
+
+ Example:
+ ```python
+ # Assume we have 4 processes.
+ from accelerate import Accelerator
+
+ accelerator = Accelerator()
+
+
+ @accelerator.on_process(process_index=2)
+ def print_something():
+ print(f"Printed on process {accelerator.process_index}")
+
+
+ print_something()
+ "Printed on process 2"
+ ```
+ """
+ # Initial construction of the decorator.
+ if (self is not None) and (process_index is not None) and (function is None):
+ return partial(self.on_process, process_index=process_index)
+ # For times when the `Accelerator` object itself utilizes this decorator.
+ if function is None:
+ if "Accelerator." in self.__qualname__:
+ function = self
+ else:
+ raise ValueError(
+ "The `on_main_process` decorator must be called with a function on an instantiated `Accelerator` object."
+ )
+
+ def _inner(*args, **kwargs):
+ return PartialState().on_process(function, process_index)(*args, **kwargs)
+
+ return _inner
+
+ def on_local_process(self, function: Callable[..., Any] = None, local_process_index: int = None):
+ """
+ A decorator that will run the decorated function on a given local process index only. Can also be called using
+ the `PartialState` class.
+
+ Args:
+ function (`Callable`, *optional*):
+ The function to decorate.
+ local_process_index (`int`, *optional*):
+ The index of the local process on which to run the function.
+
+ Example:
+ ```python
+ # Assume we have 2 servers with 4 processes each.
+ from accelerate import Accelerator
+
+ accelerator = Accelerator()
+
+
+ @accelerator.on_local_process(local_process_index=2)
+ def print_something():
+ print(f"Printed on process {accelerator.local_process_index}")
+
+
+ print_something()
+ # On server 1:
+ "Printed on process 2"
+ # On server 2:
+ "Printed on process 2"
+ ```
+ """
+ # Initial construction of the decorator.
+ if (self is not None) and (local_process_index is not None) and (function is None):
+ return partial(self.on_local_process, local_process_index=local_process_index)
+ # For times when the `Accelerator` object itself utilizes this decorator.
+ if function is None:
+ if "Accelerator." in self.__qualname__:
+ function = self
+ else:
+ raise ValueError(
+ "The `on_main_process` decorator must be called with a function on an instantiated `Accelerator` object."
+ )
+
+ def _inner(*args, **kwargs):
+ return PartialState().on_local_process(function, local_process_index)(*args, **kwargs)
+
+ return _inner
+
+ @contextmanager
+ def main_process_first(self):
+ """
+ Lets the main process go first inside a with block.
+
+ The other processes will enter the with block after the main process exits.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> with accelerator.main_process_first():
+ ... # This will be printed first by process 0 then in a seemingly
+ ... # random order by the other processes.
+ ... print(f"This will be printed by process {accelerator.process_index}")
+ ```
+ """
+ with self.state.main_process_first():
+ yield
+
+ @contextmanager
+ def local_main_process_first(self):
+ """
+ Lets the local main process go inside a with block.
+
+ The other processes will enter the with block after the main process exits.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> with accelerator.local_main_process_first():
+ ... # This will be printed first by local process 0 then in a seemingly
+ ... # random order by the other processes.
+ ... print(f"This will be printed by process {accelerator.local_process_index}")
+ ```
+ """
+ with self.state.local_main_process_first():
+ yield
+
+ @contextmanager
+ def no_sync(self, model):
+ """
+ A context manager to disable gradient synchronizations across DDP processes by calling
+ `torch.nn.parallel.DistributedDataParallel.no_sync`.
+
+ If `model` is not in DDP, this context manager does nothing
+
+ Args:
+ model (`torch.nn.Module`):
+ PyTorch Module that was prepared with `Accelerator.prepare`
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> dataloader, model, optimizer = accelerator.prepare(dataloader, model, optimizer)
+ >>> input_a = next(iter(dataloader))
+ >>> input_b = next(iter(dataloader))
+
+ >>> with accelerator.no_sync():
+ ... outputs = model(input_a)
+ ... loss = loss_func(outputs)
+ ... accelerator.backward(loss)
+ ... # No synchronization across processes, only accumulate gradients
+ >>> outputs = model(input_b)
+ >>> accelerator.backward(loss)
+ >>> # Synchronization across all processes
+ >>> optimizer.step()
+ >>> optimizer.zero_grad()
+ ```
+ """
+ context = contextlib.nullcontext
+ if self.use_distributed:
+ context = getattr(model, "no_sync", context)
+
+ with context():
+ yield
+
+ @staticmethod
+ @contextmanager
+ def trigger_sync_in_backward(model):
+ """Trigger the sync of the gradients in the next backward pass of the model after multiple forward passes under
+ `Accelerator.no_sync` (only applicable in multi-GPU scenarios).
+
+ If the script is not launched in distributed mode, this context manager does nothing.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model for which to trigger the gradient synchronization.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> dataloader, model, optimizer = accelerator.prepare(dataloader, model, optimizer)
+
+ >>> with accelerator.no_sync():
+ ... loss_a = loss_func(model(input_a)) # first forward pass
+ ... loss_b = loss_func(model(input_b)) # second forward pass
+ >>> accelerator.backward(loss_a) # No synchronization across processes, only accumulate gradients
+ >>> with accelerator.trigger_sync_in_backward(model):
+ ... accelerator.backward(loss_b) # Synchronization across all processes
+ >>> optimizer.step()
+ >>> optimizer.zero_grad()
+ ```
+ """
+ if not isinstance(model, torch.nn.parallel.DistributedDataParallel):
+ yield
+ return
+
+ old_require_backward_grad_sync = model.require_backward_grad_sync
+ old_require_forward_param_sync = model.require_forward_param_sync
+
+ # EXPERIMENTAL: This will force grad sync during `backward()`, but it is unknown if it breaks other DDP features.
+ # https://github.com/pytorch/pytorch/blob/e1502c0cdbfd17548c612f25d5a65b1e4b86224d/torch/nn/parallel/distributed.py#L1453-L1466
+ model.require_backward_grad_sync = True
+ model.require_forward_param_sync = True
+ # https://github.com/pytorch/pytorch/blob/e1502c0cdbfd17548c612f25d5a65b1e4b86224d/torch/csrc/distributed/c10d/reducer.cpp#L1371-L1402
+ model.reducer.prepare_for_backward([])
+ try:
+ yield
+ finally:
+ model.require_backward_grad_sync = old_require_backward_grad_sync
+ model.require_forward_param_sync = old_require_forward_param_sync
+
+ def _do_sync(self):
+ "Sets the right `sync_gradients` context and either resets or increases `self.step`"
+ if self.gradient_state.sync_with_dataloader and self.gradient_state.end_of_dataloader:
+ self.step = 0
+ self.gradient_state._set_sync_gradients(True)
+ else:
+ self.step += 1
+ self.gradient_state._set_sync_gradients((self.step % self.gradient_state.num_steps) == 0)
+
+ @property
+ def sync_gradients(self):
+ return self.gradient_state.sync_gradients
+
+ @sync_gradients.setter
+ def sync_gradients(self, sync_gradients):
+ self.gradient_state.sync_gradients = sync_gradients
+
+ @property
+ def gradient_accumulation_steps(self):
+ return self.gradient_state.num_steps
+
+ @gradient_accumulation_steps.setter
+ def gradient_accumulation_steps(self, gradient_accumulation_steps):
+ self.gradient_state.plugin_kwargs.update({"num_steps": gradient_accumulation_steps})
+
+ @contextmanager
+ def accumulate(self, *models):
+ """
+ A context manager that will lightly wrap around and perform gradient accumulation automatically
+
+ Args:
+ *models (list of `torch.nn.Module`):
+ PyTorch Modules that were prepared with `Accelerator.prepare`. Models passed to `accumulate()` will
+ skip gradient syncing during backward pass in distributed training
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator(gradient_accumulation_steps=1)
+ >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler)
+
+ >>> for input, output in dataloader:
+ ... with accelerator.accumulate(model):
+ ... outputs = model(input)
+ ... loss = loss_func(outputs)
+ ... loss.backward()
+ ... optimizer.step()
+ ... scheduler.step()
+ ... optimizer.zero_grad()
+ ```
+ """
+ self._do_sync()
+
+ allow_gradient_sync = (
+ self.sync_gradients # must sync if sync gradients need to complete an optimizer step
+ or (
+ # the no_sync context stops the gradients from reducing during distributed training
+ # bringing speedup (potentially at some costs). Here, no_sync can be prevented
+ # by setting sync_each_batch = True.
+ self.use_distributed # only relevant in distributed settings
+ and self.gradient_state.plugin_kwargs.get("sync_each_batch", False)
+ )
+ )
+ with contextlib.ExitStack() as cm_stack:
+ for m in models:
+ cm_stack.enter_context(contextlib.nullcontext() if allow_gradient_sync else self.no_sync(m))
+ yield
+
+ @contextmanager
+ def join_uneven_inputs(self, joinables, even_batches=None):
+ """
+ A context manager that facilitates distributed training or evaluation on uneven inputs, which acts as a wrapper
+ around `torch.distributed.algorithms.join`. This is useful when the total batch size does not evenly divide the
+ length of the dataset.
+
+ Args:
+ joinables (`list[torch.distributed.algorithms.Joinable]`):
+ A list of models or optimizers that subclass `torch.distributed.algorithms.Joinable`. Most commonly, a
+ PyTorch Module that was prepared with `Accelerator.prepare` for DistributedDataParallel training.
+ even_batches (`bool`, *optional*)
+ If set, this will override the value of `even_batches` set in the `Accelerator`. If it is not provided,
+ the default `Accelerator` value wil be used.
+
+
+
+ `join_uneven_inputs` is only supported for Distributed Data Parallel training on multiple GPUs. For any other
+ configuration, this method will have no effect.
+
+
+
+
+
+ Overidding `even_batches` will not affect iterable-style data loaders.
+
+
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator(even_batches=True)
+ >>> ddp_model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
+
+ >>> with accelerator.join_uneven_inputs([ddp_model], even_batches=False):
+ ... for input, output in dataloader:
+ ... outputs = model(input)
+ ... loss = loss_func(outputs)
+ ... loss.backward()
+ ... optimizer.step()
+ ... optimizer.zero_grad()
+ ```
+ """
+ if self.distributed_type in (
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_XPU,
+ ):
+ dl_even_batches_values = []
+
+ if even_batches is not None:
+ iterable_dl_seen = False
+ # override value in batch sampler for map-style datasets
+ for dl_idx, dl in enumerate(self._dataloaders):
+ if isinstance(dl, DataLoaderDispatcher):
+ iterable_dl_seen = True
+ continue
+ dl_even_batches_values.append((dl_idx, dl.batch_sampler.even_batches))
+ dl.batch_sampler.even_batches = even_batches
+
+ if iterable_dl_seen:
+ warnings.warn(
+ "Overridding even_batches is only supported for map-style datasets, yet some dataloaders given were iterable"
+ )
+ else:
+ even_batches = self.even_batches
+
+ enable_join = False if even_batches else True
+ try:
+ with Join(joinables, enable=enable_join, throw_on_early_termination=False):
+ yield
+ finally:
+ # reset any batch samplers that have been modified
+ for dl_idx, even_batches_value in dl_even_batches_values:
+ self._dataloaders[dl_idx].batch_sampler.even_batches = even_batches_value
+ else:
+ # Even when disabled, Join expects models to subclass Joinable, so skip entirely for single process runs
+ if self.distributed_type != DistributedType.NO:
+ warnings.warn(
+ "Joining uneven inputs is only supported for multi-GPU training, as a result `join_uneven_inputs` will have no effect."
+ )
+
+ with contextlib.nullcontext(joinables):
+ yield
+
+ def print(self, *args, **kwargs):
+ """
+ Drop in replacement of `print()` to only print once per server.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> accelerator.print("Hello world!")
+ ```
+ """
+ self.state.print(*args, **kwargs)
+
+ def _prepare_one(self, obj, first_pass=False, device_placement=None):
+ # First pass of preparation: DataLoader, model, optimizer
+ if first_pass:
+ if isinstance(obj, torch.utils.data.DataLoader):
+ return self.prepare_data_loader(obj, device_placement=device_placement)
+ elif isinstance(obj, torch.nn.Module):
+ return self.prepare_model(obj, device_placement=device_placement)
+ elif isinstance(obj, torch.optim.Optimizer):
+ optimizer = self.prepare_optimizer(obj, device_placement=device_placement)
+ return optimizer
+ # Second pass of preparation: LR scheduler (which need the full list of optimizers)
+ elif isinstance(obj, LRScheduler):
+ scheduler = self.prepare_scheduler(obj)
+ return scheduler
+ # Return the unprocessed object if previous criteria was not met
+ return obj
+
+ def prepare(self, *args, device_placement=None):
+ """
+ Prepare all objects passed in `args` for distributed training and mixed precision, then return them in the same
+ order.
+
+ Args:
+ *args (list of objects):
+ Any of the following type of objects:
+
+ - `torch.utils.data.DataLoader`: PyTorch Dataloader
+ - `torch.nn.Module`: PyTorch Module
+ - `torch.optim.Optimizer`: PyTorch Optimizer
+ - `torch.optim.lr_scheduler.LRScheduler`: PyTorch LR Scheduler
+
+ device_placement (`list[bool]`, *optional*):
+ Used to customize whether automatic device placement should be performed for each object passed. Needs
+ to be a list of the same length as `args`. Not compatible with DeepSpeed or FSDP.
+
+
+
+ You don't need to prepare a model if you only use it for inference without any kind of mixed precision
+
+
+
+ Examples:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> # Assume a model, optimizer, data_loader and scheduler are defined
+ >>> model, optimizer, data_loader, scheduler = accelerator.prepare(model, optimizer, data_loader, scheduler)
+ ```
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> # Assume a model, optimizer, data_loader and scheduler are defined
+ >>> device_placement = [True, True, False, False]
+ >>> # Will place the first to items passed in automatically to the right device but not the last two.
+ >>> model, optimizer, data_loader, scheduler = accelerator.prepare(
+ ... model, optimizer, data_loader, scheduler, device_placement=device_placement
+ ... )
+ ```
+ """
+ if device_placement is None:
+ device_placement = [None for _ in args]
+ elif self.distributed_type in (DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM):
+ raise ValueError("You can't customize device placements with DeepSpeed or Megatron-LM.")
+ elif len(device_placement) != len(args):
+ raise ValueError(
+ f"`device_placement` should be a list with {len(args)} elements (the number of objects passed)."
+ )
+
+ for obj in args:
+ # TODO: Look at enabling native TP training directly with a proper config
+ if (
+ isinstance(obj, torch.nn.Module)
+ and self.verify_device_map(obj)
+ and self.distributed_type != DistributedType.NO
+ and os.environ.get("ACCELERATE_BYPASS_DEVICE_MAP", "false") != "true"
+ ):
+ raise ValueError(
+ "You can't train a model that has been loaded with `device_map='auto'` in any distributed mode."
+ " Please rerun your script specifying `--num_processes=1` or by launching with `python {{myscript.py}}`."
+ )
+
+ if self.distributed_type == DistributedType.DEEPSPEED:
+ model_count = 0
+ for obj in args:
+ if isinstance(obj, torch.nn.Module):
+ model_count += 1
+ if model_count > 1:
+ raise AssertionError(
+ "You can't use same `Accelerator()` instance with multiple models when using DeepSpeed"
+ )
+
+ # On TPUs, putting the model on the XLA device will create new parameters, so the corresponding optimizer will
+ # have parameters disconnected from the model (so no training :-( ).
+ # If the model and optimizer have parameters on different devices we raise an error.
+ if self.distributed_type == DistributedType.XLA:
+ model_device, optimizer_device = self._get_devices()
+ if model_device is not None and optimizer_device is not None and model_device != optimizer_device:
+ raise ValueError(
+ "The model and the optimizer parameters are not on the same device, which probably means you "
+ "created an optimizer around your model **before** putting on the device. Make sure the line "
+ "model.to(device) is before the optimizer creation in your script or remove it entirely and use "
+ "the flag default value for `device_placement` in your `Accelerator` to let it handle that "
+ "part for you."
+ )
+
+ # If we're dealing with device placement, this deals with that by...
+ tpu_should_fix_optimizer = self.device_placement and self.distributed_type == DistributedType.XLA
+
+ if tpu_should_fix_optimizer:
+ # 1. grabbing old model parameters
+ old_named_params = self._get_named_parameters(*args)
+
+ if self.distributed_type in [DistributedType.MULTI_CPU, DistributedType.MULTI_XPU, DistributedType.NO]:
+ if self.device.type == "cpu" and self.state.use_ipex:
+ args = self._prepare_ipex_or_xpu(*args)
+ elif self.device.type == "xpu" and is_xpu_available():
+ args = self._prepare_ipex_or_xpu(*args)
+ if self.fp8_backend == "TE":
+ args = self._prepare_te(*args)
+ if self.distributed_type == DistributedType.DEEPSPEED:
+ result = self._prepare_deepspeed(*args)
+ elif self.distributed_type == DistributedType.MEGATRON_LM:
+ result = self._prepare_megatron_lm(*args)
+ else:
+ if self.fp8_backend == "MSAMP":
+ args, device_placement = self._prepare_msamp(*args, device_placement=device_placement)
+ result = tuple(
+ self._prepare_one(obj, first_pass=True, device_placement=d) for obj, d in zip(args, device_placement)
+ )
+ result = tuple(self._prepare_one(obj, device_placement=d) for obj, d in zip(result, device_placement))
+ if tpu_should_fix_optimizer:
+ # 2. grabbing new model parameters
+ new_named_params = self._get_named_parameters(*result)
+ # 3. building a map from the first to the second
+ mapping = {p: new_named_params[n] for n, p in old_named_params.items()}
+ # 4. using that map to update the parameters of the optimizer
+ for obj in result:
+ if isinstance(obj, torch.optim.Optimizer):
+ obj._switch_parameters(mapping)
+
+ for item in result:
+ if any(
+ item in container
+ for container in (self._dataloaders, self._models, self._optimizers, self._schedulers)
+ ):
+ item._is_accelerate_prepared = True
+
+ return result if len(result) > 1 else result[0]
+
+ def prepare_model(self, model: torch.nn.Module, device_placement: bool = None, evaluation_mode: bool = False):
+ """
+ Prepares a PyTorch model for training in any distributed setup. It is recommended to use
+ [`Accelerator.prepare`] instead.
+
+ Args:
+ model (`torch.nn.Module`):
+ A PyTorch model to prepare. You don't need to prepare a model if it is used only for inference without
+ any kind of mixed precision
+ device_placement (`bool`, *optional*):
+ Whether or not to place the model on the proper device. Will default to `self.device_placement`.
+ evaluation_mode (`bool`, *optional*, defaults to `False`):
+ Whether or not to set the model for evaluation only, by just applying mixed precision and
+ `torch.compile` (if configured in the `Accelerator` object).
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> # Assume a model is defined
+ >>> model = accelerator.prepare_model(model)
+ ```
+ """
+ if device_placement is None:
+ device_placement = self.device_placement and self.distributed_type != DistributedType.FSDP
+ self._models.append(model)
+
+ # TODO: Look at enabling native TP training directly with a proper config
+ if (
+ self.verify_device_map(model)
+ and self.distributed_type != DistributedType.NO
+ and os.environ.get("ACCELERATE_BYPASS_DEVICE_MAP", "false") != "true"
+ ):
+ raise ValueError(
+ "You can't train a model that has been loaded with `device_map='auto'` in any distributed mode."
+ " Please rerun your script specifying `--num_processes=1` or by launching with `python {{myscript.py}}`."
+ )
+
+ if self.native_amp:
+ model._original_forward = model.forward
+ autocast_context = get_mixed_precision_context_manager(self.native_amp, self.autocast_handler)
+ # NOTE: MS-AMP adds `__func__` already to `model.forward`, so we should always use `model.forward`
+ if self.fp8_backend == "MSAMP" or not hasattr(model.forward, "__func__"):
+ model_forward_func = model.forward
+ model.forward = convert_outputs_to_fp32(autocast_context(model_forward_func))
+ else:
+ model_forward_func = model.forward.__func__
+ new_forward = autocast_context(model_forward_func)
+ model.forward = MethodType(new_forward, model)
+ model.forward = MethodType(convert_outputs_to_fp32(model.forward.__func__), model)
+
+ # We prepare TE after, allowing for bf16 autocast to happen first
+ if self.fp8_backend == "TE" and not self.delayed_fp8_autocast:
+ model = apply_fp8_autowrap(model, self.fp8_recipe_handler)
+
+ if (getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False)) and getattr(
+ model, "hf_device_map", False
+ ):
+ model_devices = set(model.hf_device_map.values())
+ if len(model_devices) > 1 and self.distributed_type != DistributedType.NO:
+ raise ValueError(
+ "You can't train a model that has been loaded in 8-bit or 4-bit precision on multiple devices in any distributed mode."
+ " In order to use 8-bit or 4-bit models that have been loaded across multiple GPUs the solution is to use Naive Pipeline Parallelism."
+ " Therefore you should not specify that you are under any distributed regime in your accelerate config."
+ )
+ elif len(model_devices) == 1:
+ current_device = list(model_devices)[0]
+ current_device_index = (
+ current_device.index if isinstance(current_device, torch.device) else current_device
+ )
+
+ if torch.device(current_device_index) != self.device:
+ # if on the first device (GPU 0) we don't care
+ if (self.device.index is not None) or (current_device_index != 0):
+ raise ValueError(
+ "You can't train a model that has been loaded in 8-bit or 4-bit precision on a different device than the one "
+ "you're training on. Make sure you loaded the model on the correct device using for example `device_map={'':torch.cuda.current_device()}` or `device_map={'':torch.xpu.current_device()}`"
+ )
+
+ if ("cpu" in model_devices and not is_bitsandbytes_multi_backend_available()) or "disk" in model_devices:
+ raise ValueError(
+ "You can't train a model that has been loaded in 8-bit or 4-bit precision with CPU or disk offload. "
+ "If you want train the 8-bit or 4-bit model in CPU, please install bitsandbytes with multi-backend, see https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend"
+ )
+ elif device_placement and not self.verify_device_map(model):
+ model = model.to(self.device)
+ if not evaluation_mode:
+ if self.distributed_type in (
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_XPU,
+ ):
+ if any(p.requires_grad for p in model.parameters()):
+ kwargs = self.ddp_handler.to_kwargs() if self.ddp_handler is not None else {}
+ # TODO: Look at enabling native TP training directly with a proper config
+ if os.environ.get("ACCELERATE_BYPASS_DEVICE_MAP", "false") != "true":
+ device_ids, output_device = [self.local_process_index], self.local_process_index
+ else:
+ device_ids, output_device = None, None
+
+ model = torch.nn.parallel.DistributedDataParallel(
+ model, device_ids=device_ids, output_device=output_device, **kwargs
+ )
+ if self.ddp_handler is not None:
+ self.ddp_handler.register_comm_hook(model)
+ elif self.distributed_type == DistributedType.FSDP:
+ # We need to fix the optimizer *before* sharding the model
+ from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
+
+ # Check if the model is already a FSDP model due to `Manual Wrapping` and if so,
+ # don't wrap it again
+ # In case the model is already compiled using PyTorch 2.0 and the wrapped model in it
+ # is a FSDP model, don't wrap it again
+ is_type_fsdp = isinstance(model, FSDP) or (
+ is_compiled_module(model) and isinstance(model._orig_mod, FSDP)
+ )
+
+ if not is_type_fsdp:
+ self.state.fsdp_plugin.set_auto_wrap_policy(model)
+ fsdp_plugin = self.state.fsdp_plugin
+ kwargs = {
+ "sharding_strategy": fsdp_plugin.sharding_strategy,
+ "cpu_offload": fsdp_plugin.cpu_offload,
+ "auto_wrap_policy": fsdp_plugin.auto_wrap_policy,
+ "mixed_precision": fsdp_plugin.mixed_precision_policy,
+ "sync_module_states": fsdp_plugin.sync_module_states,
+ "backward_prefetch": fsdp_plugin.backward_prefetch,
+ "forward_prefetch": fsdp_plugin.forward_prefetch,
+ "use_orig_params": fsdp_plugin.use_orig_params,
+ "param_init_fn": fsdp_plugin.param_init_fn,
+ "ignored_modules": fsdp_plugin.ignored_modules,
+ "limit_all_gathers": fsdp_plugin.limit_all_gathers,
+ "device_id": self.device,
+ }
+ model = FSDP(model, **kwargs)
+ if fsdp_plugin.activation_checkpointing:
+ from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
+ CheckpointImpl,
+ apply_activation_checkpointing,
+ checkpoint_wrapper,
+ )
+
+ apply_activation_checkpointing(
+ model,
+ checkpoint_wrapper_fn=functools.partial(
+ checkpoint_wrapper,
+ checkpoint_impl=CheckpointImpl.NO_REENTRANT,
+ ),
+ auto_wrap_policy=fsdp_plugin.auto_wrap_policy,
+ )
+
+ # In the event the model had been loaded in low precision, but
+ # mixed precision had also been activated, then we follow DeepSpeed's
+ # strategy to hold the parameters in full precision.
+ # - assume that trainer.args.bf16 and trainer.args.fp16 are already checked against
+ # fsdp_plugin.mixed_precision_policy.
+ # - NOTE: we do not check the mixed_precision attribute on the FSDP root wrapper.
+ # * this attribute will always set by init_utils.init_core_state so its always not None.
+ # * mixed_precision.param_dtype only regards _fwd_bwd_param_dtype
+ # * if model is loaded in 16bit, and even if mixed_precision.param_dtype is None,
+ # we sill want to upcast the flat_param.
+ if self.mixed_precision != "no": # if mixed precision is set
+ upcasted_log = []
+ for module in FSDP.fsdp_modules(model):
+ # Referencing DeepSpeed Zero3
+ # - in Init, params are converted to 16bit while partitioning.
+ # - in accelerator.prepare, deepspeed.initalize is called to:
+ # * creates the DeepSpeeedEngine.
+ # * since zero_optimization() is True , calls engine._configure_zero_optimizer.
+ #
+ # Inside the DeepSpeed Zero3 optimizer configuration, which initalizes
+ # DeepSpeedZeroOptimizer_Stage3, during which:
+ # * trainable_param_groups are obtained from the attached optimizer
+ # (already partitioned in 16bit).
+ # * then _setup_for_real_optimizer -> _create_fp32_partitions
+ # which performs the fp32 upcasting.
+
+ # To mimick DeepSeepds's casting in FSDP, we look at the (single) FlatParameter held
+ # within an FSDP wrapper. This FlatParameter will be seen by the optimizer.
+ # - even though there is a torch.device('meta') guard below, we
+ # expect _init_utils._init_param_handle_from_module to already
+ # sync the parameter.
+
+ if not module._has_params:
+ continue # skip if FSDP module not managing parameters
+ param = module._flat_param
+ if (
+ param.dtype != torch.float32
+ and param.device != torch.device("meta")
+ and param.requires_grad
+ ):
+ # keep log of names_params that was upcasted
+ # NOTE: resorted to this because warnings.simplefilter("once") is somehow not working
+ name_param_log = (module.module.__class__.__name__, ", ".join(module._flat_param._fqns))
+ if name_param_log not in upcasted_log:
+ upcasted_log.append(name_param_log)
+
+ # this works because of FSDP's _runtime_utils.lazy_init.
+ # Have to be careful not to call anything before this that
+ # triggers lazy_init (e.g., _is_fsdp_root).
+ param.data = param.data.to(torch.float32) # upcasting
+ module._handle._orig_param_dtype = torch.float32 # update
+
+ # report the warnings
+ # some messages can be quite repetitive, especially when reporting about layers that have identical architecture.
+ if self.is_main_process:
+ for name_log, param_log in upcasted_log:
+ warnings.warn(
+ f"Upcasted low precision parameters in {name_log} because mixed precision turned on in FSDP. "
+ f"Affects: {param_log}."
+ )
+
+ if len(upcasted_log) > 0:
+ warnings.warn(
+ "FSDP upcast of low precision parameters may affect the precision of model checkpoints."
+ )
+
+ # if the previous and current models are same, delete the previous one
+ if len(self._models) > 1 and (self._models[-2] is self._models[-1]):
+ del self._models[-2]
+ self._models[-1] = model
+ elif self.distributed_type == DistributedType.MULTI_CPU:
+ kwargs = self.ddp_handler.to_kwargs() if self.ddp_handler is not None else {}
+ model = torch.nn.parallel.DistributedDataParallel(model, **kwargs)
+ if self.ddp_handler is not None:
+ self.ddp_handler.register_comm_hook(model)
+ elif self.distributed_type == DistributedType.XLA and self.state.fork_launched:
+ model = xmp.MpModelWrapper(model).to(self.device)
+ # Now we can apply the FP8 autocast
+ if self.delayed_fp8_autocast:
+ model = apply_fp8_autowrap(model, self.fp8_recipe_handler)
+ # torch.compile should be called last and only if the model isn't already compiled.
+ if self.state.dynamo_plugin.backend != DynamoBackend.NO and not is_compiled_module(model):
+ if not is_torch_version(">=", "2.0"):
+ raise ValueError("Using `torch.compile` requires PyTorch 2.0 or higher.")
+ model = torch.compile(model, **self.state.dynamo_plugin.to_kwargs())
+ return model
+
+ def _prepare_te(self, *args):
+ if not is_transformer_engine_available():
+ raise ImportError(
+ "`transformer_engine` was not found on your system. Please ensure that `transformer_engine` is installed"
+ )
+ model, optimizer = None, None
+ num_models, num_optimizers = 0, 0
+ result = [obj for obj in args]
+ for obj in result:
+ if isinstance(obj, torch.nn.Module):
+ model = obj
+ num_models += 1
+ elif isinstance(obj, (torch.optim.Optimizer)):
+ optimizer = obj
+ num_optimizers += 1
+ if optimizer is None and model is None:
+ return result
+ elif optimizer is None or model is None:
+ raise ValueError(
+ "You must pass a model and an optimizer together to `accelerate.prepare()` when using TransformerEngine."
+ )
+ elif num_models > 1 or num_optimizers > 1:
+ raise ValueError(
+ f"You can't use multiple models ({num_models}) or optimizers {num_optimizers} with TransformerEngine."
+ )
+ old_named_params = self._get_named_parameters(model)
+ with torch.no_grad():
+ convert_model(model)
+ new_named_params = self._get_named_parameters(model)
+ mapping = {p: new_named_params[n] for n, p in old_named_params.items()}
+ # We need to switch the optimizer params to the new params *after* the model is wrapped in FSDP
+ for param_group in optimizer.param_groups:
+ param_group["params"] = [mapping[p] for p in param_group["params"]]
+
+ return result
+
+ def _prepare_deepspeed(self, *args):
+ import deepspeed
+
+ ds_initialize = deepspeed.initialize
+ if self.fp8_backend == "MSAMP":
+ # MS-AMP requires DeepSpeed patches
+ from msamp import deepspeed as msamp_deepspeed
+
+ ds_initialize = msamp_deepspeed.initialize
+
+ deepspeed_plugin = self.deepspeed_plugin
+
+ is_dataloader_present = any(isinstance(obj, torch.utils.data.DataLoader) for obj in args)
+ result = [
+ self._prepare_one(obj, first_pass=True) if isinstance(obj, torch.utils.data.DataLoader) else obj
+ for obj in args
+ ]
+
+ if deepspeed_plugin.is_auto("train_micro_batch_size_per_gpu"):
+ if is_dataloader_present:
+ batch_sizes = [obj.batch_size for obj in args if hasattr(obj, "batch_size")]
+ if any(bs is None for bs in batch_sizes):
+ raise ValueError(
+ "At least one of the dataloaders passed to `accelerate.prepare()` has `None` as batch size. "
+ "Please set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file "
+ "or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`."
+ )
+ if self.split_batches:
+ batch_sizes = [batch_size // self.num_processes for batch_size in batch_sizes]
+
+ batch_size_per_device = min(batch_sizes) if deepspeed_plugin.is_train_batch_min else max(batch_sizes)
+ if len(batch_sizes) > 1:
+ logger.info(
+ "Since you passed both train and evaluation dataloader, `is_train_batch_min` (here "
+ f"{deepspeed_plugin.is_train_batch_min} will decide the `train_batch_size` ({batch_size_per_device})."
+ )
+ else:
+ raise ValueError(
+ "When using DeepSpeed, `accelerate.prepare()` requires you to pass at least one of training or evaluation dataloaders "
+ "with `batch_size` attribute returning an integer value "
+ "or alternatively set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file "
+ "or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`."
+ )
+ else:
+ batch_size_per_device = deepspeed_plugin.get_value("train_micro_batch_size_per_gpu")
+
+ # handle `gradient_accumulation_steps` when the value is `auto`
+ deepspeed_plugin.fill_match(
+ "gradient_accumulation_steps",
+ must_match=False,
+ gradient_accumulation_steps=self.gradient_accumulation_steps,
+ )
+
+ config_kwargs = {
+ "gradient_clipping": 1.0,
+ "zero_optimization.stage3_gather_16bit_weights_on_model_save": False,
+ }
+ # This is skipped when preparing just a model
+ if batch_size_per_device is not None:
+ config_kwargs["train_micro_batch_size_per_gpu"] = batch_size_per_device
+ config_kwargs["train_batch_size"] = (
+ batch_size_per_device * deepspeed_plugin.get_value("gradient_accumulation_steps") * self.num_processes
+ )
+
+ model = None
+ optimizer = None
+ scheduler = None
+ for obj in result:
+ if isinstance(obj, torch.nn.Module):
+ model = obj
+ elif isinstance(obj, (torch.optim.Optimizer, DummyOptim)):
+ optimizer = obj
+ elif (isinstance(obj, (LRScheduler, DummyScheduler))) or (
+ type(obj).__name__ in deepspeed.runtime.lr_schedules.VALID_LR_SCHEDULES
+ ):
+ scheduler = obj
+
+ if optimizer is not None:
+ if "optimizer" in deepspeed_plugin.deepspeed_config and not isinstance(optimizer, (DummyOptim)):
+ raise ValueError(
+ "You cannot specify an optimizer in the config file and in the code at the same time. "
+ "Please remove the optimizer from the config file or "
+ "create `accelerate.utils.DummyOptim` in the code."
+ )
+ elif "optimizer" not in deepspeed_plugin.deepspeed_config and isinstance(optimizer, (DummyOptim)):
+ raise ValueError(
+ "You cannot create a `DummyOptim` without specifying an optimizer in the config file."
+ )
+
+ if isinstance(optimizer, (torch.optim.Optimizer)):
+ deepspeed_plugin.deepspeed_config["zero_allow_untested_optimizer"] = True
+
+ if scheduler is not None:
+ if "scheduler" in deepspeed_plugin.deepspeed_config and not isinstance(scheduler, (DummyScheduler)):
+ raise ValueError(
+ "You cannot specify a scheduler in the config file and in the code at the same time. "
+ "Please remove the scheduler from the config file or "
+ "create `accelerate.utils.DummyScheduler` in the code."
+ )
+ elif (
+ "scheduler" not in deepspeed_plugin.deepspeed_config
+ and isinstance(scheduler, (DummyScheduler))
+ and scheduler.lr_scheduler_callable is None
+ ):
+ raise ValueError(
+ "Either specify a scheduler in the config file or "
+ "pass in the `lr_scheduler_callable` parameter when using `accelerate.utils.DummyScheduler`."
+ )
+
+ if optimizer is not None and scheduler is not None:
+ if isinstance(optimizer, (DummyOptim)) and not isinstance(scheduler, (DummyScheduler)):
+ raise ValueError(
+ "You can only specify `accelerate.utils.DummyScheduler` in the code when using "
+ "`accelerate.utils.DummyOptim`."
+ )
+
+ if model is not None:
+ # If we are using FP8, we need to apply the autowrap now
+ if getattr(self.fp8_recipe_handler, "backend", None) == "TE":
+ model = apply_fp8_autowrap(model, self.fp8_recipe_handler)
+ # if the model is an MOE, set the appropriate MOE layers as leaf Z3 modules
+ deepspeed_plugin.set_moe_leaf_modules(model)
+ # deal with config keys that use `auto` value and rely on model's hidden_size
+ hidden_size_based_keys = [
+ "zero_optimization.reduce_bucket_size",
+ "zero_optimization.stage3_prefetch_bucket_size",
+ "zero_optimization.stage3_param_persistence_threshold",
+ ]
+ hidden_size_auto_keys = [x for x in hidden_size_based_keys if deepspeed_plugin.is_auto(x)]
+ if len(hidden_size_auto_keys) > 0:
+ reasoning = (
+ "therefore it's not possible to automatically fill out the following `auto` entries "
+ + f"in the DeepSpeed config file: {hidden_size_auto_keys}. You can fix that by replacing "
+ + "`auto` values for these keys with an integer value of your choice."
+ )
+ if not hasattr(model, "config"):
+ raise ValueError("Can't find `model.config` entry, " + reasoning)
+
+ if hasattr(model.config, "hidden_size"):
+ hidden_size = model.config.hidden_size
+ elif hasattr(model.config, "hidden_sizes"):
+ # if there are many hidden sizes pick the largest one
+ hidden_size = max(model.config.hidden_sizes)
+ else:
+ raise ValueError(
+ "Can find neither `model.config.hidden_size` nor `model.config.hidden_sizes`, " + reasoning
+ )
+
+ config_kwargs.update(
+ {
+ "zero_optimization.reduce_bucket_size": hidden_size * hidden_size,
+ "zero_optimization.stage3_prefetch_bucket_size": int(0.9 * hidden_size * hidden_size),
+ "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size,
+ }
+ )
+
+ if isinstance(optimizer, (DummyOptim)):
+ config_kwargs.update(
+ {"optimizer.params.lr": optimizer.lr, "optimizer.params.weight_decay": optimizer.weight_decay}
+ )
+ if isinstance(scheduler, (DummyScheduler)) and scheduler.lr_scheduler_callable is None:
+ max_lr = (
+ getattr(scheduler.optimizer, "lr", None)
+ if getattr(scheduler.optimizer, "defaults", None) is None
+ else scheduler.optimizer.defaults["lr"]
+ )
+ config_kwargs.update(
+ {
+ "scheduler.params.warmup_min_lr": 0,
+ "scheduler.params.warmup_max_lr": max_lr,
+ "scheduler.params.warmup_num_steps": scheduler.warmup_num_steps,
+ }
+ )
+ if scheduler.total_num_steps is not None:
+ config_kwargs["scheduler.params.total_num_steps"] = (
+ math.ceil(scheduler.total_num_steps / self.num_processes)
+ if not self.split_batches
+ else scheduler.total_num_steps
+ )
+ deepspeed_plugin.deepspeed_config_process(must_match=False, **config_kwargs)
+ self.deepspeed_config = deepspeed_plugin.deepspeed_config
+ kwargs = dict(model=model, config_params=self.deepspeed_config)
+ if optimizer is not None:
+ if isinstance(optimizer, (DummyOptim)):
+ kwargs["model_parameters"] = optimizer.params
+ if isinstance(scheduler, (DummyScheduler)) and scheduler.lr_scheduler_callable is not None:
+ kwargs["lr_scheduler"] = scheduler.lr_scheduler_callable
+ else:
+ if self.deepspeed_config["zero_optimization"].get("offload_optimizer", {}).get(
+ "device", "none"
+ ) != "none" and self.deepspeed_config.get("zero_force_ds_cpu_optimizer", True):
+ from deepspeed.ops.adam import DeepSpeedCPUAdam
+
+ defaults = {k: v for k, v in optimizer.defaults.items() if k in ["lr", "weight_decay"]}
+ optimizer = DeepSpeedCPUAdam(optimizer.param_groups, **defaults)
+ kwargs["optimizer"] = optimizer
+ if scheduler is not None:
+ if type(scheduler).__name__ in deepspeed.runtime.lr_schedules.VALID_LR_SCHEDULES:
+ kwargs["lr_scheduler"] = scheduler
+
+ engine, optimizer, _, lr_scheduler = ds_initialize(**kwargs)
+ if optimizer is not None:
+ optimizer = DeepSpeedOptimizerWrapper(optimizer)
+ if scheduler is not None:
+ if lr_scheduler is None:
+ scheduler = AcceleratedScheduler(
+ scheduler,
+ optimizer,
+ step_with_optimizer=self.step_scheduler_with_optimizer,
+ split_batches=self.split_batches,
+ )
+ else:
+ scheduler = DeepSpeedSchedulerWrapper(lr_scheduler, optimizer)
+
+ for i in range(len(result)):
+ if isinstance(result[i], torch.nn.Module):
+ result[i] = engine
+ elif isinstance(result[i], (torch.optim.Optimizer, DummyOptim)):
+ result[i] = optimizer
+ elif (isinstance(result[i], (LRScheduler, DummyScheduler))) or (
+ type(result[i]).__name__ in deepspeed.runtime.lr_schedules.VALID_LR_SCHEDULES
+ ):
+ result[i] = scheduler
+ # pointing for deepspeed_engine_wrapped.backward()
+ if self.deepspeed_engine_wrapped is None:
+ self.deepspeed_engine_wrapped = DeepSpeedEngineWrapper(engine)
+ else:
+ logger.warning(
+ "A wrapped DeepSpeed engine reference is currently tied for this `Accelerator()` instance. "
+ "If you want to call `accelerator.backward()` referencing a new model/engine, "
+ "please create a separate `Accelerator()` instance and call `accelerator.prepare()` on it."
+ )
+ self._models.append(engine)
+ if optimizer is not None:
+ self._optimizers.append(optimizer)
+ if scheduler is not None:
+ self._schedulers.append(scheduler)
+ return tuple(result)
+
+ def _prepare_megatron_lm(self, *args):
+ megatron_lm_plugin = self.state.megatron_lm_plugin
+ micro_batch_size = None
+ if not megatron_lm_plugin.megatron_dataset_flag:
+ batch_sizes = [obj.batch_size for obj in args if hasattr(obj, "batch_size")]
+ if len(batch_sizes) == 0:
+ raise ValueError(
+ "You must specify a training or evaluation dataloader in `accelerate.prepare()` when using Megatron-LM."
+ )
+
+ micro_batch_size = min(batch_sizes) if megatron_lm_plugin.is_train_batch_min else max(batch_sizes)
+ if len(batch_sizes) > 1:
+ logger.info(
+ "Since you passed both train and evaluation dataloader, `is_train_batch_min` (here "
+ f"{megatron_lm_plugin.is_train_batch_min} will decide the `train_batch_size` ({micro_batch_size})."
+ )
+ else:
+ for obj in args:
+ if isinstance(obj, MegatronLMDummyDataLoader):
+ micro_batch_size = obj.dataset_args["micro_batch_size"]
+ break
+ if micro_batch_size is not None:
+ dp_degree = self.num_processes // (megatron_lm_plugin.tp_degree * megatron_lm_plugin.pp_degree)
+ megatron_lm_plugin.set_training_args(micro_batch_size, dp_degree)
+ else:
+ raise ValueError(
+ "When you do not pass the dataloader parameter, the `data_parallel_size`, "
+ "`micro_batch_size`, and `global_batch_size` megatron parameters will not be updated."
+ )
+ model = None
+ optimizer = None
+ scheduler = None
+ batch_data = None
+ for obj in args:
+ if isinstance(obj, torch.utils.data.DataLoader) and batch_data is None:
+ batch_data = next(iter(obj))
+ elif isinstance(obj, torch.nn.Module):
+ model = obj
+ elif isinstance(obj, (torch.optim.Optimizer)):
+ optimizer = obj
+ elif isinstance(obj, (LRScheduler, MegatronLMDummyScheduler)):
+ scheduler = obj
+
+ if model is not None:
+ megatron_lm_plugin.set_network_size_args(model, batch_data)
+ if optimizer is not None:
+ megatron_lm_plugin.set_optimizer_type(optimizer)
+ if scheduler is not None:
+ if not isinstance(scheduler, MegatronLMDummyScheduler):
+ raise ValueError(
+ "You can't use a custom scheduler with Megatron-LM. Please use the `accelerate.utils.MegatronLMDummyScheduler` instead."
+ )
+ megatron_lm_plugin.set_scheduler_args(scheduler)
+
+ # initialize megatron-lm
+ megatron_lm_initialize(self, args_defaults=megatron_lm_plugin.megatron_lm_default_args)
+
+ (model, optimizer, scheduler) = megatron_lm_prepare_model_optimizer_scheduler(self)
+ self.wait_for_everyone()
+
+ counter = 0
+ result = []
+ for obj in args:
+ if isinstance(obj, torch.utils.data.DataLoader):
+ result.append(megatron_lm_prepare_data_loader(self, obj))
+ counter += 1
+ elif isinstance(obj, MegatronLMDummyDataLoader):
+ if counter == 0:
+ obj.set_megatron_data_args()
+ dataloaders = megatron_lm_prepare_data_loader(self, obj)
+ result.append(dataloaders[counter])
+ counter += 1
+ else:
+ result.append(obj)
+
+ if model is not None:
+ model = MegatronEngine(self, model, optimizer, scheduler)
+ if optimizer is not None:
+ optimizer = MegatronLMOptimizerWrapper(optimizer)
+ if scheduler is not None:
+ scheduler = MegatronLMSchedulerWrapper(scheduler, optimizer)
+
+ for i in range(len(result)):
+ if isinstance(result[i], torch.nn.Module):
+ result[i] = model
+ elif isinstance(result[i], torch.optim.Optimizer):
+ result[i] = optimizer
+ elif isinstance(result[i], MegatronLMDummyScheduler):
+ result[i] = scheduler
+
+ if model is not None:
+ self._models.append(model)
+ if len(self._models) > 1:
+ raise AssertionError(
+ "You can't use same `Accelerator()` instance with multiple models when using Megatron-LM"
+ )
+ if optimizer is not None:
+ self._optimizers.append(optimizer)
+ if scheduler is not None:
+ self._schedulers.append(scheduler)
+
+ return tuple(result)
+
+ def _prepare_ipex_or_xpu(self, *args):
+ """
+ Prepares model and optimizer for training with IPEX or XPU acceleration. This covers 3 cases, IPEX compiled
+ with CPU only support, IPEX compiled with XPU support and training with XPU pytorch backend available in stock
+ pytorch starting from version 2.4.
+ """
+ if self.state.use_ipex:
+ if not is_ipex_available():
+ raise ImportError(
+ "IPEX is not installed or IPEX's version does not match current PyTorch version. Please refer"
+ " to https://github.com/intel/intel-extension-for-pytorch."
+ )
+
+ model = None
+ optimizer = None
+ result = [obj for obj in args]
+ for obj in result:
+ if isinstance(obj, torch.nn.Module):
+ model = obj
+ model.train()
+ elif isinstance(obj, (torch.optim.Optimizer)):
+ optimizer = obj
+ if optimizer is not None and model is not None:
+ dtype = torch.bfloat16 if self.state.mixed_precision == "bf16" else None
+ if self.device.type == "xpu" and model.device.type == "cpu":
+ model = model.to(self.device)
+ # ipex.optimize() is available only for IPEX, both IPEX-CPU and IPEX-XPU
+ if is_ipex_available():
+ import intel_extension_for_pytorch as ipex
+
+ model, optimizer = ipex.optimize(model, optimizer=optimizer, dtype=dtype, inplace=True, level="O1")
+ for i in range(len(result)):
+ if isinstance(result[i], torch.nn.Module):
+ result[i] = model
+ elif isinstance(result[i], (torch.optim.Optimizer)):
+ result[i] = optimizer
+ return tuple(result)
+
+ def _prepare_msamp(self, *args, device_placement):
+ if not is_msamp_available():
+ raise ImportError(
+ "MS-AMP was not found on your system. Please ensure that MS-AMP is available "
+ " or choose `'te'` as the backend for FP8 mixed precision training."
+ )
+ # We've already checked for FSDP + MS-AMP during `__init__`
+ import msamp
+
+ model, optimizer = None, None
+ optimizer_index = None
+ num_models, num_optimizers = 0, 0
+ result = [obj for obj in args]
+ for i, obj in enumerate(result):
+ if isinstance(obj, torch.nn.Module):
+ model = obj
+ num_models += 1
+ elif isinstance(obj, (torch.optim.Optimizer)):
+ optimizer = obj
+ optimizer_index = i
+ num_optimizers += 1
+ # DataLoader/Scheduler case
+ if optimizer is None and model is None:
+ return result, device_placement
+ elif optimizer is None or model is None:
+ raise ValueError(
+ "You must pass a model and an optimizer together to `accelerate.prepare()` when using MS-AMP."
+ )
+ elif num_models > 1 or num_optimizers > 1:
+ raise ValueError(
+ f"You can't use multiple models ({num_models}) or optimizers {num_optimizers} with MS-AMP."
+ )
+ else:
+ model, optimizer = msamp.initialize(model, optimizer, opt_level=self.fp8_recipe_handler.opt_level)
+ for i in range(len(result)):
+ if isinstance(result[i], torch.nn.Module):
+ result[i] = model
+ elif isinstance(result[i], (torch.optim.Optimizer)):
+ result[i] = optimizer
+ if optimizer_index is not None:
+ # NOTE: MS-AMP moves the optimizer, but *not* the model to the right device
+ device_placement[optimizer_index] = False
+ return tuple(result), device_placement
+
+ def prepare_data_loader(
+ self, data_loader: torch.utils.data.DataLoader, device_placement=None, slice_fn_for_dispatch=None
+ ):
+ """
+ Prepares a PyTorch DataLoader for training in any distributed setup. It is recommended to use
+ [`Accelerator.prepare`] instead.
+
+ Args:
+ data_loader (`torch.utils.data.DataLoader`):
+ A vanilla PyTorch DataLoader to prepare
+ device_placement (`bool`, *optional*):
+ Whether or not to place the batches on the proper device in the prepared dataloader. Will default to
+ `self.device_placement`.
+ slice_fn_for_dispatch (`Callable`, *optional*`):
+ If passed, this function will be used to slice tensors across `num_processes`. Will default to
+ [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will
+ be ignored otherwise.
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> data_loader = torch.utils.data.DataLoader(...)
+ >>> data_loader = accelerator.prepare_data_loader(data_loader, device_placement=True)
+ ```
+ """
+ # Ensure we can't double wrap a DataLoader due to `find_batch_size`
+ if getattr(data_loader, "_is_accelerate_prepared", False):
+ if data_loader not in self._dataloaders:
+ self._dataloaders.append(data_loader)
+ return data_loader
+ if device_placement is None:
+ device_placement = self.device_placement if self.distributed_type != DistributedType.XLA else False
+ prepared_data_loader = prepare_data_loader(
+ data_loader,
+ self.device,
+ num_processes=self.num_processes,
+ process_index=self.process_index,
+ split_batches=self.split_batches,
+ put_on_device=device_placement,
+ rng_types=self.rng_types.copy(),
+ dispatch_batches=self.dispatch_batches,
+ even_batches=self.even_batches,
+ slice_fn_for_dispatch=slice_fn_for_dispatch,
+ use_seedable_sampler=self.use_seedable_sampler,
+ non_blocking=self.non_blocking,
+ use_stateful_dataloader=self.use_stateful_dataloader,
+ )
+ self._dataloaders.append(prepared_data_loader)
+ return prepared_data_loader
+
+ def prepare_optimizer(self, optimizer: torch.optim.Optimizer, device_placement=None):
+ """
+ Prepares a PyTorch Optimizer for training in any distributed setup. It is recommended to use
+ [`Accelerator.prepare`] instead.
+
+ Args:
+ optimizer (`torch.optim.Optimizer`):
+ A vanilla PyTorch optimizer to prepare
+ device_placement (`bool`, *optional*):
+ Whether or not to place the optimizer on the proper device. Will default to `self.device_placement`.
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> optimizer = torch.optim.Adam(...)
+ >>> optimizer = accelerator.prepare_optimizer(optimizer, device_placement=True)
+ ```
+ """
+ if is_lomo_available():
+ # We need to import locally to avoid circular imports since lomo imports stuff from
+ # transformers & accelerate
+ from lomo_optim import AdaLomo, Lomo
+
+ # Support multiple optimizers: https://github.com/huggingface/accelerate/pull/2695#discussion_r1589164607
+ self.has_lomo_optimizer |= isinstance(optimizer, (Lomo, AdaLomo))
+
+ # Ensure we can't double wrap an optimizer due to `find_batch_size`
+ if getattr(optimizer, "_is_accelerate_prepared", False):
+ if optimizer not in self._optimizers:
+ self._optimizers.append(optimizer)
+ return optimizer
+ if device_placement is None:
+ device_placement = self.device_placement
+ # NOTE: Special case with MS-AMP we do *not* pass in the scaler explicitly to the `AcceleratedOptimizer`,
+ # Their optimizer handles it for us.
+ scaler = None if self.fp8_backend == "MSAMP" else self.scaler
+ optimizer = AcceleratedOptimizer(optimizer, device_placement=device_placement, scaler=scaler)
+ self._optimizers.append(optimizer)
+ return optimizer
+
+ def prepare_scheduler(self, scheduler: LRScheduler):
+ """
+ Prepares a PyTorch Scheduler for training in any distributed setup. It is recommended to use
+ [`Accelerator.prepare`] instead.
+
+ Args:
+ scheduler (`torch.optim.lr_scheduler.LRScheduler`):
+ A vanilla PyTorch scheduler to prepare
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> optimizer = torch.optim.Adam(...)
+ >>> scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, ...)
+ >>> scheduler = accelerator.prepare_scheduler(scheduler)
+ ```
+ """
+ # Ensure we can't double wrap a scheduler due to `find_batch_size`
+ if getattr(scheduler, "_is_accelerate_prepared", False):
+ if scheduler not in self._schedulers:
+ self._schedulers.append(scheduler)
+ return scheduler
+ # We try to find the optimizer associated with `scheduler`, the default is the full list.
+ optimizer = self._optimizers
+ for opt in self._optimizers:
+ if getattr(scheduler, "optimizer", None) == opt.optimizer:
+ optimizer = opt
+ break
+ scheduler = AcceleratedScheduler(
+ scheduler,
+ optimizer,
+ step_with_optimizer=self.step_scheduler_with_optimizer,
+ split_batches=self.split_batches,
+ )
+ self._schedulers.append(scheduler)
+ return scheduler
+
+ def backward(self, loss, **kwargs):
+ """
+ Scales the gradients in accordance to the `GradientAccumulationPlugin` and calls the correct `backward()` based
+ on the configuration.
+
+ Should be used in lieu of `loss.backward()`.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator(gradient_accumulation_steps=2)
+ >>> outputs = model(inputs)
+ >>> loss = loss_fn(outputs, labels)
+ >>> accelerator.backward(loss)
+ ```
+ """
+ learning_rate = kwargs.get("learning_rate")
+
+ if self.distributed_type != DistributedType.DEEPSPEED:
+ # deepspeed handles loss scaling by gradient_accumulation_steps in its `backward`
+ loss = loss / self.gradient_accumulation_steps
+ if self.distributed_type == DistributedType.DEEPSPEED:
+ self.deepspeed_engine_wrapped.backward(loss, **kwargs)
+ elif self.distributed_type == DistributedType.MEGATRON_LM:
+ return
+ elif self.scaler is not None:
+ self.scaler.scale(loss).backward(**kwargs)
+ elif learning_rate is not None and self.has_lomo_optimizer:
+ self.lomo_backward(loss, learning_rate)
+ else:
+ loss.backward(**kwargs)
+
+ def set_trigger(self):
+ """
+ Sets the internal trigger tensor to 1 on the current process. A latter check should follow using this which
+ will check across all processes.
+
+ Note:
+ Does not require `wait_for_everyone()`
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> # Assume later in the training script
+ >>> # `should_do_breakpoint` is a custom function to monitor when to break,
+ >>> # e.g. when the loss is NaN
+ >>> if should_do_breakpoint(loss):
+ ... accelerator.set_trigger()
+ >>> # Assume later in the training script
+ >>> if accelerator.check_breakpoint():
+ ... break
+ ```
+ """
+ self.flag_tensor = torch.tensor(1, device=self.device)
+
+ def check_trigger(self):
+ """
+ Checks if the internal trigger tensor has been set to 1 in any of the processes. If so, will return `True` and
+ reset the trigger tensor to 0.
+
+ Note:
+ Does not require `wait_for_everyone()`
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> # Assume later in the training script
+ >>> # `should_do_breakpoint` is a custom function to monitor when to break,
+ >>> # e.g. when the loss is NaN
+ >>> if should_do_breakpoint(loss):
+ ... accelerator.set_trigger()
+ >>> # Assume later in the training script
+ >>> if accelerator.check_trigger():
+ ... break
+ ```
+ """
+ # Now that we are outside `__init__`, we can initialize it if it is `None` on device
+ if self.flag_tensor is None:
+ self.flag_tensor = torch.tensor(0, device=self.device)
+ flag_tensor = self.reduce(self.flag_tensor)
+ if flag_tensor.item() >= 1:
+ self.flag_tensor = torch.tensor(0, device=self.device)
+ return True
+ return False
+
+ def unscale_gradients(self, optimizer=None):
+ """
+ Unscale the gradients in mixed precision training with AMP. This is a noop in all other settings.
+
+ Likely should be called through [`Accelerator.clip_grad_norm_`] or [`Accelerator.clip_grad_value_`]
+
+ Args:
+ optimizer (`torch.optim.Optimizer` or `list[torch.optim.Optimizer]`, *optional*):
+ The optimizer(s) for which to unscale gradients. If not set, will unscale gradients on all optimizers
+ that were passed to [`~Accelerator.prepare`].
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> model, optimizer = accelerator.prepare(model, optimizer)
+ >>> outputs = model(inputs)
+ >>> loss = loss_fn(outputs, labels)
+ >>> accelerator.backward(loss)
+ >>> accelerator.unscale_gradients(optimizer=optimizer)
+ ```
+ """
+ if self.native_amp and self.mixed_precision == "fp16":
+ if optimizer is None:
+ # TODO: this unscales all optimizers where we should only unscale the one where parameters are.
+ optimizer = self._optimizers
+ elif not isinstance(optimizer, (tuple, list)):
+ optimizer = [optimizer]
+ for opt in optimizer:
+ while isinstance(opt, AcceleratedOptimizer):
+ opt = opt.optimizer
+ self.scaler.unscale_(opt)
+
+ def clip_grad_norm_(self, parameters, max_norm, norm_type=2):
+ """
+ Should be used in place of `torch.nn.utils.clip_grad_norm_`.
+
+ Returns:
+ `torch.Tensor`: Total norm of the parameter gradients (viewed as a single vector).
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator(gradient_accumulation_steps=2)
+ >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler)
+
+ >>> for input, target in dataloader:
+ ... optimizer.zero_grad()
+ ... output = model(input)
+ ... loss = loss_func(output, target)
+ ... accelerator.backward(loss)
+ ... if accelerator.sync_gradients:
+ ... accelerator.clip_grad_norm_(model.parameters(), max_grad_norm)
+ ... optimizer.step()
+ ```
+ """
+ if self.distributed_type == DistributedType.FSDP:
+ self.unscale_gradients()
+ parameters = [p for p in parameters]
+ for model in self._models:
+ if parameters == [p for p in model.parameters()]:
+ return model.clip_grad_norm_(max_norm, norm_type)
+ elif self.distributed_type == DistributedType.DEEPSPEED:
+ # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed
+ # We cannot return the gradient norm because DeepSpeed does it.
+ return None
+ elif self.distributed_type == DistributedType.XLA:
+ # Reduce gradients first for XLA
+ for acc_opt in self._optimizers:
+ if not acc_opt.gradient_state.is_xla_gradients_synced:
+ opt = acc_opt
+ while isinstance(opt, AcceleratedOptimizer):
+ opt = opt.optimizer
+ gradients = xm._fetch_gradients(opt)
+ # Use xm.all_reduce to perform an in-place all-reduce. Recusrsive all-reduce each tensor
+ # one by one in self.reduce is non-inplace.
+ xm.all_reduce("sum", gradients, scale=1.0 / self.num_processes)
+ # Set is_xla_gradients_synced to True to avoid all-reduce twice in the AcceleratedOptimizer step.
+ acc_opt.gradient_state.is_xla_gradients_synced = True
+ if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true":
+ self.unscale_gradients()
+ parameters = [p for p in parameters]
+ for model in self._models:
+ if parameters == [p for p in model.parameters()]:
+ return model.clip_grad_norm_(max_norm, norm_type)
+ self.unscale_gradients()
+ return torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type=norm_type)
+
+ def clip_grad_value_(self, parameters, clip_value):
+ """
+ Should be used in place of `torch.nn.utils.clip_grad_value_`.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator(gradient_accumulation_steps=2)
+ >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler)
+
+ >>> for input, target in dataloader:
+ ... optimizer.zero_grad()
+ ... output = model(input)
+ ... loss = loss_func(output, target)
+ ... accelerator.backward(loss)
+ ... if accelerator.sync_gradients:
+ ... accelerator.clip_grad_value_(model.parameters(), clip_value)
+ ... optimizer.step()
+ ```
+ """
+ if self.distributed_type in [DistributedType.DEEPSPEED, DistributedType.FSDP]:
+ raise Exception("DeepSpeed and FSDP do not support `clip_grad_value_`. Use `clip_grad_norm_` instead.")
+ self.unscale_gradients()
+ torch.nn.utils.clip_grad_value_(parameters, clip_value)
+
+ def gather(self, tensor):
+ """
+ Gather the values in *tensor* across all processes and concatenate them on the first dimension. Useful to
+ regroup the predictions from all processes when doing evaluation.
+
+ Note:
+ This gather happens in all processes.
+
+ Args:
+ tensor (`torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`):
+ The tensors to gather across all processes.
+
+ Returns:
+ `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`: The gathered tensor(s). Note that the
+ first dimension of the result is *num_processes* multiplied by the first dimension of the input tensors.
+
+ Example:
+
+ ```python
+ >>> # Assuming four processes
+ >>> import torch
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> process_tensor = torch.tensor([accelerator.process_index])
+ >>> gathered_tensor = accelerator.gather(process_tensor)
+ >>> gathered_tensor
+ tensor([0, 1, 2, 3])
+ ```
+ """
+ return gather(tensor)
+
+ def gather_for_metrics(self, input_data, use_gather_object=False):
+ """
+ Gathers `input_data` and potentially drops duplicates in the last batch if on a distributed system. Should be
+ used for gathering the inputs and targets for metric calculation.
+
+ Args:
+ input (`torch.Tensor`, `object`, a nested tuple/list/dictionary of `torch.Tensor`, or a nested tuple/list/dictionary of `object`):
+ The tensors or objects for calculating metrics across all processes
+ use_gather_object(`bool`):
+ Whether to forcibly use gather_object instead of gather (which is already done if all objects passed do
+ not contain tensors). This flag can be useful for gathering tensors with different sizes that we don't
+ want to pad and concatenate along the first dimension. Using it with GPU tensors is not well supported
+ and inefficient as it incurs GPU -> CPU transfer since tensors would be pickled.
+
+ Example:
+
+ ```python
+ >>> # Assuming two processes, with a batch size of 5 on a dataset with 9 samples
+ >>> import torch
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> dataloader = torch.utils.data.DataLoader(range(9), batch_size=5)
+ >>> dataloader = accelerator.prepare(dataloader)
+ >>> batch = next(iter(dataloader))
+ >>> gathered_items = accelerator.gather_for_metrics(batch)
+ >>> len(gathered_items)
+ 9
+ ```
+ """
+
+ try:
+ recursively_apply(lambda x: x, input_data, error_on_other_type=True)
+ all_tensors = True
+ except TypeError:
+ all_tensors = False
+
+ use_gather_object = use_gather_object or not all_tensors
+
+ if use_gather_object:
+ data = gather_object(input_data)
+ else:
+ data = self.gather(input_data)
+
+ try:
+ if self.gradient_state.end_of_dataloader:
+ # at the end of a dataloader, `gather_for_metrics` regresses to
+ # `gather` unless the dataset has a remainder so log.
+ if self.gradient_state.remainder == -1:
+ logger.info(
+ "The used dataset had no length, returning gathered tensors. You should drop the remainder yourself."
+ )
+ return data
+ elif self.gradient_state.remainder > 0:
+ # Last batch needs to be truncated on distributed systems as it contains additional samples
+ def _adjust_samples(tensor):
+ return tensor[: self.gradient_state.remainder]
+
+ if use_gather_object:
+ # gather_object put the objects in a list
+ return _adjust_samples(data)
+ else:
+ return recursively_apply(_adjust_samples, data)
+ else: # remainder is 0
+ # no remainder even though at end of dataloader, so nothing to do.
+ return data
+ else:
+ # Not at the end of the dataloader, no need to adjust the tensors
+ return data
+ except Exception:
+ # Dataset had no length or raised an error
+ return data
+
+ def reduce(self, tensor, reduction="sum", scale=1.0):
+ """
+ Reduce the values in *tensor* across all processes based on *reduction*.
+
+ Note:
+ All processes get the reduced value.
+
+ Args:
+ tensor (`torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`):
+ The tensors to reduce across all processes.
+ reduction (`str`, *optional*, defaults to "sum"):
+ A reduction type, can be one of 'sum', 'mean', or 'none'. If 'none', will not perform any operation.
+ scale (`float`, *optional*, defaults to 1.0):
+ A default scaling value to be applied after the reduce, only valied on XLA.
+
+ Returns:
+ `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`:
+ The reduced tensor(s).
+
+ Example:
+
+ ```python
+ >>> # Assuming two processes
+ >>> import torch
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> process_tensor = torch.arange(accelerator.num_processes) + 1 + (2 * accelerator.process_index)
+ >>> process_tensor = process_tensor.to(accelerator.device)
+ >>> reduced_tensor = accelerator.reduce(process_tensor, reduction="sum")
+ >>> reduced_tensor
+ tensor([4, 6])
+ ```
+ """
+ return reduce(tensor, reduction, scale)
+
+ def pad_across_processes(self, tensor, dim=0, pad_index=0, pad_first=False):
+ """
+ Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so
+ they can safely be gathered.
+
+ Args:
+ tensor (nested list/tuple/dictionary of `torch.Tensor`):
+ The data to gather.
+ dim (`int`, *optional*, defaults to 0):
+ The dimension on which to pad.
+ pad_index (`int`, *optional*, defaults to 0):
+ The value with which to pad.
+ pad_first (`bool`, *optional*, defaults to `False`):
+ Whether to pad at the beginning or the end.
+
+ Returns:
+ `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`:
+ The padded tensor(s).
+
+ Example:
+
+ ```python
+ >>> # Assuming two processes, with the first processes having a tensor of size 1 and the second of size 2
+ >>> import torch
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> process_tensor = torch.arange(accelerator.process_index + 1).to(accelerator.device)
+ >>> padded_tensor = accelerator.pad_across_processes(process_tensor)
+ >>> padded_tensor.shape
+ torch.Size([2])
+ ```
+ """
+ return pad_across_processes(tensor, dim=dim, pad_index=pad_index, pad_first=pad_first)
+
+ def unwrap_model(self, model, keep_fp32_wrapper: bool = True):
+ """
+ Unwraps the `model` from the additional layer possible added by [`~Accelerator.prepare`]. Useful before saving
+ the model.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to unwrap.
+ keep_fp32_wrapper (`bool`, *optional*, defaults to `True`):
+ Whether to not remove the mixed precision hook if it was added.
+
+ Returns:
+ `torch.nn.Module`: The unwrapped model.
+
+ Example:
+
+ ```python
+ >>> # Assuming two GPU processes
+ >>> from torch.nn.parallel import DistributedDataParallel
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> model = accelerator.prepare(MyModel())
+ >>> print(model.__class__.__name__)
+ DistributedDataParallel
+
+ >>> model = accelerator.unwrap_model(model)
+ >>> print(model.__class__.__name__)
+ MyModel
+ ```
+ """
+ return extract_model_from_parallel(model, keep_fp32_wrapper)
+
+ def wait_for_everyone(self):
+ """
+ Will stop the execution of the current process until every other process has reached that point (so this does
+ nothing when the script is only run in one process). Useful to do before saving a model.
+
+ Example:
+
+ ```python
+ >>> # Assuming two GPU processes
+ >>> import time
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> if accelerator.is_main_process:
+ ... time.sleep(2)
+ >>> else:
+ ... print("I'm waiting for the main process to finish its sleep...")
+ >>> accelerator.wait_for_everyone()
+ >>> # Should print on every process at the same time
+ >>> print("Everyone is here")
+ ```
+ """
+ wait_for_everyone()
+
+ @on_main_process
+ def init_trackers(self, project_name: str, config: dict | None = None, init_kwargs: dict | None = {}):
+ """
+ Initializes a run for all trackers stored in `self.log_with`, potentially with starting configurations
+
+ Args:
+ project_name (`str`):
+ The name of the project. All trackers will save their data based on this
+ config (`dict`, *optional*):
+ Optional starting configuration to be logged.
+ init_kwargs (`dict`, *optional*):
+ A nested dictionary of kwargs to be passed to a specific tracker's `__init__` function. Should be
+ formatted like so:
+ ```python
+ {"wandb": {"tags": ["tag_a", "tag_b"]}}
+ ```
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator(log_with="tensorboard")
+ >>> accelerator.init_trackers(
+ ... project_name="my_project",
+ ... config={"learning_rate": 0.001, "batch_size": 32},
+ ... init_kwargs={"tensorboard": {"flush_secs": 60}},
+ ... )
+ ```
+ """
+ for tracker in self.log_with:
+ if issubclass(type(tracker), GeneralTracker):
+ # Custom trackers are already initialized
+ self.trackers.append(tracker)
+ else:
+ tracker_init = LOGGER_TYPE_TO_CLASS[str(tracker)]
+ if tracker_init.requires_logging_directory:
+ # We can skip this check since it was done in `__init__`
+ self.trackers.append(
+ tracker_init(project_name, self.logging_dir, **init_kwargs.get(str(tracker), {}))
+ )
+ else:
+ self.trackers.append(tracker_init(project_name, **init_kwargs.get(str(tracker), {})))
+ if config is not None:
+ for tracker in self.trackers:
+ tracker.store_init_configuration(config)
+
+ def get_tracker(self, name: str, unwrap: bool = False):
+ """
+ Returns a `tracker` from `self.trackers` based on `name` on the main process only.
+
+ Args:
+ name (`str`):
+ The name of a tracker, corresponding to the `.name` property.
+ unwrap (`bool`):
+ Whether to return the internal tracking mechanism or to return the wrapped tracker instead
+ (recommended).
+
+ Returns:
+ `GeneralTracker`: The tracker corresponding to `name` if it exists.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator(log_with="tensorboard")
+ >>> accelerator.init_trackers("my_project")
+ >>> tensorboard_tracker = accelerator.get_tracker("tensorboard")
+ ```
+ """
+ if len(self.trackers) > 0:
+ for tracker in self.trackers:
+ if tracker.name == name:
+ return tracker.tracker if unwrap else tracker
+ raise ValueError(f"{name} is not an available tracker stored inside the `Accelerator`.")
+ # Handle tracker only made on main process
+ return GeneralTracker(_blank=True)
+
+ @on_main_process
+ def log(self, values: dict, step: int | None = None, log_kwargs: dict | None = {}):
+ """
+ Logs `values` to all stored trackers in `self.trackers` on the main process only.
+
+ Args:
+ values (`dict`):
+ Values should be a dictionary-like object containing only types `int`, `float`, or `str`.
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ log_kwargs (`dict`, *optional*):
+ A nested dictionary of kwargs to be passed to a specific tracker's `log` function. Should be formatted
+ like so:
+ ```python
+ {"wandb": {"tags": ["tag_a", "tag_b"]}}
+ ```
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator(log_with="tensorboard")
+ >>> accelerator.init_trackers("my_project")
+ >>> accelerator.log({"loss": 0.5, "accuracy": 0.9})
+ ```
+ """
+ for tracker in self.trackers:
+ tracker.log(values, step=step, **log_kwargs.get(tracker.name, {}))
+
+ def end_training(self):
+ """
+ Runs any special end training behaviors, such as stopping trackers on the main process only or destoying
+ process group. Should always be called at the end of your script if using experiment tracking.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator(log_with="tensorboard")
+ >>> accelerator.init_trackers("my_project")
+ >>> # Do training
+ >>> accelerator.end_training()
+ ```
+ """
+ for tracker in self.trackers:
+ tracker.finish()
+
+ self.state.destroy_process_group()
+
+ def save(self, obj, f, safe_serialization=False):
+ """
+ Save the object passed to disk once per machine. Use in place of `torch.save`.
+
+ Args:
+ obj (`object`): The object to save.
+ f (`str` or `os.PathLike`): Where to save the content of `obj`.
+ safe_serialization (`bool`, *optional*, defaults to `False`): Whether to save `obj` using `safetensors`
+
+ Note:
+ If `save_on_each_node` was passed in as a `ProjectConfiguration`, will save the object once per node,
+ rather than only once on the main node.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> arr = [0, 1, 2, 3]
+ >>> accelerator.save(arr, "array.pkl")
+ ```
+ """
+ save(
+ obj,
+ f,
+ save_on_each_node=self.project_configuration.save_on_each_node,
+ safe_serialization=safe_serialization,
+ )
+
+ def save_model(
+ self,
+ model: torch.nn.Module,
+ save_directory: Union[str, os.PathLike],
+ max_shard_size: Union[int, str] = "10GB",
+ safe_serialization: bool = True,
+ ):
+ """
+ Save a model so that it can be re-loaded using load_checkpoint_in_model
+
+ Arguments:
+ model: (`torch.nn.Module`):
+ Model to be saved. The model can be wrapped or unwraped.
+ save_directory (`str` or `os.PathLike`):
+ Directory to which to save. Will be created if it doesn't exist.
+ max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`):
+ The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
+ lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
+
+
+
+ If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
+ which will be bigger than `max_shard_size`.
+
+
+
+ safe_serialization (`bool`, *optional*, defaults to `True`):
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> model = ...
+ >>> accelerator.save_model(model, save_directory)
+ ```
+ """
+
+ if os.path.isfile(save_directory):
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
+ return
+
+ os.makedirs(save_directory, exist_ok=True)
+
+ # get the state_dict of the model
+ if any(
+ [
+ module._hf_hook.offload
+ for module in model.modules()
+ if hasattr(module, "_hf_hook") and isinstance(module._hf_hook, AlignDevicesHook)
+ ]
+ ):
+ state_dict = get_state_dict_offloaded_model(model)
+ else:
+ if any(param.device == torch.device("meta") for param in model.parameters()):
+ raise RuntimeError("You can't save the model since some parameters are on the meta device.")
+ state_dict = self.get_state_dict(model)
+
+ if safe_serialization:
+ state_dict = clean_state_dict_for_safetensors(state_dict)
+ weights_name = SAFE_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME
+ filename_pattern = SAFE_WEIGHTS_PATTERN_NAME if safe_serialization else WEIGHTS_PATTERN_NAME
+
+ state_dict_split = split_torch_state_dict_into_shards(
+ state_dict, filename_pattern=filename_pattern, max_shard_size=max_shard_size
+ )
+
+ # Clean the folder from a previous save
+ for filename in os.listdir(save_directory):
+ full_filename = os.path.join(save_directory, filename)
+ # If we have a shard file that is not going to be replaced, we delete it, but only from the main process
+ # in distributed settings to avoid race conditions.
+ weights_no_suffix = weights_name.replace(".bin", "")
+
+ # make sure that file to be deleted matches format of sharded file, e.g. pytorch_model-00001-of-00005
+ filename_no_suffix = filename.replace(".bin", "")
+ reg = re.compile(r"(.*?)-\d{5}-of-\d{5}")
+
+ if (
+ filename.startswith(weights_no_suffix)
+ and os.path.isfile(full_filename)
+ and filename not in state_dict_split.filename_to_tensors.keys()
+ and reg.fullmatch(filename_no_suffix) is not None
+ and PartialState().is_main_process
+ ):
+ os.remove(full_filename)
+
+ # Save the model
+ for filename, tensors in state_dict_split.filename_to_tensors.items():
+ shard = {tensor: state_dict[tensor] for tensor in tensors}
+ self.save(shard, os.path.join(save_directory, filename), safe_serialization=safe_serialization)
+
+ # Save index if sharded
+ if state_dict_split.is_sharded:
+ index = {
+ "metadata": state_dict_split.metadata,
+ "weight_map": state_dict_split.tensor_to_filename,
+ }
+ save_index_file = SAFE_WEIGHTS_INDEX_NAME if safe_serialization else WEIGHTS_INDEX_NAME
+ save_index_file = os.path.join(save_directory, save_index_file)
+ with open(save_index_file, "w", encoding="utf-8") as f:
+ content = json.dumps(index, indent=2, sort_keys=True) + "\n"
+ f.write(content)
+ logger.info(
+ f"The model is bigger than the maximum size per checkpoint ({max_shard_size}) and is going to be "
+ f"split in {len(state_dict_split.filename_to_tensors)} checkpoint shards. You can find where each parameters has been saved in the "
+ f"index located at {save_index_file}."
+ )
+ else:
+ path_to_weights = os.path.join(save_directory, WEIGHTS_NAME)
+ logger.info(f"Model weights saved in {path_to_weights}")
+
+ def register_save_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle:
+ """
+ Registers a pre hook to be run before `save_checkpoint` is called in [`Accelerator.save_state`].
+
+ Args:
+ hook (`Callable`):
+ A function to be called in [`Accelerator.save_state`] before `save_checkpoint`.
+
+ The hook should have the following signature:
+
+ `hook(models: list[torch.nn.Module], weights: list[dict[str, torch.Tensor]], input_dir: str) -> None`
+
+ The `models` argument are the models as saved in the accelerator state under `accelerator._models`, `weigths`
+ argument are the state dicts of the `models`, and the `input_dir` argument is the `input_dir` argument passed
+ to [`Accelerator.load_state`].
+
+
+
+ Should only be used in conjunction with [`Accelerator.register_load_state_pre_hook`]. Can be useful to save
+ configurations in addition to model weights. Can also be used to overwrite model saving with a customized
+ method. In this case, make sure to remove already loaded weights from the weights list.
+
+
+
+ Returns:
+ `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling
+ `handle.remove()`
+ """
+ handle = hooks.RemovableHandle(self._save_model_state_pre_hook)
+ self._save_model_state_pre_hook[handle.id] = hook
+ return handle
+
+ def save_state(self, output_dir: str = None, safe_serialization: bool = True, **save_model_func_kwargs):
+ """
+ Saves the current states of the model, optimizer, scaler, RNG generators, and registered objects to a folder.
+
+ If a `ProjectConfiguration` was passed to the `Accelerator` object with `automatic_checkpoint_naming` enabled
+ then checkpoints will be saved to `self.project_dir/checkpoints`. If the number of current saves is greater
+ than `total_limit` then the oldest save is deleted. Each checkpoint is saved in seperate folders named
+ `checkpoint_`.
+
+ Otherwise they are just saved to `output_dir`.
+
+
+
+ Should only be used when wanting to save a checkpoint during training and restoring the state in the same
+ environment.
+
+
+
+ Args:
+ output_dir (`str` or `os.PathLike`):
+ The name of the folder to save all relevant weights and states.
+ safe_serialization (`bool`, *optional*, defaults to `True`):
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
+ save_model_func_kwargs (`dict`, *optional*):
+ Additional keyword arguments for saving model which can be passed to the underlying save function, such
+ as optional arguments for DeepSpeed's `save_checkpoint` function.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> model, optimizer, lr_scheduler = ...
+ >>> model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler)
+ >>> accelerator.save_state(output_dir="my_checkpoint")
+ ```
+ """
+ if self.project_configuration.automatic_checkpoint_naming:
+ output_dir = os.path.join(self.project_dir, "checkpoints")
+ os.makedirs(output_dir, exist_ok=True)
+ if self.project_configuration.automatic_checkpoint_naming:
+ folders = [os.path.join(output_dir, folder) for folder in os.listdir(output_dir)]
+ if (
+ self.project_configuration.total_limit is not None
+ and (len(folders) + 1 > self.project_configuration.total_limit)
+ and self.is_main_process
+ ):
+
+ def _inner(folder):
+ return list(map(int, re.findall(r"[\/]?([0-9]+)(?=[^\/]*$)", folder)))[0]
+
+ folders.sort(key=_inner)
+ logger.warning(
+ f"Deleting {len(folders) + 1 - self.project_configuration.total_limit} checkpoints to make room for new checkpoint."
+ )
+ for folder in folders[: len(folders) + 1 - self.project_configuration.total_limit]:
+ shutil.rmtree(folder)
+ output_dir = os.path.join(output_dir, f"checkpoint_{self.save_iteration}")
+ if os.path.exists(output_dir):
+ raise ValueError(
+ f"Checkpoint directory {output_dir} ({self.save_iteration}) already exists. Please manually override `self.save_iteration` with what iteration to start with."
+ )
+ self.wait_for_everyone()
+ os.makedirs(output_dir, exist_ok=True)
+ logger.info(f"Saving current state to {output_dir}")
+
+ if self.distributed_type == DistributedType.XLA:
+ # Finish running the previous step before checkpointing
+ xm.mark_step()
+
+ # Save the models taking care of FSDP and DeepSpeed nuances
+ weights = []
+ for i, model in enumerate(self._models):
+ if self.distributed_type == DistributedType.FSDP:
+ logger.info("Saving FSDP model")
+ save_fsdp_model(self.state.fsdp_plugin, self, model, output_dir, i)
+ logger.info(f"FSDP Model saved to output dir {output_dir}")
+ elif self.distributed_type == DistributedType.DEEPSPEED:
+ logger.info("Saving DeepSpeed Model and Optimizer")
+ ckpt_id = f"{MODEL_NAME}" if i == 0 else f"{MODEL_NAME}_{i}"
+ model.save_checkpoint(output_dir, ckpt_id, **save_model_func_kwargs)
+ logger.info(f"DeepSpeed Model and Optimizer saved to output dir {os.path.join(output_dir, ckpt_id)}")
+ elif self.distributed_type == DistributedType.MEGATRON_LM:
+ logger.info("Saving Megatron-LM Model, Optimizer and Scheduler")
+ model.save_checkpoint(output_dir)
+ logger.info(f"Megatron-LM Model , Optimizer and Scheduler saved to output dir {output_dir}")
+ else:
+ weights.append(self.get_state_dict(model, unwrap=False))
+
+ # Save the optimizers taking care of FSDP and DeepSpeed nuances
+ optimizers = []
+ if self.distributed_type == DistributedType.FSDP:
+ for i, opt in enumerate(self._optimizers):
+ logger.info("Saving FSDP Optimizer")
+ save_fsdp_optimizer(self.state.fsdp_plugin, self, opt, self._models[i], output_dir, i)
+ logger.info(f"FSDP Optimizer saved to output dir {output_dir}")
+ elif self.distributed_type not in [DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]:
+ optimizers = self._optimizers
+
+ # Save the lr schedulers taking care of DeepSpeed nuances
+ schedulers = []
+ if self.distributed_type == DistributedType.DEEPSPEED:
+ for i, scheduler in enumerate(self._schedulers):
+ if isinstance(scheduler, DeepSpeedSchedulerWrapper):
+ continue
+ schedulers.append(scheduler)
+ elif self.distributed_type not in [DistributedType.MEGATRON_LM]:
+ schedulers = self._schedulers
+
+ # Save the samplers of the dataloaders
+ dataloaders = self._dataloaders
+
+ # Call model loading hooks that might have been registered with
+ # accelerator.register_model_state_hook
+ for hook in self._save_model_state_pre_hook.values():
+ hook(self._models, weights, output_dir)
+
+ save_location = save_accelerator_state(
+ output_dir,
+ weights,
+ optimizers,
+ schedulers,
+ dataloaders,
+ self.state.process_index,
+ self.step,
+ self.scaler,
+ save_on_each_node=self.project_configuration.save_on_each_node,
+ safe_serialization=safe_serialization,
+ )
+ for i, obj in enumerate(self._custom_objects):
+ save_custom_state(obj, output_dir, i, save_on_each_node=self.project_configuration.save_on_each_node)
+ self.project_configuration.iteration += 1
+ return save_location
+
+ def register_load_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle:
+ """
+ Registers a pre hook to be run before [`load_checkpoint`] is called in [`Accelerator.load_state`].
+
+ Args:
+ hook (`Callable`):
+ A function to be called in [`Accelerator.load_state`] before `load_checkpoint`.
+
+ The hook should have the following signature:
+
+ `hook(models: list[torch.nn.Module], input_dir: str) -> None`
+
+ The `models` argument are the models as saved in the accelerator state under `accelerator._models`, and the
+ `input_dir` argument is the `input_dir` argument passed to [`Accelerator.load_state`].
+
+
+
+ Should only be used in conjunction with [`Accelerator.register_save_state_pre_hook`]. Can be useful to load
+ configurations in addition to model weights. Can also be used to overwrite model loading with a customized
+ method. In this case, make sure to remove already loaded models from the models list.
+
+
+
+ Returns:
+ `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling
+ `handle.remove()`
+ """
+ handle = hooks.RemovableHandle(self._load_model_state_pre_hook)
+ self._load_model_state_pre_hook[handle.id] = hook
+ return handle
+
+ def load_state(self, input_dir: str = None, **load_model_func_kwargs):
+ """
+ Loads the current states of the model, optimizer, scaler, RNG generators, and registered objects.
+
+
+
+ Should only be used in conjunction with [`Accelerator.save_state`]. If a file is not registered for
+ checkpointing, it will not be loaded if stored in the directory.
+
+
+
+ Args:
+ input_dir (`str` or `os.PathLike`):
+ The name of the folder all relevant weights and states were saved in. Can be `None` if
+ `automatic_checkpoint_naming` is used, and will pick up from the latest checkpoint.
+ load_model_func_kwargs (`dict`, *optional*):
+ Additional keyword arguments for loading model which can be passed to the underlying load function,
+ such as optional arguments for DeepSpeed's `load_checkpoint` function or a `map_location` to load the
+ model and optimizer on.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> model, optimizer, lr_scheduler = ...
+ >>> model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler)
+ >>> accelerator.load_state("my_checkpoint")
+ ```
+ """
+ if input_dir is not None:
+ # Check if folder exists
+ input_dir = os.path.expanduser(input_dir)
+ if not os.path.isdir(input_dir):
+ raise ValueError(f"Tried to find {input_dir} but folder does not exist")
+ elif self.project_configuration.automatic_checkpoint_naming:
+ # Pick up from automatic checkpoint naming
+ input_dir = os.path.join(self.project_dir, "checkpoints")
+ folders = [os.path.join(input_dir, folder) for folder in os.listdir(input_dir)]
+
+ def _inner(folder):
+ return list(map(int, re.findall(r"[\/]?([0-9]+)(?=[^\/]*$)", folder)))[0]
+
+ folders.sort(key=_inner)
+ input_dir = folders[-1]
+ else:
+ raise ValueError("No input_dir provided and automatic checkpoint naming is disabled.")
+ logger.info(f"Loading states from {input_dir}")
+
+ # Load the models taking care of FSDP and DeepSpeed nuances
+ models = []
+ for i, model in enumerate(self._models):
+ if self.distributed_type == DistributedType.FSDP:
+ logger.info("Loading FSDP model")
+ load_fsdp_model(self.state.fsdp_plugin, self, model, input_dir, i)
+ logger.info(f"FSDP Model loaded from input dir {input_dir}")
+ elif self.distributed_type == DistributedType.DEEPSPEED:
+ logger.info("Loading DeepSpeed Model and Optimizer")
+ ckpt_id = f"{MODEL_NAME}" if i == 0 else f"{MODEL_NAME}_{i}"
+ model.load_checkpoint(input_dir, ckpt_id, **load_model_func_kwargs)
+ logger.info(f"DeepSpeed Model and Optimizer loaded from input dir {os.path.join(input_dir, ckpt_id)}")
+ elif self.distributed_type == DistributedType.MEGATRON_LM:
+ logger.info("Loading Megatron-LM Model, Optimizer and Scheduler")
+ model.load_checkpoint(input_dir)
+ logger.info(f"Megatron-LM Model , Optimizer and Scheduler loaded from input dir {input_dir}")
+ else:
+ models.append(model)
+
+ # Load the optimizers taking care of FSDP and DeepSpeed nuances
+ optimizers = []
+ if self.distributed_type == DistributedType.FSDP:
+ for i, opt in enumerate(self._optimizers):
+ logger.info("Loading FSDP Optimizer")
+ load_fsdp_optimizer(self.state.fsdp_plugin, self, opt, self._models[i], input_dir, i)
+ logger.info(f"FSDP Optimizer loaded from input dir {input_dir}")
+ elif self.distributed_type not in [DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]:
+ optimizers = self._optimizers
+
+ # Load the lr schedulers taking care of DeepSpeed nuances
+ schedulers = []
+ if self.distributed_type == DistributedType.DEEPSPEED:
+ for i, scheduler in enumerate(self._schedulers):
+ if isinstance(scheduler, DeepSpeedSchedulerWrapper):
+ continue
+ schedulers.append(scheduler)
+ elif self.distributed_type not in [DistributedType.MEGATRON_LM]:
+ schedulers = self._schedulers
+
+ dataloaders = self._dataloaders
+
+ # Call model loading hooks that might have been registered with
+ # accelerator.register_model_state_hook
+ for hook in self._load_model_state_pre_hook.values():
+ hook(models, input_dir)
+
+ map_location = load_model_func_kwargs.pop("map_location", None)
+ if map_location is None:
+ if self.num_processes > 1 and self.distributed_type in (
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_NPU,
+ ):
+ map_location = "on_device"
+ else:
+ map_location = "cpu"
+
+ override_attributes = load_accelerator_state(
+ input_dir,
+ models,
+ optimizers,
+ schedulers,
+ dataloaders,
+ self.state.process_index,
+ self.scaler,
+ map_location,
+ **load_model_func_kwargs,
+ )
+ if "step" in override_attributes:
+ self.step = override_attributes["step"]
+ custom_checkpoints = [
+ f for f in os.listdir(input_dir) if re.search(r"^custom_checkpoint_\d+\.pkl$", f) is not None
+ ]
+ if len(custom_checkpoints) != len(self._custom_objects):
+ err = (
+ f"Number of custom checkpoints in folder {input_dir} does not match the number of registered objects:"
+ )
+ err += f"\n\tFound checkpoints: {len(custom_checkpoints)}"
+ err += f"\n\tRegistered objects: {len(self._custom_objects)}\n"
+ err += "Please make sure to only load checkpoints from folders that were created with the same set of registered objects,"
+ err += "or avoid using `custom_checkpoint` in the filename for files in that same directory and load them in manually."
+ raise RuntimeError(err)
+ else:
+ logger.info(f"Loading in {len(custom_checkpoints)} custom states")
+ for index, obj in enumerate(self._custom_objects):
+ load_custom_state(obj, input_dir, index)
+
+ def free_memory(self, *objects):
+ """
+ Will release all references to the internal objects stored and call the garbage collector. You should call this
+ method between two trainings with different models/optimizers. Also will reset `Accelerator.step` to 0.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> model, optimizer, scheduler = ...
+ >>> model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler)
+ >>> model, optimizer, scheduler = accelerator.free_memory(model, optimizer, scheduler)
+ ```
+ """
+ # Deepspeed needs a bit more prep that should be done first
+ if hasattr(self, "deepspeed_engine_wrapped"):
+ if self.deepspeed_engine_wrapped is not None:
+ self.deepspeed_engine_wrapped.engine.destroy()
+ self.deepspeed_engine_wrapped = None
+ objects = release_memory(*objects)
+ self._schedulers = []
+ self._optimizers = []
+ self._models = []
+ self._dataloaders = []
+ self.step = 0
+ return objects
+
+ def clear(self, *objects):
+ """
+ Alias for [`Accelerate.free_memory`], releases all references to the internal objects stored and call the
+ garbage collector. You should call this method between two trainings with different models/optimizers.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> model, optimizer, scheduler = ...
+ >>> model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler)
+ >>> model, optimizer, scheduler = accelerator.clear(model, optimizer, scheduler)
+ ```
+ """
+ return self.free_memory(*objects)
+
+ def _get_named_parameters(self, *args):
+ named_parameters = {}
+ for obj in args:
+ if isinstance(obj, torch.nn.Module):
+ obj = extract_model_from_parallel(obj)
+ named_parameters.update({n: p for n, p in obj.named_parameters()})
+ return named_parameters
+
+ def _get_devices(self, *args):
+ model_device = None
+ optimizer_device = None
+ for obj in args:
+ # Loop through model parameters and stop at the first once we have its device.
+ if isinstance(obj, torch.nn.Module):
+ for param in obj.parameters():
+ model_device = param.device
+ break
+ # Loop through optimizer parameters groups and stop at the first once we have its device.
+ if isinstance(obj, torch.optim.Optimizer):
+ for param_group in obj.param_groups:
+ if len(param_group["params"]) > 0:
+ optimizer_device = param_group["params"][0].device
+ break
+ return (model_device, optimizer_device)
+
+ def get_state_dict(self, model, unwrap=True):
+ """
+ Returns the state dictionary of a model sent through [`Accelerator.prepare`] potentially without full
+ precision.
+
+ Args:
+ model (`torch.nn.Module`):
+ A PyTorch model sent through [`Accelerator.prepare`]
+ unwrap (`bool`, *optional*, defaults to `True`):
+ Whether to return the original underlying state_dict of `model` or to return the wrapped state_dict
+
+ Returns:
+ `dict`: The state dictionary of the model potentially without full precision.
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> net = torch.nn.Linear(2, 2)
+ >>> net = accelerator.prepare(net)
+ >>> state_dict = accelerator.get_state_dict(net)
+ ```
+ """
+
+ if self.distributed_type == DistributedType.DEEPSPEED:
+ if self.deepspeed_config["zero_optimization"]["stage"] == 3:
+ if model.zero_gather_16bit_weights_on_model_save():
+ state_dict = model._zero3_consolidated_16bit_state_dict()
+ else:
+ raise ValueError(
+ "Cannot get 16bit model weights because `stage3_gather_16bit_weights_on_model_save` in DeepSpeed config is False. "
+ "To save the model weights in 16bit, set `stage3_gather_16bit_weights_on_model_save` to True in DeepSpeed config file or "
+ "set `zero3_save_16bit_model` to True when using `accelerate config`. "
+ "To save the full checkpoint, run `model.save_checkpoint(save_dir)` and use `zero_to_fp32.py` to recover weights."
+ )
+ else:
+ from deepspeed.checkpoint.utils import clone_tensors_for_torch_save
+
+ state_dict = clone_tensors_for_torch_save(self.unwrap_model(model).state_dict())
+ elif self.distributed_type == DistributedType.FSDP:
+ from torch.distributed.fsdp import FullStateDictConfig, StateDictType
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+
+ full_state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)
+ with FSDP.state_dict_type(model, StateDictType.FULL_STATE_DICT, full_state_dict_config):
+ state_dict = model.state_dict()
+ else:
+ if unwrap:
+ model = self.unwrap_model(model)
+ state_dict = model.state_dict()
+
+ return state_dict
+
+ def register_for_checkpointing(self, *objects):
+ """
+ Makes note of `objects` and will save or load them in during `save_state` or `load_state`.
+
+ These should be utilized when the state is being loaded or saved in the same script. It is not designed to be
+ used in different scripts.
+
+
+
+ Every `object` must have a `load_state_dict` and `state_dict` function to be stored.
+
+
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> # Assume `CustomObject` has a `state_dict` and `load_state_dict` function.
+ >>> obj = CustomObject()
+ >>> accelerator.register_for_checkpointing(obj)
+ >>> accelerator.save_state("checkpoint.pt")
+ ```
+ """
+ invalid_objects = []
+ for obj in objects:
+ if not hasattr(obj, "state_dict") or not hasattr(obj, "load_state_dict"):
+ invalid_objects.append(obj)
+ if len(invalid_objects) > 0:
+ err = "All `objects` must include a `state_dict` and `load_state_dict` function to be stored. The following inputs are invalid:"
+ for index, obj in enumerate(invalid_objects):
+ err += f"\n\t- Item at index {index}, `{get_pretty_name(obj)}`"
+ raise ValueError(err)
+ self._custom_objects.extend(objects)
+
+ @contextmanager
+ def autocast(self, autocast_handler: AutocastKwargs = None):
+ """
+ Will apply automatic mixed-precision inside the block inside this context manager, if it is enabled. Nothing
+ different will happen otherwise.
+
+ A different `autocast_handler` can be passed in to override the one set in the `Accelerator` object. This is
+ useful in blocks under `autocast` where you want to revert to fp32.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator(mixed_precision="fp16")
+ >>> with accelerator.autocast():
+ ... train()
+ ```
+ """
+ if autocast_handler is None:
+ autocast_handler = self.autocast_handler
+ autocast_context = get_mixed_precision_context_manager(self.native_amp, autocast_handler)
+ autocast_context.__enter__()
+ # TODO: should the `yield` be in a try/finally block?
+ yield
+ autocast_context.__exit__(*sys.exc_info())
+
+ @contextmanager
+ def profile(self, profile_handler: ProfileKwargs | None = None):
+ """
+ Will profile the code inside the context manager. The profile will be saved to a Chrome Trace file if
+ `profile_handler.output_trace_dir` is set.
+
+ A different `profile_handler` can be passed in to override the one set in the `Accelerator` object.
+
+ Args:
+ profile_handler (`ProfileKwargs`, *optional*):
+ The profile handler to use for this context manager. If not passed, will use the one set in the
+ `Accelerator` object.
+
+ Example:
+
+ ```python
+ # Profile with default settings
+ from accelerate import Accelerator
+ from accelerate.utils import ProfileKwargs
+
+ accelerator = Accelerator()
+ with accelerator.profile() as prof:
+ train()
+ accelerator.print(prof.key_averages().table())
+
+
+ # Profile with the custom handler
+ def custom_handler(prof):
+ print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=10))
+
+
+ kwargs = ProfileKwargs(schedule_option=dict(wait=1, warmup=1, active=1), on_trace_ready=custom_handler)
+ accelerator = Accelerator(kwarg_handler=[kwargs])
+ with accelerator.profile() as prof:
+ for _ in range(10):
+ train_iteration()
+ prof.step()
+
+
+ # Profile and export to Chrome Trace
+ kwargs = ProfileKwargs(output_trace_dir="output_trace")
+ accelerator = Accelerator(kwarg_handler=[kwargs])
+ with accelerator.profile():
+ train()
+ ```
+ """
+ profile_handler = profile_handler or self.profile_handler or ProfileKwargs()
+
+ with profile_handler.build() as profiler:
+ yield profiler
+
+ if profile_handler.output_trace_dir is None:
+ return
+
+ os.makedirs(profile_handler.output_trace_dir, exist_ok=True)
+ profiler.export_chrome_trace(
+ os.path.join(profile_handler.output_trace_dir, PROFILE_PATTERN_NAME.format(suffix=self.process_index))
+ )
+ self.wait_for_everyone()
+
+ @property
+ def optimizer_step_was_skipped(self):
+ """
+ Whether or not the optimizer update was skipped (because of gradient overflow in mixed precision), in which
+ case the learning rate should not be changed.
+ """
+ for optimizer in self._optimizers:
+ if optimizer.step_was_skipped:
+ return True
+ return False
+
+ def skip_first_batches(self, dataloader, num_batches: int = 0):
+ """
+ Creates a new `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`.
+
+ Args:
+ dataloader (`torch.utils.data.DataLoader`): The data loader in which to skip batches.
+ num_batches (`int`, *optional*, defaults to 0): The number of batches to skip
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler)
+ >>> skipped_dataloader = accelerator.skip_first_batches(dataloader, num_batches=2)
+ >>> # for the first epoch only
+ >>> for input, target in skipped_dataloader:
+ ... optimizer.zero_grad()
+ ... output = model(input)
+ ... loss = loss_func(output, target)
+ ... accelerator.backward(loss)
+ ... optimizer.step()
+
+ >>> # subsequent epochs
+ >>> for input, target in dataloader:
+ ... optimizer.zero_grad()
+ ... ...
+ ```
+ """
+ return skip_first_batches(dataloader, num_batches=num_batches)
+
+ def __deepcopy__(self, memo):
+ logger.info("Deep copying the `Accelerator` object, note that this will point to the same original object.")
+ return self
+
+ def verify_device_map(self, model: torch.nn.Module) -> bool:
+ """
+ Verifies that `model` has not been prepared with big model inference with a device-map resembling `auto`.
+ """
+ # Checks if any of the child modules has the attribute `hf_device_map` and this map has more than one entry.
+ for m in model.modules():
+ if hasattr(m, "hf_device_map") and len(m.hf_device_map) > 1:
+ return True
+
+ return False
+
+ def lomo_backward(self, loss: torch.Tensor, learning_rate: float) -> None:
+ """
+ Runs backward pass on LOMO optimizers.
+ """
+ if is_lomo_available():
+ # We need to import locally to avoid circular imports since lomo imports stuff from
+ # transformers & accelerate
+ from lomo_optim import AdaLomo, Lomo
+
+ if learning_rate is None:
+ raise ValueError("A learning rate must be passed in order to call backward pass with LOMO optimizers.")
+
+ _backward_called = False
+
+ for optimizer in self._optimizers:
+ if isinstance(optimizer.optimizer, (Lomo, AdaLomo)):
+ optimizer.optimizer.fused_backward(loss, learning_rate)
+ _backward_called = True
+
+ if not _backward_called:
+ raise ValueError(
+ "Backward pass not properly called on LOMO optimizers. Are you sure you passed a LOMO optimizer in accelerator.prepare()?"
+ )
+
+ @property
+ def fp8_backend(self):
+ "Returns the configured backend for training in FP8"
+ if self.mixed_precision == "fp8" and self.fp8_recipe_handler is not None:
+ return self.fp8_recipe_handler.backend
+ elif self.state.deepspeed_plugin is not None and self.state.deepspeed_plugin.enable_msamp:
+ return "MSAMP"
+ return None
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/big_modeling.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/big_modeling.py
new file mode 100644
index 0000000000000000000000000000000000000000..065d6ad6eab7ed72844ea1f8186809bed783ccfa
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/big_modeling.py
@@ -0,0 +1,633 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import logging
+import os
+from contextlib import contextmanager
+from functools import wraps
+from typing import Dict, List, Optional, Union
+
+import torch
+import torch.nn as nn
+
+from .hooks import (
+ AlignDevicesHook,
+ CpuOffload,
+ UserCpuOffloadHook,
+ add_hook_to_module,
+ attach_align_device_hook,
+ attach_align_device_hook_on_blocks,
+)
+from .utils import (
+ OffloadedWeightsLoader,
+ check_cuda_p2p_ib_support,
+ check_device_map,
+ extract_submodules_state_dict,
+ find_tied_parameters,
+ get_balanced_memory,
+ infer_auto_device_map,
+ is_mlu_available,
+ is_musa_available,
+ is_npu_available,
+ is_torch_version,
+ is_xpu_available,
+ load_checkpoint_in_model,
+ offload_state_dict,
+ parse_flag_from_env,
+ retie_parameters,
+)
+from .utils.other import recursive_getattr
+
+
+logger = logging.getLogger(__name__)
+
+
+@contextmanager
+def init_empty_weights(include_buffers: bool = None):
+ """
+ A context manager under which models are initialized with all parameters on the meta device, therefore creating an
+ empty model. Useful when just initializing the model would blow the available RAM.
+
+ Args:
+ include_buffers (`bool`, *optional*):
+ Whether or not to also put all buffers on the meta device while initializing.
+
+ Example:
+
+ ```python
+ import torch.nn as nn
+ from accelerate import init_empty_weights
+
+ # Initialize a model with 100 billions parameters in no time and without using any RAM.
+ with init_empty_weights():
+ tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
+ ```
+
+
+
+ Any model created under this context manager has no weights. As such you can't do something like
+ `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
+ Make sure to overwrite the default device_map param for [`load_checkpoint_and_dispatch`], otherwise dispatch is not
+ called.
+
+
+ """
+ if include_buffers is None:
+ include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False)
+ with init_on_device(torch.device("meta"), include_buffers=include_buffers) as f:
+ yield f
+
+
+@contextmanager
+def init_on_device(device: torch.device, include_buffers: bool = None):
+ """
+ A context manager under which models are initialized with all parameters on the specified device.
+
+ Args:
+ device (`torch.device`):
+ Device to initialize all parameters on.
+ include_buffers (`bool`, *optional*):
+ Whether or not to also put all buffers on the meta device while initializing.
+
+ Example:
+
+ ```python
+ import torch.nn as nn
+ from accelerate import init_on_device
+
+ with init_on_device(device=torch.device("cuda")):
+ tst = nn.Liner(100, 100) # on `cuda` device
+ ```
+ """
+ if include_buffers is None:
+ include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False)
+
+ # TODO(shingjan): remove the torch version check once older versions are deprecated
+ if is_torch_version(">=", "2.0") and include_buffers:
+ with device:
+ yield
+ return
+
+ old_register_parameter = nn.Module.register_parameter
+ if include_buffers:
+ old_register_buffer = nn.Module.register_buffer
+
+ def register_empty_parameter(module, name, param):
+ old_register_parameter(module, name, param)
+ if param is not None:
+ param_cls = type(module._parameters[name])
+ kwargs = module._parameters[name].__dict__
+ kwargs["requires_grad"] = param.requires_grad
+ module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
+
+ def register_empty_buffer(module, name, buffer, persistent=True):
+ old_register_buffer(module, name, buffer, persistent=persistent)
+ if buffer is not None:
+ module._buffers[name] = module._buffers[name].to(device)
+
+ # Patch tensor creation
+ if include_buffers:
+ tensor_constructors_to_patch = {
+ torch_function_name: getattr(torch, torch_function_name)
+ for torch_function_name in ["empty", "zeros", "ones", "full"]
+ }
+ else:
+ tensor_constructors_to_patch = {}
+
+ def patch_tensor_constructor(fn):
+ def wrapper(*args, **kwargs):
+ kwargs["device"] = device
+ return fn(*args, **kwargs)
+
+ return wrapper
+
+ try:
+ nn.Module.register_parameter = register_empty_parameter
+ if include_buffers:
+ nn.Module.register_buffer = register_empty_buffer
+ for torch_function_name in tensor_constructors_to_patch.keys():
+ setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
+ yield
+ finally:
+ nn.Module.register_parameter = old_register_parameter
+ if include_buffers:
+ nn.Module.register_buffer = old_register_buffer
+ for torch_function_name, old_torch_function in tensor_constructors_to_patch.items():
+ setattr(torch, torch_function_name, old_torch_function)
+
+
+def cpu_offload(
+ model: nn.Module,
+ execution_device: Optional[torch.device] = None,
+ offload_buffers: bool = False,
+ state_dict: Optional[Dict[str, torch.Tensor]] = None,
+ preload_module_classes: Optional[List[str]] = None,
+):
+ """
+ Activates full CPU offload for a model. As a result, all parameters of the model will be offloaded and only one
+ copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that
+ state dict and put on the execution device passed as they are needed, then offloaded again.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to offload.
+ execution_device (`torch.device`, *optional*):
+ The device on which the forward pass of the model will be executed (should be a GPU). Will default to the
+ model first parameter device.
+ offload_buffers (`bool`, *optional*, defaults to `False`):
+ Whether or not to offload the buffers with the model parameters.
+ state_dict (`Dict[str, torch.Tensor]`, *optional*):
+ The state dict of the model that will be kept on CPU.
+ preload_module_classes (`List[str]`, *optional*):
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
+ of the forward. This should only be used for classes that have submodules which are registered but not
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
+ """
+ if execution_device is None:
+ execution_device = next(iter(model.parameters())).device
+ if state_dict is None:
+ state_dict = {n: p.to("cpu") for n, p in model.state_dict().items()}
+
+ add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True)
+ attach_align_device_hook(
+ model,
+ execution_device=execution_device,
+ offload=True,
+ offload_buffers=offload_buffers,
+ weights_map=state_dict,
+ preload_module_classes=preload_module_classes,
+ )
+
+ return model
+
+
+def cpu_offload_with_hook(
+ model: torch.nn.Module,
+ execution_device: Optional[Union[int, str, torch.device]] = None,
+ prev_module_hook: Optional[UserCpuOffloadHook] = None,
+):
+ """
+ Offloads a model on the CPU and puts it back to an execution device when executed. The difference with
+ [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when
+ the `offload` method of the returned `hook` is called. Useful for pipelines running a model in a loop.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to offload.
+ execution_device(`str`, `int` or `torch.device`, *optional*):
+ The device on which the model should be executed. Will default to the MPS device if it's available, then
+ GPU 0 if there is a GPU, and finally to the CPU.
+ prev_module_hook (`UserCpuOffloadHook`, *optional*):
+ The hook sent back by this function for a previous model in the pipeline you are running. If passed, its
+ offload method will be called just before the forward of the model to which this hook is attached.
+
+ Example:
+
+ ```py
+ model_1, hook_1 = cpu_offload_with_hook(model_1, cuda_device)
+ model_2, hook_2 = cpu_offload_with_hook(model_2, cuda_device, prev_module_hook=hook_1)
+ model_3, hook_3 = cpu_offload_with_hook(model_3, cuda_device, prev_module_hook=hook_2)
+
+ hid_1 = model_1(input)
+ for i in range(50):
+ # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop.
+ hid_2 = model_2(hid_1)
+ # model2 is offloaded to the CPU just before this forward.
+ hid_3 = model_3(hid_3)
+
+ # For model3, you need to manually call the hook offload method.
+ hook_3.offload()
+ ```
+ """
+ hook = CpuOffload(execution_device=execution_device, prev_module_hook=prev_module_hook)
+ add_hook_to_module(model, hook, append=True)
+ user_hook = UserCpuOffloadHook(model, hook)
+ return model, user_hook
+
+
+def disk_offload(
+ model: nn.Module,
+ offload_dir: Union[str, os.PathLike],
+ execution_device: Optional[torch.device] = None,
+ offload_buffers: bool = False,
+ preload_module_classes: Optional[List[str]] = None,
+):
+ """
+ Activates full disk offload for a model. As a result, all parameters of the model will be offloaded as
+ memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and
+ put on the execution device passed as they are needed, then offloaded again.
+
+ Args:
+ model (`torch.nn.Module`): The model to offload.
+ offload_dir (`str` or `os.PathLike`):
+ The folder in which to offload the model weights (or where the model weights are already offloaded).
+ execution_device (`torch.device`, *optional*):
+ The device on which the forward pass of the model will be executed (should be a GPU). Will default to the
+ model's first parameter device.
+ offload_buffers (`bool`, *optional*, defaults to `False`):
+ Whether or not to offload the buffers with the model parameters.
+ preload_module_classes (`List[str]`, *optional*):
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
+ of the forward. This should only be used for classes that have submodules which are registered but not
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
+ """
+ if not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")):
+ offload_state_dict(offload_dir, model.state_dict())
+ if execution_device is None:
+ execution_device = next(iter(model.parameters())).device
+ weights_map = OffloadedWeightsLoader(save_folder=offload_dir)
+
+ add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True)
+ attach_align_device_hook(
+ model,
+ execution_device=execution_device,
+ offload=True,
+ offload_buffers=offload_buffers,
+ weights_map=weights_map,
+ preload_module_classes=preload_module_classes,
+ )
+
+ return model
+
+
+def dispatch_model(
+ model: nn.Module,
+ device_map: Dict[str, Union[str, int, torch.device]],
+ main_device: Optional[torch.device] = None,
+ state_dict: Optional[Dict[str, torch.Tensor]] = None,
+ offload_dir: Optional[Union[str, os.PathLike]] = None,
+ offload_index: Optional[Dict[str, str]] = None,
+ offload_buffers: bool = False,
+ skip_keys: Optional[Union[str, List[str]]] = None,
+ preload_module_classes: Optional[List[str]] = None,
+ force_hooks: bool = False,
+):
+ """
+ Dispatches a model according to a given device map. Layers of the model might be spread across GPUs, offloaded on
+ the CPU or even the disk.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to dispatch.
+ device_map (`Dict[str, Union[str, int, torch.device]]`):
+ A dictionary mapping module names in the models `state_dict` to the device they should go to. Note that
+ `"disk"` is accepted even if it's not a proper value for `torch.device`.
+ main_device (`str`, `int` or `torch.device`, *optional*):
+ The main execution device. Will default to the first device in the `device_map` different from `"cpu"` or
+ `"disk"`.
+ state_dict (`Dict[str, torch.Tensor]`, *optional*):
+ The state dict of the part of the model that will be kept on CPU.
+ offload_dir (`str` or `os.PathLike`):
+ The folder in which to offload the model weights (or where the model weights are already offloaded).
+ offload_index (`Dict`, *optional*):
+ A dictionary from weight name to their information (`dtype`/ `shape` or safetensors filename). Will default
+ to the index saved in `save_folder`.
+ offload_buffers (`bool`, *optional*, defaults to `False`):
+ Whether or not to offload the buffers with the model parameters.
+ skip_keys (`str` or `List[str]`, *optional*):
+ A list of keys to ignore when moving inputs or outputs between devices.
+ preload_module_classes (`List[str]`, *optional*):
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
+ of the forward. This should only be used for classes that have submodules which are registered but not
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
+ force_hooks (`bool`, *optional*, defaults to `False`):
+ Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a
+ single device.
+ """
+ # Error early if the device map is incomplete.
+ check_device_map(model, device_map)
+
+ # for backward compatibility
+ is_bnb_quantized = (
+ getattr(model, "is_quantized", False) or getattr(model, "is_loaded_in_8bit", False)
+ ) and getattr(model, "quantization_method", "bitsandbytes") == "bitsandbytes"
+
+ # We attach hooks if the device_map has at least 2 different devices or if
+ # force_hooks is set to `True`. Otherwise, the model in already loaded
+ # in the unique device and the user can decide where to dispatch the model.
+ # If the model is quantized, we always force-dispatch the model
+ if (len(set(device_map.values())) > 1) or is_bnb_quantized or force_hooks:
+ if main_device is None:
+ if set(device_map.values()) == {"cpu"} or set(device_map.values()) == {"cpu", "disk"}:
+ main_device = "cpu"
+ else:
+ main_device = [d for d in device_map.values() if d not in ["cpu", "disk"]][0]
+
+ if main_device != "cpu":
+ cpu_modules = [name for name, device in device_map.items() if device == "cpu"]
+ if state_dict is None and len(cpu_modules) > 0:
+ state_dict = extract_submodules_state_dict(model.state_dict(), cpu_modules)
+
+ disk_modules = [name for name, device in device_map.items() if device == "disk"]
+ if offload_dir is None and offload_index is None and len(disk_modules) > 0:
+ raise ValueError(
+ "We need an `offload_dir` to dispatch this model according to this `device_map`, the following submodules "
+ f"need to be offloaded: {', '.join(disk_modules)}."
+ )
+ if (
+ len(disk_modules) > 0
+ and offload_index is None
+ and (not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")))
+ ):
+ disk_state_dict = extract_submodules_state_dict(model.state_dict(), disk_modules)
+ offload_state_dict(offload_dir, disk_state_dict)
+
+ execution_device = {
+ name: main_device if device in ["cpu", "disk"] else device for name, device in device_map.items()
+ }
+ execution_device[""] = main_device
+ offloaded_devices = ["disk"] if main_device == "cpu" or main_device == "mps" else ["cpu", "disk"]
+ offload = {name: device in offloaded_devices for name, device in device_map.items()}
+ save_folder = offload_dir if len(disk_modules) > 0 else None
+ if state_dict is not None or save_folder is not None or offload_index is not None:
+ device = main_device if offload_index is not None else None
+ weights_map = OffloadedWeightsLoader(
+ state_dict=state_dict, save_folder=save_folder, index=offload_index, device=device
+ )
+ else:
+ weights_map = None
+
+ # When dispatching the model's parameters to the devices specified in device_map, we want to avoid allocating memory several times for the
+ # tied parameters. The dictionary tied_params_map keeps track of the already allocated data for a given tied parameter (represented by its
+ # original pointer) on each devices.
+ tied_params = find_tied_parameters(model)
+
+ tied_params_map = {}
+ for group in tied_params:
+ for param_name in group:
+ # data_ptr() is enough here, as `find_tied_parameters` finds tied params simply by comparing `param1 is param2`, so we don't need
+ # to care about views of tensors through storage_offset.
+ data_ptr = recursive_getattr(model, param_name).data_ptr()
+ tied_params_map[data_ptr] = {}
+
+ # Note: To handle the disk offloading case, we can not simply use weights_map[param_name].data_ptr() as the reference pointer,
+ # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
+
+ attach_align_device_hook_on_blocks(
+ model,
+ execution_device=execution_device,
+ offload=offload,
+ offload_buffers=offload_buffers,
+ weights_map=weights_map,
+ skip_keys=skip_keys,
+ preload_module_classes=preload_module_classes,
+ tied_params_map=tied_params_map,
+ )
+
+ # warn if there is any params on the meta device
+ offloaded_devices_str = " and ".join(
+ [device for device in set(device_map.values()) if device in ("cpu", "disk")]
+ )
+ if len(offloaded_devices_str) > 0:
+ logger.warning(
+ f"Some parameters are on the meta device because they were offloaded to the {offloaded_devices_str}."
+ )
+
+ # Attaching the hook may break tied weights, so we retie them
+ retie_parameters(model, tied_params)
+
+ # add warning to cuda and to method
+ def add_warning(fn, model):
+ @wraps(fn)
+ def wrapper(*args, **kwargs):
+ warning_msg = "You shouldn't move a model that is dispatched using accelerate hooks."
+ if str(fn.__name__) == "to":
+ to_device = torch._C._nn._parse_to(*args, **kwargs)[0]
+ if to_device is not None:
+ logger.warning(warning_msg)
+ else:
+ logger.warning(warning_msg)
+ for param in model.parameters():
+ if param.device == torch.device("meta"):
+ raise RuntimeError("You can't move a model that has some modules offloaded to cpu or disk.")
+ return fn(*args, **kwargs)
+
+ return wrapper
+
+ # Make sure to update _accelerate_added_attributes in hooks.py if you add any hook
+ model.to = add_warning(model.to, model)
+ if is_npu_available():
+ model.npu = add_warning(model.npu, model)
+ elif is_mlu_available():
+ model.mlu = add_warning(model.mlu, model)
+ elif is_musa_available():
+ model.musa = add_warning(model.musa, model)
+ elif is_xpu_available():
+ model.xpu = add_warning(model.xpu, model)
+ else:
+ model.cuda = add_warning(model.cuda, model)
+
+ # Check if we are using multi-gpus with RTX 4000 series
+ use_multi_gpu = len([device for device in set(device_map.values()) if device not in ("cpu", "disk")]) > 1
+ if use_multi_gpu and not check_cuda_p2p_ib_support():
+ logger.warning(
+ "We've detected an older driver with an RTX 4000 series GPU. These drivers have issues with P2P. "
+ "This can affect the multi-gpu inference when using accelerate device_map."
+ "Please make sure to update your driver to the latest version which resolves this."
+ )
+ else:
+ device = list(device_map.values())[0]
+ # `torch.Tensor.to()` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)).
+ if is_npu_available() and isinstance(device, int):
+ device = f"npu:{device}"
+ elif is_mlu_available() and isinstance(device, int):
+ device = f"mlu:{device}"
+ elif is_musa_available() and isinstance(device, int):
+ device = f"musa:{device}"
+ elif is_xpu_available() and isinstance(device, int):
+ device = f"xpu:{device}"
+ if device != "disk":
+ model.to(device)
+ else:
+ raise ValueError(
+ "You are trying to offload the whole model to the disk. Please use the `disk_offload` function instead."
+ )
+ # Convert OrderedDict back to dict for easier usage
+ model.hf_device_map = dict(device_map)
+ return model
+
+
+def load_checkpoint_and_dispatch(
+ model: nn.Module,
+ checkpoint: Union[str, os.PathLike],
+ device_map: Optional[Union[str, Dict[str, Union[int, str, torch.device]]]] = None,
+ max_memory: Optional[Dict[Union[int, str], Union[int, str]]] = None,
+ no_split_module_classes: Optional[List[str]] = None,
+ offload_folder: Optional[Union[str, os.PathLike]] = None,
+ offload_buffers: bool = False,
+ dtype: Optional[Union[str, torch.dtype]] = None,
+ offload_state_dict: Optional[bool] = None,
+ skip_keys: Optional[Union[str, List[str]]] = None,
+ preload_module_classes: Optional[List[str]] = None,
+ force_hooks: bool = False,
+ strict: bool = False,
+):
+ """
+ Loads a (potentially sharded) checkpoint inside a model, potentially sending weights to a given device as they are
+ loaded and adds the various hooks that will make this model run properly (even if split across devices).
+
+ Args:
+ model (`torch.nn.Module`): The model in which we want to load a checkpoint.
+ checkpoint (`str` or `os.PathLike`):
+ The folder checkpoint to load. It can be:
+ - a path to a file containing a whole model state dict
+ - a path to a `.json` file containing the index to a sharded checkpoint
+ - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint.
+ device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*):
+ A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer
+ name, once a given module name is inside, every submodule of it will be sent to the same device.
+
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For more
+ information about each option see [here](../concept_guides/big_model_inference#designing-a-device-map).
+ Defaults to None, which means [`dispatch_model`] will not be called.
+ max_memory (`Dict`, *optional*):
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each GPU
+ and the available CPU RAM if unset.
+ no_split_module_classes (`List[str]`, *optional*):
+ A list of layer class names that should never be split across device (for instance any layer that has a
+ residual connection).
+ offload_folder (`str` or `os.PathLike`, *optional*):
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
+ offload_buffers (`bool`, *optional*, defaults to `False`):
+ In the layers that are offloaded on the CPU or the hard drive, whether or not to offload the buffers as
+ well as the parameters.
+ dtype (`str` or `torch.dtype`, *optional*):
+ If provided, the weights will be converted to that type when loaded.
+ offload_state_dict (`bool`, *optional*):
+ If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if
+ the weight of the CPU state dict + the biggest shard does not fit. Will default to `True` if the device map
+ picked contains `"disk"` values.
+ skip_keys (`str` or `List[str]`, *optional*):
+ A list of keys to ignore when moving inputs or outputs between devices.
+ preload_module_classes (`List[str]`, *optional*):
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
+ of the forward. This should only be used for classes that have submodules which are registered but not
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
+ force_hooks (`bool`, *optional*, defaults to `False`):
+ Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a
+ single device.
+ strict (`bool`, *optional*, defaults to `False`):
+ Whether to strictly enforce that the keys in the checkpoint state_dict match the keys of the model's
+ state_dict.
+
+ Example:
+
+ ```python
+ >>> from accelerate import init_empty_weights, load_checkpoint_and_dispatch
+ >>> from huggingface_hub import hf_hub_download
+ >>> from transformers import AutoConfig, AutoModelForCausalLM
+
+ >>> # Download the Weights
+ >>> checkpoint = "EleutherAI/gpt-j-6B"
+ >>> weights_location = hf_hub_download(checkpoint, "pytorch_model.bin")
+
+ >>> # Create a model and initialize it with empty weights
+ >>> config = AutoConfig.from_pretrained(checkpoint)
+ >>> with init_empty_weights():
+ ... model = AutoModelForCausalLM.from_config(config)
+
+ >>> # Load the checkpoint and dispatch it to the right devices
+ >>> model = load_checkpoint_and_dispatch(
+ ... model, weights_location, device_map="auto", no_split_module_classes=["GPTJBlock"]
+ ... )
+ ```
+ """
+ if isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
+ raise ValueError(
+ "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or "
+ "'sequential'."
+ )
+ if isinstance(device_map, str):
+ if device_map != "sequential":
+ max_memory = get_balanced_memory(
+ model,
+ max_memory=max_memory,
+ no_split_module_classes=no_split_module_classes,
+ dtype=dtype,
+ low_zero=(device_map == "balanced_low_0"),
+ )
+ device_map = infer_auto_device_map(
+ model,
+ max_memory=max_memory,
+ no_split_module_classes=no_split_module_classes,
+ dtype=dtype,
+ offload_buffers=offload_buffers,
+ )
+ if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
+ offload_state_dict = True
+ load_checkpoint_in_model(
+ model,
+ checkpoint,
+ device_map=device_map,
+ offload_folder=offload_folder,
+ dtype=dtype,
+ offload_state_dict=offload_state_dict,
+ offload_buffers=offload_buffers,
+ strict=strict,
+ )
+ if device_map is None:
+ return model
+ return dispatch_model(
+ model,
+ device_map=device_map,
+ offload_dir=offload_folder,
+ offload_buffers=offload_buffers,
+ skip_keys=skip_keys,
+ preload_module_classes=preload_module_classes,
+ force_hooks=force_hooks,
+ )
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/checkpointing.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/checkpointing.py
new file mode 100644
index 0000000000000000000000000000000000000000..259ff80c29391d03760c299fbde25e3c8c05ab9e
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/checkpointing.py
@@ -0,0 +1,302 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import random
+from pathlib import Path
+from typing import List
+
+import numpy as np
+import torch
+from safetensors.torch import load_model
+from torch.cuda.amp import GradScaler
+
+from .utils import (
+ MODEL_NAME,
+ OPTIMIZER_NAME,
+ RNG_STATE_NAME,
+ SAFE_MODEL_NAME,
+ SAFE_WEIGHTS_NAME,
+ SAMPLER_NAME,
+ SCALER_NAME,
+ SCHEDULER_NAME,
+ WEIGHTS_NAME,
+ get_pretty_name,
+ is_mlu_available,
+ is_torch_xla_available,
+ is_xpu_available,
+ save,
+)
+
+
+if is_torch_xla_available():
+ import torch_xla.core.xla_model as xm
+
+from .logging import get_logger
+from .state import PartialState
+
+
+logger = get_logger(__name__)
+
+
+def save_accelerator_state(
+ output_dir: str,
+ model_states: List[dict],
+ optimizers: list,
+ schedulers: list,
+ dataloaders: list,
+ process_index: int,
+ step: int,
+ scaler: GradScaler = None,
+ save_on_each_node: bool = False,
+ safe_serialization: bool = True,
+):
+ """
+ Saves the current states of the models, optimizers, scaler, and RNG generators to a given directory.
+
+
+
+ If `safe_serialization` is `True`, models will be saved with `safetensors` while the rest are saved using native
+ `pickle`.
+
+
+
+ Args:
+ output_dir (`str` or `os.PathLike`):
+ The name of the folder to save all relevant weights and states.
+ model_states (`List[torch.nn.Module]`):
+ A list of model states
+ optimizers (`List[torch.optim.Optimizer]`):
+ A list of optimizer instances
+ schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
+ A list of learning rate schedulers
+ dataloaders (`List[torch.utils.data.DataLoader]`):
+ A list of dataloader instances to save their sampler states
+ process_index (`int`):
+ The current process index in the Accelerator state
+ step (`int`):
+ The current step in the internal step tracker
+ scaler (`torch.amp.GradScaler`, *optional*):
+ An optional gradient scaler instance to save;
+ save_on_each_node (`bool`, *optional*):
+ Whether to save on every node, or only the main node.
+ safe_serialization (`bool`, *optional*, defaults to `True`):
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
+ """
+ output_dir = Path(output_dir)
+ # Model states
+ for i, state in enumerate(model_states):
+ weights_name = WEIGHTS_NAME if not safe_serialization else SAFE_WEIGHTS_NAME
+ if i > 0:
+ weights_name = weights_name.replace(".", f"_{i}.")
+ output_model_file = output_dir.joinpath(weights_name)
+ save(state, output_model_file, save_on_each_node=save_on_each_node, safe_serialization=safe_serialization)
+ logger.info(f"Model weights saved in {output_model_file}")
+ # Optimizer states
+ for i, opt in enumerate(optimizers):
+ state = opt.state_dict()
+ optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin"
+ output_optimizer_file = output_dir.joinpath(optimizer_name)
+ save(state, output_optimizer_file, save_on_each_node=save_on_each_node, safe_serialization=False)
+ logger.info(f"Optimizer state saved in {output_optimizer_file}")
+ # Scheduler states
+ for i, scheduler in enumerate(schedulers):
+ state = scheduler.state_dict()
+ scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin"
+ output_scheduler_file = output_dir.joinpath(scheduler_name)
+ save(state, output_scheduler_file, save_on_each_node=save_on_each_node, safe_serialization=False)
+ logger.info(f"Scheduler state saved in {output_scheduler_file}")
+ # DataLoader states
+ for i, dataloader in enumerate(dataloaders):
+ sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin"
+ output_sampler_file = output_dir.joinpath(sampler_name)
+ # Only save if we have our custom sampler
+ from .data_loader import IterableDatasetShard, SeedableRandomSampler
+
+ if isinstance(dataloader.dataset, IterableDatasetShard):
+ sampler = dataloader.get_sampler()
+ if isinstance(sampler, SeedableRandomSampler):
+ save(sampler, output_sampler_file, save_on_each_node=save_on_each_node, safe_serialization=False)
+ if getattr(dataloader, "use_stateful_dataloader", False):
+ dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin"
+ output_dataloader_state_dict_file = output_dir.joinpath(dataloader_state_dict_name)
+ state_dict = dataloader.state_dict()
+ torch.save(state_dict, output_dataloader_state_dict_file)
+ logger.info(f"Sampler state for dataloader {i} saved in {output_sampler_file}")
+
+ # GradScaler state
+ if scaler is not None:
+ state = scaler.state_dict()
+ output_scaler_file = output_dir.joinpath(SCALER_NAME)
+ torch.save(state, output_scaler_file)
+ logger.info(f"Gradient scaler state saved in {output_scaler_file}")
+ # Random number generator states
+ states = {}
+ states_name = f"{RNG_STATE_NAME}_{process_index}.pkl"
+ states["step"] = step
+ states["random_state"] = random.getstate()
+ states["numpy_random_seed"] = np.random.get_state()
+ states["torch_manual_seed"] = torch.get_rng_state()
+ if is_xpu_available():
+ states["torch_xpu_manual_seed"] = torch.xpu.get_rng_state_all()
+ if is_mlu_available():
+ states["torch_mlu_manual_seed"] = torch.mlu.get_rng_state_all()
+ else:
+ states["torch_cuda_manual_seed"] = torch.cuda.get_rng_state_all()
+ if is_torch_xla_available():
+ states["xm_seed"] = xm.get_rng_state()
+ output_states_file = output_dir.joinpath(states_name)
+ torch.save(states, output_states_file)
+ logger.info(f"Random states saved in {output_states_file}")
+ return output_dir
+
+
+def load_accelerator_state(
+ input_dir,
+ models,
+ optimizers,
+ schedulers,
+ dataloaders,
+ process_index,
+ scaler=None,
+ map_location=None,
+ **load_model_func_kwargs,
+):
+ """
+ Loads states of the models, optimizers, scaler, and RNG generators from a given directory.
+
+ Args:
+ input_dir (`str` or `os.PathLike`):
+ The name of the folder to load all relevant weights and states.
+ models (`List[torch.nn.Module]`):
+ A list of model instances
+ optimizers (`List[torch.optim.Optimizer]`):
+ A list of optimizer instances
+ schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
+ A list of learning rate schedulers
+ process_index (`int`):
+ The current process index in the Accelerator state
+ scaler (`torch.amp.GradScaler`, *optional*):
+ An optional *GradScaler* instance to load
+ map_location (`str`, *optional*):
+ What device to load the optimizer state onto. Should be one of either "cpu" or "on_device".
+ load_model_func_kwargs (`dict`, *optional*):
+ Additional arguments that can be passed to the model's `load_state_dict` method.
+
+ Returns:
+ `dict`: Contains the `Accelerator` attributes to override while loading the state.
+ """
+ # stores the `Accelerator` attributes to override
+ override_attributes = dict()
+ if map_location not in [None, "cpu", "on_device"]:
+ raise TypeError(
+ "Unsupported optimizer map location passed, please choose one of `None`, `'cpu'`, or `'on_device'`"
+ )
+ if map_location is None:
+ map_location = "cpu"
+ elif map_location == "on_device":
+ map_location = PartialState().device
+
+ input_dir = Path(input_dir)
+ # Model states
+ for i, model in enumerate(models):
+ ending = f"_{i}" if i > 0 else ""
+ input_model_file = input_dir.joinpath(f"{SAFE_MODEL_NAME}{ending}.safetensors")
+ if input_model_file.exists():
+ load_model(model, input_model_file, device=str(map_location), **load_model_func_kwargs)
+ else:
+ # Load with torch
+ input_model_file = input_dir.joinpath(f"{MODEL_NAME}{ending}.bin")
+ state_dict = torch.load(input_model_file, map_location=map_location)
+ model.load_state_dict(state_dict, **load_model_func_kwargs)
+ logger.info("All model weights loaded successfully")
+
+ # Optimizer states
+ for i, opt in enumerate(optimizers):
+ optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin"
+ input_optimizer_file = input_dir.joinpath(optimizer_name)
+ optimizer_state = torch.load(input_optimizer_file, map_location=map_location)
+ optimizers[i].load_state_dict(optimizer_state)
+ logger.info("All optimizer states loaded successfully")
+
+ # Scheduler states
+ for i, scheduler in enumerate(schedulers):
+ scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin"
+ input_scheduler_file = input_dir.joinpath(scheduler_name)
+ scheduler.load_state_dict(torch.load(input_scheduler_file))
+ logger.info("All scheduler states loaded successfully")
+
+ for i, dataloader in enumerate(dataloaders):
+ sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin"
+ input_sampler_file = input_dir.joinpath(sampler_name)
+ # Only load if we have our custom sampler
+ from .data_loader import IterableDatasetShard, SeedableRandomSampler
+
+ if isinstance(dataloader.dataset, IterableDatasetShard):
+ sampler = dataloader.get_sampler()
+ if isinstance(sampler, SeedableRandomSampler):
+ sampler = dataloader.set_sampler(torch.load(input_sampler_file))
+ if getattr(dataloader, "use_stateful_dataloader", False):
+ dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin"
+ input_dataloader_state_dict_file = input_dir.joinpath(dataloader_state_dict_name)
+ if input_dataloader_state_dict_file.exists():
+ state_dict = torch.load(input_dataloader_state_dict_file)
+ dataloader.load_state_dict(state_dict)
+ logger.info("All dataloader sampler states loaded successfully")
+
+ # GradScaler state
+ if scaler is not None:
+ input_scaler_file = input_dir.joinpath(SCALER_NAME)
+ scaler.load_state_dict(torch.load(input_scaler_file))
+ logger.info("GradScaler state loaded successfully")
+
+ # Random states
+ try:
+ states = torch.load(input_dir.joinpath(f"{RNG_STATE_NAME}_{process_index}.pkl"))
+ if "step" in states:
+ override_attributes["step"] = states["step"]
+ random.setstate(states["random_state"])
+ np.random.set_state(states["numpy_random_seed"])
+ torch.set_rng_state(states["torch_manual_seed"])
+ if is_xpu_available():
+ torch.xpu.set_rng_state_all(states["torch_xpu_manual_seed"])
+ if is_mlu_available():
+ torch.mlu.set_rng_state_all(states["torch_mlu_manual_seed"])
+ else:
+ torch.cuda.set_rng_state_all(states["torch_cuda_manual_seed"])
+ if is_torch_xla_available():
+ xm.set_rng_state(states["xm_seed"])
+ logger.info("All random states loaded successfully")
+ except Exception:
+ logger.info("Could not load random states")
+
+ return override_attributes
+
+
+def save_custom_state(obj, path, index: int = 0, save_on_each_node: bool = False):
+ """
+ Saves the state of `obj` to `{path}/custom_checkpoint_{index}.pkl`
+ """
+ # Should this be the right way to get a qual_name type value from `obj`?
+ save_location = Path(path) / f"custom_checkpoint_{index}.pkl"
+ logger.info(f"Saving the state of {get_pretty_name(obj)} to {save_location}")
+ save(obj.state_dict(), save_location, save_on_each_node=save_on_each_node)
+
+
+def load_custom_state(obj, path, index: int = 0):
+ """
+ Loads the state of `obj` at `{path}/custom_checkpoint_{index}.pkl`
+ """
+ load_location = f"{path}/custom_checkpoint_{index}.pkl"
+ logger.info(f"Loading the state of {get_pretty_name(obj)} from {load_location}")
+ obj.load_state_dict(torch.load(load_location, map_location="cpu"))
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/__init__.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9cbe26c257b515f657c05e1996d517e69613972
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/accelerate_cli.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/accelerate_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9790e5805c225f78c073595f7f38e9f22cc9dbf
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/accelerate_cli.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from accelerate.commands.config import get_config_parser
+from accelerate.commands.env import env_command_parser
+from accelerate.commands.estimate import estimate_command_parser
+from accelerate.commands.launch import launch_command_parser
+from accelerate.commands.merge import merge_command_parser
+from accelerate.commands.test import test_command_parser
+from accelerate.commands.tpu import tpu_command_parser
+from accelerate.commands.utils import CustomArgumentParser
+
+
+def main():
+ parser = CustomArgumentParser("Accelerate CLI tool", usage="accelerate []", allow_abbrev=False)
+ subparsers = parser.add_subparsers(help="accelerate command helpers")
+
+ # Register commands
+ get_config_parser(subparsers=subparsers)
+ estimate_command_parser(subparsers=subparsers)
+ env_command_parser(subparsers=subparsers)
+ launch_command_parser(subparsers=subparsers)
+ merge_command_parser(subparsers=subparsers)
+ tpu_command_parser(subparsers=subparsers)
+ test_command_parser(subparsers=subparsers)
+
+ # Let's go
+ args = parser.parse_args()
+
+ if not hasattr(args, "func"):
+ parser.print_help()
+ exit(1)
+
+ # Run
+ args.func(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/__init__.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..649a15888cccd070b3d4ca9a600457c6ad59d4d3
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/__init__.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+
+from .config import config_command_parser
+from .config_args import default_config_file, load_config_from_file # noqa: F401
+from .default import default_command_parser
+from .update import update_command_parser
+
+
+def get_config_parser(subparsers=None):
+ parent_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
+ # The main config parser
+ config_parser = config_command_parser(subparsers)
+ # The subparser to add commands to
+ subcommands = config_parser.add_subparsers(title="subcommands", dest="subcommand")
+
+ # Then add other parsers with the parent parser
+ default_command_parser(subcommands, parents=[parent_parser])
+ update_command_parser(subcommands, parents=[parent_parser])
+
+ return config_parser
+
+
+def main():
+ config_parser = get_config_parser()
+ args = config_parser.parse_args()
+
+ if not hasattr(args, "func"):
+ config_parser.print_help()
+ exit(1)
+
+ # Run
+ args.func(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/cluster.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/cluster.py
new file mode 100644
index 0000000000000000000000000000000000000000..0862b9c9b09a0be7b393e0d79035cd0ee70a0867
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/cluster.py
@@ -0,0 +1,828 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+
+from ...utils import (
+ ComputeEnvironment,
+ DistributedType,
+ is_deepspeed_available,
+ is_fp8_available,
+ is_mlu_available,
+ is_mps_available,
+ is_msamp_available,
+ is_musa_available,
+ is_npu_available,
+ is_transformer_engine_available,
+ is_transformers_available,
+ is_xpu_available,
+)
+from ...utils.constants import (
+ DEEPSPEED_MULTINODE_LAUNCHERS,
+ FSDP_AUTO_WRAP_POLICY,
+ FSDP_BACKWARD_PREFETCH,
+ FSDP_SHARDING_STRATEGY,
+ FSDP_STATE_DICT_TYPE,
+ TORCH_DYNAMO_MODES,
+)
+from .config_args import ClusterConfig
+from .config_utils import (
+ DYNAMO_BACKENDS,
+ _ask_field,
+ _ask_options,
+ _convert_distributed_mode,
+ _convert_dynamo_backend,
+ _convert_fp8_backend,
+ _convert_mixed_precision,
+ _convert_yes_no_to_bool,
+)
+
+
+def get_cluster_input():
+ distributed_type = _ask_options(
+ "Which type of machine are you using?",
+ [
+ "No distributed training",
+ "multi-CPU",
+ "multi-XPU",
+ "multi-GPU",
+ "multi-NPU",
+ "multi-MLU",
+ "multi-MUSA",
+ "TPU",
+ ],
+ _convert_distributed_mode,
+ )
+
+ machine_rank = 0
+ num_machines = 1
+ num_processes = 1
+ gpu_ids = None
+ main_process_ip = None
+ main_process_port = None
+ rdzv_backend = "static"
+ same_network = True
+ debug = False
+
+ if distributed_type in [
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_XPU,
+ DistributedType.MULTI_CPU,
+ ]:
+ num_machines = _ask_field(
+ "How many different machines will you use (use more than 1 for multi-node training)? [1]: ",
+ int,
+ default=1,
+ )
+ if num_machines > 1:
+ machine_rank = _ask_options(
+ "What is the rank of this machine?",
+ list(range(num_machines)),
+ int,
+ )
+ main_process_ip = _ask_field(
+ "What is the IP address of the machine that will host the main process? ",
+ )
+ main_process_port = _ask_field(
+ "What is the port you will use to communicate with the main process? ",
+ int,
+ )
+ same_network = _ask_field(
+ "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]: ",
+ _convert_yes_no_to_bool,
+ default=True,
+ error_message="Please enter yes or no.",
+ )
+ if not same_network:
+ rdzv_backend = _ask_field(
+ "What rendezvous backend will you use? ('static', 'c10d', ...): ", default="static"
+ )
+ debug = _ask_field(
+ "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+
+ if distributed_type == DistributedType.NO:
+ use_cpu = _ask_field(
+ "Do you want to run your training on CPU only (even if a GPU / Apple Silicon / Ascend NPU device is available)? [yes/NO]:",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ elif distributed_type == DistributedType.MULTI_CPU:
+ use_cpu = True
+ else:
+ use_cpu = False
+
+ ipex_config = {}
+ mpirun_config = {}
+ if use_cpu:
+ ipex_config["ipex"] = _ask_field(
+ "Do you want to use Intel PyTorch Extension (IPEX) to speed up training on CPU? [yes/NO]:",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if distributed_type == DistributedType.MULTI_CPU:
+ use_mpirun = _ask_field(
+ "Do you want accelerate to launch mpirun? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if use_mpirun:
+ mpirun_hostfile = _ask_field(
+ "Please enter the path to the hostfile to use with mpirun [~/hostfile]: ",
+ str,
+ default="~/hostfile",
+ )
+ mpirun_config["mpirun_hostfile"] = os.path.expanduser(mpirun_hostfile.strip())
+ mpirun_config["mpirun_ccl"] = _ask_field("Enter the number of oneCCL worker threads [1]: ", default=1)
+ if (
+ not use_cpu
+ and is_xpu_available()
+ and distributed_type
+ not in [
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.XLA,
+ DistributedType.MULTI_MUSA,
+ ]
+ ):
+ ipex_config["use_xpu"] = _ask_field(
+ "Do you want to use XPU plugin to speed up training on XPU? [yes/NO]:",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+
+ dynamo_config = {}
+ use_dynamo = _ask_field(
+ "Do you wish to optimize your script with torch dynamo?[yes/NO]:",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if use_dynamo:
+ prefix = "dynamo_"
+ dynamo_config[prefix + "backend"] = _ask_options(
+ "Which dynamo backend would you like to use?",
+ [x.lower() for x in DYNAMO_BACKENDS],
+ _convert_dynamo_backend,
+ default=2,
+ )
+ use_custom_options = _ask_field(
+ "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+
+ if use_custom_options:
+ dynamo_config[prefix + "mode"] = _ask_options(
+ "Which mode do you want to use?",
+ TORCH_DYNAMO_MODES,
+ lambda x: TORCH_DYNAMO_MODES[int(x)],
+ default=0,
+ )
+ dynamo_config[prefix + "use_fullgraph"] = _ask_field(
+ "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ dynamo_config[prefix + "use_dynamic"] = _ask_field(
+ "Do you want to enable dynamic shape tracing? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+
+ use_mps = not use_cpu and is_mps_available()
+ deepspeed_config = {}
+ if (
+ distributed_type
+ in [
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_XPU,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.NO,
+ ]
+ and not use_mps
+ ):
+ use_deepspeed = _ask_field(
+ "Do you want to use DeepSpeed? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if use_deepspeed:
+ distributed_type = DistributedType.DEEPSPEED
+ assert (
+ is_deepspeed_available()
+ ), "DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source"
+
+ if distributed_type == DistributedType.DEEPSPEED:
+ use_deepspeed_config = _ask_field(
+ "Do you want to specify a json file to a DeepSpeed config? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if use_deepspeed_config:
+ deepspeed_config["deepspeed_config_file"] = _ask_field(
+ "Please enter the path to the json DeepSpeed config file: ",
+ str,
+ default="none",
+ )
+ else:
+ deepspeed_config["zero_stage"] = _ask_options(
+ "What should be your DeepSpeed's ZeRO optimization stage?",
+ [0, 1, 2, 3],
+ int,
+ default=2,
+ )
+
+ deepspeed_devices = ["none", "cpu", "nvme"]
+ if deepspeed_config["zero_stage"] >= 2:
+ deepspeed_config["offload_optimizer_device"] = _ask_options(
+ "Where to offload optimizer states?", deepspeed_devices, lambda x: deepspeed_devices[int(x)]
+ )
+ deepspeed_config["offload_param_device"] = _ask_options(
+ "Where to offload parameters?", deepspeed_devices, lambda x: deepspeed_devices[int(x)]
+ )
+ if deepspeed_config["offload_param_device"] == "nvme":
+ deepspeed_config["offload_param_nvme_path"] = _ask_field(
+ "Nvme Path to offload parameters?",
+ str,
+ default="/nvme",
+ )
+ if deepspeed_config["offload_optimizer_device"] == "nvme":
+ deepspeed_config["offload_optimizer_nvme_path"] = _ask_field(
+ "Nvme Path to offload optimizer states?",
+ str,
+ default="/nvme",
+ )
+ deepspeed_config["gradient_accumulation_steps"] = _ask_field(
+ "How many gradient accumulation steps you're passing in your script? [1]: ",
+ int,
+ default=1,
+ )
+ use_gradient_clipping = _ask_field(
+ "Do you want to use gradient clipping? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if use_gradient_clipping:
+ deepspeed_config["gradient_clipping"] = _ask_field(
+ "What is the gradient clipping value? [1.0]: ",
+ float,
+ default=1.0,
+ )
+ if deepspeed_config["zero_stage"] == 3:
+ deepspeed_config["zero3_save_16bit_model"] = _ask_field(
+ "Do you want to save 16-bit model weights when using ZeRO Stage-3? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ deepspeed_config["zero3_init_flag"] = _ask_field(
+ "Do you want to enable `deepspeed.zero.Init` when using ZeRO Stage-3 for constructing massive models? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if deepspeed_config["zero3_init_flag"]:
+ if not is_transformers_available():
+ raise Exception(
+ "When `zero3_init_flag` is set, it requires Transformers to be installed. "
+ "Please run `pip3 install transformers`."
+ )
+ use_moe = _ask_field(
+ "Do you want to enable Mixture-of-Experts training (MoE)? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if use_moe:
+ deepspeed_config["deepspeed_moe_layer_cls_names"] = _ask_field(
+ "Specify the comma-separated list of transformers MoE layer class names (case-sensitive), e.g : "
+ " `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ... : ",
+ str,
+ )
+
+ if num_machines > 1:
+ launcher_query = "Which Type of launcher do you want to use?"
+ deepspeed_config["deepspeed_multinode_launcher"] = _ask_options(
+ launcher_query,
+ DEEPSPEED_MULTINODE_LAUNCHERS,
+ lambda x: DEEPSPEED_MULTINODE_LAUNCHERS[int(x)],
+ )
+
+ if deepspeed_config["deepspeed_multinode_launcher"] != DEEPSPEED_MULTINODE_LAUNCHERS[1]:
+ deepspeed_config["deepspeed_hostfile"] = _ask_field(
+ "DeepSpeed configures multi-node compute resources with hostfile. "
+ "Each row is of the format `hostname slots=[num_gpus]`, e.g., `localhost slots=2`; "
+ "for more information please refer official [documentation]"
+ "(https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node). "
+ "Please specify the location of hostfile: ",
+ str,
+ )
+
+ is_exclusion_filter = _ask_field(
+ "Do you want to specify exclusion filter string? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if is_exclusion_filter:
+ deepspeed_config["deepspeed_exclusion_filter"] = _ask_field(
+ "DeepSpeed exclusion filter string: ",
+ str,
+ )
+
+ is_inclusion_filter = _ask_field(
+ "Do you want to specify inclusion filter string? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if is_inclusion_filter:
+ deepspeed_config["deepspeed_inclusion_filter"] = _ask_field(
+ "DeepSpeed inclusion filter string: ",
+ str,
+ )
+
+ fsdp_config = {}
+ if distributed_type in [
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_XPU,
+ ]:
+ use_fsdp = _ask_field(
+ "Do you want to use FullyShardedDataParallel? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if use_fsdp:
+ distributed_type = DistributedType.FSDP
+ if distributed_type == DistributedType.FSDP:
+ sharding_strategy_query = "What should be your sharding strategy?"
+ fsdp_config["fsdp_sharding_strategy"] = _ask_options(
+ sharding_strategy_query,
+ FSDP_SHARDING_STRATEGY,
+ lambda x: FSDP_SHARDING_STRATEGY[int(x)],
+ )
+ fsdp_config["fsdp_offload_params"] = _ask_field(
+ "Do you want to offload parameters and gradients to CPU? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ fsdp_wrap_query = "What should be your auto wrap policy?"
+ fsdp_config["fsdp_auto_wrap_policy"] = _ask_options(
+ fsdp_wrap_query,
+ FSDP_AUTO_WRAP_POLICY,
+ lambda x: FSDP_AUTO_WRAP_POLICY[int(x)],
+ )
+ if fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[0]:
+ use_no_split_modules = _ask_field(
+ "Do you want to use the model's `_no_split_modules` to wrap. Only applicable for 🤗 Transformers [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if not use_no_split_modules:
+ fsdp_config["fsdp_transformer_layer_cls_to_wrap"] = _ask_field(
+ "Specify the comma-separated list of transformer layer class names (case-sensitive) to wrap ,e.g, :"
+ "`BertLayer`, `GPTJBlock`, `T5Block`, `BertLayer,BertEmbeddings,BertSelfOutput` ...? : ",
+ str,
+ )
+ elif fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[1]:
+ fsdp_config["fsdp_min_num_params"] = _ask_field(
+ "What should be your FSDP's minimum number of parameters for Default Auto Wrapping Policy? [1e8]: ",
+ int,
+ default=100000000,
+ )
+ fsdp_backward_prefetch_query = "What should be your FSDP's backward prefetch policy?"
+ fsdp_config["fsdp_backward_prefetch"] = _ask_options(
+ fsdp_backward_prefetch_query,
+ FSDP_BACKWARD_PREFETCH,
+ lambda x: FSDP_BACKWARD_PREFETCH[int(x)],
+ )
+ fsdp_state_dict_type_query = "What should be your FSDP's state dict type?"
+ fsdp_config["fsdp_state_dict_type"] = _ask_options(
+ fsdp_state_dict_type_query,
+ FSDP_STATE_DICT_TYPE,
+ lambda x: FSDP_STATE_DICT_TYPE[int(x)],
+ default=2,
+ )
+ fsdp_config["fsdp_forward_prefetch"] = _ask_field(
+ "Do you want to enable FSDP's forward prefetch policy? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ fsdp_config["fsdp_use_orig_params"] = _ask_field(
+ "Do you want to enable FSDP's `use_orig_params` feature? [YES/no]: ",
+ _convert_yes_no_to_bool,
+ default=True,
+ error_message="Please enter yes or no.",
+ )
+ fsdp_config["fsdp_cpu_ram_efficient_loading"] = _ask_field(
+ "Do you want to enable CPU RAM efficient model loading? Only applicable for 🤗 Transformers models. [YES/no]: ",
+ _convert_yes_no_to_bool,
+ default=True,
+ error_message="Please enter yes or no.",
+ )
+ if fsdp_config["fsdp_cpu_ram_efficient_loading"]:
+ fsdp_config["fsdp_sync_module_states"] = True
+ else:
+ fsdp_config["fsdp_sync_module_states"] = _ask_field(
+ "Do you want each individually wrapped FSDP unit to broadcast module parameters from rank 0 at the start? [YES/no]: ",
+ _convert_yes_no_to_bool,
+ default=True,
+ error_message="Please enter yes or no.",
+ )
+ fsdp_config["fsdp_activation_checkpointing"] = _ask_field(
+ "Do you want to enable FSDP activation checkpointing? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+
+ megatron_lm_config = {}
+ if distributed_type in [DistributedType.MULTI_GPU]:
+ use_megatron_lm = _ask_field(
+ "Do you want to use Megatron-LM ? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if use_megatron_lm:
+ distributed_type = DistributedType.MEGATRON_LM
+ if distributed_type == DistributedType.MEGATRON_LM:
+ prefix = "megatron_lm_"
+ megatron_lm_config[prefix + "tp_degree"] = _ask_field(
+ "What is the Tensor Parallelism degree/size? [1]:",
+ int,
+ default=1,
+ error_message="Please enter an integer.",
+ )
+ if megatron_lm_config[prefix + "tp_degree"] > 1:
+ megatron_lm_config[prefix + "sequence_parallelism"] = _ask_field(
+ "Do you want to enable Sequence Parallelism? [YES/no]: ",
+ _convert_yes_no_to_bool,
+ default=True,
+ error_message="Please enter yes or no.",
+ )
+
+ megatron_lm_config[prefix + "pp_degree"] = _ask_field(
+ "What is the Pipeline Parallelism degree/size? [1]:",
+ int,
+ default=1,
+ error_message="Please enter an integer.",
+ )
+ if megatron_lm_config[prefix + "pp_degree"] > 1:
+ megatron_lm_config[prefix + "num_micro_batches"] = _ask_field(
+ "What is the number of micro-batches? [1]:",
+ int,
+ default=1,
+ error_message="Please enter an integer.",
+ )
+
+ megatron_lm_config[prefix + "recompute_activations"] = _ask_field(
+ "Do you want to enable selective activation recomputation? [YES/no]: ",
+ _convert_yes_no_to_bool,
+ default=True,
+ error_message="Please enter yes or no.",
+ )
+
+ megatron_lm_config[prefix + "use_distributed_optimizer"] = _ask_field(
+ "Do you want to use distributed optimizer "
+ "which shards optimizer state and gradients across data parallel ranks? [YES/no]: ",
+ _convert_yes_no_to_bool,
+ default=True,
+ error_message="Please enter yes or no.",
+ )
+
+ megatron_lm_config[prefix + "gradient_clipping"] = _ask_field(
+ "What is the gradient clipping value based on global L2 Norm (0 to disable)? [1.0]: ",
+ float,
+ default=1.0,
+ )
+ # TPU specific defaults
+ tpu_commands = None
+ tpu_command_file = None
+ tpu_downcast_bf16 = "no"
+ tpu_env = []
+ tpu_name = None
+ tpu_vm = None
+ tpu_zone = None
+ tpu_use_sudo = False
+ tpu_use_cluster = False
+
+ if distributed_type in [
+ DistributedType.MULTI_CPU,
+ DistributedType.MULTI_XPU,
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_NPU,
+ DistributedType.XLA,
+ ]:
+ machine_type = str(distributed_type).split(".")[1].replace("MULTI_", "")
+ if machine_type == "TPU":
+ machine_type += " cores"
+ elif machine_type == "CPU":
+ machine_type = "processes"
+ else:
+ machine_type += "(s)"
+ num_processes = _ask_field(
+ f"How many {machine_type} should be used for distributed training? [1]:",
+ int,
+ default=1,
+ error_message="Please enter an integer.",
+ )
+ elif distributed_type in [DistributedType.FSDP, DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]:
+ num_processes = _ask_field(
+ "How many GPU(s) should be used for distributed training? [1]:",
+ int,
+ default=1,
+ error_message="Please enter an integer.",
+ )
+ else:
+ num_processes = 1
+
+ if (distributed_type == DistributedType.MULTI_GPU) and (num_machines == 1) and (num_processes == 1):
+ raise ValueError(
+ 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."
+ )
+
+ if (
+ distributed_type
+ in [
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_XPU,
+ DistributedType.NO,
+ ]
+ and not use_cpu
+ and not use_mps
+ ):
+ if is_npu_available():
+ machine_type = "NPU(s)"
+ elif is_mlu_available():
+ machine_type = "MLU(s)"
+ elif is_musa_available():
+ machine_type = "MUSA(s)"
+ else:
+ machine_type = "GPU(s)"
+ gpu_ids = _ask_field(
+ f"What {machine_type} (by id) should be used for training on this machine as a comma-seperated list? [all]:",
+ default="all",
+ )
+
+ # CPU affinity is only supported on NVIDIA hardware for now
+ enable_cpu_affinity = False
+ if distributed_type in (DistributedType.NO, DistributedType.MULTI_GPU) and not use_cpu and not use_mps:
+ enable_cpu_affinity = _ask_field(
+ "Would you like to enable numa efficiency? (Currently only supported on NVIDIA hardware). [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+
+ fp8_config = None
+ if distributed_type == DistributedType.XLA:
+ mixed_precision = "no"
+ main_training_function = _ask_field(
+ "What is the name of the function in your script that should be launched in all parallel scripts? [main]: ",
+ default="main",
+ )
+ tpu_use_cluster = _ask_field(
+ "Are you using a TPU cluster? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if tpu_use_cluster:
+ tpu_name = _ask_field(
+ "What is the name of your TPU cluster? ",
+ default=None,
+ error_message="Please enter the name of your TPU cluster.",
+ )
+ tpu_zone = _ask_field(
+ "What is the zone of your TPU cluster? ",
+ default=None,
+ error_message="Please enter the zone of your TPU cluster.",
+ )
+ tpu_use_sudo = _ask_field(
+ "To run a python script in a TPU pod, should `sudo` be used? [yes/NO]: ",
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ run_commands = _ask_field(
+ "Do you have code you wish to run on startup in each pod? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if run_commands:
+ use_command_file = _ask_field(
+ "Is this code located in a bash script? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if use_command_file:
+ tpu_command_file = _ask_field(
+ "What is the path to your bash script? ",
+ default=None,
+ error_message="Please enter the path to your bash script.",
+ )
+ tpu_command_file = os.path.abspath(tpu_command_file)
+ else:
+ print("Please enter each command seperately you wish to run on startup in each pod.")
+ tpu_commands = []
+ another_command = True
+ while another_command:
+ tpu_commands.append(
+ _ask_field(
+ "Please enter a single command to be ran ",
+ default=None,
+ error_message="Please enter the commands you wish to run on startup in each pod as a single string.",
+ )
+ )
+ another_command = _ask_field(
+ "Do you wish to add another command? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ tpu_vm = _ask_field(
+ "If not using an instance group, what are the names of the Compute VM instances to be used, seperated by a comma: ",
+ default="",
+ ).split(",")
+ tpu_env = _ask_field(
+ "What environment variables do you wish to set in each pod, seperated by a comma: ",
+ default="",
+ ).split(",")
+
+ else:
+ main_training_function = "main"
+ if distributed_type == DistributedType.DEEPSPEED and use_deepspeed_config:
+ mixed_precision = None
+ else:
+ mixed_precision = _ask_options(
+ "Do you wish to use mixed precision?",
+ ["no", "fp16", "bf16", "fp8"],
+ _convert_mixed_precision,
+ )
+ if mixed_precision == "fp8":
+ if not is_fp8_available():
+ raise ValueError("FP8 (either Transformer Engine or MSAMP) is not installed on this machine.")
+ fp8_config = {}
+ fp8_config["backend"] = _ask_options(
+ "Which FP8 backend do you want to use?",
+ ["te", "msamp"],
+ _convert_fp8_backend,
+ )
+ if fp8_config["backend"] == "TE":
+ if not is_transformer_engine_available():
+ raise ValueError("TransformersEngine was selected, but it is not installed on this machine.")
+ fp8_config["use_autocast_during_eval"] = _ask_field(
+ "Do you want to use FP8 autocast during eval mode? Generally better metrics are found when this is disabled [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ )
+ fp8_config["margin"] = _ask_field(
+ "What margin should be used for gradient scaling? [0]: ",
+ int,
+ default=0,
+ )
+ fp8_config["interval"] = _ask_field(
+ "What interval should be used for for how often the scaling factor is recomputed? [1]: ",
+ int,
+ default=1,
+ )
+ fp8_config["fp8_format"] = _ask_options(
+ "Which weight format should be used?",
+ ["HYBRID", "E4M3"],
+ lambda x: "HYBRID" if x == 0 else "E4M3",
+ default=0,
+ )
+ fp8_config["amax_history_length"] = _ask_field(
+ "What length of history should be used for the amax scaling factor computation? [1024]: ",
+ int,
+ default=1024,
+ )
+ fp8_config["amax_compute_algorithm"] = _ask_options(
+ "Which algorithm should be used for the amax scaling factor computation?",
+ ["max", "most_recent"],
+ lambda x: "max" if x == 0 else "most_recent",
+ default=0,
+ )
+ fp8_config["override_linear_precision"] = _ask_field(
+ "Do you want to to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ )
+ if fp8_config["override_linear_precision"]:
+ fprop = _ask_field(
+ "Should `fprop` be executed in higher precision? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ )
+ dgrad = _ask_field(
+ "Should `dgrad` be executed in higher precision? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ )
+ wgrad = _ask_field(
+ "Should `wgrad` be executed in higher precision? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ )
+ fp8_config["override_linear_precision"] = (fprop, dgrad, wgrad)
+
+ elif fp8_config["backend"] == "MSAMP":
+ if not is_msamp_available():
+ raise ValueError("MSAMP was selected, but it is not installed on this machine.")
+ fp8_config["optimization_level"] = _ask_options(
+ "Which optimization level should be used?",
+ ["O1", "O2"],
+ lambda x: "O1" if x == 0 else "O2",
+ default=1,
+ )
+
+ if use_dynamo and mixed_precision == "no" and not use_cpu:
+ print(
+ "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts."
+ )
+
+ if distributed_type == DistributedType.XLA and mixed_precision == "bf16":
+ tpu_downcast_bf16 = _ask_field(
+ "Should `torch.float` be cast as `bfloat16` and `torch.double` remain `float32` on TPUs?", default="no"
+ )
+
+ return ClusterConfig(
+ compute_environment=ComputeEnvironment.LOCAL_MACHINE,
+ distributed_type=distributed_type,
+ num_processes=num_processes,
+ gpu_ids=gpu_ids,
+ mixed_precision=mixed_precision,
+ downcast_bf16=tpu_downcast_bf16,
+ machine_rank=machine_rank,
+ num_machines=num_machines,
+ main_process_ip=main_process_ip,
+ main_process_port=main_process_port,
+ main_training_function=main_training_function,
+ fp8_config=fp8_config,
+ deepspeed_config=deepspeed_config,
+ fsdp_config=fsdp_config,
+ megatron_lm_config=megatron_lm_config,
+ ipex_config=ipex_config,
+ mpirun_config=mpirun_config,
+ use_cpu=use_cpu,
+ rdzv_backend=rdzv_backend,
+ same_network=same_network,
+ commands=tpu_commands,
+ command_file=tpu_command_file,
+ tpu_env=tpu_env,
+ tpu_name=tpu_name,
+ tpu_vm=tpu_vm,
+ tpu_zone=tpu_zone,
+ tpu_use_sudo=tpu_use_sudo,
+ tpu_use_cluster=tpu_use_cluster,
+ dynamo_config=dynamo_config,
+ debug=debug,
+ enable_cpu_affinity=enable_cpu_affinity,
+ )
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..72414f2abe62d76bd5133f4b0ed99bf34133f6f6
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+import os
+
+from accelerate.utils import ComputeEnvironment
+
+from .cluster import get_cluster_input
+from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401
+from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401
+from .sagemaker import get_sagemaker_input
+
+
+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"
+
+
+def get_user_input():
+ compute_environment = _ask_options(
+ "In which compute environment are you running?",
+ ["This machine", "AWS (Amazon SageMaker)"],
+ _convert_compute_environment,
+ )
+ if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
+ config = get_sagemaker_input()
+ else:
+ config = get_cluster_input()
+ return config
+
+
+def config_command_parser(subparsers=None):
+ if subparsers is not None:
+ parser = subparsers.add_parser("config", description=description)
+ else:
+ parser = argparse.ArgumentParser("Accelerate config command", description=description)
+
+ parser.add_argument(
+ "--config_file",
+ default=None,
+ help=(
+ "The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
+ "with 'huggingface'."
+ ),
+ )
+
+ if subparsers is not None:
+ parser.set_defaults(func=config_command)
+ return parser
+
+
+def config_command(args):
+ config = get_user_input()
+ if args.config_file is not None:
+ config_file = args.config_file
+ else:
+ if not os.path.isdir(cache_dir):
+ os.makedirs(cache_dir)
+ config_file = default_yaml_config_file
+
+ if config_file.endswith(".json"):
+ config.to_json_file(config_file)
+ else:
+ config.to_yaml_file(config_file)
+ print(f"accelerate configuration saved at {config_file}")
+
+
+def main():
+ parser = config_command_parser()
+ args = parser.parse_args()
+ config_command(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config_args.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config_args.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3991b2808dc715676e147f8b7d6d1440d9fb6e1
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config_args.py
@@ -0,0 +1,252 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import os
+from dataclasses import dataclass
+from enum import Enum
+from typing import List, Optional, Union
+
+import yaml
+
+from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
+from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION
+
+
+hf_cache_home = os.path.expanduser(
+ os.environ.get("HF_HOME", os.path.join(os.environ.get("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
+)
+cache_dir = os.path.join(hf_cache_home, "accelerate")
+default_json_config_file = os.path.join(cache_dir, "default_config.yaml")
+default_yaml_config_file = os.path.join(cache_dir, "default_config.yaml")
+
+# For backward compatibility: the default config is the json one if it's the only existing file.
+if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
+ default_config_file = default_yaml_config_file
+else:
+ default_config_file = default_json_config_file
+
+
+def load_config_from_file(config_file):
+ if config_file is not None:
+ if not os.path.isfile(config_file):
+ raise FileNotFoundError(
+ f"The passed configuration file `{config_file}` does not exist. "
+ "Please pass an existing file to `accelerate launch`, or use the default one "
+ "created through `accelerate config` and run `accelerate launch` "
+ "without the `--config_file` argument."
+ )
+ else:
+ config_file = default_config_file
+ with open(config_file, encoding="utf-8") as f:
+ if config_file.endswith(".json"):
+ if (
+ json.load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE)
+ == ComputeEnvironment.LOCAL_MACHINE
+ ):
+ config_class = ClusterConfig
+ else:
+ config_class = SageMakerConfig
+ return config_class.from_json_file(json_file=config_file)
+ else:
+ if (
+ yaml.safe_load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE)
+ == ComputeEnvironment.LOCAL_MACHINE
+ ):
+ config_class = ClusterConfig
+ else:
+ config_class = SageMakerConfig
+ return config_class.from_yaml_file(yaml_file=config_file)
+
+
+@dataclass
+class BaseConfig:
+ compute_environment: ComputeEnvironment
+ distributed_type: Union[DistributedType, SageMakerDistributedType]
+ mixed_precision: str
+ use_cpu: bool
+ debug: bool
+
+ def to_dict(self):
+ result = self.__dict__
+ # For serialization, it's best to convert Enums to strings (or their underlying value type).
+
+ def _convert_enums(value):
+ if isinstance(value, Enum):
+ return value.value
+ if isinstance(value, dict):
+ if not bool(value):
+ return None
+ for key1, value1 in value.items():
+ value[key1] = _convert_enums(value1)
+ return value
+
+ for key, value in result.items():
+ result[key] = _convert_enums(value)
+ result = {k: v for k, v in result.items() if v is not None}
+ return result
+
+ @staticmethod
+ def process_config(config_dict):
+ """
+ Processes `config_dict` and sets default values for any missing keys
+ """
+ if "compute_environment" not in config_dict:
+ config_dict["compute_environment"] = ComputeEnvironment.LOCAL_MACHINE
+ if "distributed_type" not in config_dict:
+ raise ValueError("A `distributed_type` must be specified in the config file.")
+ if "num_processes" not in config_dict and config_dict["distributed_type"] == DistributedType.NO:
+ config_dict["num_processes"] = 1
+ if "mixed_precision" not in config_dict:
+ config_dict["mixed_precision"] = "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
+ if "fp16" in config_dict: # Convert the config to the new format.
+ del config_dict["fp16"]
+ if "dynamo_backend" in config_dict: # Convert the config to the new format.
+ dynamo_backend = config_dict.pop("dynamo_backend")
+ config_dict["dynamo_config"] = {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
+ if "use_cpu" not in config_dict:
+ config_dict["use_cpu"] = False
+ if "debug" not in config_dict:
+ config_dict["debug"] = False
+ if "enable_cpu_affinity" not in config_dict:
+ config_dict["enable_cpu_affinity"] = False
+ return config_dict
+
+ @classmethod
+ def from_json_file(cls, json_file=None):
+ json_file = default_json_config_file if json_file is None else json_file
+ with open(json_file, encoding="utf-8") as f:
+ config_dict = json.load(f)
+ config_dict = cls.process_config(config_dict)
+ extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys()))
+ if len(extra_keys) > 0:
+ raise ValueError(
+ f"The config file at {json_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`"
+ " version or fix (and potentially remove) these keys from your config file."
+ )
+
+ return cls(**config_dict)
+
+ def to_json_file(self, json_file):
+ with open(json_file, "w", encoding="utf-8") as f:
+ content = json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
+ f.write(content)
+
+ @classmethod
+ def from_yaml_file(cls, yaml_file=None):
+ yaml_file = default_yaml_config_file if yaml_file is None else yaml_file
+ with open(yaml_file, encoding="utf-8") as f:
+ config_dict = yaml.safe_load(f)
+ config_dict = cls.process_config(config_dict)
+ extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys()))
+ if len(extra_keys) > 0:
+ raise ValueError(
+ f"The config file at {yaml_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`"
+ " version or fix (and potentially remove) these keys from your config file."
+ )
+ return cls(**config_dict)
+
+ def to_yaml_file(self, yaml_file):
+ with open(yaml_file, "w", encoding="utf-8") as f:
+ yaml.safe_dump(self.to_dict(), f)
+
+ def __post_init__(self):
+ if isinstance(self.compute_environment, str):
+ self.compute_environment = ComputeEnvironment(self.compute_environment)
+ if isinstance(self.distributed_type, str):
+ if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
+ self.distributed_type = SageMakerDistributedType(self.distributed_type)
+ else:
+ self.distributed_type = DistributedType(self.distributed_type)
+ if getattr(self, "dynamo_config", None) is None:
+ self.dynamo_config = {}
+
+
+@dataclass
+class ClusterConfig(BaseConfig):
+ num_processes: int = -1 # For instance if we use SLURM and the user manually passes it in
+ machine_rank: int = 0
+ num_machines: int = 1
+ gpu_ids: Optional[str] = None
+ main_process_ip: Optional[str] = None
+ main_process_port: Optional[int] = None
+ rdzv_backend: Optional[str] = "static"
+ same_network: Optional[bool] = False
+ main_training_function: str = "main"
+ enable_cpu_affinity: bool = False
+
+ # args for FP8 training
+ fp8_config: dict = None
+ # args for deepspeed_plugin
+ deepspeed_config: dict = None
+ # args for fsdp
+ fsdp_config: dict = None
+ # args for megatron_lm
+ megatron_lm_config: dict = None
+ # args for ipex
+ ipex_config: dict = None
+ # args for mpirun
+ mpirun_config: dict = None
+ # args for TPU
+ downcast_bf16: bool = False
+
+ # args for TPU pods
+ tpu_name: str = None
+ tpu_zone: str = None
+ tpu_use_cluster: bool = False
+ tpu_use_sudo: bool = False
+ command_file: str = None
+ commands: List[str] = None
+ tpu_vm: List[str] = None
+ tpu_env: List[str] = None
+
+ # args for dynamo
+ dynamo_config: dict = None
+
+ def __post_init__(self):
+ if self.deepspeed_config is None:
+ self.deepspeed_config = {}
+ if self.fsdp_config is None:
+ self.fsdp_config = {}
+ if self.megatron_lm_config is None:
+ self.megatron_lm_config = {}
+ if self.ipex_config is None:
+ self.ipex_config = {}
+ if self.mpirun_config is None:
+ self.mpirun_config = {}
+ if self.fp8_config is None:
+ self.fp8_config = {}
+ return super().__post_init__()
+
+
+@dataclass
+class SageMakerConfig(BaseConfig):
+ ec2_instance_type: str
+ iam_role_name: str
+ image_uri: Optional[str] = None
+ profile: Optional[str] = None
+ region: str = "us-east-1"
+ num_machines: int = 1
+ gpu_ids: str = "all"
+ base_job_name: str = f"accelerate-sagemaker-{num_machines}"
+ pytorch_version: str = SAGEMAKER_PYTORCH_VERSION
+ transformers_version: str = SAGEMAKER_TRANSFORMERS_VERSION
+ py_version: str = SAGEMAKER_PYTHON_VERSION
+ sagemaker_inputs_file: str = None
+ sagemaker_metrics_file: str = None
+ additional_args: dict = None
+ dynamo_config: dict = None
+ enable_cpu_affinity: bool = False
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config_utils.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f62570813a479bf8f695d11a7daa15e54a2e0b70
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/config_utils.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+
+from ...utils.dataclasses import (
+ ComputeEnvironment,
+ DistributedType,
+ DynamoBackend,
+ FP8BackendType,
+ PrecisionType,
+ SageMakerDistributedType,
+)
+from ..menu import BulletMenu
+
+
+DYNAMO_BACKENDS = [
+ "EAGER",
+ "AOT_EAGER",
+ "INDUCTOR",
+ "AOT_TS_NVFUSER",
+ "NVPRIMS_NVFUSER",
+ "CUDAGRAPHS",
+ "OFI",
+ "FX2TRT",
+ "ONNXRT",
+ "TENSORRT",
+ "AOT_TORCHXLA_TRACE_ONCE",
+ "TORHCHXLA_TRACE_ONCE",
+ "IPEX",
+ "TVM",
+]
+
+
+def _ask_field(input_text, convert_value=None, default=None, error_message=None):
+ ask_again = True
+ while ask_again:
+ result = input(input_text)
+ try:
+ if default is not None and len(result) == 0:
+ return default
+ return convert_value(result) if convert_value is not None else result
+ except Exception:
+ if error_message is not None:
+ print(error_message)
+
+
+def _ask_options(input_text, options=[], convert_value=None, default=0):
+ menu = BulletMenu(input_text, options)
+ result = menu.run(default_choice=default)
+ return convert_value(result) if convert_value is not None else result
+
+
+def _convert_compute_environment(value):
+ value = int(value)
+ return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value])
+
+
+def _convert_distributed_mode(value):
+ value = int(value)
+ return DistributedType(
+ ["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "MULTI_MLU", "MULTI_MUSA", "XLA"][value]
+ )
+
+
+def _convert_dynamo_backend(value):
+ value = int(value)
+ return DynamoBackend(DYNAMO_BACKENDS[value]).value
+
+
+def _convert_mixed_precision(value):
+ value = int(value)
+ return PrecisionType(["no", "fp16", "bf16", "fp8"][value])
+
+
+def _convert_sagemaker_distributed_mode(value):
+ value = int(value)
+ return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value])
+
+
+def _convert_fp8_backend(value):
+ value = int(value)
+ return FP8BackendType(["TE", "MSAMP"][value])
+
+
+def _convert_yes_no_to_bool(value):
+ return {"yes": True, "no": False}[value.lower()]
+
+
+class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter):
+ """
+ A custom formatter that will remove the usage line from the help message for subcommands.
+ """
+
+ def _format_usage(self, usage, actions, groups, prefix):
+ usage = super()._format_usage(usage, actions, groups, prefix)
+ usage = usage.replace(" [] ", "")
+ return usage
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/default.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/default.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcaa4902e56ab6ca2e698d65d96bc93d6ed761e1
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/default.py
@@ -0,0 +1,142 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from pathlib import Path
+
+import torch
+
+from ...utils import is_mlu_available, is_musa_available, is_npu_available, is_xpu_available
+from .config_args import ClusterConfig, default_json_config_file
+from .config_utils import SubcommandHelpFormatter
+
+
+description = "Create a default config file for Accelerate with only a few flags set."
+
+
+def write_basic_config(mixed_precision="no", save_location: str = default_json_config_file, use_xpu: bool = False):
+ """
+ Creates and saves a basic cluster config to be used on a local machine with potentially multiple GPUs. Will also
+ set CPU if it is a CPU-only machine.
+
+ Args:
+ mixed_precision (`str`, *optional*, defaults to "no"):
+ Mixed Precision to use. Should be one of "no", "fp16", or "bf16"
+ save_location (`str`, *optional*, defaults to `default_json_config_file`):
+ Optional custom save location. Should be passed to `--config_file` when using `accelerate launch`. Default
+ location is inside the huggingface cache folder (`~/.cache/huggingface`) but can be overriden by setting
+ the `HF_HOME` environmental variable, followed by `accelerate/default_config.yaml`.
+ use_xpu (`bool`, *optional*, defaults to `False`):
+ Whether to use XPU if available.
+ """
+ path = Path(save_location)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ if path.exists():
+ print(
+ f"Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`."
+ )
+ return False
+ mixed_precision = mixed_precision.lower()
+ if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
+ raise ValueError(
+ f"`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}"
+ )
+ config = {
+ "compute_environment": "LOCAL_MACHINE",
+ "mixed_precision": mixed_precision,
+ }
+ if is_mlu_available():
+ num_mlus = torch.mlu.device_count()
+ config["num_processes"] = num_mlus
+ config["use_cpu"] = False
+ if num_mlus > 1:
+ config["distributed_type"] = "MULTI_MLU"
+ else:
+ config["distributed_type"] = "NO"
+ elif is_musa_available():
+ num_musas = torch.musa.device_count()
+ config["num_processes"] = num_musas
+ config["use_cpu"] = False
+ if num_musas > 1:
+ config["distributed_type"] = "MULTI_MUSA"
+ else:
+ config["distributed_type"] = "NO"
+ elif torch.cuda.is_available():
+ num_gpus = torch.cuda.device_count()
+ config["num_processes"] = num_gpus
+ config["use_cpu"] = False
+ if num_gpus > 1:
+ config["distributed_type"] = "MULTI_GPU"
+ else:
+ config["distributed_type"] = "NO"
+ elif is_xpu_available() and use_xpu:
+ num_xpus = torch.xpu.device_count()
+ config["num_processes"] = num_xpus
+ config["use_cpu"] = False
+ if num_xpus > 1:
+ config["distributed_type"] = "MULTI_XPU"
+ else:
+ config["distributed_type"] = "NO"
+ elif is_npu_available():
+ num_npus = torch.npu.device_count()
+ config["num_processes"] = num_npus
+ config["use_cpu"] = False
+ if num_npus > 1:
+ config["distributed_type"] = "MULTI_NPU"
+ else:
+ config["distributed_type"] = "NO"
+ else:
+ num_xpus = 0
+ config["use_cpu"] = True
+ config["num_processes"] = 1
+ config["distributed_type"] = "NO"
+ config["debug"] = False
+ config["enable_cpu_affinity"] = False
+ config = ClusterConfig(**config)
+ config.to_json_file(path)
+ return path
+
+
+def default_command_parser(parser, parents):
+ parser = parser.add_parser("default", parents=parents, help=description, formatter_class=SubcommandHelpFormatter)
+ parser.add_argument(
+ "--config_file",
+ default=default_json_config_file,
+ help=(
+ "The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
+ "with 'huggingface'."
+ ),
+ dest="save_location",
+ )
+
+ parser.add_argument(
+ "--mixed_precision",
+ choices=["no", "fp16", "bf16"],
+ type=str,
+ help="Whether or not to use mixed precision training. "
+ "Choose between FP16 and BF16 (bfloat16) training. "
+ "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.",
+ default="no",
+ )
+ parser.set_defaults(func=default_config_command)
+ return parser
+
+
+def default_config_command(args):
+ config_file = write_basic_config(args.mixed_precision, args.save_location)
+ if config_file:
+ print(f"accelerate configuration saved at {config_file}")
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/sagemaker.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/sagemaker.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e3491fee0ad28df82683a89d128bbc097053c2f
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/sagemaker.py
@@ -0,0 +1,267 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import json
+import os
+
+from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
+from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
+from ...utils.imports import is_boto3_available
+from .config_args import SageMakerConfig
+from .config_utils import (
+ DYNAMO_BACKENDS,
+ _ask_field,
+ _ask_options,
+ _convert_dynamo_backend,
+ _convert_mixed_precision,
+ _convert_sagemaker_distributed_mode,
+ _convert_yes_no_to_bool,
+)
+
+
+if is_boto3_available():
+ import boto3 # noqa: F401
+
+
+def _create_iam_role_for_sagemaker(role_name):
+ iam_client = boto3.client("iam")
+
+ sagemaker_trust_policy = {
+ "Version": "2012-10-17",
+ "Statement": [
+ {"Effect": "Allow", "Principal": {"Service": "sagemaker.amazonaws.com"}, "Action": "sts:AssumeRole"}
+ ],
+ }
+ try:
+ # create the role, associated with the chosen trust policy
+ iam_client.create_role(
+ RoleName=role_name, AssumeRolePolicyDocument=json.dumps(sagemaker_trust_policy, indent=2)
+ )
+ policy_document = {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Action": [
+ "sagemaker:*",
+ "ecr:GetDownloadUrlForLayer",
+ "ecr:BatchGetImage",
+ "ecr:BatchCheckLayerAvailability",
+ "ecr:GetAuthorizationToken",
+ "cloudwatch:PutMetricData",
+ "cloudwatch:GetMetricData",
+ "cloudwatch:GetMetricStatistics",
+ "cloudwatch:ListMetrics",
+ "logs:CreateLogGroup",
+ "logs:CreateLogStream",
+ "logs:DescribeLogStreams",
+ "logs:PutLogEvents",
+ "logs:GetLogEvents",
+ "s3:CreateBucket",
+ "s3:ListBucket",
+ "s3:GetBucketLocation",
+ "s3:GetObject",
+ "s3:PutObject",
+ ],
+ "Resource": "*",
+ }
+ ],
+ }
+ # attach policy to role
+ iam_client.put_role_policy(
+ RoleName=role_name,
+ PolicyName=f"{role_name}_policy_permission",
+ PolicyDocument=json.dumps(policy_document, indent=2),
+ )
+ except iam_client.exceptions.EntityAlreadyExistsException:
+ print(f"role {role_name} already exists. Using existing one")
+
+
+def _get_iam_role_arn(role_name):
+ iam_client = boto3.client("iam")
+ return iam_client.get_role(RoleName=role_name)["Role"]["Arn"]
+
+
+def get_sagemaker_input():
+ credentials_configuration = _ask_options(
+ "How do you want to authorize?",
+ ["AWS Profile", "Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) "],
+ int,
+ )
+ aws_profile = None
+ if credentials_configuration == 0:
+ aws_profile = _ask_field("Enter your AWS Profile name: [default] ", default="default")
+ os.environ["AWS_PROFILE"] = aws_profile
+ else:
+ print(
+ "Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,"
+ "`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`"
+ )
+ aws_access_key_id = _ask_field("AWS Access Key ID: ")
+ os.environ["AWS_ACCESS_KEY_ID"] = aws_access_key_id
+
+ aws_secret_access_key = _ask_field("AWS Secret Access Key: ")
+ os.environ["AWS_SECRET_ACCESS_KEY"] = aws_secret_access_key
+
+ aws_region = _ask_field("Enter your AWS Region: [us-east-1]", default="us-east-1")
+ os.environ["AWS_DEFAULT_REGION"] = aws_region
+
+ role_management = _ask_options(
+ "Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?",
+ ["Provide IAM Role name", "Create new IAM role using credentials"],
+ int,
+ )
+ if role_management == 0:
+ iam_role_name = _ask_field("Enter your IAM role name: ")
+ else:
+ iam_role_name = "accelerate_sagemaker_execution_role"
+ print(f'Accelerate will create an iam role "{iam_role_name}" using the provided credentials')
+ _create_iam_role_for_sagemaker(iam_role_name)
+
+ is_custom_docker_image = _ask_field(
+ "Do you want to use custom Docker image? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ docker_image = None
+ if is_custom_docker_image:
+ docker_image = _ask_field("Enter your Docker image: ", lambda x: str(x).lower())
+
+ is_sagemaker_inputs_enabled = _ask_field(
+ "Do you want to provide SageMaker input channels with data locations? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ sagemaker_inputs_file = None
+ if is_sagemaker_inputs_enabled:
+ sagemaker_inputs_file = _ask_field(
+ "Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ",
+ lambda x: str(x).lower(),
+ )
+
+ is_sagemaker_metrics_enabled = _ask_field(
+ "Do you want to enable SageMaker metrics? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ sagemaker_metrics_file = None
+ if is_sagemaker_metrics_enabled:
+ sagemaker_metrics_file = _ask_field(
+ "Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ",
+ lambda x: str(x).lower(),
+ )
+
+ distributed_type = _ask_options(
+ "What is the distributed mode?",
+ ["No distributed training", "Data parallelism"],
+ _convert_sagemaker_distributed_mode,
+ )
+ dynamo_config = {}
+ use_dynamo = _ask_field(
+ "Do you wish to optimize your script with torch dynamo?[yes/NO]:",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ if use_dynamo:
+ prefix = "dynamo_"
+ dynamo_config[prefix + "backend"] = _ask_options(
+ "Which dynamo backend would you like to use?",
+ [x.lower() for x in DYNAMO_BACKENDS],
+ _convert_dynamo_backend,
+ default=2,
+ )
+ use_custom_options = _ask_field(
+ "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+
+ if use_custom_options:
+ dynamo_config[prefix + "mode"] = _ask_options(
+ "Which mode do you want to use?",
+ TORCH_DYNAMO_MODES,
+ lambda x: TORCH_DYNAMO_MODES[int(x)],
+ default="default",
+ )
+ dynamo_config[prefix + "use_fullgraph"] = _ask_field(
+ "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ dynamo_config[prefix + "use_dynamic"] = _ask_field(
+ "Do you want to enable dynamic shape tracing? [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+ ec2_instance_query = "Which EC2 instance type you want to use for your training?"
+ if distributed_type != SageMakerDistributedType.NO:
+ ec2_instance_type = _ask_options(
+ ec2_instance_query, SAGEMAKER_PARALLEL_EC2_INSTANCES, lambda x: SAGEMAKER_PARALLEL_EC2_INSTANCES[int(x)]
+ )
+ else:
+ ec2_instance_query += "? [ml.p3.2xlarge]:"
+ ec2_instance_type = _ask_field(ec2_instance_query, lambda x: str(x).lower(), default="ml.p3.2xlarge")
+
+ debug = False
+ if distributed_type != SageMakerDistributedType.NO:
+ debug = _ask_field(
+ "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ",
+ _convert_yes_no_to_bool,
+ default=False,
+ error_message="Please enter yes or no.",
+ )
+
+ num_machines = 1
+ if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
+ num_machines = _ask_field(
+ "How many machines do you want use? [1]: ",
+ int,
+ default=1,
+ )
+
+ mixed_precision = _ask_options(
+ "Do you wish to use FP16 or BF16 (mixed precision)?",
+ ["no", "fp16", "bf16", "fp8"],
+ _convert_mixed_precision,
+ )
+
+ if use_dynamo and mixed_precision == "no":
+ print(
+ "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts."
+ )
+
+ return SageMakerConfig(
+ image_uri=docker_image,
+ compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER,
+ distributed_type=distributed_type,
+ use_cpu=False,
+ dynamo_config=dynamo_config,
+ ec2_instance_type=ec2_instance_type,
+ profile=aws_profile,
+ region=aws_region,
+ iam_role_name=iam_role_name,
+ mixed_precision=mixed_precision,
+ num_machines=num_machines,
+ sagemaker_inputs_file=sagemaker_inputs_file,
+ sagemaker_metrics_file=sagemaker_metrics_file,
+ debug=debug,
+ )
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/update.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/update.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f025594b04ada3e3a78687befc5c1bc1d236adf
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/config/update.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python
+
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from pathlib import Path
+
+from .config_args import default_config_file, load_config_from_file
+from .config_utils import SubcommandHelpFormatter
+
+
+description = "Update an existing config file with the latest defaults while maintaining the old configuration."
+
+
+def update_config(args):
+ """
+ Update an existing config file with the latest defaults while maintaining the old configuration.
+ """
+ config_file = args.config_file
+ if config_file is None and Path(default_config_file).exists():
+ config_file = default_config_file
+ elif not Path(config_file).exists():
+ raise ValueError(f"The passed config file located at {config_file} doesn't exist.")
+ config = load_config_from_file(config_file)
+
+ if config_file.endswith(".json"):
+ config.to_json_file(config_file)
+ else:
+ config.to_yaml_file(config_file)
+ return config_file
+
+
+def update_command_parser(parser, parents):
+ parser = parser.add_parser("update", parents=parents, help=description, formatter_class=SubcommandHelpFormatter)
+ parser.add_argument(
+ "--config_file",
+ default=None,
+ help=(
+ "The path to the config file to update. Will default to a file named default_config.yaml in the cache "
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
+ "with 'huggingface'."
+ ),
+ )
+
+ parser.set_defaults(func=update_config_command)
+ return parser
+
+
+def update_config_command(args):
+ config_file = update_config(args)
+ print(f"Sucessfully updated the configuration file at {config_file}.")
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/env.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..7dd5995f6b480562d1c75fcb236a95a9f60d7f6f
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/env.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python
+
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+import os
+import platform
+import subprocess
+
+import numpy as np
+import psutil
+import torch
+
+from accelerate import __version__ as version
+from accelerate.commands.config import default_config_file, load_config_from_file
+
+from ..utils import is_mlu_available, is_musa_available, is_npu_available, is_xpu_available
+
+
+def env_command_parser(subparsers=None):
+ if subparsers is not None:
+ parser = subparsers.add_parser("env")
+ else:
+ parser = argparse.ArgumentParser("Accelerate env command")
+
+ parser.add_argument(
+ "--config_file", default=None, help="The config file to use for the default values in the launching script."
+ )
+
+ if subparsers is not None:
+ parser.set_defaults(func=env_command)
+ return parser
+
+
+def env_command(args):
+ pt_version = torch.__version__
+ pt_cuda_available = torch.cuda.is_available()
+ pt_xpu_available = is_xpu_available()
+ pt_mlu_available = is_mlu_available()
+ pt_musa_available = is_musa_available()
+ pt_npu_available = is_npu_available()
+
+ accelerate_config = "Not found"
+ # Get the default from the config file.
+ if args.config_file is not None or os.path.isfile(default_config_file):
+ accelerate_config = load_config_from_file(args.config_file).to_dict()
+
+ # if we can run which, get it
+ command = None
+ bash_location = "Not found"
+ if os.name == "nt":
+ command = ["where", "accelerate"]
+ elif os.name == "posix":
+ command = ["which", "accelerate"]
+ if command is not None:
+ bash_location = subprocess.check_output(command, text=True, stderr=subprocess.STDOUT).strip()
+ info = {
+ "`Accelerate` version": version,
+ "Platform": platform.platform(),
+ "`accelerate` bash location": bash_location,
+ "Python version": platform.python_version(),
+ "Numpy version": np.__version__,
+ "PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})",
+ "PyTorch XPU available": str(pt_xpu_available),
+ "PyTorch NPU available": str(pt_npu_available),
+ "PyTorch MLU available": str(pt_mlu_available),
+ "PyTorch MUSA available": str(pt_musa_available),
+ "System RAM": f"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB",
+ }
+ if pt_cuda_available:
+ info["GPU type"] = torch.cuda.get_device_name()
+ if pt_mlu_available:
+ info["MLU type"] = torch.mlu.get_device_name()
+ if pt_npu_available:
+ info["CANN version"] = torch.version.cann
+
+ print("\nCopy-and-paste the text below in your GitHub issue\n")
+ print("\n".join([f"- {prop}: {val}" for prop, val in info.items()]))
+
+ print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:")
+ accelerate_config_str = (
+ "\n".join([f"\t- {prop}: {val}" for prop, val in accelerate_config.items()])
+ if isinstance(accelerate_config, dict)
+ else f"\t{accelerate_config}"
+ )
+ print(accelerate_config_str)
+
+ info["`Accelerate` configs"] = accelerate_config
+
+ return info
+
+
+def main() -> int:
+ parser = env_command_parser()
+ args = parser.parse_args()
+ env_command(args)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/estimate.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/estimate.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cd731b222143e54b5f15e21bf386819ee6cacdd
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/estimate.py
@@ -0,0 +1,309 @@
+#!/usr/bin/env python
+
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from huggingface_hub import model_info
+from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
+
+from accelerate import init_empty_weights
+from accelerate.commands.utils import CustomArgumentParser
+from accelerate.utils import (
+ calculate_maximum_sizes,
+ convert_bytes,
+ is_timm_available,
+ is_transformers_available,
+)
+
+
+if is_transformers_available():
+ import transformers
+ from transformers import AutoConfig, AutoModel
+
+if is_timm_available():
+ import timm
+
+
+def verify_on_hub(repo: str, token: str = None):
+ "Verifies that the model is on the hub and returns the model info."
+ try:
+ return model_info(repo, token=token)
+ except (OSError, GatedRepoError):
+ return "gated"
+ except RepositoryNotFoundError:
+ return "repo"
+
+
+def check_has_model(error):
+ """
+ Checks what library spawned `error` when a model is not found
+ """
+ if is_timm_available() and isinstance(error, RuntimeError) and "Unknown model" in error.args[0]:
+ return "timm"
+ elif (
+ is_transformers_available()
+ and isinstance(error, OSError)
+ and "does not appear to have a file named" in error.args[0]
+ ):
+ return "transformers"
+ else:
+ return "unknown"
+
+
+def create_empty_model(model_name: str, library_name: str, trust_remote_code: bool = False, access_token: str = None):
+ """
+ Creates an empty model from its parent library on the `Hub` to calculate the overall memory consumption.
+
+ Args:
+ model_name (`str`):
+ The model name on the Hub
+ library_name (`str`):
+ The library the model has an integration with, such as `transformers`. Will be used if `model_name` has no
+ metadata on the Hub to determine the library.
+ trust_remote_code (`bool`, `optional`, defaults to `False`):
+ Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
+ should only be set to `True` for repositories you trust and in which you have read the code, as it will
+ execute code present on the Hub on your local machine.
+ access_token (`str`, `optional`, defaults to `None`):
+ The access token to use to access private or gated models on the Hub. (for use on the Gradio app)
+
+ Returns:
+ `torch.nn.Module`: The torch model that has been initialized on the `meta` device.
+
+ """
+ model_info = verify_on_hub(model_name, access_token)
+ # Simplified errors
+ if model_info == "gated":
+ raise GatedRepoError(
+ f"Repo for model `{model_name}` is gated. You must be authenticated to access it. Please run `huggingface-cli login`."
+ )
+ elif model_info == "repo":
+ raise RepositoryNotFoundError(
+ f"Repo for model `{model_name}` does not exist on the Hub. If you are trying to access a private repo,"
+ " make sure you are authenticated via `huggingface-cli login` and have access."
+ )
+ if library_name is None:
+ library_name = getattr(model_info, "library_name", False)
+ if not library_name:
+ raise ValueError(
+ 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`)"
+ )
+ if library_name == "transformers":
+ if not is_transformers_available():
+ raise ImportError(
+ f"To check `{model_name}`, `transformers` must be installed. Please install it via `pip install transformers`"
+ )
+ print(f"Loading pretrained config for `{model_name}` from `transformers`...")
+ if model_info.config is None:
+ raise RuntimeError(f"Tried to load `{model_name}` with `transformers` but it does not have any metadata.")
+
+ auto_map = model_info.config.get("auto_map", False)
+ config = AutoConfig.from_pretrained(model_name, trust_remote_code=trust_remote_code, token=access_token)
+ with init_empty_weights():
+ # remote code could specify a specific `AutoModel` class in the `auto_map`
+ constructor = AutoModel
+ if isinstance(auto_map, dict):
+ value = None
+ for key in auto_map.keys():
+ if key.startswith("AutoModelFor"):
+ value = key
+ break
+ if value is not None:
+ constructor = getattr(transformers, value)
+ model = constructor.from_config(config, trust_remote_code=trust_remote_code)
+ elif library_name == "timm":
+ if not is_timm_available():
+ raise ImportError(
+ f"To check `{model_name}`, `timm` must be installed. Please install it via `pip install timm`"
+ )
+ print(f"Loading pretrained config for `{model_name}` from `timm`...")
+ with init_empty_weights():
+ model = timm.create_model(model_name, pretrained=False)
+ else:
+ raise ValueError(
+ f"Library `{library_name}` is not supported yet, please open an issue on GitHub for us to add support."
+ )
+ return model
+
+
+def create_ascii_table(headers: list, rows: list, title: str):
+ "Creates a pretty table from a list of rows, minimal version of `tabulate`."
+ sep_char, in_between = "│", "─"
+ column_widths = []
+ for i in range(len(headers)):
+ column_values = [row[i] for row in rows] + [headers[i]]
+ max_column_width = max(len(value) for value in column_values)
+ column_widths.append(max_column_width)
+
+ formats = [f"%{column_widths[i]}s" for i in range(len(rows[0]))]
+
+ pattern = f"{sep_char}{sep_char.join(formats)}{sep_char}"
+ diff = 0
+
+ def make_row(left_char, middle_char, right_char):
+ return f"{left_char}{middle_char.join([in_between * n for n in column_widths])}{in_between * diff}{right_char}"
+
+ separator = make_row("├", "┼", "┤")
+ if len(title) > sum(column_widths):
+ diff = abs(len(title) - len(separator))
+ column_widths[-1] += diff
+
+ # Update with diff
+ separator = make_row("├", "┼", "┤")
+ initial_rows = [
+ make_row("┌", in_between, "┐"),
+ f"{sep_char}{title.center(len(separator) - 2)}{sep_char}",
+ make_row("├", "┬", "┤"),
+ ]
+ table = "\n".join(initial_rows) + "\n"
+ column_widths[-1] += diff
+ centered_line = [text.center(column_widths[i]) for i, text in enumerate(headers)]
+ table += f"{pattern % tuple(centered_line)}\n{separator}\n"
+ for i, line in enumerate(rows):
+ centered_line = [t.center(column_widths[i]) for i, t in enumerate(line)]
+ table += f"{pattern % tuple(centered_line)}\n"
+ table += f'└{"┴".join([in_between * n for n in column_widths])}┘'
+
+ return table
+
+
+def estimate_command_parser(subparsers=None):
+ if subparsers is not None:
+ parser = subparsers.add_parser("estimate-memory")
+ else:
+ parser = CustomArgumentParser(description="Model size estimator for fitting a model onto CUDA memory.")
+
+ parser.add_argument("model_name", type=str, help="The model name on the Hugging Face Hub.")
+ parser.add_argument(
+ "--library_name",
+ type=str,
+ help="The library the model has an integration with, such as `transformers`, needed only if this information is not stored on the Hub.",
+ choices=["timm", "transformers"],
+ )
+ parser.add_argument(
+ "--dtypes",
+ type=str,
+ nargs="+",
+ default=["float32", "float16", "int8", "int4"],
+ help="The dtypes to use for the model, must be one (or many) of `float32`, `float16`, `int8`, and `int4`",
+ choices=["float32", "float16", "int8", "int4"],
+ )
+ parser.add_argument(
+ "--trust_remote_code",
+ action="store_true",
+ help="""Whether or not to allow for custom models defined on the Hub in their own modeling files. This flag
+ should only be used for repositories you trust and in which you have read the code, as it will execute
+ code present on the Hub on your local machine.""",
+ default=False,
+ )
+
+ if subparsers is not None:
+ parser.set_defaults(func=estimate_command)
+ return parser
+
+
+def estimate_training_usage(bytes: int, mixed_precision: str, msamp_config: str = None) -> dict:
+ """
+ Given an amount of `bytes` and `mixed_precision`, calculates how much training memory is needed for a batch size of
+ 1.
+
+ Args:
+ bytes (`int`):
+ The size of the model being trained.
+ mixed_precision (`str`):
+ The mixed precision that would be ran.
+ msamp_config (`str`):
+ The msamp config to estimate the training memory for if `mixed_precision` is set to `"fp8"`.
+ """
+ memory_sizes = {"model": -1, "optimizer": -1, "gradients": -1, "step": -1}
+ fp32_size = bytes
+ fp16_size = bytes // 2
+
+ if mixed_precision == "float32":
+ memory_sizes["model"] = fp32_size
+ memory_sizes["gradients"] = fp32_size
+ memory_sizes["optimizer"] = fp32_size * 2
+ memory_sizes["step"] = fp32_size * 4
+ elif mixed_precision in ("float16", "bfloat16") or (mixed_precision == "fp8" and msamp_config is None):
+ # With native `TransformersEngine`, there is no memory savings with FP8
+ # With mixed precision training, the model has weights stored
+ # in FP16 and FP32
+ memory_sizes["model"] = fp32_size
+ # 1.5 from weight gradient + computation (GEMM)
+ memory_sizes["gradients"] = fp32_size + fp16_size
+ # 2x from optimizer states
+ memory_sizes["optimizer"] = fp32_size * 2 # Optimizer states
+ memory_sizes["step"] = memory_sizes["optimizer"]
+ return memory_sizes
+
+
+def gather_data(args):
+ "Creates an empty model and gathers the data for the sizes"
+ try:
+ model = create_empty_model(
+ args.model_name, library_name=args.library_name, trust_remote_code=args.trust_remote_code
+ )
+ except (RuntimeError, OSError) as e:
+ library = check_has_model(e)
+ if library != "unknown":
+ raise RuntimeError(
+ f"Tried to load `{args.model_name}` with `{library}` but a possible model to load was not found inside the repo."
+ )
+ raise e
+
+ total_size, largest_layer = calculate_maximum_sizes(model)
+
+ data = []
+
+ for dtype in args.dtypes:
+ dtype_total_size = total_size
+ dtype_largest_layer = largest_layer[0]
+ dtype_training_size = estimate_training_usage(dtype_total_size, dtype)
+ if dtype == "float16":
+ dtype_total_size /= 2
+ dtype_largest_layer /= 2
+ elif dtype == "int8":
+ dtype_total_size /= 4
+ dtype_largest_layer /= 4
+ elif dtype == "int4":
+ dtype_total_size /= 8
+ dtype_largest_layer /= 8
+ data.append([dtype, dtype_largest_layer, dtype_total_size, dtype_training_size])
+ return data
+
+
+def estimate_command(args):
+ data = gather_data(args)
+ for row in data:
+ for i, item in enumerate(row):
+ if isinstance(item, (int, float)):
+ row[i] = convert_bytes(item)
+ elif isinstance(item, dict):
+ training_usage = max(item.values())
+ row[i] = convert_bytes(training_usage) if training_usage != -1 else "N/A"
+
+ headers = ["dtype", "Largest Layer", "Total Size", "Training using Adam"]
+
+ title = f"Memory Usage for loading `{args.model_name}`"
+ table = create_ascii_table(headers, data, title)
+ print(table)
+
+
+def main():
+ parser = estimate_command_parser()
+ args = parser.parse_args()
+ estimate_command(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/launch.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/launch.py
new file mode 100644
index 0000000000000000000000000000000000000000..92e27cbfd4a9f11ebbfb113adaa7cf6b488ac084
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/launch.py
@@ -0,0 +1,1178 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+import importlib
+import logging
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import psutil
+import torch
+
+from accelerate.commands.config import default_config_file, load_config_from_file
+from accelerate.commands.config.config_args import SageMakerConfig
+from accelerate.commands.config.config_utils import DYNAMO_BACKENDS
+from accelerate.commands.utils import CustomArgumentParser
+from accelerate.state import get_int_from_env
+from accelerate.utils import (
+ ComputeEnvironment,
+ DistributedType,
+ PrepareForLaunch,
+ _filter_args,
+ check_cuda_p2p_ib_support,
+ convert_dict_to_env_variables,
+ is_bf16_available,
+ is_deepspeed_available,
+ is_mlu_available,
+ is_musa_available,
+ is_npu_available,
+ is_rich_available,
+ is_sagemaker_available,
+ is_torch_version,
+ is_torch_xla_available,
+ is_xpu_available,
+ patch_environment,
+ prepare_deepspeed_cmd_env,
+ prepare_multi_gpu_env,
+ prepare_sagemager_args_inputs,
+ prepare_simple_launcher_cmd_env,
+ prepare_tpu,
+ str_to_bool,
+)
+from accelerate.utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS, TORCH_DYNAMO_MODES
+
+
+if is_rich_available():
+ from rich import get_console
+ from rich.logging import RichHandler
+
+ FORMAT = "%(message)s"
+ logging.basicConfig(format=FORMAT, datefmt="[%X]", handlers=[RichHandler()])
+
+
+logger = logging.getLogger(__name__)
+
+
+options_to_group = {
+ "multi_gpu": "Distributed GPUs",
+ "tpu": "TPU",
+ "use_deepspeed": "DeepSpeed Arguments",
+ "use_fsdp": "FSDP Arguments",
+ "use_megatron_lm": "Megatron-LM Arguments",
+ "fp8_backend": "FP8 Arguments",
+}
+
+
+def clean_option(option):
+ "Finds all cases of - after the first two characters and changes them to _"
+ if "fp8_backend" in option:
+ option = "--fp8_backend"
+ if option.startswith("--"):
+ return option[2:].replace("-", "_")
+
+
+class CustomHelpFormatter(argparse.HelpFormatter):
+ """
+ This is a custom help formatter that will hide all arguments that are not used in the command line when the help is
+ called. This is useful for the case where the user is using a specific platform and only wants to see the arguments
+ for that platform.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.titles = [
+ "Hardware Selection Arguments",
+ "Resource Selection Arguments",
+ "Training Paradigm Arguments",
+ "positional arguments",
+ "optional arguments",
+ ]
+
+ def add_argument(self, action: argparse.Action):
+ if "accelerate" in sys.argv[0] and "launch" in sys.argv[1:]:
+ args = sys.argv[2:]
+ else:
+ args = sys.argv[1:]
+
+ if len(args) > 1:
+ args = list(map(clean_option, args))
+ used_platforms = [arg for arg in args if arg in options_to_group.keys()]
+ used_titles = [options_to_group[o] for o in used_platforms]
+ if action.container.title not in self.titles + used_titles:
+ action.help = argparse.SUPPRESS
+ elif action.container.title == "Hardware Selection Arguments":
+ if set(action.option_strings).isdisjoint(set(args)):
+ action.help = argparse.SUPPRESS
+ else:
+ action.help = action.help + " (currently selected)"
+ elif action.container.title == "Training Paradigm Arguments":
+ if set(action.option_strings).isdisjoint(set(args)):
+ action.help = argparse.SUPPRESS
+ else:
+ action.help = action.help + " (currently selected)"
+
+ action.option_strings = [s for s in action.option_strings if "-" not in s[2:]]
+ super().add_argument(action)
+
+ def end_section(self):
+ if len(self._current_section.items) < 2:
+ self._current_section.items = []
+ self._current_section.heading = ""
+ super().end_section()
+
+
+def launch_command_parser(subparsers=None):
+ 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`)"
+ if subparsers is not None:
+ parser = subparsers.add_parser(
+ "launch", description=description, add_help=False, allow_abbrev=False, formatter_class=CustomHelpFormatter
+ )
+ else:
+ parser = CustomArgumentParser(
+ "Accelerate launch command",
+ description=description,
+ add_help=False,
+ allow_abbrev=False,
+ formatter_class=CustomHelpFormatter,
+ )
+
+ parser.add_argument("-h", "--help", action="help", help="Show this help message and exit.")
+
+ parser.add_argument(
+ "--config_file",
+ default=None,
+ help="The config file to use for the default values in the launching script.",
+ )
+ parser.add_argument(
+ "--quiet",
+ "-q",
+ action="store_true",
+ help="Silence subprocess errors from the launch stack trace and only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations)",
+ )
+ # Hardware selection arguments
+ hardware_args = parser.add_argument_group(
+ "Hardware Selection Arguments", "Arguments for selecting the hardware to be used."
+ )
+ hardware_args.add_argument(
+ "--cpu", default=False, action="store_true", help="Whether or not to force the training on the CPU."
+ )
+ hardware_args.add_argument(
+ "--multi_gpu",
+ default=False,
+ action="store_true",
+ help="Whether or not this should launch a distributed GPU training.",
+ )
+ hardware_args.add_argument(
+ "--tpu", default=False, action="store_true", help="Whether or not this should launch a TPU training."
+ )
+ hardware_args.add_argument(
+ "--ipex",
+ default=False,
+ action="store_true",
+ help="Whether or not this should launch a Intel PyTorch Extension (IPEX) training.",
+ )
+
+ # Resource selection arguments
+ resource_args = parser.add_argument_group(
+ "Resource Selection Arguments", "Arguments for fine-tuning how available hardware should be used."
+ )
+ resource_args.add_argument(
+ "--mixed_precision",
+ type=str,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether or not to use mixed precision training. "
+ "Choose between FP16 and BF16 (bfloat16) training. "
+ "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.",
+ )
+ resource_args.add_argument(
+ "--num_processes", type=int, default=None, help="The total number of processes to be launched in parallel."
+ )
+ resource_args.add_argument(
+ "--num_machines", type=int, default=None, help="The total number of machines used in this training."
+ )
+ resource_args.add_argument(
+ "--num_cpu_threads_per_process",
+ type=int,
+ default=None,
+ help="The number of CPU threads per process. Can be tuned for optimal performance.",
+ )
+ resource_args.add_argument(
+ "--enable_cpu_affinity",
+ default=False,
+ action="store_true",
+ help="Whether or not CPU affinity and balancing should be enabled. Currently only supported on NVIDIA hardware.",
+ )
+ # Dynamo arguments
+ resource_args.add_argument(
+ "--dynamo_backend",
+ type=str,
+ choices=["no"] + [b.lower() for b in DYNAMO_BACKENDS],
+ help="Choose a backend to optimize your training with dynamo, see more at "
+ "https://github.com/pytorch/torchdynamo.",
+ )
+ resource_args.add_argument(
+ "--dynamo_mode",
+ type=str,
+ default="default",
+ choices=TORCH_DYNAMO_MODES,
+ help="Choose a mode to optimize your training with dynamo.",
+ )
+ resource_args.add_argument(
+ "--dynamo_use_fullgraph",
+ default=False,
+ action="store_true",
+ help="Whether to use full graph mode for dynamo or it is ok to break model into several subgraphs",
+ )
+ resource_args.add_argument(
+ "--dynamo_use_dynamic",
+ default=False,
+ action="store_true",
+ help="Whether to enable dynamic shape tracing.",
+ )
+
+ # Training Paradigm arguments
+ paradigm_args = parser.add_argument_group(
+ "Training Paradigm Arguments", "Arguments for selecting which training paradigm to be used."
+ )
+ paradigm_args.add_argument(
+ "--use_deepspeed",
+ default=False,
+ action="store_true",
+ help="Whether to use deepspeed.",
+ )
+ paradigm_args.add_argument(
+ "--use_fsdp",
+ default=False,
+ action="store_true",
+ help="Whether to use fsdp.",
+ )
+ paradigm_args.add_argument(
+ "--use_megatron_lm",
+ default=False,
+ action="store_true",
+ help="Whether to use Megatron-LM.",
+ )
+ paradigm_args.add_argument(
+ "--use_xpu",
+ default=False,
+ action="store_true",
+ help="Whether to use IPEX plugin to speed up training on XPU specifically.",
+ )
+
+ # distributed GPU training arguments
+ distributed_args = parser.add_argument_group("Distributed GPUs", "Arguments related to distributed GPU training.")
+ distributed_args.add_argument(
+ "--gpu_ids",
+ default=None,
+ help="What GPUs (by id) should be used for training on this machine as a comma-seperated list",
+ )
+ distributed_args.add_argument(
+ "--same_network",
+ default=False,
+ action="store_true",
+ help="Whether all machines used for multinode training exist on the same local network.",
+ )
+ distributed_args.add_argument(
+ "--machine_rank", type=int, default=None, help="The rank of the machine on which this script is launched."
+ )
+ distributed_args.add_argument(
+ "--main_process_ip", type=str, default=None, help="The IP address of the machine of rank 0."
+ )
+ distributed_args.add_argument(
+ "--main_process_port",
+ type=int,
+ default=None,
+ help="The port to use to communicate with the machine of rank 0.",
+ )
+ distributed_args.add_argument(
+ "-t",
+ "--tee",
+ default="0",
+ type=str,
+ help="Tee std streams into a log file and also to console.",
+ )
+ distributed_args.add_argument(
+ "--log_dir",
+ type=str,
+ default=None,
+ help=(
+ "Base directory to use for log files when using torchrun/torch.distributed.run as launcher. "
+ "Use with --tee to redirect std streams info log files."
+ ),
+ )
+ distributed_args.add_argument(
+ "--role",
+ type=str,
+ default="default",
+ help="User-defined role for the workers.",
+ )
+ # Rendezvous related arguments
+ distributed_args.add_argument(
+ "--rdzv_backend",
+ type=str,
+ default="static",
+ help="The rendezvous method to use, such as 'static' (the default) or 'c10d'",
+ )
+ distributed_args.add_argument(
+ "--rdzv_conf",
+ type=str,
+ default="",
+ help="Additional rendezvous configuration (=,=,...).",
+ )
+ distributed_args.add_argument(
+ "--max_restarts",
+ type=int,
+ default=0,
+ help="Maximum number of worker group restarts before failing.",
+ )
+ distributed_args.add_argument(
+ "--monitor_interval",
+ type=float,
+ default=0.1,
+ help="Interval, in seconds, to monitor the state of workers.",
+ )
+ parser.add_argument(
+ "-m",
+ "--module",
+ action="store_true",
+ help="Change each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'.",
+ )
+ parser.add_argument(
+ "--no_python",
+ action="store_true",
+ help="Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script.",
+ )
+
+ # TPU arguments
+ tpu_args = parser.add_argument_group("TPU", "Arguments related to TPU.")
+ tpu_args.add_argument(
+ "--tpu_cluster",
+ action="store_true",
+ dest="tpu_use_cluster",
+ help="Whether to use a GCP TPU pod for training.",
+ )
+ tpu_args.add_argument(
+ "--no_tpu_cluster",
+ action="store_false",
+ dest="tpu_use_cluster",
+ help="Should not be passed explicitly, this is for internal use only.",
+ )
+ tpu_args.add_argument(
+ "--tpu_use_sudo",
+ action="store_true",
+ help="Whether to use `sudo` when running the TPU training script in each pod.",
+ )
+ tpu_args.add_argument(
+ "--vm",
+ type=str,
+ action="append",
+ help=(
+ "List of single Compute VM instance names. "
+ "If not provided we assume usage of instance groups. For TPU pods."
+ ),
+ )
+ tpu_args.add_argument(
+ "--env",
+ type=str,
+ action="append",
+ help="List of environment variables to set on the Compute VM instances. For TPU pods.",
+ )
+ tpu_args.add_argument(
+ "--main_training_function",
+ type=str,
+ default=None,
+ help="The name of the main function to be executed in your script (only for TPU training).",
+ )
+ tpu_args.add_argument(
+ "--downcast_bf16",
+ action="store_true",
+ 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.",
+ )
+
+ # DeepSpeed arguments
+ deepspeed_args = parser.add_argument_group("DeepSpeed Arguments", "Arguments related to DeepSpeed.")
+ deepspeed_args.add_argument(
+ "--deepspeed_config_file",
+ default=None,
+ type=str,
+ help="DeepSpeed config file.",
+ )
+ deepspeed_args.add_argument(
+ "--zero_stage",
+ default=None,
+ type=int,
+ help="DeepSpeed's ZeRO optimization stage (useful only when `use_deepspeed` flag is passed). "
+ "If unspecified, will default to `2`.",
+ )
+ deepspeed_args.add_argument(
+ "--offload_optimizer_device",
+ default=None,
+ type=str,
+ help="Decides where (none|cpu|nvme) to offload optimizer states (useful only when `use_deepspeed` flag is passed). "
+ "If unspecified, will default to 'none'.",
+ )
+ deepspeed_args.add_argument(
+ "--offload_param_device",
+ default=None,
+ type=str,
+ help="Decides where (none|cpu|nvme) to offload parameters (useful only when `use_deepspeed` flag is passed). "
+ "If unspecified, will default to 'none'.",
+ )
+ deepspeed_args.add_argument(
+ "--offload_optimizer_nvme_path",
+ default=None,
+ type=str,
+ help="Decides Nvme Path to offload optimizer states (useful only when `use_deepspeed` flag is passed). "
+ "If unspecified, will default to 'none'.",
+ )
+ deepspeed_args.add_argument(
+ "--offload_param_nvme_path",
+ default=None,
+ type=str,
+ help="Decides Nvme Path to offload parameters (useful only when `use_deepspeed` flag is passed). "
+ "If unspecified, will default to 'none'.",
+ )
+ deepspeed_args.add_argument(
+ "--gradient_accumulation_steps",
+ default=None,
+ type=int,
+ help="No of gradient_accumulation_steps used in your training script (useful only when `use_deepspeed` flag is passed). "
+ "If unspecified, will default to `1`.",
+ )
+ deepspeed_args.add_argument(
+ "--gradient_clipping",
+ default=None,
+ type=float,
+ help="gradient clipping value used in your training script (useful only when `use_deepspeed` flag is passed). "
+ "If unspecified, will default to `1.0`.",
+ )
+ deepspeed_args.add_argument(
+ "--zero3_init_flag",
+ default=None,
+ type=str,
+ help="Decides Whether (true|false) to enable `deepspeed.zero.Init` for constructing massive models. "
+ "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `true`.",
+ )
+ deepspeed_args.add_argument(
+ "--zero3_save_16bit_model",
+ default=None,
+ type=str,
+ help="Decides Whether (true|false) to save 16-bit model weights when using ZeRO Stage-3. "
+ "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `false`.",
+ )
+ deepspeed_args.add_argument(
+ "--deepspeed_hostfile",
+ default=None,
+ type=str,
+ help="DeepSpeed hostfile for configuring multi-node compute resources.",
+ )
+ deepspeed_args.add_argument(
+ "--deepspeed_exclusion_filter",
+ default=None,
+ type=str,
+ help="DeepSpeed exclusion filter string when using mutli-node setup.",
+ )
+ deepspeed_args.add_argument(
+ "--deepspeed_inclusion_filter",
+ default=None,
+ type=str,
+ help="DeepSpeed inclusion filter string when using mutli-node setup.",
+ )
+ deepspeed_args.add_argument(
+ "--deepspeed_multinode_launcher",
+ default=None,
+ type=str,
+ help="DeepSpeed multi-node launcher to use. If unspecified, will default to `pdsh`.",
+ )
+ deepspeed_args.add_argument(
+ "--deepspeed_moe_layer_cls_names",
+ default=None,
+ type=str,
+ help="comma-separated list of transformer MoE layer class names (case-sensitive) to wrap ,e.g, `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ..."
+ " (useful only when `use_deepspeed` flag is passed).",
+ )
+
+ # fsdp arguments
+ fsdp_args = parser.add_argument_group("FSDP Arguments", "Arguments related to Fully Shared Data Parallelism.")
+ fsdp_args.add_argument(
+ "--fsdp_offload_params",
+ default="false",
+ type=str,
+ help="Decides Whether (true|false) to offload parameters and gradients to CPU. (useful only when `use_fsdp` flag is passed).",
+ )
+ fsdp_args.add_argument(
+ "--fsdp_min_num_params",
+ type=int,
+ default=1e8,
+ help="FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `use_fsdp` flag is passed).",
+ )
+ fsdp_args.add_argument(
+ "--fsdp_sharding_strategy",
+ type=str,
+ default="FULL_SHARD",
+ help="FSDP's Sharding Strategy. (useful only when `use_fsdp` flag is passed).",
+ )
+ fsdp_args.add_argument(
+ "--fsdp_auto_wrap_policy",
+ type=str,
+ default=None,
+ help="FSDP's auto wrap policy. (useful only when `use_fsdp` flag is passed).",
+ )
+ fsdp_args.add_argument(
+ "--fsdp_transformer_layer_cls_to_wrap",
+ default=None,
+ type=str,
+ help="Transformer layer class name (case-sensitive) to wrap ,e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... "
+ "(useful only when `use_fsdp` flag is passed).",
+ )
+ fsdp_args.add_argument(
+ "--fsdp_backward_prefetch",
+ default=None,
+ type=str,
+ help="FSDP's backward prefetch policy. (useful only when `use_fsdp` flag is passed).",
+ )
+ fsdp_args.add_argument(
+ "--fsdp_state_dict_type",
+ default=None,
+ type=str,
+ help="FSDP's state dict type. (useful only when `use_fsdp` flag is passed).",
+ )
+ fsdp_args.add_argument(
+ "--fsdp_forward_prefetch",
+ default="false",
+ type=str,
+ help="If True, then FSDP explicitly prefetches the next upcoming "
+ "all-gather while executing in the forward pass (useful only when `use_fsdp` flag is passed).",
+ )
+ fsdp_args.add_argument(
+ "--fsdp_use_orig_params",
+ default="true",
+ type=str,
+ help="If True, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable paramteres."
+ " (useful only when `use_fsdp` flag is passed).",
+ )
+ fsdp_args.add_argument(
+ "--fsdp_cpu_ram_efficient_loading",
+ default="true",
+ type=str,
+ help="If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. "
+ "Only applicable for 🤗 Transformers. When using this, `--fsdp_sync_module_states` needs to True. "
+ "(useful only when `use_fsdp` flag is passed).",
+ )
+ fsdp_args.add_argument(
+ "--fsdp_sync_module_states",
+ default="true",
+ type=str,
+ help="If True, each individually wrapped FSDP unit will broadcast module parameters from rank 0."
+ " (useful only when `use_fsdp` flag is passed).",
+ )
+ fsdp_args.add_argument(
+ "--fsdp_activation_checkpointing",
+ default="false",
+ type=str,
+ 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).",
+ )
+
+ # megatron_lm args
+ megatron_lm_args = parser.add_argument_group("Megatron-LM Arguments", "Arguments related to Megatron-LM.")
+ megatron_lm_args.add_argument(
+ "--megatron_lm_tp_degree",
+ type=int,
+ default=1,
+ help="Megatron-LM's Tensor Parallelism (TP) degree. (useful only when `use_megatron_lm` flag is passed).",
+ )
+ megatron_lm_args.add_argument(
+ "--megatron_lm_pp_degree",
+ type=int,
+ default=1,
+ help="Megatron-LM's Pipeline Parallelism (PP) degree. (useful only when `use_megatron_lm` flag is passed).",
+ )
+ megatron_lm_args.add_argument(
+ "--megatron_lm_num_micro_batches",
+ type=int,
+ default=None,
+ help="Megatron-LM's number of micro batches when PP degree > 1. (useful only when `use_megatron_lm` flag is passed).",
+ )
+ megatron_lm_args.add_argument(
+ "--megatron_lm_sequence_parallelism",
+ default=None,
+ type=str,
+ help="Decides Whether (true|false) to enable Sequence Parallelism when TP degree > 1. "
+ "(useful only when `use_megatron_lm` flag is passed).",
+ )
+ megatron_lm_args.add_argument(
+ "--megatron_lm_recompute_activations",
+ default=None,
+ type=str,
+ help="Decides Whether (true|false) to enable Selective Activation Recomputation. "
+ "(useful only when `use_megatron_lm` flag is passed).",
+ )
+ megatron_lm_args.add_argument(
+ "--megatron_lm_use_distributed_optimizer",
+ default=None,
+ type=str,
+ help="Decides Whether (true|false) to use distributed optimizer "
+ "which shards optimizer state and gradients across Data Pralellel (DP) ranks. "
+ "(useful only when `use_megatron_lm` flag is passed).",
+ )
+ megatron_lm_args.add_argument(
+ "--megatron_lm_gradient_clipping",
+ default=1.0,
+ type=float,
+ help="Megatron-LM's gradient clipping value based on global L2 Norm (0 to disable). "
+ "(useful only when `use_megatron_lm` flag is passed).",
+ )
+
+ # FP8 arguments
+ fp8_args = parser.add_argument_group(
+ "FP8 Arguments", "Arguments related to FP8 training (requires `--mixed_precision=fp8`)"
+ )
+ fp8_args.add_argument(
+ "--fp8_backend",
+ type=str,
+ choices=["te", "msamp"],
+ help="Choose a backend to train with FP8 (te: TransformerEngine, msamp: MS-AMP)",
+ )
+ fp8_args.add_argument(
+ "--fp8_use_autocast_during_eval",
+ default=False,
+ action="store_true",
+ 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.",
+ )
+ fp8_args.add_argument(
+ "--fp8_margin",
+ type=int,
+ default=0,
+ help="The margin to use for the gradient scaling (useful only when `--fp8_backend=te` is passed).",
+ )
+ fp8_args.add_argument(
+ "--fp8_interval",
+ type=int,
+ default=1,
+ help="The interval to use for how often the scaling factor is recomputed (useful only when `--fp8_backend=te` is passed).",
+ )
+ fp8_args.add_argument(
+ "--fp8_format",
+ type=str,
+ default="E4M3",
+ choices=["E4M3", "HYBRID"],
+ help="The format to use for the FP8 recipe (useful only when `--fp8_backend=te` is passed).",
+ )
+ fp8_args.add_argument(
+ "--fp8_amax_history_len",
+ type=int,
+ default=1024,
+ help="The length of the history to use for the scaling factor computation (useful only when `--fp8_backend=te` is passed).",
+ )
+ fp8_args.add_argument(
+ "--fp8_amax_compute_algo",
+ type=str,
+ default="most_recent",
+ choices=["max", "most_recent"],
+ help="The algorithm to use for the scaling factor computation. (useful only when `--fp8_backend=te` is passed).",
+ )
+ fp8_args.add_argument(
+ "--fp8_override_linear_precision",
+ type=lambda x: tuple(map(str_to_bool, x.split(","))),
+ default=(False, False, False),
+ 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).",
+ )
+ fp8_args.add_argument(
+ "--fp8_opt_level",
+ type=str,
+ default="O2",
+ choices=["O1", "O2"],
+ help="What level of 8-bit collective communication should be used with MS-AMP (useful only when `--fp8_backend=msamp` is passed).",
+ )
+
+ # AWS arguments
+ aws_args = parser.add_argument_group("AWS Arguments", "Arguments related to AWS.")
+ aws_args.add_argument(
+ "--aws_access_key_id",
+ type=str,
+ default=None,
+ help="The AWS_ACCESS_KEY_ID used to launch the Amazon SageMaker training job",
+ )
+ aws_args.add_argument(
+ "--aws_secret_access_key",
+ type=str,
+ default=None,
+ help="The AWS_SECRET_ACCESS_KEY used to launch the Amazon SageMaker training job.",
+ )
+ parser.add_argument(
+ "--debug",
+ action="store_true",
+ help="Whether to print out the torch.distributed stack trace when something fails.",
+ )
+ parser.add_argument(
+ "training_script",
+ type=str,
+ help=(
+ "The full path to the script to be launched in parallel, followed by all the arguments for the training "
+ "script."
+ ),
+ )
+
+ # MPI arguments
+ mpirun_args = parser.add_argument_group("MPI Arguments", "Arguments related to mpirun for Multi-CPU")
+ mpirun_args.add_argument(
+ "--mpirun_hostfile",
+ type=str,
+ default=None,
+ help="Location for a hostfile for using Accelerate to launch a multi-CPU training job with mpirun. This will "
+ "get passed to the MPI --hostfile or -f parameter, depending on which MPI program is installed.",
+ )
+ mpirun_args.add_argument(
+ "--mpirun_ccl",
+ type=int,
+ default=1,
+ help="The number of oneCCL worker threads when using Accelerate to launch multi-CPU training with mpirun.",
+ )
+
+ # Other arguments of the training scripts
+ parser.add_argument("training_script_args", nargs=argparse.REMAINDER, help="Arguments of the training script.")
+
+ if subparsers is not None:
+ parser.set_defaults(func=launch_command)
+ return parser
+
+
+def simple_launcher(args):
+ cmd, current_env = prepare_simple_launcher_cmd_env(args)
+
+ process = subprocess.Popen(cmd, env=current_env)
+ process.wait()
+ if process.returncode != 0:
+ if not args.quiet:
+ raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd)
+ else:
+ sys.exit(1)
+
+
+def multi_gpu_launcher(args):
+ import torch.distributed.run as distrib_run
+
+ current_env = prepare_multi_gpu_env(args)
+ if not check_cuda_p2p_ib_support():
+ message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled."
+ warn = False
+ if "NCCL_P2P_DISABLE" not in current_env:
+ current_env["NCCL_P2P_DISABLE"] = "1"
+ warn = True
+ if "NCCL_IB_DISABLE" not in current_env:
+ current_env["NCCL_IB_DISABLE"] = "1"
+ warn = True
+ if warn:
+ logger.warning(message)
+
+ debug = getattr(args, "debug", False)
+ args = _filter_args(
+ args,
+ distrib_run.get_args_parser(),
+ ["--training_script", args.training_script, "--training_script_args", args.training_script_args],
+ )
+
+ with patch_environment(**current_env):
+ try:
+ distrib_run.run(args)
+ except Exception:
+ if is_rich_available() and debug:
+ console = get_console()
+ console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]")
+ console.print_exception(suppress=[__file__], show_locals=False)
+ else:
+ raise
+
+
+def deepspeed_launcher(args):
+ import torch.distributed.run as distrib_run
+
+ if not is_deepspeed_available():
+ raise ImportError("DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source.")
+ else:
+ from deepspeed.launcher.runner import DEEPSPEED_ENVIRONMENT_NAME
+
+ cmd, current_env = prepare_deepspeed_cmd_env(args)
+ if not check_cuda_p2p_ib_support():
+ message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled."
+ warn = False
+ if "NCCL_P2P_DISABLE" not in current_env:
+ current_env["NCCL_P2P_DISABLE"] = "1"
+ warn = True
+ if "NCCL_IB_DISABLE" not in current_env:
+ current_env["NCCL_IB_DISABLE"] = "1"
+ warn = True
+ if warn:
+ logger.warning(message)
+
+ if args.num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]:
+ with open(DEEPSPEED_ENVIRONMENT_NAME, "a") as f:
+ valid_env_items = convert_dict_to_env_variables(current_env)
+ if len(valid_env_items) > 1:
+ f.writelines(valid_env_items)
+
+ process = subprocess.Popen(cmd, env=current_env)
+ process.wait()
+ if process.returncode != 0:
+ if not args.quiet:
+ raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd)
+ else:
+ sys.exit(1)
+ else:
+ debug = getattr(args, "debug", False)
+ args = _filter_args(
+ args,
+ distrib_run.get_args_parser(),
+ ["--training_script", args.training_script, "--training_script_args", args.training_script_args],
+ )
+ with patch_environment(**current_env):
+ try:
+ distrib_run.run(args)
+ except Exception:
+ if is_rich_available() and debug:
+ console = get_console()
+ console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]")
+ console.print_exception(suppress=[__file__], show_locals=False)
+ else:
+ raise
+
+
+def tpu_launcher(args):
+ import torch_xla.distributed.xla_multiprocessing as xmp
+
+ if args.no_python:
+ raise ValueError("--no_python cannot be used with TPU launcher")
+
+ args, current_env = prepare_tpu(args, {})
+
+ if args.module:
+ mod_name = args.training_script
+ else:
+ # Import training_script as a module
+ script_path = Path(args.training_script)
+ sys.path.append(str(script_path.parent.resolve()))
+ mod_name = script_path.stem
+
+ mod = importlib.import_module(mod_name)
+ if not hasattr(mod, args.main_training_function):
+ raise ValueError(
+ f"Your training script should have a function named {args.main_training_function}, or you should pass a "
+ "different value to `--main_training_function`."
+ )
+
+ # Patch sys.argv
+ sys.argv = [mod.__file__] + args.training_script_args
+
+ main_function = getattr(mod, args.main_training_function)
+ with patch_environment(**current_env):
+ xmp.spawn(PrepareForLaunch(main_function), args=(), nprocs=args.num_processes)
+
+
+def tpu_pod_launcher(args):
+ from torch_xla.distributed import xla_dist
+
+ current_env = {}
+ args, current_env = prepare_tpu(args, current_env, True)
+ debug = getattr(args, "debug", False)
+
+ training_script = args.training_script
+ training_script_args = args.training_script_args
+ new_args = _filter_args(
+ args, xla_dist.get_args_parser(), ["--tpu", args.tpu_name, "--positional", "", "--restart-tpuvm-pod-server"]
+ )
+
+ if args.tpu_use_sudo:
+ new_cmd = ["sudo"]
+ else:
+ new_cmd = []
+
+ new_cmd += [
+ "accelerate-launch",
+ "--tpu",
+ "--no_tpu_cluster",
+ "--num_machines",
+ "1",
+ "--mixed_precision",
+ "no",
+ "--dynamo_backend",
+ "no",
+ "--num_processes",
+ str(args.num_processes),
+ "--main_training_function",
+ str(args.main_training_function),
+ training_script,
+ ] + training_script_args
+
+ new_args.positional = new_cmd
+ bad_flags = ""
+ for arg in vars(new_args):
+ if arg.startswith("docker_"):
+ value = getattr(new_args, arg)
+ if value != "" and value is not None:
+ bad_flags += f'{arg}="{value}"\n'
+ if bad_flags != "":
+ raise ValueError(
+ f"Docker containers are not supported for TPU pod launcher currently, please remove the following flags:\n{bad_flags}"
+ )
+ new_args.env = [f"{k}={v}" for k, v in current_env.items()]
+ new_args.env.append("ACCELERATE_IN_TPU_POD=1")
+ try:
+ xla_dist.resolve_and_execute(new_args)
+ except Exception:
+ if is_rich_available() and debug:
+ console = get_console()
+ console.print("\n[bold red]Using --debug, `torch_xla.xla_dist` Stack Trace:[/bold red]")
+ console.print_exception(suppress=[__file__], show_locals=False)
+ else:
+ raise
+
+
+def sagemaker_launcher(sagemaker_config: SageMakerConfig, args):
+ if not is_sagemaker_available():
+ raise ImportError(
+ "Please install sagemaker to be able to launch training on Amazon SageMaker with `pip install accelerate[sagemaker]`"
+ )
+ if args.module or args.no_python:
+ raise ValueError(
+ "SageMaker requires a python training script file and cannot be used with --module or --no_python"
+ )
+
+ from sagemaker.huggingface import HuggingFace
+
+ args, sagemaker_inputs = prepare_sagemager_args_inputs(sagemaker_config, args)
+
+ huggingface_estimator = HuggingFace(**args)
+
+ huggingface_estimator.fit(inputs=sagemaker_inputs)
+ print(f"You can find your model data at: {huggingface_estimator.model_data}")
+
+
+def _validate_launch_command(args):
+ # Sanity checks
+ if sum([args.multi_gpu, args.cpu, args.tpu, args.use_deepspeed, args.use_fsdp]) > 1:
+ raise ValueError(
+ "You can only use one of `--cpu`, `--multi_gpu`, `--tpu`, `--use_deepspeed`, `--use_fsdp` at a time."
+ )
+ if args.multi_gpu and (args.num_processes is not None) and (args.num_processes < 2):
+ raise ValueError("You need to use at least 2 processes to use `--multi_gpu`.")
+
+ defaults = None
+ warned = []
+ mp_from_config_flag = False
+ # Get the default from the config file.
+ if args.config_file is not None or os.path.isfile(default_config_file) and not args.cpu:
+ defaults = load_config_from_file(args.config_file)
+ if (
+ not args.multi_gpu
+ and not args.tpu
+ and not args.tpu_use_cluster
+ and not args.use_deepspeed
+ and not args.use_fsdp
+ and not args.use_megatron_lm
+ ):
+ args.use_deepspeed = defaults.distributed_type == DistributedType.DEEPSPEED
+ args.multi_gpu = (
+ True
+ if defaults.distributed_type
+ in (
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_XPU,
+ )
+ else False
+ )
+ args.tpu = defaults.distributed_type == DistributedType.XLA
+ args.use_fsdp = defaults.distributed_type == DistributedType.FSDP
+ args.use_megatron_lm = defaults.distributed_type == DistributedType.MEGATRON_LM
+ args.tpu_use_cluster = defaults.tpu_use_cluster if args.tpu else False
+ if args.gpu_ids is None:
+ if defaults.gpu_ids is not None:
+ args.gpu_ids = defaults.gpu_ids
+ else:
+ args.gpu_ids = "all"
+
+ if args.multi_gpu and args.num_machines is None:
+ args.num_machines = defaults.num_machines
+
+ if len(args.gpu_ids.split(",")) < 2 and (args.gpu_ids != "all") and args.multi_gpu and args.num_machines <= 1:
+ raise ValueError(
+ "Less than two GPU ids were configured and tried to run on on multiple GPUs. "
+ "Please ensure at least two are specified for `--gpu_ids`, or use `--gpu_ids='all'`."
+ )
+ if defaults.compute_environment == ComputeEnvironment.LOCAL_MACHINE:
+ # Update args with the defaults
+ for name, attr in defaults.__dict__.items():
+ if isinstance(attr, dict):
+ for k in defaults.deepspeed_config:
+ setattr(args, k, defaults.deepspeed_config[k])
+ for k in defaults.fsdp_config:
+ arg_to_set = k
+ if "fsdp" not in arg_to_set:
+ arg_to_set = "fsdp_" + arg_to_set
+ setattr(args, arg_to_set, defaults.fsdp_config[k])
+ for k in defaults.megatron_lm_config:
+ setattr(args, k, defaults.megatron_lm_config[k])
+ for k in defaults.dynamo_config:
+ setattr(args, k, defaults.dynamo_config[k])
+ for k in defaults.ipex_config:
+ setattr(args, k, defaults.ipex_config[k])
+ for k in defaults.mpirun_config:
+ setattr(args, k, defaults.mpirun_config[k])
+ continue
+
+ # Those args are handled separately
+ if (
+ name not in ["compute_environment", "mixed_precision", "distributed_type"]
+ and getattr(args, name, None) is None
+ ):
+ setattr(args, name, attr)
+ if not args.debug:
+ args.debug = defaults.debug
+
+ if not args.mixed_precision:
+ if defaults.mixed_precision is None:
+ args.mixed_precision = "no"
+ else:
+ args.mixed_precision = defaults.mixed_precision
+ mp_from_config_flag = True
+ else:
+ if args.use_cpu or (args.use_xpu and torch.xpu.is_available()):
+ native_amp = is_torch_version(">=", "1.10")
+ else:
+ native_amp = is_bf16_available(True)
+ if (
+ args.mixed_precision == "bf16"
+ and not native_amp
+ and not (args.tpu and is_torch_xla_available(check_is_tpu=True))
+ ):
+ raise ValueError("bf16 mixed precision requires PyTorch >= 1.10 and a supported device.")
+
+ # Silently set the default here
+ if args.dynamo_backend is None:
+ args.dynamo_backend = "no"
+ if args.num_processes == -1:
+ raise ValueError("You need to manually pass in `--num_processes` using this config yaml.")
+ else:
+ if args.num_processes is None:
+ if args.use_xpu and is_xpu_available():
+ args.num_processes = torch.xpu.device_count()
+ elif is_mlu_available():
+ args.num_processes = torch.mlu.device_count()
+ elif is_musa_available():
+ args.num_processes = torch.musa.device_count()
+ elif is_npu_available():
+ args.num_processes = torch.npu.device_count()
+ else:
+ args.num_processes = torch.cuda.device_count()
+ warned.append(f"\t`--num_processes` was set to a value of `{args.num_processes}`")
+ if args.debug is None:
+ args.debug = False
+ if (
+ not args.multi_gpu
+ and args.num_processes > 1
+ and (
+ (args.use_xpu and is_xpu_available() and torch.xpu.device_count() > 1)
+ or (is_mlu_available() and torch.mlu.device_count() > 1)
+ or (is_musa_available() and torch.musa.device_count() > 1)
+ or (is_npu_available() and torch.npu.device_count() > 1)
+ or (torch.cuda.device_count() > 1)
+ )
+ ):
+ warned.append(
+ "\t\tMore than one GPU was found, enabling multi-GPU training.\n"
+ "\t\tIf this was unintended please pass in `--num_processes=1`."
+ )
+ args.multi_gpu = True
+ if args.num_machines is None:
+ warned.append("\t`--num_machines` was set to a value of `1`")
+ args.num_machines = 1
+ if args.mixed_precision is None:
+ warned.append("\t`--mixed_precision` was set to a value of `'no'`")
+ args.mixed_precision = "no"
+ if not hasattr(args, "use_cpu"):
+ args.use_cpu = args.cpu
+ if args.dynamo_backend is None:
+ warned.append("\t`--dynamo_backend` was set to a value of `'no'`")
+ args.dynamo_backend = "no"
+ if args.debug:
+ logger.debug("Running script in debug mode, expect distributed operations to be slightly slower.")
+
+ is_aws_env_disabled = defaults is None or (
+ defaults is not None and defaults.compute_environment != ComputeEnvironment.AMAZON_SAGEMAKER
+ )
+ if is_aws_env_disabled and args.num_cpu_threads_per_process is None:
+ args.num_cpu_threads_per_process = get_int_from_env(["OMP_NUM_THREADS"], 1)
+ if args.use_cpu and args.num_processes >= 1 and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0:
+ local_size = get_int_from_env(
+ ["MPI_LOCALNRANKS", "OMPI_COMM_WORLD_LOCAL_SIZE", "MV2_COMM_WORLD_LOCAL_SIZE"],
+ max(int(args.num_processes / args.num_machines), 1),
+ )
+ threads_per_process = int(psutil.cpu_count(logical=False) / local_size)
+ if threads_per_process > 1:
+ args.num_cpu_threads_per_process = threads_per_process
+ warned.append(
+ 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"
+ )
+
+ if any(warned):
+ message = "The following values were not passed to `accelerate launch` and had defaults used instead:\n"
+ message += "\n".join(warned)
+ message += (
+ "\nTo avoid this warning pass in values for each of the problematic parameters or run `accelerate config`."
+ )
+ logger.warning(message)
+ return args, defaults, mp_from_config_flag
+
+
+def launch_command(args):
+ args, defaults, mp_from_config_flag = _validate_launch_command(args)
+ # Use the proper launcher
+ if args.use_deepspeed and not args.cpu:
+ args.deepspeed_fields_from_accelerate_config = list(defaults.deepspeed_config.keys()) if defaults else []
+ if mp_from_config_flag:
+ args.deepspeed_fields_from_accelerate_config.append("mixed_precision")
+ args.deepspeed_fields_from_accelerate_config = ",".join(args.deepspeed_fields_from_accelerate_config)
+ deepspeed_launcher(args)
+ elif args.use_fsdp and not args.cpu:
+ multi_gpu_launcher(args)
+ elif args.use_megatron_lm and not args.cpu:
+ multi_gpu_launcher(args)
+ elif args.multi_gpu and not args.cpu:
+ multi_gpu_launcher(args)
+ elif args.tpu and not args.cpu:
+ if args.tpu_use_cluster:
+ tpu_pod_launcher(args)
+ else:
+ tpu_launcher(args)
+ elif defaults is not None and defaults.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
+ sagemaker_launcher(defaults, args)
+ else:
+ simple_launcher(args)
+
+
+def main():
+ parser = launch_command_parser()
+ args = parser.parse_args()
+ launch_command(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/__init__.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2c851cc0b192ab8207d3fa68d7409868c84354c
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from .selection_menu import BulletMenu
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/cursor.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/cursor.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1f0bb7b68025ae4fe0c2c76c095eb36b4e64f2c
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/cursor.py
@@ -0,0 +1,65 @@
+# Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+A utility for showing and hiding the terminal cursor on Windows and Linux, based on https://github.com/bchao1/bullet
+"""
+
+import os
+import sys
+from contextlib import contextmanager
+
+
+# Windows only
+if os.name == "nt":
+ import ctypes
+ import msvcrt # noqa
+
+ class CursorInfo(ctypes.Structure):
+ # _fields is a specific attr expected by ctypes
+ _fields_ = [("size", ctypes.c_int), ("visible", ctypes.c_byte)]
+
+
+def hide_cursor():
+ if os.name == "nt":
+ ci = CursorInfo()
+ handle = ctypes.windll.kernel32.GetStdHandle(-11)
+ ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
+ ci.visible = False
+ ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
+ elif os.name == "posix":
+ sys.stdout.write("\033[?25l")
+ sys.stdout.flush()
+
+
+def show_cursor():
+ if os.name == "nt":
+ ci = CursorInfo()
+ handle = ctypes.windll.kernel32.GetStdHandle(-11)
+ ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
+ ci.visible = True
+ ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
+ elif os.name == "posix":
+ sys.stdout.write("\033[?25h")
+ sys.stdout.flush()
+
+
+@contextmanager
+def hide():
+ "Context manager to hide the terminal cursor"
+ try:
+ hide_cursor()
+ yield
+ finally:
+ show_cursor()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/helpers.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..de46f37ddcf4591167e3e01791391e4b1729034f
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/helpers.py
@@ -0,0 +1,59 @@
+# Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+A variety of helper functions and constants when dealing with terminal menu choices, based on
+https://github.com/bchao1/bullet
+"""
+
+import enum
+import shutil
+import sys
+
+
+TERMINAL_WIDTH, _ = shutil.get_terminal_size()
+
+CURSOR_TO_CHAR = {"UP": "A", "DOWN": "B", "RIGHT": "C", "LEFT": "D"}
+
+
+class Direction(enum.Enum):
+ UP = 0
+ DOWN = 1
+
+
+def forceWrite(content, end=""):
+ sys.stdout.write(str(content) + end)
+ sys.stdout.flush()
+
+
+def writeColor(content, color, end=""):
+ forceWrite(f"\u001b[{color}m{content}\u001b[0m", end)
+
+
+def reset_cursor():
+ forceWrite("\r")
+
+
+def move_cursor(num_lines: int, direction: str):
+ forceWrite(f"\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}")
+
+
+def clear_line():
+ forceWrite(" " * TERMINAL_WIDTH)
+ reset_cursor()
+
+
+def linebreak():
+ reset_cursor()
+ forceWrite("-" * TERMINAL_WIDTH)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/input.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/input.py
new file mode 100644
index 0000000000000000000000000000000000000000..2690f86aa61f7ac648f4a9c2040a34ee35147201
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/input.py
@@ -0,0 +1,86 @@
+# Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+This file contains utilities for handling input from the user and registering specific keys to specific functions,
+based on https://github.com/bchao1/bullet
+"""
+
+from typing import List
+
+from .keymap import KEYMAP, get_character
+
+
+def mark(key: str):
+ """
+ Mark the function with the key code so it can be handled in the register
+ """
+
+ def decorator(func):
+ handle = getattr(func, "handle_key", [])
+ handle += [key]
+ func.handle_key = handle
+ return func
+
+ return decorator
+
+
+def mark_multiple(*keys: List[str]):
+ """
+ Mark the function with the key codes so it can be handled in the register
+ """
+
+ def decorator(func):
+ handle = getattr(func, "handle_key", [])
+ handle += keys
+ func.handle_key = handle
+ return func
+
+ return decorator
+
+
+class KeyHandler(type):
+ """
+ Metaclass that adds the key handlers to the class
+ """
+
+ def __new__(cls, name, bases, attrs):
+ new_cls = super().__new__(cls, name, bases, attrs)
+ if not hasattr(new_cls, "key_handler"):
+ new_cls.key_handler = {}
+ new_cls.handle_input = KeyHandler.handle_input
+
+ for value in attrs.values():
+ handled_keys = getattr(value, "handle_key", [])
+ for key in handled_keys:
+ new_cls.key_handler[key] = value
+ return new_cls
+
+ @staticmethod
+ def handle_input(cls):
+ "Finds and returns the selected character if it exists in the handler"
+ char = get_character()
+ if char != KEYMAP["undefined"]:
+ char = ord(char)
+ handler = cls.key_handler.get(char)
+ if handler:
+ cls.current_selection = char
+ return handler(cls)
+ else:
+ return None
+
+
+def register(cls):
+ """Adds KeyHandler metaclass to the class"""
+ return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy())
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/keymap.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/keymap.py
new file mode 100644
index 0000000000000000000000000000000000000000..787db12860fe21c6786dda69c34fcccab114f2f8
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/keymap.py
@@ -0,0 +1,133 @@
+# Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+Utilities relating to parsing raw characters from the keyboard, based on https://github.com/bchao1/bullet
+"""
+
+import os
+import string
+import sys
+
+
+ARROW_KEY_FLAG = 1 << 8
+
+KEYMAP = {
+ "tab": ord("\t"),
+ "newline": ord("\r"),
+ "esc": 27,
+ "up": 65 + ARROW_KEY_FLAG,
+ "down": 66 + ARROW_KEY_FLAG,
+ "right": 67 + ARROW_KEY_FLAG,
+ "left": 68 + ARROW_KEY_FLAG,
+ "mod_int": 91,
+ "undefined": sys.maxsize,
+ "interrupt": 3,
+ "insert": 50,
+ "delete": 51,
+ "pg_up": 53,
+ "pg_down": 54,
+}
+
+KEYMAP["arrow_begin"] = KEYMAP["up"]
+KEYMAP["arrow_end"] = KEYMAP["left"]
+
+if sys.platform == "win32":
+ WIN_CH_BUFFER = []
+ WIN_KEYMAP = {
+ b"\xe0H": KEYMAP["up"] - ARROW_KEY_FLAG,
+ b"\x00H": KEYMAP["up"] - ARROW_KEY_FLAG,
+ b"\xe0P": KEYMAP["down"] - ARROW_KEY_FLAG,
+ b"\x00P": KEYMAP["down"] - ARROW_KEY_FLAG,
+ b"\xe0M": KEYMAP["right"] - ARROW_KEY_FLAG,
+ b"\x00M": KEYMAP["right"] - ARROW_KEY_FLAG,
+ b"\xe0K": KEYMAP["left"] - ARROW_KEY_FLAG,
+ b"\x00K": KEYMAP["left"] - ARROW_KEY_FLAG,
+ }
+
+for i in range(10):
+ KEYMAP[str(i)] = ord(str(i))
+
+
+def get_raw_chars():
+ "Gets raw characters from inputs"
+ if os.name == "nt":
+ import msvcrt
+
+ encoding = "mbcs"
+ # Flush the keyboard buffer
+ while msvcrt.kbhit():
+ msvcrt.getch()
+ if len(WIN_CH_BUFFER) == 0:
+ # Read the keystroke
+ ch = msvcrt.getch()
+
+ # If it is a prefix char, get second part
+ if ch in (b"\x00", b"\xe0"):
+ ch2 = ch + msvcrt.getch()
+ # Translate actual Win chars to bullet char types
+ try:
+ chx = chr(WIN_KEYMAP[ch2])
+ WIN_CH_BUFFER.append(chr(KEYMAP["mod_int"]))
+ WIN_CH_BUFFER.append(chx)
+ if ord(chx) in (
+ KEYMAP["insert"] - 1 << 9,
+ KEYMAP["delete"] - 1 << 9,
+ KEYMAP["pg_up"] - 1 << 9,
+ KEYMAP["pg_down"] - 1 << 9,
+ ):
+ WIN_CH_BUFFER.append(chr(126))
+ ch = chr(KEYMAP["esc"])
+ except KeyError:
+ ch = ch2[1]
+ else:
+ ch = ch.decode(encoding)
+ else:
+ ch = WIN_CH_BUFFER.pop(0)
+ elif os.name == "posix":
+ import termios
+ import tty
+
+ fd = sys.stdin.fileno()
+ old_settings = termios.tcgetattr(fd)
+ try:
+ tty.setraw(fd)
+ ch = sys.stdin.read(1)
+ finally:
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
+ return ch
+
+
+def get_character():
+ "Gets a character from the keyboard and returns the key code"
+ char = get_raw_chars()
+ if ord(char) in [KEYMAP["interrupt"], KEYMAP["newline"]]:
+ return char
+
+ elif ord(char) == KEYMAP["esc"]:
+ combo = get_raw_chars()
+ if ord(combo) == KEYMAP["mod_int"]:
+ key = get_raw_chars()
+ if ord(key) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(key) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG:
+ return chr(ord(key) + ARROW_KEY_FLAG)
+ else:
+ return KEYMAP["undefined"]
+ else:
+ return get_raw_chars()
+
+ else:
+ if char in string.printable:
+ return char
+ else:
+ return KEYMAP["undefined"]
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/selection_menu.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/selection_menu.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee9a771a54ef666ee46b67ae6c75fb957d49efdd
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/menu/selection_menu.py
@@ -0,0 +1,144 @@
+# Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+Main driver for the selection menu, based on https://github.com/bchao1/bullet
+"""
+
+import builtins
+import sys
+
+from ...utils.imports import _is_package_available
+from . import cursor, input
+from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
+from .keymap import KEYMAP
+
+
+in_colab = False
+try:
+ in_colab = _is_package_available("google.colab")
+except ModuleNotFoundError:
+ pass
+
+
+@input.register
+class BulletMenu:
+ """
+ A CLI menu to select a choice from a list of choices using the keyboard.
+ """
+
+ def __init__(self, prompt: str = None, choices: list = []):
+ self.position = 0
+ self.choices = choices
+ self.prompt = prompt
+ if sys.platform == "win32":
+ self.arrow_char = "*"
+ else:
+ self.arrow_char = "➔ "
+
+ def write_choice(self, index, end: str = ""):
+ if sys.platform != "win32":
+ writeColor(self.choices[index], 32, end)
+ else:
+ forceWrite(self.choices[index], end)
+
+ def print_choice(self, index: int):
+ "Prints the choice at the given index"
+ if index == self.position:
+ forceWrite(f" {self.arrow_char} ")
+ self.write_choice(index)
+ else:
+ forceWrite(f" {self.choices[index]}")
+ reset_cursor()
+
+ def move_direction(self, direction: Direction, num_spaces: int = 1):
+ "Should not be directly called, used to move a direction of either up or down"
+ old_position = self.position
+ if direction == Direction.DOWN:
+ if self.position + 1 >= len(self.choices):
+ return
+ self.position += num_spaces
+ else:
+ if self.position - 1 < 0:
+ return
+ self.position -= num_spaces
+ clear_line()
+ self.print_choice(old_position)
+ move_cursor(num_spaces, direction.name)
+ self.print_choice(self.position)
+
+ @input.mark(KEYMAP["up"])
+ def move_up(self):
+ self.move_direction(Direction.UP)
+
+ @input.mark(KEYMAP["down"])
+ def move_down(self):
+ self.move_direction(Direction.DOWN)
+
+ @input.mark(KEYMAP["newline"])
+ def select(self):
+ move_cursor(len(self.choices) - self.position, "DOWN")
+ return self.position
+
+ @input.mark(KEYMAP["interrupt"])
+ def interrupt(self):
+ move_cursor(len(self.choices) - self.position, "DOWN")
+ raise KeyboardInterrupt
+
+ @input.mark_multiple(*[KEYMAP[str(number)] for number in range(10)])
+ def select_row(self):
+ index = int(chr(self.current_selection))
+ movement = index - self.position
+ if index == self.position:
+ return
+ if index < len(self.choices):
+ if self.position > index:
+ self.move_direction(Direction.UP, -movement)
+ elif self.position < index:
+ self.move_direction(Direction.DOWN, movement)
+ else:
+ return
+ else:
+ return
+
+ def run(self, default_choice: int = 0):
+ "Start the menu and return the selected choice"
+ if self.prompt:
+ linebreak()
+ forceWrite(self.prompt, "\n")
+ if in_colab:
+ forceWrite("Please input a choice index (starting from 0), and press enter", "\n")
+ else:
+ forceWrite("Please select a choice using the arrow or number keys, and selecting with enter", "\n")
+ self.position = default_choice
+ for i in range(len(self.choices)):
+ self.print_choice(i)
+ forceWrite("\n")
+ move_cursor(len(self.choices) - self.position, "UP")
+ with cursor.hide():
+ while True:
+ if in_colab:
+ try:
+ choice = int(builtins.input())
+ except ValueError:
+ choice = default_choice
+ else:
+ choice = self.handle_input()
+ if choice is not None:
+ reset_cursor()
+ for _ in range(len(self.choices) + 1):
+ move_cursor(1, "UP")
+ clear_line()
+ self.write_choice(choice, "\n")
+ return choice
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/merge.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/merge.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5c538165e9adc22f7d71b4752f3d390729639b7
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/merge.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from accelerate.commands.utils import CustomArgumentParser
+from accelerate.utils import merge_fsdp_weights
+
+
+description = """Utility to merge the weights from multiple FSDP checkpoints into a single combined checkpoint. Should be used if
+`SHARDED_STATE_DICT` was used for the model. Weights will be saved to `{output_path}`.
+
+This is a CPU-bound process and requires enough RAM to load the entire model state dict."""
+
+
+def merge_command(args):
+ merge_fsdp_weights(
+ args.checkpoint_directory, args.output_path, not args.unsafe_serialization, args.remove_checkpoint_dir
+ )
+
+
+def merge_command_parser(subparsers=None):
+ if subparsers is not None:
+ parser = subparsers.add_parser("merge-weights", description=description)
+ else:
+ parser = CustomArgumentParser(description=description)
+
+ parser.add_argument("checkpoint_directory", type=str, help="A directory containing sharded weights saved by FSDP.")
+ parser.add_argument(
+ "output_path",
+ type=str,
+ help="The path to save the merged weights. Defaults to the current directory. ",
+ )
+ parser.add_argument(
+ "--unsafe_serialization",
+ action="store_false",
+ default=False,
+ help="Whether to save the merged weights as `.bin` rather than `.safetensors` (not recommended).",
+ )
+ parser.add_argument(
+ "--remove_checkpoint_dir",
+ action="store_true",
+ help="Whether to remove the checkpoint directory after merging.",
+ default=False,
+ )
+
+ if subparsers is not None:
+ parser.set_defaults(func=merge_command)
+ return parser
+
+
+def main():
+ parser = merge_command_parser()
+ args = parser.parse_args()
+ merge_command(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/test.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/test.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0d2f7bcf14727aa13e3438f4cd6e6f140f5bb2f
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/test.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+
+from accelerate.test_utils import execute_subprocess_async, path_in_accelerate_package
+
+
+def test_command_parser(subparsers=None):
+ if subparsers is not None:
+ parser = subparsers.add_parser("test")
+ else:
+ parser = argparse.ArgumentParser("Accelerate test command")
+
+ parser.add_argument(
+ "--config_file",
+ default=None,
+ help=(
+ "The path to use to store the config file. Will default to a file named default_config.yaml in the cache "
+ "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have "
+ "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed "
+ "with 'huggingface'."
+ ),
+ )
+
+ if subparsers is not None:
+ parser.set_defaults(func=test_command)
+ return parser
+
+
+def test_command(args):
+ script_name = path_in_accelerate_package("test_utils", "scripts", "test_script.py")
+
+ if args.config_file is None:
+ test_args = [script_name]
+ else:
+ test_args = f"--config_file={args.config_file} {script_name}".split()
+
+ cmd = ["accelerate-launch"] + test_args
+ result = execute_subprocess_async(cmd)
+ if result.returncode == 0:
+ print("Test is a success! You are ready for your distributed training!")
+
+
+def main():
+ parser = test_command_parser()
+ args = parser.parse_args()
+ test_command(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/tpu.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/tpu.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc0f07bf8697bfdb6484d3bf817f2e18b1313b00
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/tpu.py
@@ -0,0 +1,157 @@
+#!/usr/bin/env python
+
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+import os
+import subprocess
+
+from packaging.version import Version, parse
+
+from accelerate.commands.config.config_args import default_config_file, load_config_from_file
+
+
+_description = "Run commands across TPU VMs for initial setup before running `accelerate launch`."
+
+
+def tpu_command_parser(subparsers=None):
+ if subparsers is not None:
+ parser = subparsers.add_parser("tpu-config", description=_description)
+ else:
+ parser = argparse.ArgumentParser("Accelerate tpu-config command", description=_description)
+ # Core arguments
+ config_args = parser.add_argument_group(
+ "Config Arguments", "Arguments that can be configured through `accelerate config`."
+ )
+ config_args.add_argument(
+ "--config_file",
+ type=str,
+ default=None,
+ help="Path to the config file to use for accelerate.",
+ )
+ config_args.add_argument(
+ "--tpu_name",
+ default=None,
+ help="The name of the TPU to use. If not specified, will use the TPU specified in the config file.",
+ )
+ config_args.add_argument(
+ "--tpu_zone",
+ default=None,
+ help="The zone of the TPU to use. If not specified, will use the zone specified in the config file.",
+ )
+ pod_args = parser.add_argument_group("TPU Arguments", "Arguments for options ran inside the TPU.")
+ pod_args.add_argument(
+ "--use_alpha",
+ action="store_true",
+ help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.",
+ )
+ pod_args.add_argument(
+ "--command_file",
+ default=None,
+ help="The path to the file containing the commands to run on the pod on startup.",
+ )
+ pod_args.add_argument(
+ "--command",
+ action="append",
+ nargs="+",
+ help="A command to run on the pod. Can be passed multiple times.",
+ )
+ pod_args.add_argument(
+ "--install_accelerate",
+ action="store_true",
+ help="Whether to install accelerate on the pod. Defaults to False.",
+ )
+ pod_args.add_argument(
+ "--accelerate_version",
+ default="latest",
+ 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.",
+ )
+ pod_args.add_argument(
+ "--debug", action="store_true", help="If set, will print the command that would be run instead of running it."
+ )
+
+ if subparsers is not None:
+ parser.set_defaults(func=tpu_command_launcher)
+ return parser
+
+
+def tpu_command_launcher(args):
+ defaults = None
+
+ # Get the default from the config file if it exists.
+ if args.config_file is not None or os.path.isfile(default_config_file):
+ defaults = load_config_from_file(args.config_file)
+ if not args.command_file and defaults.command_file is not None and not args.command:
+ args.command_file = defaults.command_file
+ if not args.command and defaults.commands is not None:
+ args.command = defaults.commands
+ if not args.tpu_name:
+ args.tpu_name = defaults.tpu_name
+ if not args.tpu_zone:
+ args.tpu_zone = defaults.tpu_zone
+ if args.accelerate_version == "dev":
+ args.accelerate_version = "git+https://github.com/huggingface/accelerate.git"
+ elif args.accelerate_version == "latest":
+ args.accelerate_version = "accelerate -U"
+ elif isinstance(parse(args.accelerate_version), Version):
+ args.accelerate_version = f"accelerate=={args.accelerate_version}"
+
+ if not args.command_file and not args.command:
+ raise ValueError("You must specify either a command file or a command to run on the pod.")
+
+ if args.command_file:
+ with open(args.command_file) as f:
+ args.command = [f.read().splitlines()]
+
+ # To turn list of lists into list of strings
+ if isinstance(args.command[0], list):
+ args.command = [line for cmd in args.command for line in cmd]
+ # Default to the shared folder and install accelerate
+ new_cmd = ["cd /usr/share"]
+ if args.install_accelerate:
+ new_cmd += [f"pip install {args.accelerate_version}"]
+ new_cmd += args.command
+ args.command = "; ".join(new_cmd)
+
+ # Then send it to gcloud
+ # Eventually try to use google-api-core to do this instead of subprocess
+ cmd = ["gcloud"]
+ if args.use_alpha:
+ cmd += ["alpha"]
+ cmd += [
+ "compute",
+ "tpus",
+ "tpu-vm",
+ "ssh",
+ args.tpu_name,
+ "--zone",
+ args.tpu_zone,
+ "--command",
+ args.command,
+ "--worker",
+ "all",
+ ]
+ if args.debug:
+ print(f"Running {' '.join(cmd)}")
+ return
+ subprocess.run(cmd)
+ print("Successfully setup pod.")
+
+
+def main():
+ parser = tpu_command_parser()
+ args = parser.parse_args()
+
+ tpu_command_launcher(args)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/utils.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b65215fac7666b475af98b17e264ef6701239bc1
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/commands/utils.py
@@ -0,0 +1,120 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+
+
+class _StoreAction(argparse.Action):
+ """
+ Custom action that allows for `-` or `_` to be passed in for an argument.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ new_option_strings = []
+ for option_string in self.option_strings:
+ new_option_strings.append(option_string)
+ if "_" in option_string[2:]:
+ # Add `-` version to the option string
+ new_option_strings.append(option_string.replace("_", "-"))
+ self.option_strings = new_option_strings
+
+ def __call__(self, parser, namespace, values, option_string=None):
+ setattr(namespace, self.dest, values)
+
+
+class _StoreConstAction(_StoreAction):
+ """
+ Same as `argparse._StoreConstAction` but uses the custom `_StoreAction`.
+ """
+
+ def __init__(self, option_strings, dest, const, default=None, required=False, help=None):
+ super().__init__(
+ option_strings=option_strings,
+ dest=dest,
+ nargs=0,
+ const=const,
+ default=default,
+ required=required,
+ help=help,
+ )
+
+ def __call__(self, parser, namespace, values, option_string=None):
+ setattr(namespace, self.dest, self.const)
+
+
+class _StoreTrueAction(_StoreConstAction):
+ """
+ Same as `argparse._StoreTrueAction` but uses the custom `_StoreConstAction`.
+ """
+
+ def __init__(
+ self,
+ option_strings,
+ dest,
+ default=None,
+ required=False,
+ help=None,
+ ):
+ super().__init__(
+ option_strings=option_strings, dest=dest, const=True, default=default, required=required, help=help
+ )
+
+
+class CustomArgumentGroup(argparse._ArgumentGroup):
+ """
+ Custom argument group that allows for the use of `-` or `_` in arguments passed and overrides the help for each
+ when applicable.
+ """
+
+ def _add_action(self, action):
+ args = vars(action)
+ if isinstance(action, argparse._StoreTrueAction):
+ action = _StoreTrueAction(
+ args["option_strings"], args["dest"], args["default"], args["required"], args["help"]
+ )
+ elif isinstance(action, argparse._StoreConstAction):
+ action = _StoreConstAction(
+ args["option_strings"],
+ args["dest"],
+ args["const"],
+ args["default"],
+ args["required"],
+ args["help"],
+ )
+ elif isinstance(action, argparse._StoreAction):
+ action = _StoreAction(**args)
+ action = super()._add_action(action)
+ return action
+
+
+class CustomArgumentParser(argparse.ArgumentParser):
+ """
+ Custom argument parser that allows for the use of `-` or `_` in arguments passed and overrides the help for each
+ when applicable.
+ """
+
+ def add_argument(self, *args, **kwargs):
+ if "action" in kwargs:
+ # Translate action -> class
+ if kwargs["action"] == "store_true":
+ kwargs["action"] = _StoreTrueAction
+ else:
+ kwargs["action"] = _StoreAction
+ super().add_argument(*args, **kwargs)
+
+ def add_argument_group(self, *args, **kwargs):
+ group = CustomArgumentGroup(self, *args, **kwargs)
+ self._action_groups.append(group)
+ return group
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/data_loader.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/data_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..c793e85f8dc66d6564853e7b41356005b83d4bb9
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/data_loader.py
@@ -0,0 +1,1314 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from contextlib import suppress
+from typing import Callable, List, Optional, Union
+
+import torch
+from torch.utils.data import BatchSampler, DataLoader, IterableDataset, RandomSampler
+
+from .logging import get_logger
+from .state import DistributedType, GradientState, PartialState, is_torch_xla_available
+from .utils import (
+ RNGType,
+ broadcast,
+ broadcast_object_list,
+ concatenate,
+ find_batch_size,
+ get_data_structure,
+ initialize_tensors,
+ is_torch_version,
+ is_torchdata_stateful_dataloader_available,
+ send_to_device,
+ slice_tensors,
+ synchronize_rng_states,
+)
+
+
+logger = get_logger(__name__)
+
+# kwargs of the DataLoader in min version 1.4.0.
+_PYTORCH_DATALOADER_KWARGS = {
+ "batch_size": 1,
+ "shuffle": False,
+ "sampler": None,
+ "batch_sampler": None,
+ "num_workers": 0,
+ "collate_fn": None,
+ "pin_memory": False,
+ "drop_last": False,
+ "timeout": 0,
+ "worker_init_fn": None,
+ "multiprocessing_context": None,
+ "generator": None,
+ "prefetch_factor": 2,
+ "persistent_workers": False,
+}
+
+# kwargs added after by version
+_PYTORCH_DATALOADER_ADDITIONAL_KWARGS = {}
+
+for v, additional_kwargs in _PYTORCH_DATALOADER_ADDITIONAL_KWARGS.items():
+ if is_torch_version(">=", v):
+ _PYTORCH_DATALOADER_KWARGS.update(additional_kwargs)
+
+
+class SeedableRandomSampler(RandomSampler):
+ """
+ Same as a random sampler, except that in `__iter__` a seed can be used.
+
+ Needed specifically in distributed cases, when the random generator for each GPU needs to start from the same seed
+ and be fully reproducable on multiple iterations.
+
+ If a custom `generator` is passed, it will rely on its initial seed as well as the current iteration it is on
+ (stored in `self.epoch`).
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.epoch = 0
+ self.initial_seed = torch.random.initial_seed()
+
+ def __iter__(self):
+ if self.generator is None:
+ self.generator = torch.Generator()
+ self.generator.manual_seed(self.initial_seed)
+
+ # Allow `self.epoch` to modify the seed of the generator
+ seed = self.epoch + self.initial_seed
+ # print("Setting seed at epoch", self.epoch, seed)
+ self.generator.manual_seed(seed)
+ yield from super().__iter__()
+ self.set_epoch(self.epoch + 1)
+
+ def set_epoch(self, epoch: int):
+ "Sets the current iteration of the sampler."
+ self.epoch = epoch
+
+
+class BatchSamplerShard(BatchSampler):
+ """
+ Wraps a PyTorch `BatchSampler` to generate batches for one of the processes only. Instances of this class will
+ always yield a number of batches that is a round multiple of `num_processes` and that all have the same size.
+ Depending on the value of the `drop_last` attribute of the batch sampler passed, it will either stop the iteration
+ at the first batch that would be too small / not present on all processes or loop with indices from the beginning.
+
+ Args:
+ batch_sampler (`torch.utils.data.sampler.BatchSampler`):
+ The batch sampler to split in several shards.
+ num_processes (`int`, *optional*, defaults to 1):
+ The number of processes running concurrently.
+ process_index (`int`, *optional*, defaults to 0):
+ The index of the current process.
+ split_batches (`bool`, *optional*, defaults to `False`):
+ Whether the shards should be created by splitting a batch to give a piece of it on each process, or by
+ yielding different full batches on each process.
+
+ On two processes with a sampler of `[[0, 1, 2, 3], [4, 5, 6, 7]]`, this will result in:
+
+ - the sampler on process 0 to yield `[0, 1, 2, 3]` and the sampler on process 1 to yield `[4, 5, 6, 7]` if
+ this argument is set to `False`.
+ - the sampler on process 0 to yield `[0, 1]` then `[4, 5]` and the sampler on process 1 to yield `[2, 3]`
+ then `[6, 7]` if this argument is set to `True`.
+ even_batches (`bool`, *optional*, defaults to `True`):
+ Whether or not to loop back at the beginning of the sampler when the number of samples is not a round
+ multiple of (original batch size / number of processes).
+
+
+
+ `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`
+ equal to `False`
+
+ """
+
+ def __init__(
+ self,
+ batch_sampler: BatchSampler,
+ num_processes: int = 1,
+ process_index: int = 0,
+ split_batches: bool = False,
+ even_batches: bool = True,
+ ):
+ if split_batches and batch_sampler.batch_size % num_processes != 0:
+ raise ValueError(
+ f"To use `BatchSamplerShard` in `split_batches` mode, the batch size ({batch_sampler.batch_size}) "
+ f"needs to be a round multiple of the number of processes ({num_processes})."
+ )
+ self.batch_sampler = batch_sampler
+ self.num_processes = num_processes
+ self.process_index = process_index
+ self.split_batches = split_batches
+ self.even_batches = even_batches
+ self.batch_size = getattr(batch_sampler, "batch_size", None)
+ self.drop_last = getattr(batch_sampler, "drop_last", False)
+ if self.batch_size is None and self.even_batches:
+ raise ValueError(
+ "You need to use `even_batches=False` when the batch sampler has no batch size. If you "
+ "are not calling this method directly, set `accelerator.even_batches=False` instead."
+ )
+
+ @property
+ def total_length(self):
+ return len(self.batch_sampler)
+
+ def __len__(self):
+ if self.split_batches:
+ # Split batches does not change the length of the batch sampler
+ return len(self.batch_sampler)
+ if len(self.batch_sampler) % self.num_processes == 0:
+ # If the length is a round multiple of the number of processes, it's easy.
+ return len(self.batch_sampler) // self.num_processes
+ length = len(self.batch_sampler) // self.num_processes
+ if self.drop_last:
+ # Same if we drop the remainder.
+ return length
+ elif self.even_batches:
+ # When we even batches we always get +1
+ return length + 1
+ else:
+ # Otherwise it depends on the process index.
+ return length + 1 if self.process_index < len(self.batch_sampler) % self.num_processes else length
+
+ def __iter__(self):
+ return self._iter_with_split() if self.split_batches else self._iter_with_no_split()
+
+ def _iter_with_split(self):
+ initial_data = []
+ batch_length = self.batch_sampler.batch_size // self.num_processes
+ for idx, batch in enumerate(self.batch_sampler):
+ if idx == 0:
+ initial_data = batch
+ if len(batch) == self.batch_size:
+ # If the batch is full, we yield the part of it this process is responsible of.
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
+
+ # If drop_last is True of the last batch was full, iteration is over, otherwise...
+ if not self.drop_last and len(initial_data) > 0 and len(batch) < self.batch_size:
+ if not self.even_batches:
+ if len(batch) > batch_length * self.process_index:
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
+ else:
+ # For degenerate cases where the dataset has less than num_process * batch_size samples
+ while len(initial_data) < self.batch_size:
+ initial_data += initial_data
+ batch = batch + initial_data
+ yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
+
+ def _iter_with_no_split(self):
+ initial_data = []
+ batch_to_yield = []
+ for idx, batch in enumerate(self.batch_sampler):
+ # We gather the initial indices in case we need to circle back at the end.
+ if not self.drop_last and idx < self.num_processes:
+ initial_data += batch
+ # We identify the batch to yield but wait until we ar sure every process gets a full batch before actually
+ # yielding it.
+ if idx % self.num_processes == self.process_index:
+ batch_to_yield = batch
+ if idx % self.num_processes == self.num_processes - 1 and (
+ self.batch_size is None or len(batch) == self.batch_size
+ ):
+ yield batch_to_yield
+ batch_to_yield = []
+
+ # If drop_last is True, iteration is over, otherwise...
+ if not self.drop_last and len(initial_data) > 0:
+ if not self.even_batches:
+ if len(batch_to_yield) > 0:
+ yield batch_to_yield
+ else:
+ # ... we yield the complete batch we had saved before if it has the proper length
+ if len(batch_to_yield) == self.batch_size:
+ yield batch_to_yield
+
+ # For degenerate cases where the dataset has less than num_process * batch_size samples
+ while len(initial_data) < self.num_processes * self.batch_size:
+ initial_data += initial_data
+
+ # If the last batch seen was of the proper size, it has been yielded by its process so we move to the next
+ if len(batch) == self.batch_size:
+ batch = []
+ idx += 1
+
+ # Make sure we yield a multiple of self.num_processes batches
+ cycle_index = 0
+ while idx % self.num_processes != 0 or len(batch) > 0:
+ end_index = cycle_index + self.batch_size - len(batch)
+ batch += initial_data[cycle_index:end_index]
+ if idx % self.num_processes == self.process_index:
+ yield batch
+ cycle_index = end_index
+ batch = []
+ idx += 1
+
+
+class IterableDatasetShard(IterableDataset):
+ """
+ Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will
+ always yield a number of samples that is a round multiple of the actual batch size (depending of the value of
+ `split_batches`, this is either `batch_size` or `batch_size x num_processes`). Depending on the value of the
+ `drop_last` attribute of the batch sampler passed, it will either stop the iteration at the first batch that would
+ be too small or loop with indices from the beginning.
+
+ Args:
+ dataset (`torch.utils.data.dataset.IterableDataset`):
+ The batch sampler to split in several shards.
+ batch_size (`int`, *optional*, defaults to 1):
+ The size of the batches per shard (if `split_batches=False`) or the size of the batches (if
+ `split_batches=True`).
+ drop_last (`bool`, *optional*, defaults to `False`):
+ Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the
+ beginning.
+ num_processes (`int`, *optional*, defaults to 1):
+ The number of processes running concurrently.
+ process_index (`int`, *optional*, defaults to 0):
+ The index of the current process.
+ split_batches (`bool`, *optional*, defaults to `False`):
+ Whether the shards should be created by splitting a batch to give a piece of it on each process, or by
+ yielding different full batches on each process.
+
+ On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7]`, this will result in:
+
+ - 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
+ argument is set to `False`.
+ - the shard on process 0 to yield `[0, 1, 4, 5]` and the sampler on process 1 to yield `[2, 3, 6, 7]` if
+ this argument is set to `True`.
+ """
+
+ def __init__(
+ self,
+ dataset: IterableDataset,
+ batch_size: int = 1,
+ drop_last: bool = False,
+ num_processes: int = 1,
+ process_index: int = 0,
+ split_batches: bool = False,
+ ):
+ if split_batches and batch_size > 1 and batch_size % num_processes != 0:
+ raise ValueError(
+ f"To use `IterableDatasetShard` in `split_batches` mode, the batch size ({batch_size}) "
+ f"needs to be a round multiple of the number of processes ({num_processes})."
+ )
+ self.dataset = dataset
+ self.batch_size = batch_size
+ self.drop_last = drop_last
+ self.num_processes = num_processes
+ self.process_index = process_index
+ self.split_batches = split_batches
+
+ def set_epoch(self, epoch):
+ self.epoch = epoch
+ if hasattr(self.dataset, "set_epoch"):
+ self.dataset.set_epoch(epoch)
+
+ def __len__(self):
+ # We will just raise the downstream error if the underlying dataset is not sized
+ if self.drop_last:
+ return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size
+ else:
+ return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size
+
+ def __iter__(self):
+ if (
+ not hasattr(self.dataset, "set_epoch")
+ and hasattr(self.dataset, "generator")
+ and isinstance(self.dataset.generator, torch.Generator)
+ ):
+ self.dataset.generator.manual_seed(self.epoch)
+ real_batch_size = self.batch_size if self.split_batches else (self.batch_size * self.num_processes)
+ process_batch_size = (self.batch_size // self.num_processes) if self.split_batches else self.batch_size
+ process_slice = range(self.process_index * process_batch_size, (self.process_index + 1) * process_batch_size)
+
+ first_batch = None
+ current_batch = []
+ for element in self.dataset:
+ current_batch.append(element)
+ # Wait to have a full batch before yielding elements.
+ if len(current_batch) == real_batch_size:
+ for i in process_slice:
+ yield current_batch[i]
+ if first_batch is None:
+ first_batch = current_batch.copy()
+ current_batch = []
+
+ # Finished if drop_last is True, otherwise complete the last batch with elements from the beginning.
+ if not self.drop_last and len(current_batch) > 0:
+ if first_batch is None:
+ first_batch = current_batch.copy()
+ while len(current_batch) < real_batch_size:
+ current_batch += first_batch
+ for i in process_slice:
+ yield current_batch[i]
+
+
+class DataLoaderStateMixin:
+ """
+ Mixin class that adds a state to a `DataLoader` to keep track of the status inside the dataloader such as at the
+ end of the iteration, the number of items in the dataset in the last batch relative to the batch size, and other
+ useful information that might be needed.
+
+ **Available attributes:**
+
+ - **end_of_dataloader** (`bool`) -- Whether at the last iteration or batch
+ - **remainder** (`int`) -- The number of items that are remaining in the last batch, relative to the total
+ batch size
+
+
+
+ Inheriters of this class should ensure that the class creates a `GradientState()` instance, stored in
+ `self.gradient_state`.
+
+
+
+ """
+
+ def __init_subclass__(cls, **kwargs):
+ cls.end_of_dataloader = False
+ cls.remainder = -1
+
+ def reset(self):
+ self.end_of_dataloader = False
+ self.remainder = -1
+
+ def begin(self):
+ "Prepares the gradient state for the current dataloader"
+ self.reset()
+ with suppress(Exception):
+ if not self._drop_last:
+ length = getattr(self.dataset, "total_dataset_length", len(self.dataset))
+ self.remainder = length % self.total_batch_size
+ self.gradient_state._add_dataloader(self)
+
+ def end(self):
+ "Cleans up the gradient state after exiting the dataloader"
+ self.gradient_state._remove_dataloader(self)
+
+
+class DataLoaderAdapter:
+ """
+ A class which wraps around a PyTorch `DataLoader` (or variants of it) to be used with the `Accelerator`. For
+ compatability reasons, this class inherits from the class it wraps around, so it can be used as a drop-in.
+ """
+
+ def __init__(self, dataset, use_stateful_dataloader=False, batch_sampler=None, **kwargs):
+ self.use_stateful_dataloader = use_stateful_dataloader
+ if is_torchdata_stateful_dataloader_available():
+ from torchdata.stateful_dataloader import StatefulDataLoader
+
+ if use_stateful_dataloader and not is_torchdata_stateful_dataloader_available():
+ raise ImportError(
+ "StatefulDataLoader is not available. Please install torchdata version 0.8.0 or higher to use it."
+ )
+ if use_stateful_dataloader:
+ self.base_dataloader = StatefulDataLoader(dataset, batch_sampler=batch_sampler, **kwargs)
+ else:
+ self.base_dataloader = DataLoader(dataset, batch_sampler=batch_sampler, **kwargs)
+
+ if hasattr(self.base_dataloader, "state_dict"):
+ self.dl_state_dict = self.base_dataloader.state_dict()
+
+ def __getattr__(self, name):
+ # Avoid infinite recursion if we try to access a nonexistent base_dataloader attribute.
+ if name == "base_dataloader":
+ raise AttributeError()
+ # Delegate attribute access to the internal dataloader
+ return getattr(self.base_dataloader, name)
+
+ def state_dict(self):
+ return self.dl_state_dict
+
+ def load_state_dict(self, state_dict):
+ self.base_dataloader.load_state_dict(state_dict)
+
+ @property
+ def __class__(self):
+ """
+ In order to maintain backwards compatability with other code, we need to ensure `isinstance(obj, DataLoader)`
+ returs true. This is because some downstream code assumes that the `DataLoader` is the base class of the
+ object.
+ """
+ return self.base_dataloader.__class__
+
+ def __len__(self):
+ return len(self.base_dataloader)
+
+ def adjust_state_dict_for_prefetch(self):
+ """
+ Adjusts the state dict for prefetching. Natively, this will adjust all of the iters yielded keys in
+ `self.dl_state_dict` by a factor of `num_processes - 1`, however if a custom correction is needed, this can be
+ overridden.
+
+ This should modify `self.dl_state_dict` directly
+ """
+ # The state dict will be off by a factor of `n-1` batch too many during DDP,
+ # so we need to adjust it here
+ if PartialState().distributed_type != DistributedType.NO:
+ factor = PartialState().num_processes - 1
+ if self.dl_state_dict["_sampler_iter_yielded"] > 0:
+ self.dl_state_dict["_sampler_iter_yielded"] -= factor
+ if self.dl_state_dict["_num_yielded"] > 0:
+ self.dl_state_dict["_num_yielded"] -= factor
+ if self.dl_state_dict["_index_sampler_state"] is not None:
+ if (
+ "samples_yielded" in self.dl_state_dict["_index_sampler_state"]
+ and self.dl_state_dict["_index_sampler_state"]["samples_yielded"] > 0
+ ):
+ self.dl_state_dict["_index_sampler_state"]["samples_yielded"] -= self.batch_size * factor
+
+ def _update_state_dict(self):
+ # The state_dict of the underlying base_dataloader may be ahead of what is currently being yielded.
+ # E.g. the implementation of DataLoaderShard involves having an underlying iterator 1 element ahead of
+ # what it wants to yield.
+ #
+ # _update_state_dict is called to snapshot the state_dict that would properly recover the DataLoaderAdapter.
+ if hasattr(self.base_dataloader, "state_dict"):
+ self.dl_state_dict = self.base_dataloader.state_dict()
+ # Potentially modify the state_dict to adjust for prefetching
+ self.adjust_state_dict_for_prefetch()
+ # Then tag if we are at the end of the dataloader
+ self.dl_state_dict["_iterator_finished"] = self.end_of_dataloader
+
+
+class DataLoaderShard(DataLoaderAdapter, DataLoaderStateMixin):
+ """
+ Subclass of `DataLoaderAdapter` that will deal with device placement and current distributed setup.
+
+ Args:
+ dataset (`torch.utils.data.dataset.Dataset`):
+ The dataset to use to build this dataloader.
+ device (`torch.device`, *optional*):
+ If passed, the device to put all batches on.
+ rng_types (list of `str` or [`~utils.RNGType`]):
+ The list of random number generators to synchronize at the beginning of each iteration. Should be one or
+ several of:
+
+ - `"torch"`: the base torch random number generator
+ - `"cuda"`: the CUDA random number generator (GPU only)
+ - `"xla"`: the XLA random number generator (TPU only)
+ - `"generator"`: an optional `torch.Generator`
+ synchronized_generator (`torch.Generator`, *optional*):
+ A random number generator to keep synchronized across processes.
+ skip_batches (`int`, *optional*, defaults to 0):
+ The number of batches to skip at the beginning.
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
+ Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`.
+ **kwargs (additional keyword arguments, *optional*):
+ All other keyword arguments to pass to the regular `DataLoader` initialization.
+
+ **Available attributes:**
+
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
+ number of processes
+
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
+ """
+
+ def __init__(
+ self,
+ dataset,
+ device=None,
+ rng_types=None,
+ synchronized_generator=None,
+ skip_batches=0,
+ use_stateful_dataloader=False,
+ _drop_last: bool = False,
+ _non_blocking: bool = False,
+ **kwargs,
+ ):
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
+ self.device = device
+ self.rng_types = rng_types
+ self.synchronized_generator = synchronized_generator
+ self.skip_batches = skip_batches
+ self.gradient_state = GradientState()
+ self._drop_last = _drop_last
+ self._non_blocking = _non_blocking
+ self.iteration = 0
+
+ def __iter__(self):
+ if self.rng_types is not None:
+ synchronize_rng_states(self.rng_types, self.synchronized_generator)
+ self.begin()
+
+ self.set_epoch(self.iteration)
+ dataloader_iter = self.base_dataloader.__iter__()
+ # We iterate one batch ahead to check when we are at the end
+ try:
+ current_batch = next(dataloader_iter)
+ except StopIteration:
+ yield
+
+ batch_index = 0
+ while True:
+ try:
+ # But we still move it to the device so it is done before `StopIteration` is reached
+ if self.device is not None:
+ current_batch = send_to_device(current_batch, self.device, non_blocking=self._non_blocking)
+ self._update_state_dict()
+ next_batch = next(dataloader_iter)
+ if batch_index >= self.skip_batches:
+ yield current_batch
+ batch_index += 1
+ current_batch = next_batch
+ except StopIteration:
+ self.end_of_dataloader = True
+ self._update_state_dict()
+ if batch_index >= self.skip_batches:
+ yield current_batch
+ break
+
+ self.iteration += 1
+ self.end()
+
+ def __reduce__(self):
+ """
+ Define the `__reduce__` method to ensure a `DataLoaderShard` can be pickled and unpickled. This needs to be
+ explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
+ `__class__` member.
+ """
+ args = super().__reduce__()
+ return (DataLoaderShard, *args[1:])
+
+ def set_epoch(self, epoch: int):
+ # In case it is manually passed in, the user can set it to what they like
+ if self.iteration != epoch:
+ self.iteration = epoch
+ if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"):
+ self.batch_sampler.sampler.set_epoch(epoch)
+ # We support if a custom `Dataset` implementation has `set_epoch`
+ # or in general HF datasets `Datasets`
+ elif hasattr(self.dataset, "set_epoch"):
+ self.dataset.set_epoch(epoch)
+
+ @property
+ def total_batch_size(self):
+ batch_sampler = self.sampler if isinstance(self.sampler, BatchSampler) else self.batch_sampler
+ return (
+ batch_sampler.batch_size
+ if getattr(batch_sampler, "split_batches", False)
+ else (batch_sampler.batch_size * getattr(batch_sampler, "num_processes", 1))
+ )
+
+ @property
+ def total_dataset_length(self):
+ if hasattr(self.dataset, "total_length"):
+ return self.dataset.total_length
+ else:
+ return len(self.dataset)
+
+ def get_sampler(self):
+ return get_sampler(self)
+
+ def set_sampler(self, sampler):
+ sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler)
+ if sampler_is_batch_sampler:
+ self.sampler.sampler = sampler
+ else:
+ self.batch_sampler.sampler = sampler
+ if hasattr(self.batch_sampler, "batch_sampler"):
+ self.batch_sampler.batch_sampler.sampler = sampler
+
+
+if is_torch_xla_available():
+ import torch_xla.distributed.parallel_loader as xpl
+
+ class MpDeviceLoaderWrapper(xpl.MpDeviceLoader):
+ """
+ Wrapper for the xpl.MpDeviceLoader class that knows the total batch size.
+
+ XLA preloading threads will all call DataLoaderShard's __iter__(). Remove rng_types from DataLoaderShard to
+ prevent it from using the XLA device in the preloading threads, and synchronize the RNG once from the main
+ thread only.
+
+ **Available attributes:**
+
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
+ number of processes
+
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
+ """
+
+ def __init__(self, dataloader: DataLoaderShard, device: torch.device):
+ super().__init__(dataloader, device)
+ self._rng_types = self._loader.rng_types
+ self._loader.rng_types = None
+ self.device = device
+
+ def __iter__(self):
+ if self._rng_types is not None:
+ synchronize_rng_states(self._rng_types, self._loader.synchronized_generator)
+
+ return super().__iter__()
+
+ def set_epoch(self, epoch: int):
+ if hasattr(self.dataloader, "set_epoch"):
+ self.dataloader.set_epoch(epoch)
+
+ @property
+ def total_batch_size(self):
+ return self._loader.total_batch_size
+
+ @property
+ def total_dataset_length(self):
+ return self._loader.total_dataset_length
+
+ @property
+ def batch_sampler(self):
+ return self._loader.batch_sampler
+
+ @property
+ def dataloader(self):
+ return self._loader
+
+
+class DataLoaderDispatcher(DataLoaderAdapter, DataLoaderStateMixin):
+ """
+ Subclass of `DataLoaderAdapter` that will iterate and preprocess on process 0 only, then dispatch on each process
+ their part of the batch.
+
+ Args:
+ split_batches (`bool`, *optional*, defaults to `False`):
+ Whether the resulting `DataLoader` should split the batches of the original data loader across devices or
+ yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of
+ `num_processes` batches at each iteration). Another way to see this is that the observed batch size will be
+ the same as the initial `dataloader` if this option is set to `True`, the batch size of the initial
+ `dataloader` multiplied by `num_processes` otherwise. Setting this option to `True` requires that the batch
+ size of the `dataloader` is a round multiple of `batch_size`.
+ skip_batches (`int`, *optional*, defaults to 0):
+ The number of batches to skip at the beginning of an iteration.
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
+ Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`.
+
+ **Available attributes:**
+
+ - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.
+ Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total
+ number of processes
+
+ - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.
+ """
+
+ def __init__(
+ self,
+ dataset,
+ split_batches: bool = False,
+ skip_batches=0,
+ use_stateful_dataloader=False,
+ _drop_last: bool = False,
+ _non_blocking: bool = False,
+ slice_fn=None,
+ **kwargs,
+ ):
+ shuffle = False
+ if is_torch_version(">=", "1.11.0"):
+ from torch.utils.data.datapipes.iter.combinatorics import ShufflerIterDataPipe
+
+ # We need to save the shuffling state of the DataPipe
+ if isinstance(dataset, ShufflerIterDataPipe):
+ shuffle = dataset._shuffle_enabled
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
+ self.split_batches = split_batches
+ if shuffle:
+ torch.utils.data.graph_settings.apply_shuffle_settings(dataset, shuffle=shuffle)
+
+ self.gradient_state = GradientState()
+ self.state = PartialState()
+ self._drop_last = _drop_last
+ self._non_blocking = _non_blocking
+ self.skip_batches = skip_batches
+
+ self.slice_fn = slice_tensors if slice_fn is None else slice_fn
+ self.iteration = 0
+
+ def _fetch_batches(self, iterator):
+ batches, batch = None, None
+ # On process 0, we gather the batch to dispatch.
+ if self.state.process_index == 0:
+ try:
+ if self.split_batches:
+ # One batch of the main iterator is dispatched and split.
+ self._update_state_dict()
+ batch = next(iterator)
+ else:
+ # num_processes batches of the main iterator are concatenated then dispatched and split.
+ # We add the batches one by one so we have the remainder available when drop_last=False.
+ batches = []
+ for _ in range(self.state.num_processes):
+ self._update_state_dict()
+ batches.append(next(iterator))
+ try:
+ batch = concatenate(batches, dim=0)
+ except RuntimeError as e:
+ raise RuntimeError(
+ "You can't use batches of different size with `dispatch_batches=True` or when using an `IterableDataset`."
+ "either pass `dispatch_batches=False` and have each process fetch its own batch "
+ " or pass `split_batches=True`. By doing so, the main process will fetch a full batch and "
+ "slice it into `num_processes` batches for each process."
+ ) from e
+ # In both cases, we need to get the structure of the batch that we will broadcast on other
+ # processes to initialize the tensors with the right shape.
+ # data_structure, stop_iteration
+ batch_info = [get_data_structure(batch), False]
+ except StopIteration:
+ batch_info = [None, True]
+ else:
+ batch_info = [None, self._stop_iteration]
+ # This is inplace, so after this instruction, every process has the same `batch_info` as process 0.
+ broadcast_object_list(batch_info)
+ self._stop_iteration = batch_info[1]
+ if self._stop_iteration:
+ # If drop_last is False and split_batches is False, we may have a remainder to take care of.
+ if not self.split_batches and not self._drop_last:
+ if self.state.process_index == 0 and len(batches) > 0:
+ batch = concatenate(batches, dim=0)
+ batch_info = [get_data_structure(batch), False]
+ else:
+ batch_info = [None, True]
+ broadcast_object_list(batch_info)
+ return batch, batch_info
+
+ def __iter__(self):
+ self.begin()
+ self.set_epoch(self.iteration)
+ main_iterator = None
+ if is_torch_version(">=", "2.0.1"):
+ # NOTE PyTorch DataLoader adds forward compatibilities for DataPipes, which broadcasts
+ # shared seed to all dist processes. Thus, we need to create iterator for all dist processes.
+ # But, we only iterate through the DataLoader on process 0.
+ main_iterator = self.base_dataloader.__iter__()
+ elif self.state.process_index == 0:
+ main_iterator = self.base_dataloader.__iter__()
+ stop_iteration = False
+ self._stop_iteration = False
+ first_batch = None
+ next_batch, next_batch_info = self._fetch_batches(main_iterator)
+ batch_index = 0
+ while not stop_iteration:
+ batch, batch_info = next_batch, next_batch_info
+
+ if self.state.process_index != 0:
+ # Initialize tensors on other processes than process 0.
+ batch = initialize_tensors(batch_info[0])
+ batch = send_to_device(batch, self.state.device, non_blocking=self._non_blocking)
+ # Broadcast the batch before splitting it.
+ batch = broadcast(batch, from_process=0)
+
+ if not self._drop_last and first_batch is None:
+ # We keep at least num processes elements of the first batch to be able to complete the last batch
+ first_batch = self.slice_fn(
+ batch,
+ slice(0, self.state.num_processes),
+ process_index=self.state.process_index,
+ num_processes=self.state.num_processes,
+ )
+
+ if batch is None:
+ raise ValueError(
+ f"Batch does not contain any data (`{batch}`). At the end of all iterable data available before expected stop iteration."
+ )
+
+ observed_batch_size = find_batch_size(batch)
+ batch_size = observed_batch_size // self.state.num_processes
+
+ stop_iteration = self._stop_iteration
+ if not stop_iteration:
+ # We may still be at the end of the dataloader without knowing it yet: if there is nothing left in
+ # the dataloader since the number of batches is a round multiple of the number of processes.
+ next_batch, next_batch_info = self._fetch_batches(main_iterator)
+ # next_batch_info[0] is None when there are no more batches, otherwise we still need to process them.
+ if self._stop_iteration and next_batch_info[0] is None:
+ stop_iteration = True
+
+ if not self._drop_last and stop_iteration and observed_batch_size % self.state.num_processes != 0:
+ # If the last batch is not complete, let's add the first batch to it.
+ batch = concatenate([batch, first_batch], dim=0)
+ # Batch size computation above is wrong, it's off by 1 so we fix it.
+ batch_size += 1
+
+ data_slice = slice(self.state.process_index * batch_size, (self.state.process_index + 1) * batch_size)
+ batch = self.slice_fn(
+ batch,
+ data_slice,
+ process_index=self.state.process_index,
+ num_processes=self.state.num_processes,
+ )
+
+ if stop_iteration:
+ self.end_of_dataloader = True
+ self._update_state_dict()
+ self.remainder = observed_batch_size
+ if batch_index >= self.skip_batches:
+ yield batch
+ batch_index += 1
+ self.iteration += 1
+ self.end()
+
+ def set_epoch(self, epoch: int):
+ # In case it is manually passed in, the user can set it to what they like
+ if self.iteration != epoch:
+ self.iteration = epoch
+ if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"):
+ self.batch_sampler.sampler.set_epoch(epoch)
+ elif hasattr(self.dataset, "set_epoch"):
+ self.dataset.set_epoch(epoch)
+
+ def __len__(self):
+ whole_length = len(self.base_dataloader)
+ if self.split_batches:
+ return whole_length
+ elif self._drop_last:
+ return whole_length // self.state.num_processes
+ else:
+ return math.ceil(whole_length / self.state.num_processes)
+
+ def __reduce__(self):
+ """
+ Define the `__reduce__` method to ensure a `DataLoaderDispatcher` can be pickled and unpickled. This needs to
+ be explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
+ `__class__` member.
+ """
+ args = super().__reduce__()
+ return (DataLoaderDispatcher, *args[1:])
+
+ @property
+ def total_batch_size(self):
+ return (
+ self.dataset.batch_size if self.split_batches else (self.dataset.batch_size * self.dataset.num_processes)
+ )
+
+ @property
+ def total_dataset_length(self):
+ return len(self.dataset)
+
+ def get_sampler(self):
+ return get_sampler(self)
+
+ def set_sampler(self, sampler):
+ sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler)
+ if sampler_is_batch_sampler:
+ self.sampler.sampler = sampler
+ else:
+ self.batch_sampler.sampler = sampler
+ if hasattr(self.batch_sampler, "batch_sampler"):
+ self.batch_sampler.batch_sampler.sampler = sampler
+
+
+def get_sampler(dataloader):
+ """
+ Get the sampler associated to the dataloader
+
+ Args:
+ dataloader (`torch.utils.data.dataloader.DataLoader`):
+ The data loader to split across several devices.
+ Returns:
+ `torch.utils.data.Sampler`: The sampler associated to the dataloader
+ """
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
+ if sampler_is_batch_sampler:
+ sampler = getattr(dataloader.sampler, "sampler", None)
+ else:
+ sampler = getattr(dataloader.batch_sampler, "sampler", None)
+ return sampler
+
+
+def prepare_data_loader(
+ dataloader: DataLoader,
+ device: Optional[torch.device] = None,
+ num_processes: Optional[int] = None,
+ process_index: Optional[int] = None,
+ split_batches: bool = False,
+ put_on_device: bool = False,
+ rng_types: Optional[List[Union[str, RNGType]]] = None,
+ dispatch_batches: Optional[bool] = None,
+ even_batches: bool = True,
+ slice_fn_for_dispatch: Optional[Callable] = None,
+ use_seedable_sampler: bool = False,
+ non_blocking: bool = False,
+ use_stateful_dataloader: bool = False,
+) -> DataLoader:
+ """
+ Wraps a PyTorch `DataLoader` to generate batches for one of the processes only.
+
+ Depending on the value of the `drop_last` attribute of the `dataloader` passed, it will either stop the iteration
+ at the first batch that would be too small / not present on all processes or loop with indices from the beginning.
+
+ Args:
+ dataloader (`torch.utils.data.dataloader.DataLoader`):
+ The data loader to split across several devices.
+ device (`torch.device`):
+ The target device for the returned `DataLoader`.
+ num_processes (`int`, *optional*):
+ The number of processes running concurrently. Will default to the value given by [`~state.PartialState`].
+ process_index (`int`, *optional*):
+ The index of the current process. Will default to the value given by [`~state.PartialState`].
+ split_batches (`bool`, *optional*, defaults to `False`):
+ Whether the resulting `DataLoader` should split the batches of the original data loader across devices or
+ yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of
+ `num_processes` batches at each iteration).
+
+ Another way to see this is that the observed batch size will be the same as the initial `dataloader` if
+ this option is set to `True`, the batch size of the initial `dataloader` multiplied by `num_processes`
+ otherwise.
+
+ Setting this option to `True` requires that the batch size of the `dataloader` is a round multiple of
+ `batch_size`.
+ put_on_device (`bool`, *optional*, defaults to `False`):
+ Whether or not to put the batches on `device` (only works if the batches are nested list, tuples or
+ dictionaries of tensors).
+ rng_types (list of `str` or [`~utils.RNGType`]):
+ The list of random number generators to synchronize at the beginning of each iteration. Should be one or
+ several of:
+
+ - `"torch"`: the base torch random number generator
+ - `"cuda"`: the CUDA random number generator (GPU only)
+ - `"xla"`: the XLA random number generator (TPU only)
+ - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your
+ dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type.
+
+ dispatch_batches (`bool`, *optional*):
+ If set to `True`, the dataloader prepared is only iterated through on the main process and then the batches
+ are split and broadcast to each process. Will default to `True` when the underlying dataset is an
+ `IterableDataset`, `False` otherwise.
+ even_batches (`bool`, *optional*, defaults to `True`):
+ If set to `True`, in cases where the total batch size across all processes does not exactly divide the
+ dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among
+ all workers.
+ slice_fn_for_dispatch (`Callable`, *optional*`):
+ If passed, this function will be used to slice tensors across `num_processes`. Will default to
+ [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will be
+ ignored otherwise.
+ use_seedable_sampler (`bool`, *optional*, defaults to `False`):
+ Whether to use the [`~data_loader.SeedableRandomSampler`] instead of a `RandomSampler` for better
+ reproducability. Comes at a cost of potentially different performances due to different shuffling
+ algorithms but ensures results will be the *exact* same. Should be paired with `set_seed()` at every
+ `self.set_epoch`
+ non_blocking (`bool`, *optional*, defaults to `False`):
+ If set to `True`, dataloader will utilize non-blocking host-to-device transfers. If the dataloader has
+ `pin_memory` set to `True`, this will help to increase overlap between data transfer and computations.
+ use_stateful_dataloader (`bool`, *optional*, defaults to `False`):
+ "If set to true, the dataloader prepared by the Accelerator will be backed by "
+ "[torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader).
+ This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed."
+
+
+ Returns:
+ `torch.utils.data.dataloader.DataLoader`: A new data loader that will yield the portion of the batches
+
+
+
+ `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`
+ equal to `False`
+
+
+ """
+ if dispatch_batches is None:
+ if not put_on_device:
+ dispatch_batches = False
+ else:
+ dispatch_batches = isinstance(dataloader.dataset, IterableDataset)
+
+ if dispatch_batches and not put_on_device:
+ raise ValueError("Using `dispatch_batches=True` requires `put_on_device=True`.")
+ # Grab defaults from PartialState
+ state = PartialState()
+ if num_processes is None:
+ num_processes = state.num_processes
+ if process_index is None:
+ process_index = state.process_index
+
+ # Sanity check
+ if split_batches:
+ if dataloader.batch_size is not None:
+ batch_size_for_check = dataloader.batch_size
+ else:
+ # For custom batch_sampler
+ if hasattr(dataloader.batch_sampler, "batch_size"):
+ batch_size_for_check = dataloader.batch_sampler.batch_size
+ else:
+ raise ValueError(
+ "In order to use `split_batches==True` you must have a `batch_size` attribute either in the passed "
+ "`dataloader` or `dataloader.batch_sampler` objects, and it has to return a natural number. "
+ "Your `dataloader.batch_size` is None and `dataloader.batch_sampler` "
+ f"(`{type(dataloader.batch_sampler)}`) does not have the `batch_size` attribute set."
+ )
+
+ if batch_size_for_check > 1 and batch_size_for_check % num_processes != 0:
+ raise ValueError(
+ f"To use a `DataLoader` in `split_batches` mode, the batch size ({dataloader.batch_size}) "
+ f"needs to be a round multiple of the number of processes ({num_processes})."
+ )
+
+ new_dataset = dataloader.dataset
+ # Iterable dataset doesn't like batch_sampler, but data_loader creates a default one for it
+ new_batch_sampler = dataloader.batch_sampler if not isinstance(new_dataset, IterableDataset) else None
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
+ synchronized_generator = None
+
+ sampler = get_sampler(dataloader)
+ if isinstance(sampler, RandomSampler) and use_seedable_sampler:
+ # When iterating through the dataloader during distributed processes
+ # we want to ensure that on each process we are iterating through the same
+ # samples in the same order if a seed is set. This requires a tweak
+ # to the `torch.utils.data.RandomSampler` class (if used).
+ sampler = SeedableRandomSampler(
+ data_source=sampler.data_source,
+ replacement=sampler.replacement,
+ num_samples=sampler._num_samples,
+ generator=getattr(sampler, "generator", torch.Generator()),
+ )
+
+ if isinstance(dataloader.sampler, RandomSampler) and state.distributed_type == DistributedType.XLA:
+ # isinstance(dataloader.sampler, RandomSampler) indicates the original dataloader has `shuffle` enabled.
+ generator = torch.Generator().manual_seed(42)
+ dataloader.generator = generator
+ dataloader.sampler.generator = generator
+ # No change if no multiprocess
+ if (num_processes != 1 or state.distributed_type == DistributedType.MEGATRON_LM) and not dispatch_batches:
+ if isinstance(new_dataset, IterableDataset):
+ if getattr(dataloader.dataset, "generator", None) is not None:
+ synchronized_generator = dataloader.dataset.generator
+ new_dataset = IterableDatasetShard(
+ new_dataset,
+ batch_size=dataloader.batch_size,
+ drop_last=dataloader.drop_last,
+ num_processes=num_processes,
+ process_index=process_index,
+ split_batches=split_batches,
+ )
+ else:
+ if not use_seedable_sampler and hasattr(sampler, "generator"):
+ if sampler.generator is None:
+ sampler.generator = torch.Generator()
+ synchronized_generator = sampler.generator
+ batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler
+ new_batch_sampler = BatchSamplerShard(
+ batch_sampler,
+ num_processes=num_processes,
+ process_index=process_index,
+ split_batches=split_batches,
+ even_batches=even_batches,
+ )
+
+ # We ignore all of those since they are all dealt with by our new_batch_sampler
+ ignore_kwargs = [
+ "batch_size",
+ "shuffle",
+ "sampler",
+ "batch_sampler",
+ "drop_last",
+ ]
+
+ if rng_types is not None and synchronized_generator is None and "generator" in rng_types:
+ rng_types.remove("generator")
+
+ kwargs = {
+ k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])
+ for k in _PYTORCH_DATALOADER_KWARGS
+ if k not in ignore_kwargs
+ }
+
+ # Need to provide batch_size as batch_sampler is None for Iterable dataset
+ if new_batch_sampler is None:
+ kwargs["drop_last"] = dataloader.drop_last
+ kwargs["batch_size"] = (
+ dataloader.batch_size // num_processes if split_batches and not dispatch_batches else dataloader.batch_size
+ )
+ if dispatch_batches:
+ kwargs.pop("generator")
+ dataloader = DataLoaderDispatcher(
+ new_dataset,
+ split_batches=split_batches,
+ batch_sampler=new_batch_sampler,
+ _drop_last=dataloader.drop_last,
+ _non_blocking=non_blocking,
+ slice_fn=slice_fn_for_dispatch,
+ use_stateful_dataloader=use_stateful_dataloader,
+ **kwargs,
+ )
+ elif sampler_is_batch_sampler:
+ dataloader = DataLoaderShard(
+ new_dataset,
+ device=device if put_on_device and state.distributed_type != DistributedType.XLA else None,
+ sampler=new_batch_sampler,
+ batch_size=dataloader.batch_size,
+ rng_types=rng_types,
+ _drop_last=dataloader.drop_last,
+ _non_blocking=non_blocking,
+ synchronized_generator=synchronized_generator,
+ use_stateful_dataloader=use_stateful_dataloader,
+ **kwargs,
+ )
+ else:
+ dataloader = DataLoaderShard(
+ new_dataset,
+ device=device if put_on_device and state.distributed_type != DistributedType.XLA else None,
+ batch_sampler=new_batch_sampler,
+ rng_types=rng_types,
+ synchronized_generator=synchronized_generator,
+ _drop_last=dataloader.drop_last,
+ _non_blocking=non_blocking,
+ use_stateful_dataloader=use_stateful_dataloader,
+ **kwargs,
+ )
+
+ if isinstance(sampler, SeedableRandomSampler) and use_seedable_sampler:
+ dataloader.set_sampler(sampler)
+ if state.distributed_type == DistributedType.XLA:
+ return MpDeviceLoaderWrapper(dataloader, device)
+ return dataloader
+
+
+class SkipBatchSampler(BatchSampler):
+ """
+ A `torch.utils.data.BatchSampler` that skips the first `n` batches of another `torch.utils.data.BatchSampler`.
+ Should not be used if the original dataloader is a `StatefulDataLoader`.
+ """
+
+ def __init__(self, batch_sampler, skip_batches=0):
+ self.batch_sampler = batch_sampler
+ self.skip_batches = skip_batches
+
+ def __iter__(self):
+ for index, samples in enumerate(self.batch_sampler):
+ if index >= self.skip_batches:
+ yield samples
+
+ @property
+ def total_length(self):
+ return len(self.batch_sampler)
+
+ def __len__(self):
+ return len(self.batch_sampler) - self.skip_batches
+
+
+class SkipDataLoader(DataLoaderAdapter, DataLoaderStateMixin):
+ """
+ Subclass of a PyTorch `DataLoader` that will skip the first batches. Generally it's preferable to use
+ `skip_first_batches`/`torchdata.StatefulDataLoader` instead of this class.
+
+ Args:
+ dataset (`torch.utils.data.dataset.Dataset`):
+ The dataset to use to build this dataloader.
+ skip_batches (`int`, *optional*, defaults to 0):
+ The number of batches to skip at the beginning.
+ kwargs:
+ All other keyword arguments to pass to the regular `DataLoader` initialization.
+ """
+
+ def __init__(self, dataset, skip_batches=0, use_stateful_dataloader=False, **kwargs):
+ super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs)
+ self.skip_batches = skip_batches
+ self.gradient_state = GradientState()
+
+ def __iter__(self):
+ self.begin()
+ for index, batch in enumerate(self.base_dataloader.__iter__()):
+ if index >= self.skip_batches:
+ self._update_state_dict()
+ yield batch
+ self.end()
+
+ def __len__(self):
+ return len(self.base_dataloader) - self.skip_batches
+
+ def __reduce__(self):
+ """
+ Define the `__reduce__` method to ensure a `SkipDataLoader` can be pickled and unpickled. This needs to be
+ explicitly defined since default pickling behavior is broken by `DataLoaderAdapter` messing with its
+ `__class__` member.
+ """
+ args = super().__reduce__()
+ return (SkipDataLoader, *args[1:])
+
+
+def skip_first_batches(dataloader, num_batches=0):
+ """
+ Creates a `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`. Should not be used if
+ the original dataloader is a `StatefulDataLoader`.
+ """
+ state = PartialState()
+ if state.distributed_type == DistributedType.XLA:
+ device = dataloader.device
+ dataloader = dataloader.dataloader
+
+ dataset = dataloader.dataset
+ sampler_is_batch_sampler = False
+ if isinstance(dataset, IterableDataset):
+ new_batch_sampler = None
+ else:
+ sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)
+ batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler
+ new_batch_sampler = SkipBatchSampler(batch_sampler, skip_batches=num_batches)
+
+ # We ignore all of those since they are all dealt with by our new_batch_sampler
+ ignore_kwargs = [
+ "batch_size",
+ "shuffle",
+ "sampler",
+ "batch_sampler",
+ "drop_last",
+ ]
+
+ kwargs = {
+ k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])
+ for k in _PYTORCH_DATALOADER_KWARGS
+ if k not in ignore_kwargs
+ }
+
+ # Need to provide batch_size as batch_sampler is None for Iterable dataset
+ if new_batch_sampler is None:
+ kwargs["drop_last"] = dataloader.drop_last
+ kwargs["batch_size"] = dataloader.batch_size
+
+ if isinstance(dataloader, DataLoaderDispatcher):
+ if new_batch_sampler is None:
+ # Need to manually skip batches in the dataloader
+ kwargs["skip_batches"] = num_batches
+ dataloader = DataLoaderDispatcher(
+ dataset,
+ split_batches=dataloader.split_batches,
+ batch_sampler=new_batch_sampler,
+ _drop_last=dataloader._drop_last,
+ **kwargs,
+ )
+ elif isinstance(dataloader, DataLoaderShard):
+ if new_batch_sampler is None:
+ # Need to manually skip batches in the dataloader
+ kwargs["skip_batches"] = num_batches
+ elif sampler_is_batch_sampler:
+ kwargs["sampler"] = new_batch_sampler
+ kwargs["batch_size"] = dataloader.batch_size
+ else:
+ kwargs["batch_sampler"] = new_batch_sampler
+ dataloader = DataLoaderShard(
+ dataset,
+ device=dataloader.device,
+ rng_types=dataloader.rng_types,
+ synchronized_generator=dataloader.synchronized_generator,
+ **kwargs,
+ )
+ else:
+ if new_batch_sampler is None:
+ # Need to manually skip batches in the dataloader
+ dataloader = SkipDataLoader(dataset, skip_batches=num_batches, **kwargs)
+ else:
+ dataloader = DataLoader(dataset, batch_sampler=new_batch_sampler, **kwargs)
+
+ if state.distributed_type == DistributedType.XLA:
+ dataloader = MpDeviceLoaderWrapper(dataloader, device)
+
+ return dataloader
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/hooks.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..14d57e336612c7827d76c093c877501085222401
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/hooks.py
@@ -0,0 +1,720 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import functools
+from typing import Dict, List, Mapping, Optional, Union
+
+import torch
+import torch.nn as nn
+
+from .state import PartialState
+from .utils import (
+ PrefixedDataset,
+ find_device,
+ named_module_tensors,
+ send_to_device,
+ set_module_tensor_to_device,
+)
+from .utils.memory import clear_device_cache
+from .utils.modeling import get_non_persistent_buffers
+from .utils.other import recursive_getattr
+
+
+_accelerate_added_attributes = ["to", "cuda", "npu", "xpu", "mlu", "musa"]
+
+
+class ModelHook:
+ """
+ A hook that contains callbacks to be executed just before and after the forward method of a model. The difference
+ with PyTorch existing hooks is that they get passed along the kwargs.
+
+ Class attribute:
+ - **no_grad** (`bool`, *optional*, defaults to `False`) -- Whether or not to execute the actual forward pass under
+ the `torch.no_grad()` context manager.
+ """
+
+ no_grad = False
+
+ def init_hook(self, module):
+ """
+ To be executed when the hook is attached to the module.
+
+ Args:
+ module (`torch.nn.Module`): The module attached to this hook.
+ """
+ return module
+
+ def pre_forward(self, module, *args, **kwargs):
+ """
+ To be executed just before the forward method of the model.
+
+ Args:
+ module (`torch.nn.Module`): The module whose forward pass will be executed just after this event.
+ args (`Tuple[Any]`): The positional arguments passed to the module.
+ kwargs (`Dict[Str, Any]`): The keyword arguments passed to the module.
+
+ Returns:
+ `Tuple[Tuple[Any], Dict[Str, Any]]`: A tuple with the treated `args` and `kwargs`.
+ """
+ return args, kwargs
+
+ def post_forward(self, module, output):
+ """
+ To be executed just after the forward method of the model.
+
+ Args:
+ module (`torch.nn.Module`): The module whose forward pass been executed just before this event.
+ output (`Any`): The output of the module.
+
+ Returns:
+ `Any`: The processed `output`.
+ """
+ return output
+
+ def detach_hook(self, module):
+ """
+ To be executed when the hook is detached from a module.
+
+ Args:
+ module (`torch.nn.Module`): The module detached from this hook.
+ """
+ return module
+
+
+class SequentialHook(ModelHook):
+ """
+ A hook that can contain several hooks and iterates through them at each event.
+ """
+
+ def __init__(self, *hooks):
+ self.hooks = hooks
+
+ def init_hook(self, module):
+ for hook in self.hooks:
+ module = hook.init_hook(module)
+ return module
+
+ def pre_forward(self, module, *args, **kwargs):
+ for hook in self.hooks:
+ args, kwargs = hook.pre_forward(module, *args, **kwargs)
+ return args, kwargs
+
+ def post_forward(self, module, output):
+ for hook in self.hooks:
+ output = hook.post_forward(module, output)
+ return output
+
+ def detach_hook(self, module):
+ for hook in self.hooks:
+ module = hook.detach_hook(module)
+ return module
+
+
+def add_hook_to_module(module: nn.Module, hook: ModelHook, append: bool = False):
+ """
+ Adds a hook to a given module. This will rewrite the `forward` method of the module to include the hook, to remove
+ this behavior and restore the original `forward` method, use `remove_hook_from_module`.
+
+
+
+ If the module already contains a hook, this will replace it with the new hook passed by default. To chain two hooks
+ together, pass `append=True`, so it chains the current and new hook into an instance of the `SequentialHook` class.
+
+
+
+ Args:
+ module (`torch.nn.Module`):
+ The module to attach a hook to.
+ hook (`ModelHook`):
+ The hook to attach.
+ append (`bool`, *optional*, defaults to `False`):
+ Whether the hook should be chained with an existing one (if module already contains a hook) or not.
+
+ Returns:
+ `torch.nn.Module`: The same module, with the hook attached (the module is modified in place, so the result can
+ be discarded).
+ """
+
+ if append and (getattr(module, "_hf_hook", None) is not None):
+ old_hook = module._hf_hook
+ remove_hook_from_module(module)
+ hook = SequentialHook(old_hook, hook)
+
+ if hasattr(module, "_hf_hook") and hasattr(module, "_old_forward"):
+ # If we already put some hook on this module, we replace it with the new one.
+ old_forward = module._old_forward
+ else:
+ old_forward = module.forward
+ module._old_forward = old_forward
+
+ module = hook.init_hook(module)
+ module._hf_hook = hook
+
+ def new_forward(module, *args, **kwargs):
+ args, kwargs = module._hf_hook.pre_forward(module, *args, **kwargs)
+ if module._hf_hook.no_grad:
+ with torch.no_grad():
+ output = module._old_forward(*args, **kwargs)
+ else:
+ output = module._old_forward(*args, **kwargs)
+ return module._hf_hook.post_forward(module, output)
+
+ # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail.
+ # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409
+ if "GraphModuleImpl" in str(type(module)):
+ module.__class__.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward)
+ else:
+ module.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward)
+
+ return module
+
+
+def remove_hook_from_module(module: nn.Module, recurse=False):
+ """
+ Removes any hook attached to a module via `add_hook_to_module`.
+
+ Args:
+ module (`torch.nn.Module`): The module to attach a hook to.
+ recurse (`bool`, **optional**): Whether to remove the hooks recursively
+
+ Returns:
+ `torch.nn.Module`: The same module, with the hook detached (the module is modified in place, so the result can
+ be discarded).
+ """
+
+ if hasattr(module, "_hf_hook"):
+ module._hf_hook.detach_hook(module)
+ delattr(module, "_hf_hook")
+
+ if hasattr(module, "_old_forward"):
+ # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail.
+ # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409
+ if "GraphModuleImpl" in str(type(module)):
+ module.__class__.forward = module._old_forward
+ else:
+ module.forward = module._old_forward
+ delattr(module, "_old_forward")
+
+ # Remove accelerate added warning hooks from dispatch_model
+ for attr in _accelerate_added_attributes:
+ module.__dict__.pop(attr, None)
+
+ if recurse:
+ for child in module.children():
+ remove_hook_from_module(child, recurse)
+
+ return module
+
+
+class AlignDevicesHook(ModelHook):
+ """
+ A generic `ModelHook` that ensures inputs and model weights are on the same device for the forward pass of the
+ associated module, potentially offloading the weights after the forward pass.
+
+ Args:
+ execution_device (`torch.device`, *optional*):
+ The device on which inputs and model weights should be placed before the forward pass.
+ offload (`bool`, *optional*, defaults to `False`):
+ Whether or not the weights should be offloaded after the forward pass.
+ io_same_device (`bool`, *optional*, defaults to `False`):
+ Whether or not the output should be placed on the same device as the input was.
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
+ offload_buffers (`bool`, *optional*, defaults to `False`):
+ Whether or not to include the associated module's buffers when offloading.
+ place_submodules (`bool`, *optional*, defaults to `False`):
+ Whether to place the submodules on `execution_device` during the `init_hook` event.
+ """
+
+ def __init__(
+ self,
+ execution_device: Optional[Union[int, str, torch.device]] = None,
+ offload: bool = False,
+ io_same_device: bool = False,
+ weights_map: Optional[Mapping] = None,
+ offload_buffers: bool = False,
+ place_submodules: bool = False,
+ skip_keys: Optional[Union[str, List[str]]] = None,
+ tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None,
+ ):
+ self.execution_device = execution_device
+ self.offload = offload
+ self.io_same_device = io_same_device
+ self.weights_map = weights_map
+ self.offload_buffers = offload_buffers
+ self.place_submodules = place_submodules
+ self.skip_keys = skip_keys
+
+ # Will contain the input device when `io_same_device=True`.
+ self.input_device = None
+ self.param_original_devices = {}
+ self.buffer_original_devices = {}
+ self.tied_params_names = set()
+
+ # The hook pre_forward/post_forward need to have knowledge of this dictionary, as with offloading we want to avoid duplicating memory
+ # for tied weights already loaded on the target execution device.
+ self.tied_params_map = tied_params_map
+
+ def __repr__(self):
+ return (
+ f"AlignDevicesHook(execution_device={self.execution_device}, offload={self.offload}, "
+ f"io_same_device={self.io_same_device}, offload_buffers={self.offload_buffers}, "
+ f"place_submodules={self.place_submodules}, skip_keys={repr(self.skip_keys)})"
+ )
+
+ def init_hook(self, module):
+ # In case the AlignDevicesHook is on meta device, ignore tied weights as data_ptr() is then always zero.
+ if self.execution_device == "meta" or self.execution_device == torch.device("meta"):
+ self.tied_params_map = None
+
+ if not self.offload and self.execution_device is not None:
+ for name, _ in named_module_tensors(module, recurse=self.place_submodules):
+ set_module_tensor_to_device(module, name, self.execution_device, tied_params_map=self.tied_params_map)
+ elif self.offload:
+ self.original_devices = {
+ name: param.device for name, param in named_module_tensors(module, recurse=self.place_submodules)
+ }
+ if self.weights_map is None:
+ self.weights_map = {
+ name: param.to("cpu")
+ for name, param in named_module_tensors(
+ module, include_buffers=self.offload_buffers, recurse=self.place_submodules
+ )
+ }
+ for name, _ in named_module_tensors(
+ module, include_buffers=self.offload_buffers, recurse=self.place_submodules, remove_non_persistent=True
+ ):
+ # When using disk offloading, we can not rely on `weights_map[name].data_ptr()` as the reference pointer,
+ # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer.
+ # 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]
+ # to add on the fly pointers to `tied_params_map` in the pre_forward call.
+ if (
+ self.tied_params_map is not None
+ and recursive_getattr(module, name).data_ptr() in self.tied_params_map
+ ):
+ self.tied_params_names.add(name)
+
+ set_module_tensor_to_device(module, name, "meta")
+
+ if not self.offload_buffers and self.execution_device is not None:
+ for name, _ in module.named_buffers(recurse=self.place_submodules):
+ set_module_tensor_to_device(
+ module, name, self.execution_device, tied_params_map=self.tied_params_map
+ )
+ elif self.offload_buffers and self.execution_device is not None:
+ for name in get_non_persistent_buffers(module, recurse=self.place_submodules):
+ set_module_tensor_to_device(
+ module, name, self.execution_device, tied_params_map=self.tied_params_map
+ )
+
+ return module
+
+ def pre_forward(self, module, *args, **kwargs):
+ if self.io_same_device:
+ self.input_device = find_device([args, kwargs])
+ if self.offload:
+ self.tied_pointers_to_remove = set()
+
+ for name, _ in named_module_tensors(
+ module,
+ include_buffers=self.offload_buffers,
+ recurse=self.place_submodules,
+ remove_non_persistent=True,
+ ):
+ fp16_statistics = None
+ value = self.weights_map[name]
+ if "weight" in name and name.replace("weight", "SCB") in self.weights_map.keys():
+ if value.dtype == torch.int8:
+ fp16_statistics = self.weights_map[name.replace("weight", "SCB")]
+
+ # In case we are using offloading with tied weights, we need to keep track of the offloaded weights
+ # that are loaded on device at this point, as we will need to remove them as well from the dictionary
+ # self.tied_params_map in order to allow to free memory.
+ if name in self.tied_params_names and value.data_ptr() not in self.tied_params_map:
+ self.tied_params_map[value.data_ptr()] = {}
+
+ if (
+ value is not None
+ and self.tied_params_map is not None
+ and value.data_ptr() in self.tied_params_map
+ and self.execution_device not in self.tied_params_map[value.data_ptr()]
+ ):
+ self.tied_pointers_to_remove.add((value.data_ptr(), self.execution_device))
+
+ set_module_tensor_to_device(
+ module,
+ name,
+ self.execution_device,
+ value=value,
+ fp16_statistics=fp16_statistics,
+ tied_params_map=self.tied_params_map,
+ )
+
+ return send_to_device(args, self.execution_device), send_to_device(
+ kwargs, self.execution_device, skip_keys=self.skip_keys
+ )
+
+ def post_forward(self, module, output):
+ if self.offload:
+ for name, _ in named_module_tensors(
+ module,
+ include_buffers=self.offload_buffers,
+ recurse=self.place_submodules,
+ remove_non_persistent=True,
+ ):
+ set_module_tensor_to_device(module, name, "meta")
+ if type(module).__name__ == "Linear8bitLt":
+ module.state.SCB = None
+ module.state.CxB = None
+
+ # We may have loaded tied weights into self.tied_params_map (avoiding to load them several times in e.g. submodules): remove them from
+ # this dictionary to allow the garbage collector to do its job.
+ for value_pointer, device in self.tied_pointers_to_remove:
+ del self.tied_params_map[value_pointer][device]
+ self.tied_pointers_to_remove = set()
+
+ if self.io_same_device and self.input_device is not None:
+ output = send_to_device(output, self.input_device, skip_keys=self.skip_keys)
+
+ return output
+
+ def detach_hook(self, module):
+ if self.offload:
+ for name, device in self.original_devices.items():
+ if device != torch.device("meta"):
+ set_module_tensor_to_device(module, name, device, value=self.weights_map.get(name, None))
+ return module
+
+
+def attach_execution_device_hook(
+ module: torch.nn.Module,
+ execution_device: Union[int, str, torch.device],
+ skip_keys: Optional[Union[str, List[str]]] = None,
+ preload_module_classes: Optional[List[str]] = None,
+ tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None,
+):
+ """
+ Recursively attaches `AlignDevicesHook` to all submodules of a given model to make sure they have the right
+ execution device
+
+ Args:
+ module (`torch.nn.Module`):
+ The module where we want to attach the hooks.
+ execution_device (`int`, `str` or `torch.device`):
+ The device on which inputs and model weights should be placed before the forward pass.
+ skip_keys (`str` or `List[str]`, *optional*):
+ A list of keys to ignore when moving inputs or outputs between devices.
+ preload_module_classes (`List[str]`, *optional*):
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
+ of the forward. This should only be used for classes that have submodules which are registered but not
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
+ instead of duplicating memory.
+ """
+ if not hasattr(module, "_hf_hook") and len(module.state_dict()) > 0:
+ add_hook_to_module(
+ module,
+ AlignDevicesHook(execution_device, skip_keys=skip_keys, tied_params_map=tied_params_map),
+ )
+
+ # Break the recursion if we get to a preload module.
+ if preload_module_classes is not None and module.__class__.__name__ in preload_module_classes:
+ return
+
+ for child in module.children():
+ attach_execution_device_hook(child, execution_device, skip_keys=skip_keys, tied_params_map=tied_params_map)
+
+
+def attach_align_device_hook(
+ module: torch.nn.Module,
+ execution_device: Optional[torch.device] = None,
+ offload: bool = False,
+ weights_map: Optional[Mapping] = None,
+ offload_buffers: bool = False,
+ module_name: str = "",
+ skip_keys: Optional[Union[str, List[str]]] = None,
+ preload_module_classes: Optional[List[str]] = None,
+ tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None,
+):
+ """
+ Recursively attaches `AlignDevicesHook` to all submodules of a given model that have direct parameters and/or
+ buffers.
+
+ Args:
+ module (`torch.nn.Module`):
+ The module where we want to attach the hooks.
+ execution_device (`torch.device`, *optional*):
+ The device on which inputs and model weights should be placed before the forward pass.
+ offload (`bool`, *optional*, defaults to `False`):
+ Whether or not the weights should be offloaded after the forward pass.
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
+ offload_buffers (`bool`, *optional*, defaults to `False`):
+ Whether or not to include the associated module's buffers when offloading.
+ module_name (`str`, *optional*, defaults to `""`):
+ The name of the module.
+ skip_keys (`str` or `List[str]`, *optional*):
+ A list of keys to ignore when moving inputs or outputs between devices.
+ preload_module_classes (`List[str]`, *optional*):
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
+ of the forward. This should only be used for classes that have submodules which are registered but not
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
+ instead of duplicating memory.
+ """
+ # Attach the hook on this module if it has any direct tensor.
+ directs = named_module_tensors(module)
+ full_offload = (
+ offload and preload_module_classes is not None and module.__class__.__name__ in preload_module_classes
+ )
+
+ if len(list(directs)) > 0 or full_offload:
+ if weights_map is not None:
+ prefix = f"{module_name}." if len(module_name) > 0 else ""
+ prefixed_weights_map = PrefixedDataset(weights_map, prefix)
+ else:
+ prefixed_weights_map = None
+ hook = AlignDevicesHook(
+ execution_device=execution_device,
+ offload=offload,
+ weights_map=prefixed_weights_map,
+ offload_buffers=offload_buffers,
+ place_submodules=full_offload,
+ skip_keys=skip_keys,
+ tied_params_map=tied_params_map,
+ )
+ add_hook_to_module(module, hook, append=True)
+
+ # We stop the recursion in case we hit the full offload.
+ if full_offload:
+ return
+
+ # Recurse on all children of the module.
+ for child_name, child in module.named_children():
+ child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name
+ attach_align_device_hook(
+ child,
+ execution_device=execution_device,
+ offload=offload,
+ weights_map=weights_map,
+ offload_buffers=offload_buffers,
+ module_name=child_name,
+ preload_module_classes=preload_module_classes,
+ skip_keys=skip_keys,
+ tied_params_map=tied_params_map,
+ )
+
+
+def remove_hook_from_submodules(module: nn.Module):
+ """
+ Recursively removes all hooks attached on the submodules of a given model.
+
+ Args:
+ module (`torch.nn.Module`): The module on which to remove all hooks.
+ """
+ remove_hook_from_module(module)
+ for child in module.children():
+ remove_hook_from_submodules(child)
+
+
+def attach_align_device_hook_on_blocks(
+ module: nn.Module,
+ execution_device: Optional[Union[torch.device, Dict[str, torch.device]]] = None,
+ offload: Union[bool, Dict[str, bool]] = False,
+ weights_map: Mapping = None,
+ offload_buffers: bool = False,
+ module_name: str = "",
+ skip_keys: Optional[Union[str, List[str]]] = None,
+ preload_module_classes: Optional[List[str]] = None,
+ tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None,
+):
+ """
+ Attaches `AlignDevicesHook` to all blocks of a given model as needed.
+
+ Args:
+ module (`torch.nn.Module`):
+ The module where we want to attach the hooks.
+ execution_device (`torch.device` or `Dict[str, torch.device]`, *optional*):
+ The device on which inputs and model weights should be placed before the forward pass. It can be one device
+ for the whole module, or a dictionary mapping module name to device.
+ offload (`bool`, *optional*, defaults to `False`):
+ Whether or not the weights should be offloaded after the forward pass. It can be one boolean for the whole
+ module, or a dictionary mapping module name to boolean.
+ weights_map (`Mapping[str, torch.Tensor]`, *optional*):
+ When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values.
+ offload_buffers (`bool`, *optional*, defaults to `False`):
+ Whether or not to include the associated module's buffers when offloading.
+ module_name (`str`, *optional*, defaults to `""`):
+ The name of the module.
+ skip_keys (`str` or `List[str]`, *optional*):
+ A list of keys to ignore when moving inputs or outputs between devices.
+ preload_module_classes (`List[str]`, *optional*):
+ A list of classes whose instances should load all their weights (even in the submodules) at the beginning
+ of the forward. This should only be used for classes that have submodules which are registered but not
+ called directly during the forward, for instance if a `dense` linear layer is registered, but at forward,
+ `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly.
+ tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`):
+ A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution
+ device, this parameter is useful to reuse the first available pointer of a shared weight for all others,
+ instead of duplicating memory.
+ """
+ # If one device and one offload, we've got one hook.
+ if not isinstance(execution_device, Mapping) and not isinstance(offload, dict):
+ if not offload:
+ hook = AlignDevicesHook(
+ execution_device=execution_device,
+ io_same_device=True,
+ skip_keys=skip_keys,
+ place_submodules=True,
+ tied_params_map=tied_params_map,
+ )
+ add_hook_to_module(module, hook)
+ else:
+ attach_align_device_hook(
+ module,
+ execution_device=execution_device,
+ offload=True,
+ weights_map=weights_map,
+ offload_buffers=offload_buffers,
+ module_name=module_name,
+ skip_keys=skip_keys,
+ tied_params_map=tied_params_map,
+ )
+ return
+
+ if not isinstance(execution_device, Mapping):
+ execution_device = {key: execution_device for key in offload.keys()}
+ if not isinstance(offload, Mapping):
+ offload = {key: offload for key in execution_device.keys()}
+
+ if module_name in execution_device and module_name in offload and not offload[module_name]:
+ hook = AlignDevicesHook(
+ execution_device=execution_device[module_name],
+ offload_buffers=offload_buffers,
+ io_same_device=(module_name == ""),
+ place_submodules=True,
+ skip_keys=skip_keys,
+ tied_params_map=tied_params_map,
+ )
+ add_hook_to_module(module, hook)
+ attach_execution_device_hook(
+ module, execution_device[module_name], skip_keys=skip_keys, tied_params_map=tied_params_map
+ )
+ elif module_name in execution_device and module_name in offload:
+ attach_align_device_hook(
+ module,
+ execution_device=execution_device[module_name],
+ offload=True,
+ weights_map=weights_map,
+ offload_buffers=offload_buffers,
+ module_name=module_name,
+ skip_keys=skip_keys,
+ preload_module_classes=preload_module_classes,
+ tied_params_map=tied_params_map,
+ )
+ if not hasattr(module, "_hf_hook"):
+ hook = AlignDevicesHook(
+ execution_device=execution_device[module_name],
+ io_same_device=(module_name == ""),
+ skip_keys=skip_keys,
+ tied_params_map=tied_params_map,
+ )
+ add_hook_to_module(module, hook)
+ attach_execution_device_hook(
+ module,
+ execution_device[module_name],
+ preload_module_classes=preload_module_classes,
+ skip_keys=skip_keys,
+ tied_params_map=tied_params_map,
+ )
+ elif module_name == "":
+ hook = AlignDevicesHook(
+ execution_device=execution_device.get(""),
+ io_same_device=True,
+ skip_keys=skip_keys,
+ tied_params_map=tied_params_map,
+ )
+ add_hook_to_module(module, hook)
+
+ for child_name, child in module.named_children():
+ child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name
+ attach_align_device_hook_on_blocks(
+ child,
+ execution_device=execution_device,
+ offload=offload,
+ weights_map=weights_map,
+ offload_buffers=offload_buffers,
+ module_name=child_name,
+ preload_module_classes=preload_module_classes,
+ skip_keys=skip_keys,
+ tied_params_map=tied_params_map,
+ )
+
+
+class CpuOffload(ModelHook):
+ """
+ Offloads a model on the CPU until its forward pass is called. The model will not be offloaded back to the CPU after
+ the forward, the user needs to call the `init_hook` method again for this.
+
+ Args:
+ execution_device(`str`, `int` or `torch.device`, *optional*):
+ The device on which the model should be executed. Will default to the MPS device if it's available, then
+ GPU 0 if there is a GPU, and finally to the CPU.
+ prev_module_hook (`UserCpuOffloadHook`, *optional*):
+ The hook sent back by [`cpu_offload_with_hook`] for a previous model in the pipeline you are running. If
+ passed, its offload method will be called just before the forward of the model to which this hook is
+ attached.
+ """
+
+ def __init__(
+ self,
+ execution_device: Optional[Union[str, int, torch.device]] = None,
+ prev_module_hook: Optional["UserCpuOffloadHook"] = None,
+ ):
+ self.prev_module_hook = prev_module_hook
+
+ self.execution_device = execution_device if execution_device is not None else PartialState().default_device
+
+ def init_hook(self, module):
+ return module.to("cpu")
+
+ def pre_forward(self, module, *args, **kwargs):
+ if self.prev_module_hook is not None:
+ self.prev_module_hook.offload()
+ clear_device_cache()
+ module.to(self.execution_device)
+ return send_to_device(args, self.execution_device), send_to_device(kwargs, self.execution_device)
+
+
+class UserCpuOffloadHook:
+ """
+ A simple hook grouping a model and a `ModelHook`, which provides easy APIs for to call the init method of the hook
+ or remove it entirely.
+ """
+
+ def __init__(self, model, hook):
+ self.model = model
+ self.hook = hook
+
+ def offload(self):
+ self.hook.init_hook(self.model)
+
+ def remove(self):
+ remove_hook_from_module(self.model)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/inference.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ee0bdd6f6359011b5a5081e3403ab31c40cafb2
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/inference.py
@@ -0,0 +1,184 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+from types import MethodType
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+from .state import PartialState
+from .utils import (
+ calculate_maximum_sizes,
+ convert_bytes,
+ copy_tensor_to_devices,
+ ignorant_find_batch_size,
+ infer_auto_device_map,
+ is_pippy_available,
+ pad_input_tensors,
+ send_to_device,
+)
+
+
+def generate_device_map(model, num_processes: int = 1, no_split_module_classes=None, max_memory: dict = None):
+ """
+ Calculates the device map for `model` with an offset for PiPPy
+ """
+ if num_processes == 1:
+ return infer_auto_device_map(model, no_split_module_classes=no_split_module_classes, clean_result=False)
+ if max_memory is None:
+ model_size, shared = calculate_maximum_sizes(model)
+
+ # Split into `n` chunks for each GPU
+ memory = (model_size + shared[0]) / num_processes
+ memory = convert_bytes(memory)
+ value, ending = memory.split(" ")
+
+ # Add a chunk to deal with potential extra shared memory instances
+ memory = math.ceil(float(value)) * 1.1
+ memory = f"{memory} {ending}"
+ max_memory = {i: memory for i in range(num_processes)}
+ device_map = infer_auto_device_map(
+ model,
+ max_memory=max_memory,
+ no_split_module_classes=no_split_module_classes,
+ clean_result=False,
+ )
+ return device_map
+
+
+def find_pippy_batch_size(args, kwargs):
+ found_batch_size = None
+ if args is not None:
+ for arg in args:
+ found_batch_size = ignorant_find_batch_size(arg)
+ if found_batch_size is not None:
+ break
+ if kwargs is not None and found_batch_size is None:
+ for kwarg in kwargs.values():
+ found_batch_size = ignorant_find_batch_size(kwarg)
+ if found_batch_size is not None:
+ break
+ return found_batch_size
+
+
+def build_pipeline(model, split_points, args, kwargs, num_chunks):
+ """
+ Attaches the split points to the model based on `self.device_map` and generates a `PipelineStage`. Requires passing
+ in needed `args` and `kwargs` as the model needs on the CPU.
+
+ Users can pass in custom `num_chunks` as an optional hyper-parameter. By default will use
+ `AcceleratorState.num_processes`
+ """
+ # Note: We import here to reduce import time from general modules, and isolate outside dependencies
+ from torch.distributed.pipelining import ScheduleGPipe, SplitPoint, pipeline
+
+ # We need to annotate the split points in the model for PiPPy
+ state = PartialState()
+ split_spec = {split_point: SplitPoint.BEGINNING for split_point in split_points}
+ pipe = pipeline(
+ model,
+ mb_args=args,
+ mb_kwargs=kwargs,
+ split_spec=split_spec,
+ )
+ stage = pipe.build_stage(state.local_process_index, device=state.device)
+ schedule = ScheduleGPipe(stage, num_chunks)
+
+ return schedule
+
+
+def pippy_forward(forward, num_chunks, gather_output, *args, **kwargs):
+ state = PartialState()
+ output = None
+
+ if state.num_processes == 1:
+ output = forward(*args, **kwargs)
+ elif state.is_local_main_process:
+ found_batch_size = find_pippy_batch_size(args, kwargs)
+ if found_batch_size is None:
+ raise ValueError("Could not find batch size from args or kwargs")
+ else:
+ if found_batch_size != num_chunks:
+ args = pad_input_tensors(args, found_batch_size, num_chunks)
+ kwargs = pad_input_tensors(kwargs, found_batch_size, num_chunks)
+ forward(*args, **kwargs)
+ elif state.is_last_process:
+ output = forward()
+ else:
+ forward()
+ if gather_output:
+ # Each node will get a copy of the full output which is only on the last GPU
+ output = copy_tensor_to_devices(output)
+ return output
+
+
+def prepare_pippy(
+ model,
+ split_points: Optional[Union[str, List[str]]] = "auto",
+ no_split_module_classes: Optional[List[str]] = None,
+ example_args: Optional[Tuple[Any]] = (),
+ example_kwargs: Optional[Dict[str, Any]] = None,
+ num_chunks: Optional[int] = None,
+ gather_output: Optional[bool] = False,
+):
+ """
+ Wraps `model` for pipeline parallel inference.
+
+ Args:
+ model (`torch.nn.Module`):
+ A model we want to split for pipeline-parallel inference
+ split_points (`str` or `List[str]`, defaults to 'auto'):
+ How to generate the split points and chunk the model across each GPU. 'auto' will find the best balanced
+ split given any model. Should be a list of layer names in the model to split by otherwise.
+ no_split_module_classes (`List[str]`):
+ A list of class names for layers we don't want to be split.
+ example_args (tuple of model inputs):
+ The expected inputs for the model that uses order-based inputs for a *single process*. Recommended to use
+ this method if possible.
+ example_kwargs (dict of model inputs)
+ The expected inputs for the model that uses dictionary-based inputs for a *single process*. This is a
+ *highly* limiting structure that requires the same keys be present at *all* inference calls. Not
+ recommended unless the prior condition is true for all cases.
+ num_chunks (`int`, defaults to the number of available GPUs):
+ The number of different stages the Pipeline will have. By default it will assign one chunk per GPU, but
+ this can be tuned and played with. In general one should have num_chunks >= num_gpus.
+ gather_output (`bool`, defaults to `False`):
+ If `True`, the output from the last GPU (which holds the true outputs) is sent across to all GPUs.
+ """
+ if not is_pippy_available():
+ raise ImportError("Using `torch.distributed.pipelining` requires PyTorch 2.4.0 or later.")
+ state = PartialState()
+ example_args = send_to_device(example_args, "cpu")
+ example_kwargs = send_to_device(example_kwargs, "cpu")
+ if num_chunks is None:
+ num_chunks = state.num_processes
+ if split_points == "auto":
+ device_map = generate_device_map(model, num_chunks, no_split_module_classes=no_split_module_classes)
+ split_points = []
+ for i in range(1, num_chunks):
+ split_points.append(next(k for k, v in device_map.items() if v == i))
+ model.hf_split_points = split_points
+ stage = build_pipeline(model, split_points, example_args, example_kwargs, num_chunks)
+ model._original_forward = model.forward
+ model._original_call = model.__call__
+ model.pippy_stage = stage
+ model.hf_split_points = split_points
+
+ def forward(*args, **kwargs):
+ return pippy_forward(stage.step, num_chunks, gather_output, *args, **kwargs)
+
+ # To act like a decorator so that it can be popped when doing `extract_model_from_parallel`
+ # Note: creates an infinite recursion loop with `generate`
+ model_forward = MethodType(forward, model)
+ forward.__wrapped__ = model_forward
+ model.forward = forward
+ return model
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/launchers.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/launchers.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b8dc5aef23f4769f261a132728f04efece59056
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/launchers.py
@@ -0,0 +1,302 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import sys
+import tempfile
+
+import torch
+
+from .state import AcceleratorState, PartialState
+from .utils import (
+ PrecisionType,
+ PrepareForLaunch,
+ are_libraries_initialized,
+ check_cuda_p2p_ib_support,
+ get_gpu_info,
+ is_mps_available,
+ is_torch_version,
+ patch_environment,
+)
+from .utils.constants import ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION
+
+
+def test_launch():
+ "Verify a `PartialState` can be initialized."
+ _ = PartialState()
+
+
+def notebook_launcher(
+ function,
+ args=(),
+ num_processes=None,
+ mixed_precision="no",
+ use_port="29500",
+ master_addr="127.0.0.1",
+ node_rank=0,
+ num_nodes=1,
+ rdzv_backend="static",
+ rdzv_endpoint="",
+ rdzv_conf=None,
+ rdzv_id="none",
+ max_restarts=0,
+ monitor_interval=0.1,
+ log_line_prefix_template=None,
+):
+ """
+ Launches a training function, using several processes or multiple nodes if it's possible in the current environment
+ (TPU with multiple cores for instance).
+
+
+
+ To use this function absolutely zero calls to a CUDA device must be made in the notebook session before calling. If
+ any have been made, you will need to restart the notebook and make sure no cells use any CUDA capability.
+
+ Setting `ACCELERATE_DEBUG_MODE="1"` in your environment will run a test before truly launching to ensure that none
+ of those calls have been made.
+
+
+
+ Args:
+ function (`Callable`):
+ The training function to execute. If it accepts arguments, the first argument should be the index of the
+ process run.
+ args (`Tuple`):
+ Tuple of arguments to pass to the function (it will receive `*args`).
+ num_processes (`int`, *optional*):
+ The number of processes to use for training. Will default to 8 in Colab/Kaggle if a TPU is available, to
+ the number of GPUs available otherwise.
+ mixed_precision (`str`, *optional*, defaults to `"no"`):
+ If `fp16` or `bf16`, will use mixed precision training on multi-GPU.
+ use_port (`str`, *optional*, defaults to `"29500"`):
+ The port to use to communicate between processes when launching a multi-GPU training.
+ master_addr (`str`, *optional*, defaults to `"127.0.0.1"`):
+ The address to use for communication between processes.
+ node_rank (`int`, *optional*, defaults to 0):
+ The rank of the current node.
+ num_nodes (`int`, *optional*, defaults to 1):
+ The number of nodes to use for training.
+ rdzv_backend (`str`, *optional*, defaults to `"static"`):
+ The rendezvous method to use, such as 'static' (the default) or 'c10d'
+ rdzv_endpoint (`str`, *optional*, defaults to `""`):
+ The endpoint of the rdzv sync. storage.
+ rdzv_conf (`Dict`, *optional*, defaults to `None`):
+ Additional rendezvous configuration.
+ rdzv_id (`str`, *optional*, defaults to `"none"`):
+ The unique run id of the job.
+ max_restarts (`int`, *optional*, defaults to 0):
+ The maximum amount of restarts that elastic agent will conduct on workers before failure.
+ monitor_interval (`float`, *optional*, defaults to 0.1):
+ The interval in seconds that is used by the elastic_agent as a period of monitoring workers.
+ log_line_prefix_template (`str`, *optional*, defaults to `None`):
+ The prefix template for elastic launch logging. Available from PyTorch 2.2.0.
+
+ Example:
+
+ ```python
+ # Assume this is defined in a Jupyter Notebook on an instance with two GPUs
+ from accelerate import notebook_launcher
+
+
+ def train(*args):
+ # Your training function here
+ ...
+
+
+ notebook_launcher(train, args=(arg1, arg2), num_processes=2, mixed_precision="fp16")
+ ```
+ """
+ # Are we in a google colab or a Kaggle Kernel?
+ in_colab = False
+ in_kaggle = False
+ if any(key.startswith("KAGGLE") for key in os.environ.keys()):
+ in_kaggle = True
+ elif "IPython" in sys.modules:
+ in_colab = "google.colab" in str(sys.modules["IPython"].get_ipython())
+
+ try:
+ mixed_precision = PrecisionType(mixed_precision.lower())
+ except ValueError:
+ raise ValueError(
+ f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}."
+ )
+
+ if (in_colab or in_kaggle) and (os.environ.get("TPU_NAME", None) is not None):
+ # TPU launch
+ import torch_xla.distributed.xla_multiprocessing as xmp
+
+ if len(AcceleratorState._shared_state) > 0:
+ raise ValueError(
+ "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside "
+ "your training function. Restart your notebook and make sure no cells initializes an "
+ "`Accelerator`."
+ )
+ if num_processes is None:
+ num_processes = 8
+
+ launcher = PrepareForLaunch(function, distributed_type="XLA")
+ print(f"Launching a training on {num_processes} TPU cores.")
+ xmp.spawn(launcher, args=args, nprocs=num_processes, start_method="fork")
+ elif in_colab and get_gpu_info()[1] < 2:
+ # No need for a distributed launch otherwise as it's either CPU or one GPU.
+ if torch.cuda.is_available():
+ print("Launching training on one GPU.")
+ else:
+ print("Launching training on one CPU.")
+ function(*args)
+ else:
+ if num_processes is None:
+ raise ValueError(
+ "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call."
+ )
+ if node_rank >= num_nodes:
+ raise ValueError("The node_rank must be less than the number of nodes.")
+ if num_processes > 1:
+ # Multi-GPU launch
+ from torch.distributed.launcher.api import LaunchConfig, elastic_launch
+ from torch.multiprocessing import start_processes
+ from torch.multiprocessing.spawn import ProcessRaisedException
+
+ if len(AcceleratorState._shared_state) > 0:
+ raise ValueError(
+ "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized "
+ "inside your training function. Restart your notebook and make sure no cells initializes an "
+ "`Accelerator`."
+ )
+ # Check for specific libraries known to initialize CUDA that users constantly use
+ problematic_imports = are_libraries_initialized("bitsandbytes")
+ if len(problematic_imports) > 0:
+ err = (
+ "Could not start distributed process. Libraries known to initialize CUDA upon import have been "
+ "imported already. Please keep these imports inside your training function to try and help with this:"
+ )
+ for lib_name in problematic_imports:
+ err += f"\n\t* `{lib_name}`"
+ raise RuntimeError(err)
+
+ patched_env = dict(
+ nproc=num_processes,
+ node_rank=node_rank,
+ world_size=num_nodes * num_processes,
+ master_addr=master_addr,
+ master_port=use_port,
+ mixed_precision=mixed_precision,
+ )
+
+ # Check for CUDA P2P and IB issues
+ if not check_cuda_p2p_ib_support():
+ patched_env["nccl_p2p_disable"] = "1"
+ patched_env["nccl_ib_disable"] = "1"
+
+ # torch.distributed will expect a few environment variable to be here. We set the ones common to each
+ # process here (the other ones will be set be the launcher).
+ with patch_environment(**patched_env):
+ # First dummy launch
+ if os.environ.get("ACCELERATE_DEBUG_MODE", "false").lower() == "true":
+ launcher = PrepareForLaunch(test_launch, distributed_type="MULTI_GPU")
+ try:
+ start_processes(launcher, args=(), nprocs=num_processes, start_method="fork")
+ except ProcessRaisedException as e:
+ err = "An issue was found when verifying a stable environment for the notebook launcher."
+ if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
+ raise RuntimeError(
+ f"{err}"
+ "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
+ "Please review your imports and test them when running the `notebook_launcher()` to identify "
+ "which one is problematic and causing CUDA to be initialized."
+ ) from e
+ else:
+ raise RuntimeError(f"{err} The following error was raised: {e}") from e
+ # Now the actual launch
+ launcher = PrepareForLaunch(function, distributed_type="MULTI_GPU")
+ print(f"Launching training on {num_processes} GPUs.")
+ try:
+ if rdzv_conf is None:
+ rdzv_conf = {}
+ if rdzv_backend == "static":
+ rdzv_conf["rank"] = node_rank
+ if not rdzv_endpoint:
+ rdzv_endpoint = f"{master_addr}:{use_port}"
+ launch_config_kwargs = dict(
+ min_nodes=num_nodes,
+ max_nodes=num_nodes,
+ nproc_per_node=num_processes,
+ run_id=rdzv_id,
+ rdzv_endpoint=rdzv_endpoint,
+ rdzv_backend=rdzv_backend,
+ rdzv_configs=rdzv_conf,
+ max_restarts=max_restarts,
+ monitor_interval=monitor_interval,
+ start_method="fork",
+ )
+ if is_torch_version(">=", ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION):
+ launch_config_kwargs["log_line_prefix_template"] = log_line_prefix_template
+ elastic_launch(config=LaunchConfig(**launch_config_kwargs), entrypoint=function)(*args)
+ except ProcessRaisedException as e:
+ if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
+ raise RuntimeError(
+ "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. "
+ "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
+ "Please review your imports and test them when running the `notebook_launcher()` to identify "
+ "which one is problematic and causing CUDA to be initialized."
+ ) from e
+ else:
+ raise RuntimeError(f"An issue was found when launching the training: {e}") from e
+
+ else:
+ # No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
+ if is_mps_available():
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
+ print("Launching training on MPS.")
+ elif torch.cuda.is_available():
+ print("Launching training on one GPU.")
+ else:
+ print("Launching training on CPU.")
+ function(*args)
+
+
+def debug_launcher(function, args=(), num_processes=2):
+ """
+ Launches a training function using several processes on CPU for debugging purposes.
+
+
+
+ This function is provided for internal testing and debugging, but it's not intended for real trainings. It will
+ only use the CPU.
+
+
+
+ Args:
+ function (`Callable`):
+ The training function to execute.
+ args (`Tuple`):
+ Tuple of arguments to pass to the function (it will receive `*args`).
+ num_processes (`int`, *optional*, defaults to 2):
+ The number of processes to use for training.
+ """
+ from torch.multiprocessing import start_processes
+
+ with tempfile.NamedTemporaryFile() as tmp_file:
+ # torch.distributed will expect a few environment variable to be here. We set the ones common to each
+ # process here (the other ones will be set be the launcher).
+ with patch_environment(
+ world_size=num_processes,
+ master_addr="127.0.0.1",
+ master_port="29500",
+ accelerate_mixed_precision="no",
+ accelerate_debug_rdv_file=tmp_file.name,
+ accelerate_use_cpu="yes",
+ ):
+ launcher = PrepareForLaunch(function, debug=True)
+ start_processes(launcher, args=args, nprocs=num_processes, start_method="fork")
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/local_sgd.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/local_sgd.py
new file mode 100644
index 0000000000000000000000000000000000000000..382c34bc91c42c423db5caf37a6579260e29d090
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/local_sgd.py
@@ -0,0 +1,103 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import torch
+
+from accelerate import Accelerator, DistributedType
+
+
+class LocalSGD:
+ """
+ A helper class to support local SGD on top of Accelerator. It simply runs a given number of updates independently
+ on each device, and averages model weights every K synchronization step.
+
+ It should be used only in the multi-GPU (or multi-CPU) setup without extensions such as DeepSpeed. In particular,
+ this is a simple implementation that cannot support scenarios such as model parallelism.
+
+
+ Although we are not aware of the true origins of this simple approach, the idea of local SGD is quite old and goes
+ back to at least:
+
+ Zhang, J., De Sa, C., Mitliagkas, I., & Ré, C. (2016). [Parallel SGD: When does averaging help?. arXiv preprint
+ arXiv:1606.07365.](https://arxiv.org/abs/1606.07365)
+
+ We credit the term Local SGD to the following paper (but there might be earlier references we are not aware of).
+
+ Stich, Sebastian Urban. ["Local SGD Converges Fast and Communicates Little." ICLR 2019-International Conference on
+ Learning Representations. No. CONF. 2019.](https://arxiv.org/abs/1805.09767)
+
+ """
+
+ def __enter__(self):
+ if self.enabled:
+ self.model_sync_obj = self.model.no_sync()
+ self.model_sync_obj.__enter__()
+
+ return self
+
+ def __exit__(self, type, value, tb):
+ if self.enabled:
+ # Average all models on exit
+ self._sync_and_avg_model_params()
+ self.model_sync_obj.__exit__(type, value, tb)
+
+ def __init__(self, accelerator: Accelerator, model: torch.nn.Module, local_sgd_steps: int, enabled: bool = True):
+ """
+ Constructor.
+
+ Args:
+ model (`torch.nn.Module):
+ The model whose parameters we need to average.
+ accelerator (`Accelerator`):
+ Accelerator object.
+ local_sgd_steps (`int`):
+ A number of local SGD steps (before model parameters are synchronized).
+ enabled (`bool):
+ Local SGD is disabled if this parameter set to `False`.
+ """
+ if accelerator.distributed_type not in [
+ DistributedType.NO,
+ DistributedType.MULTI_CPU,
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_NPU,
+ ]:
+ raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)")
+ self.enabled = enabled and accelerator.distributed_type != DistributedType.NO
+ self.num_steps = 0
+ if self.enabled:
+ self.accelerator = accelerator
+ self.model = model
+ self.local_sgd_steps = local_sgd_steps
+
+ def step(self):
+ """
+ This function makes a "step" and synchronizes model parameters if necessary.
+ """
+ self.num_steps += 1
+ if not self.enabled:
+ return
+
+ if self.num_steps % self.local_sgd_steps == 0:
+ self._sync_and_avg_model_params()
+
+ def _sync_and_avg_model_params(self):
+ """
+ Synchronize + Average model parameters across all GPUs
+ """
+
+ self.accelerator.wait_for_everyone()
+ with self.accelerator.autocast():
+ for param in self.model.parameters():
+ param.data = self.accelerator.reduce(param.data, reduction="mean")
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/logging.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..1615bc313b74d4f01166384435b6c499ff616f49
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/logging.py
@@ -0,0 +1,125 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import functools
+import logging
+import os
+
+from .state import PartialState
+
+
+class MultiProcessAdapter(logging.LoggerAdapter):
+ """
+ An adapter to assist with logging in multiprocess.
+
+ `log` takes in an additional `main_process_only` kwarg, which dictates whether it should be called on all processes
+ or only the main executed one. Default is `main_process_only=True`.
+
+ Does not require an `Accelerator` object to be created first.
+ """
+
+ @staticmethod
+ def _should_log(main_process_only):
+ "Check if log should be performed"
+ state = PartialState()
+ return not main_process_only or (main_process_only and state.is_main_process)
+
+ def log(self, level, msg, *args, **kwargs):
+ """
+ Delegates logger call after checking if we should log.
+
+ Accepts a new kwarg of `main_process_only`, which will dictate whether it will be logged across all processes
+ or only the main executed one. Default is `True` if not passed
+
+ Also accepts "in_order", which if `True` makes the processes log one by one, in order. This is much easier to
+ read, but comes at the cost of sometimes needing to wait for the other processes. Default is `False` to not
+ break with the previous behavior.
+
+ `in_order` is ignored if `main_process_only` is passed.
+ """
+ if PartialState._shared_state == {}:
+ raise RuntimeError(
+ "You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility."
+ )
+ main_process_only = kwargs.pop("main_process_only", True)
+ in_order = kwargs.pop("in_order", False)
+ # set `stacklevel` to exclude ourself in `Logger.findCaller()` while respecting user's choice
+ kwargs.setdefault("stacklevel", 2)
+
+ if self.isEnabledFor(level):
+ if self._should_log(main_process_only):
+ msg, kwargs = self.process(msg, kwargs)
+ self.logger.log(level, msg, *args, **kwargs)
+
+ elif in_order:
+ state = PartialState()
+ for i in range(state.num_processes):
+ if i == state.process_index:
+ msg, kwargs = self.process(msg, kwargs)
+ self.logger.log(level, msg, *args, **kwargs)
+ state.wait_for_everyone()
+
+ @functools.lru_cache(None)
+ def warning_once(self, *args, **kwargs):
+ """
+ This method is identical to `logger.warning()`, but will emit the warning with the same message only once
+
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the
+ cache. The assumption here is that all warning messages are unique across the code. If they aren't then need to
+ switch to another type of cache that includes the caller frame information in the hashing function.
+ """
+ self.warning(*args, **kwargs)
+
+
+def get_logger(name: str, log_level: str = None):
+ """
+ Returns a `logging.Logger` for `name` that can handle multiprocessing.
+
+ If a log should be called on all processes, pass `main_process_only=False` If a log should be called on all
+ processes and in order, also pass `in_order=True`
+
+ Args:
+ name (`str`):
+ The name for the logger, such as `__file__`
+ log_level (`str`, *optional*):
+ The log level to use. If not passed, will default to the `LOG_LEVEL` environment variable, or `INFO` if not
+
+ Example:
+
+ ```python
+ >>> from accelerate.logging import get_logger
+ >>> from accelerate import Accelerator
+
+ >>> logger = get_logger(__name__)
+
+ >>> accelerator = Accelerator()
+ >>> logger.info("My log", main_process_only=False)
+ >>> logger.debug("My log", main_process_only=True)
+
+ >>> logger = get_logger(__name__, log_level="DEBUG")
+ >>> logger.info("My log")
+ >>> logger.debug("My second log")
+
+ >>> array = ["a", "b", "c", "d"]
+ >>> letter_at_rank = array[accelerator.process_index]
+ >>> logger.info(letter_at_rank, in_order=True)
+ ```
+ """
+ if log_level is None:
+ log_level = os.environ.get("ACCELERATE_LOG_LEVEL", None)
+ logger = logging.getLogger(name)
+ if log_level is not None:
+ logger.setLevel(log_level.upper())
+ logger.root.setLevel(log_level.upper())
+ return MultiProcessAdapter(logger, {})
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/memory_utils.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/memory_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa2e2c8b9d7d0064c3e5e282737a7ad6919bde29
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/memory_utils.py
@@ -0,0 +1,22 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import warnings
+
+
+warnings.warn(
+ "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: "
+ "`from accelerate import find_executable_batch_size` to avoid this warning.",
+ FutureWarning,
+)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/optimizer.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..acc238a1a9989153678e092977fd45e973cb8ef1
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/optimizer.py
@@ -0,0 +1,205 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import inspect
+
+import torch
+
+from .state import AcceleratorState, GradientState
+from .utils import DistributedType, honor_type, is_lomo_available, is_torch_xla_available
+
+
+if is_torch_xla_available():
+ import torch_xla.core.xla_model as xm
+
+
+def move_to_device(state, device):
+ if isinstance(state, (list, tuple)):
+ return honor_type(state, (move_to_device(t, device) for t in state))
+ elif isinstance(state, dict):
+ return type(state)({k: move_to_device(v, device) for k, v in state.items()})
+ elif isinstance(state, torch.Tensor):
+ return state.to(device)
+ return state
+
+
+class AcceleratedOptimizer(torch.optim.Optimizer):
+ """
+ Internal wrapper around a torch optimizer.
+
+ Conditionally will perform `step` and `zero_grad` if gradients should be synchronized when performing gradient
+ accumulation.
+
+ Args:
+ optimizer (`torch.optim.optimizer.Optimizer`):
+ The optimizer to wrap.
+ device_placement (`bool`, *optional*, defaults to `True`):
+ Whether or not the optimizer should handle device placement. If so, it will place the state dictionary of
+ `optimizer` on the right device.
+ scaler (`torch.cuda.amp.grad_scaler.GradScaler`, *optional*):
+ The scaler to use in the step function if training with mixed precision.
+ """
+
+ def __init__(self, optimizer, device_placement=True, scaler=None):
+ self.optimizer = optimizer
+ self.scaler = scaler
+ self.accelerator_state = AcceleratorState()
+ self.gradient_state = GradientState()
+ self.device_placement = device_placement
+ self._is_overflow = False
+
+ if self.scaler is not None:
+ self._accelerate_step_called = False
+ self._optimizer_original_step_method = self.optimizer.step
+ self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step)
+
+ # Handle device placement
+ if device_placement:
+ state_dict = self.optimizer.state_dict()
+ if self.accelerator_state.distributed_type == DistributedType.XLA:
+ xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device)
+ else:
+ state_dict = move_to_device(state_dict, self.accelerator_state.device)
+ self.optimizer.load_state_dict(state_dict)
+
+ @property
+ def state(self):
+ return self.optimizer.state
+
+ @state.setter
+ def state(self, state):
+ self.optimizer.state = state
+
+ @property
+ def param_groups(self):
+ return self.optimizer.param_groups
+
+ @param_groups.setter
+ def param_groups(self, param_groups):
+ self.optimizer.param_groups = param_groups
+
+ @property
+ def defaults(self):
+ return self.optimizer.defaults
+
+ @defaults.setter
+ def defaults(self, defaults):
+ self.optimizer.defaults = defaults
+
+ def add_param_group(self, param_group):
+ self.optimizer.add_param_group(param_group)
+
+ def load_state_dict(self, state_dict):
+ if self.accelerator_state.distributed_type == DistributedType.XLA and self.device_placement:
+ xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device)
+ self.optimizer.load_state_dict(state_dict)
+
+ def state_dict(self):
+ return self.optimizer.state_dict()
+
+ def zero_grad(self, set_to_none=None):
+ if self.gradient_state.sync_gradients:
+ accept_arg = "set_to_none" in inspect.signature(self.optimizer.zero_grad).parameters
+ if accept_arg:
+ if set_to_none is None:
+ set_to_none = True
+ self.optimizer.zero_grad(set_to_none=set_to_none)
+ else:
+ if set_to_none is not None:
+ raise ValueError("`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer.")
+ self.optimizer.zero_grad()
+
+ def train(self):
+ """
+ Sets the optimizer to "train" mode. Useful for optimizers like `schedule_free`
+ """
+ if hasattr(self.optimizer, "train") and callable(self.optimizer.train):
+ self.optimizer.train()
+
+ def eval(self):
+ """
+ Sets the optimizer to "eval" mode. Useful for optimizers like `schedule_free`
+ """
+ if hasattr(self.optimizer, "eval") and callable(self.optimizer.eval):
+ self.optimizer.eval()
+
+ def step(self, closure=None):
+ if is_lomo_available():
+ from lomo_optim import AdaLomo, Lomo
+
+ if (
+ not self.gradient_state.is_xla_gradients_synced
+ and self.accelerator_state.distributed_type == DistributedType.XLA
+ ):
+ gradients = xm._fetch_gradients(self.optimizer)
+ xm.all_reduce("sum", gradients, scale=1.0 / xm.xrt_world_size())
+ self.gradient_state.is_xla_gradients_synced = True
+
+ if is_lomo_available():
+ # `step` should be a no-op for LOMO optimizers.
+ if isinstance(self.optimizer, (Lomo, AdaLomo)):
+ return
+
+ if self.gradient_state.sync_gradients:
+ if self.scaler is not None:
+ self.optimizer.step = self._optimizer_patched_step_method
+
+ self.scaler.step(self.optimizer, closure)
+ self.scaler.update()
+
+ if not self._accelerate_step_called:
+ # If the optimizer step was skipped, gradient overflow was detected.
+ self._is_overflow = True
+ else:
+ self._is_overflow = False
+ # Reset the step method to the original one
+ self.optimizer.step = self._optimizer_original_step_method
+ # Reset the indicator
+ self._accelerate_step_called = False
+ else:
+ self.optimizer.step(closure)
+ if self.accelerator_state.distributed_type == DistributedType.XLA:
+ self.gradient_state.is_xla_gradients_synced = False
+
+ def _switch_parameters(self, parameters_map):
+ for param_group in self.optimizer.param_groups:
+ param_group["params"] = [parameters_map.get(p, p) for p in param_group["params"]]
+
+ @property
+ def step_was_skipped(self):
+ """Whether or not the optimizer step was skipped."""
+ return self._is_overflow
+
+ def __getstate__(self):
+ _ignored_keys = [
+ "_accelerate_step_called",
+ "_optimizer_original_step_method",
+ "_optimizer_patched_step_method",
+ ]
+ return {k: v for k, v in self.__dict__.items() if k not in _ignored_keys}
+
+ def __setstate__(self, state):
+ self.__dict__.update(state)
+ if self.scaler is not None:
+ self._accelerate_step_called = False
+ self._optimizer_original_step_method = self.optimizer.step
+ self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step)
+
+
+def patch_optimizer_step(accelerated_optimizer: AcceleratedOptimizer, method):
+ def patched_step(*args, **kwargs):
+ accelerated_optimizer._accelerate_step_called = True
+ return method(*args, **kwargs)
+
+ return patched_step
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/scheduler.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fa8a13f238afd7b908ee8e8cb8e0620f48d4ff8
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/scheduler.py
@@ -0,0 +1,98 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation
+
+import warnings
+
+from .state import AcceleratorState, GradientState
+
+
+warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler")
+
+
+class AcceleratedScheduler:
+ """
+ A wrapper around a learning rate scheduler that will only step when the optimizer(s) have a training step. Useful
+ to avoid making a scheduler step too fast when gradients went overflow and there was no training step (in mixed
+ precision training)
+
+ When performing gradient accumulation scheduler lengths should not be changed accordingly, Accelerate will always
+ step the scheduler to account for it.
+
+ Args:
+ scheduler (`torch.optim.lr_scheduler._LRScheduler`):
+ The scheduler to wrap.
+ optimizers (one or a list of `torch.optim.Optimizer`):
+ The optimizers used.
+ step_with_optimizer (`bool`, *optional*, defaults to `True`):
+ Whether or not the scheduler should be stepped at each optimizer step.
+ split_batches (`bool`, *optional*, defaults to `False`):
+ Whether or not the dataloaders split one batch across the different processes (so batch size is the same
+ regardless of the number of processes) or create batches on each process (so batch size is the original
+ batch size multiplied by the number of processes).
+ """
+
+ def __init__(self, scheduler, optimizers, step_with_optimizer: bool = True, split_batches: bool = False):
+ self.scheduler = scheduler
+ self.optimizers = optimizers if isinstance(optimizers, (list, tuple)) else [optimizers]
+ self.split_batches = split_batches
+ self.step_with_optimizer = step_with_optimizer
+ self.gradient_state = GradientState()
+
+ def step(self, *args, **kwargs):
+ if not self.step_with_optimizer:
+ # No link between scheduler and optimizer -> just step
+ self.scheduler.step(*args, **kwargs)
+ return
+
+ # Otherwise, first make sure the optimizer was stepped.
+ if not self.gradient_state.sync_gradients:
+ if self.gradient_state.adjust_scheduler:
+ self.scheduler._step_count += 1
+ return
+
+ for opt in self.optimizers:
+ if opt.step_was_skipped:
+ return
+ if self.split_batches:
+ # Split batches -> the training dataloader batch size is not changed so one step per training step
+ self.scheduler.step(*args, **kwargs)
+ else:
+ # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do
+ # num_processes steps per training step
+ num_processes = AcceleratorState().num_processes
+ for _ in range(num_processes):
+ # Special case when using OneCycle and `drop_last` was not used
+ if hasattr(self.scheduler, "total_steps"):
+ if self.scheduler._step_count <= self.scheduler.total_steps:
+ self.scheduler.step(*args, **kwargs)
+ else:
+ self.scheduler.step(*args, **kwargs)
+
+ # Passthroughs
+ def get_last_lr(self):
+ return self.scheduler.get_last_lr()
+
+ def state_dict(self):
+ return self.scheduler.state_dict()
+
+ def load_state_dict(self, state_dict):
+ self.scheduler.load_state_dict(state_dict)
+
+ def get_lr(self):
+ return self.scheduler.get_lr()
+
+ def print_lr(self, *args, **kwargs):
+ return self.scheduler.print_lr(*args, **kwargs)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/state.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/state.py
new file mode 100644
index 0000000000000000000000000000000000000000..47d718704a6438c3691b3244c9f959650777e553
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/state.py
@@ -0,0 +1,1257 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import logging
+import os
+import threading
+import warnings
+from contextlib import contextmanager
+from functools import partial
+from typing import Any, Callable, Optional
+
+import torch
+
+from .utils import (
+ DistributedType,
+ DynamoBackend,
+ GradientAccumulationPlugin,
+ check_cuda_p2p_ib_support,
+ check_fp8_capability,
+ deepspeed_required,
+ get_ccl_version,
+ get_cpu_distributed_information,
+ get_int_from_env,
+ is_ccl_available,
+ is_datasets_available,
+ is_deepspeed_available,
+ is_fp8_available,
+ is_ipex_available,
+ is_mlu_available,
+ is_mps_available,
+ is_musa_available,
+ is_npu_available,
+ is_torch_xla_available,
+ is_xpu_available,
+ parse_choice_from_env,
+ parse_flag_from_env,
+ set_numa_affinity,
+)
+from .utils.dataclasses import SageMakerDistributedType
+
+
+if is_torch_xla_available():
+ import torch_xla.core.xla_model as xm
+
+if is_mlu_available(check_device=False):
+ import torch_mlu # noqa: F401
+
+if is_musa_available(check_device=False):
+ import torch_musa # noqa: F401
+
+if is_npu_available(check_device=False):
+ import torch_npu # noqa: F401
+
+logger = logging.getLogger(__name__)
+
+
+def is_initialized() -> bool:
+ """
+ Checks if the `AcceleratorState` has been initialized from `Accelerator`. Same as `AcceleratorState.initialized`,
+ but works as a module method.
+ """
+ return AcceleratorState._shared_state != {}
+
+
+# Lambda function that does nothing
+def do_nothing(*args, **kwargs):
+ return None
+
+
+class ThreadLocalSharedDict(threading.local):
+ """
+ Descriptor that holds a dict shared between instances of a class in the same thread.
+
+ Note: Descriptors have slightly different semantics than just a dict field on its own.
+ `PartialState(...)._shared_state` and `PartialState._shared_state` (instance vs class) give the same value: the
+ underlying _storage dict. Likewise, `PartialState(...)._shared_state = {...}` overrides the _storage dict inside
+ the descriptor as you would expect. However, `PartialState._shared_state = {}` actually replaces the descriptor
+ object with a dict instead Thus, you should modify the _storage dict in-place (e.g. `_shared_state.clear()`).
+
+ See Python documentation for an explanation of descriptors: https://docs.python.org/3/howto/descriptor.html
+
+ This is required for using PyTorch/XLA with PJRT in multithreaded mode (required for TPU v2 and v3).
+
+ See https://github.com/pytorch/xla/blob/r2.0/docs/pjrt.md#multithreading-on-tpu-v2v3
+ """
+
+ def __init__(self, thread_local: bool = False):
+ self._storage = {}
+
+ def __get__(self, obj, objtype=None):
+ return self._storage
+
+ def __set__(self, obj, value):
+ self._storage = value
+
+
+# Prefer global shared dictionary, except when using TPU.
+SharedDict = dict if not is_torch_xla_available() else ThreadLocalSharedDict
+
+
+# Inspired by Alex Martelli's 'Borg'.
+class PartialState:
+ """
+ Singleton class that has information about the current training environment and functions to help with process
+ control. Designed to be used when only process control and device execution states are needed. Does *not* need to
+ be initialized from `Accelerator`.
+
+ Args:
+ cpu (`bool`, *optional*):
+ Whether or not to force the script to execute on CPU. Will ignore any accelerators available if set to
+ `True` and force the execution on the CPU.
+ kwargs (additional keyword arguments, *optional*):
+ Additional keyword arguments to pass to the relevent `init_process_group` function. Valid `kwargs` can be
+ found in [`utils.InitProcessGroupKwargs`]. See the example section for detailed usage.
+
+ **Available attributes:**
+
+ - **device** (`torch.device`) -- The device to use.
+ - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently
+ in use.
+ - **local_process_index** (`int`) -- The index of the current process on the current server.
+ - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type
+ of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8').
+ - **num_processes** (`int`) -- The number of processes currently launched in parallel.
+ - **process_index** (`int`) -- The index of the current process.
+ - **is_last_process** (`bool`) -- Whether or not the current process is the last one.
+ - **is_main_process** (`bool`) -- Whether or not the current process is the main one.
+ - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node.
+ - **debug** (`bool`) -- Whether or not the current script is being run in debug mode.
+
+ Example:
+ ```python
+ from accelerate.utils import InitProcessGroupKwargs
+
+ # To include `InitProcessGroupKwargs`, init then call `.to_kwargs()`
+ kwargs = InitProcessGroupKwargs(...).to_kwargs()
+ state = PartialState(**kwargs)
+ ```
+ """
+
+ _shared_state = SharedDict()
+ _known_attrs = [
+ "_cpu",
+ "_mixed_precision",
+ "_shared_state",
+ "backend",
+ "debug",
+ "device",
+ "distributed_type",
+ "fork_launched",
+ "local_process_index",
+ "num_processes",
+ "process_index",
+ ]
+
+ def __init__(self, cpu: bool = False, **kwargs):
+ self.__dict__ = self._shared_state
+ if not self.initialized:
+ self._cpu = cpu
+ self.backend = None
+ env_device = os.environ.get("ACCELERATE_TORCH_DEVICE", None)
+ self.device = torch.device(env_device) if env_device is not None else None
+ self.debug = parse_flag_from_env("ACCELERATE_DEBUG_MODE")
+ use_sagemaker_dp = kwargs.pop("_use_sagemaker_dp", None)
+ dist_information = None
+ if use_sagemaker_dp is None:
+ use_sagemaker_dp = (
+ os.environ.get("ACCELERATE_USE_SAGEMAKER", "false") == "true"
+ and os.environ.get("ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE") != SageMakerDistributedType.NO
+ )
+
+ # Sets up self.backend + imports
+ original_backend = kwargs.pop("backend", None)
+ backend, distributed_type = self._prepare_backend(cpu, use_sagemaker_dp, original_backend)
+ if original_backend is not None and backend != original_backend:
+ raise ValueError(f"Your assigned backend {original_backend} is not avaliable, please use {backend}")
+ self.backend = backend
+ self.distributed_type = distributed_type
+ use_deepspeed = False
+ if not cpu and self.backend != "xla":
+ if int(os.environ.get("LOCAL_RANK", -1)) != -1:
+ # Deal with spawning deepspeed
+ if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true":
+ if not is_deepspeed_available():
+ raise ImportError(
+ "DeepSpeed is not available => install it using `pip3 install deepspeed` or build it from source"
+ )
+ from deepspeed import comm as dist
+
+ if not dist.is_initialized():
+ dist.init_distributed(dist_backend=self.backend, auto_mpi_discovery=False, **kwargs)
+ # We need to flag to `use_deepspeed` to be True to override `distributed_type` later
+ use_deepspeed = True
+ # Deal with all other backends but XPU and CPU, that gets handled special later
+ elif (
+ self.distributed_type not in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU)
+ and not torch.distributed.is_initialized()
+ ):
+ torch.distributed.init_process_group(backend=self.backend, **kwargs)
+ # XPU and CPU require special env configs to be set
+ if self.distributed_type in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU):
+ dist_information = get_cpu_distributed_information()
+ os.environ["RANK"] = str(dist_information.rank)
+ os.environ["WORLD_SIZE"] = str(dist_information.world_size)
+ os.environ["LOCAL_RANK"] = str(dist_information.local_rank)
+ os.environ["LOCAL_WORLD_SIZE"] = str(dist_information.local_world_size)
+ if not os.environ.get("MASTER_PORT", None):
+ os.environ["MASTER_PORT"] = "29500"
+ if (
+ not os.environ.get("MASTER_ADDR", None)
+ and dist_information.local_world_size != dist_information.world_size
+ and self.backend != "mpi"
+ ):
+ raise ValueError(
+ "Tried to launch on distributed with multinode, but `MASTER_ADDR` env was not set, "
+ "please try exporting rank 0's hostname as `MASTER_ADDR`"
+ )
+ kwargs["rank"] = dist_information.rank
+ kwargs["world_size"] = dist_information.world_size
+
+ if (
+ self.distributed_type == DistributedType.MULTI_CPU
+ and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0
+ ):
+ import psutil
+
+ num_cpu_threads_per_process = int(
+ psutil.cpu_count(logical=False) / dist_information.local_world_size
+ )
+ if num_cpu_threads_per_process == 0:
+ num_cpu_threads_per_process = 1
+ torch.set_num_threads(num_cpu_threads_per_process)
+ warnings.warn(
+ f"OMP_NUM_THREADS/MKL_NUM_THREADS unset, we set it at {num_cpu_threads_per_process} to improve oob"
+ " performance."
+ )
+
+ if not torch.distributed.is_initialized():
+ torch.distributed.init_process_group(backend=self.backend, **kwargs)
+
+ # No backend == no distributed training
+ if self.backend is None:
+ self.distributed_type = DistributedType.NO
+ self.num_processes = 1
+ self.process_index = 0
+ self.local_process_index = 0
+ elif self.backend == "xla":
+ # XLA needs device setting first for `set_replication`
+ self.set_device()
+ xm.set_replication(self.device, xm.get_xla_supported_devices())
+ self.num_processes = xm.xrt_world_size()
+ self.process_index = xm.get_ordinal()
+ if is_torch_xla_available(check_is_tpu=True):
+ self.local_process_index = xm.get_local_ordinal()
+ else:
+ self.local_process_index = int(os.environ.get("LOCAL_RANK", -1))
+ else:
+ self.num_processes = torch.distributed.get_world_size()
+ self.process_index = torch.distributed.get_rank()
+ self.local_process_index = (
+ int(os.environ.get("LOCAL_RANK", -1)) if dist_information is None else dist_information.local_rank
+ )
+ self.set_device()
+ # Now we can change to deepseed
+ if use_deepspeed:
+ self.distributed_type = DistributedType.DEEPSPEED
+
+ # Set CPU affinity if enabled
+ if parse_flag_from_env("ACCELERATE_CPU_AFFINITY", False):
+ set_numa_affinity(self.local_process_index)
+
+ # Check for old RTX 4000's that can't use P2P or IB and are on old drivers
+ if self.device.type == "cuda" and not check_cuda_p2p_ib_support():
+ if "NCCL_P2P_DISABLE" not in os.environ or "NCCL_IB_DISABLE" not in os.environ:
+ raise NotImplementedError(
+ "Using RTX 4000 series doesn't support faster communication broadband via P2P or IB. "
+ 'Please set `NCCL_P2P_DISABLE="1"` and `NCCL_IB_DISABLE="1" or use `accelerate launch` which '
+ "will do this automatically."
+ )
+ # Important: This should be the *only* code outside of `self.initialized!`
+ self.fork_launched = parse_flag_from_env("FORK_LAUNCHED", 0)
+
+ def __repr__(self) -> str:
+ return (
+ f"Distributed environment: {self.distributed_type}{(' Backend: ' + self.backend) if self.backend else ''}\n"
+ f"Num processes: {self.num_processes}\n"
+ f"Process index: {self.process_index}\n"
+ f"Local process index: {self.local_process_index}\n"
+ f"Device: {self.device}\n"
+ )
+
+ @staticmethod
+ def _reset_state():
+ "Resets `_shared_state`, is used internally and should not be called"
+ PartialState._shared_state.clear()
+
+ @property
+ def initialized(self) -> bool:
+ "Returns whether the `PartialState` has been initialized"
+ return self._shared_state != {}
+
+ @property
+ def use_distributed(self):
+ """
+ Whether the Accelerator is configured for distributed training
+ """
+ return self.distributed_type != DistributedType.NO and self.num_processes > 1
+
+ @property
+ def is_last_process(self) -> bool:
+ "Returns whether the current process is the last one"
+ return self.process_index == self.num_processes - 1
+
+ @property
+ def is_main_process(self) -> bool:
+ "Returns whether the current process is the main process"
+ return (
+ self.process_index == 0 if self.distributed_type != DistributedType.MEGATRON_LM else self.is_last_process
+ )
+
+ @property
+ def is_local_main_process(self) -> bool:
+ "Returns whether the current process is the main process on the local node"
+ return (
+ self.local_process_index == 0
+ if self.distributed_type != DistributedType.MEGATRON_LM
+ else self.is_last_process
+ )
+
+ def wait_for_everyone(self):
+ """
+ Will stop the execution of the current process until every other process has reached that point (so this does
+ nothing when the script is only run in one process). Useful to do before saving a model.
+
+ Example:
+
+ ```python
+ >>> # Assuming two GPU processes
+ >>> import time
+ >>> from accelerate.state import PartialState
+
+ >>> state = PartialState()
+ >>> if state.is_main_process:
+ ... time.sleep(2)
+ >>> else:
+ ... print("I'm waiting for the main process to finish its sleep...")
+ >>> state.wait_for_everyone()
+ >>> # Should print on every process at the same time
+ >>> print("Everyone is here")
+ ```
+ """
+ if self.distributed_type in (
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_XPU,
+ DistributedType.MULTI_CPU,
+ DistributedType.DEEPSPEED,
+ DistributedType.FSDP,
+ ):
+ torch.distributed.barrier()
+ elif self.distributed_type == DistributedType.XLA:
+ xm.rendezvous("accelerate.utils.wait_for_everyone")
+
+ def _goes_first(self, is_main: bool):
+ if not is_main:
+ self.wait_for_everyone()
+
+ yield
+
+ if is_main:
+ self.wait_for_everyone()
+
+ @contextmanager
+ def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False):
+ """
+ Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
+ distributed inference, such as with different prompts.
+
+ Note that when using a `dict`, all keys need to have the same number of elements.
+
+ Args:
+ inputs (`list`, `tuple`, `torch.Tensor`, `dict` of `list`/`tuple`/`torch.Tensor`, or `datasets.Dataset`):
+ The input to split between processes.
+ apply_padding (`bool`, `optional`, defaults to `False`):
+ Whether to apply padding by repeating the last element of the input so that all processes have the same
+ number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing
+ in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.
+
+
+ Example:
+
+ ```python
+ # Assume there are two processes
+ from accelerate import PartialState
+
+ state = PartialState()
+ with state.split_between_processes(["A", "B", "C"]) as inputs:
+ print(inputs)
+ # Process 0
+ ["A", "B"]
+ # Process 1
+ ["C"]
+
+ with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
+ print(inputs)
+ # Process 0
+ ["A", "B"]
+ # Process 1
+ ["C", "C"]
+ ```
+ """
+ if self.num_processes == 1:
+ yield inputs
+ return
+ length = len(inputs)
+ # Nested dictionary of any types
+ if isinstance(inputs, dict):
+ length = len(inputs[list(inputs.keys())[0]])
+ if not all(len(v) == length for v in inputs.values()):
+ raise ValueError("All values in the dictionary must have the same length")
+ num_samples_per_process, num_extras = divmod(length, self.num_processes)
+ start_index = self.process_index * num_samples_per_process + min(self.process_index, num_extras)
+ end_index = start_index + num_samples_per_process + (1 if self.process_index < num_extras else 0)
+
+ def _split_values(inputs, start_index, end_index):
+ if isinstance(inputs, (list, tuple, torch.Tensor)):
+ if start_index >= len(inputs):
+ result = inputs[-1:]
+ else:
+ result = inputs[start_index:end_index]
+ if apply_padding:
+ if isinstance(result, torch.Tensor):
+ from accelerate.utils import pad_across_processes, send_to_device
+
+ # The tensor needs to be on the device before we can pad it
+ tensorized_result = send_to_device(result, self.device)
+ result = pad_across_processes(tensorized_result, pad_index=inputs[-1])
+ else:
+ result += [result[-1]] * (num_samples_per_process + 1 - len(result))
+ return result
+ elif isinstance(inputs, dict):
+ for key in inputs.keys():
+ inputs[key] = _split_values(inputs[key], start_index, end_index)
+ return inputs
+ else:
+ if is_datasets_available():
+ from datasets import Dataset
+
+ if isinstance(inputs, Dataset):
+ if start_index >= len(inputs):
+ start_index = len(inputs) - 1
+ if end_index > len(inputs):
+ end_index = len(inputs)
+ result_idcs = list(range(start_index, end_index))
+ if apply_padding:
+ result_idcs += [end_index - 1] * (num_samples_per_process + 1 - len(result_idcs))
+ return inputs.select(result_idcs)
+ return inputs
+
+ yield _split_values(inputs, start_index, end_index)
+
+ @contextmanager
+ def main_process_first(self):
+ """
+ Lets the main process go first inside a with block.
+
+ The other processes will enter the with block after the main process exits.
+
+ Example:
+
+ ```python
+ >>> from accelerate import Accelerator
+
+ >>> accelerator = Accelerator()
+ >>> with accelerator.main_process_first():
+ ... # This will be printed first by process 0 then in a seemingly
+ ... # random order by the other processes.
+ ... print(f"This will be printed by process {accelerator.process_index}")
+ ```
+ """
+ yield from self._goes_first(self.is_main_process)
+
+ @contextmanager
+ def local_main_process_first(self):
+ """
+ Lets the local main process go inside a with block.
+
+ The other processes will enter the with block after the main process exits.
+
+ Example:
+
+ ```python
+ >>> from accelerate.state import PartialState
+
+ >>> state = PartialState()
+ >>> with state.local_main_process_first():
+ ... # This will be printed first by local process 0 then in a seemingly
+ ... # random order by the other processes.
+ ... print(f"This will be printed by process {state.local_process_index}")
+ ```
+ """
+ yield from self._goes_first(self.is_local_main_process)
+
+ def on_main_process(self, function: Callable[..., Any] = None):
+ """
+ Decorator that only runs the decorated function on the main process.
+
+ Args:
+ function (`Callable`): The function to decorate.
+
+ Example:
+
+ ```python
+ >>> from accelerate.state import PartialState
+
+ >>> state = PartialState()
+
+
+ >>> @state.on_main_process
+ ... def print_something():
+ ... print("This will be printed by process 0 only.")
+
+
+ >>> print_something()
+ "This will be printed by process 0 only"
+ ```
+ """
+ if not self.initialized:
+ raise ValueError("The `PartialState` or `Accelerator` must be initialized before calling this function.")
+ if self.is_main_process or not self.use_distributed:
+ return function
+ return do_nothing
+
+ def on_local_main_process(self, function: Callable[..., Any] = None):
+ """
+ Decorator that only runs the decorated function on the local main process.
+
+ Args:
+ function (`Callable`): The function to decorate.
+
+ Example:
+ ```python
+ # Assume we have 2 servers with 4 processes each.
+ from accelerate.state import PartialState
+
+ state = PartialState()
+
+
+ @state.on_local_main_process
+ def print_something():
+ print("This will be printed by process 0 only on each server.")
+
+
+ print_something()
+ # On server 1:
+ "This will be printed by process 0 only"
+ # On server 2:
+ "This will be printed by process 0 only"
+ ```
+ """
+ if self.is_local_main_process or not self.use_distributed:
+ return function
+ return do_nothing
+
+ def on_last_process(self, function: Callable[..., Any]):
+ """
+ Decorator that only runs the decorated function on the last process.
+
+ Args:
+ function (`Callable`): The function to decorate.
+
+ Example:
+ ```python
+ # Assume we have 4 processes.
+ from accelerate.state import PartialState
+
+ state = PartialState()
+
+
+ @state.on_last_process
+ def print_something():
+ print(f"Printed on process {state.process_index}")
+
+
+ print_something()
+ "Printed on process 3"
+ ```
+ """
+ if self.is_last_process or not self.use_distributed:
+ return function
+ return do_nothing
+
+ def on_process(self, function: Callable[..., Any] = None, process_index: int = None):
+ """
+ Decorator that only runs the decorated function on the process with the given index.
+
+ Args:
+ function (`Callable`, `optional`):
+ The function to decorate.
+ process_index (`int`, `optional`):
+ The index of the process on which to run the function.
+
+ Example:
+ ```python
+ # Assume we have 4 processes.
+ from accelerate.state import PartialState
+
+ state = PartialState()
+
+
+ @state.on_process(process_index=2)
+ def print_something():
+ print(f"Printed on process {state.process_index}")
+
+
+ print_something()
+ "Printed on process 2"
+ ```
+ """
+ if function is None:
+ return partial(self.on_process, process_index=process_index)
+ if (self.process_index == process_index) or (not self.use_distributed):
+ return function
+ return do_nothing
+
+ def on_local_process(self, function: Callable[..., Any] = None, local_process_index: int = None):
+ """
+ Decorator that only runs the decorated function on the process with the given index on the current node.
+
+ Args:
+ function (`Callable`, *optional*):
+ The function to decorate.
+ local_process_index (`int`, *optional*):
+ The index of the local process on which to run the function.
+
+ Example:
+ ```python
+ # Assume we have 2 servers with 4 processes each.
+ from accelerate import Accelerator
+
+ accelerator = Accelerator()
+
+
+ @accelerator.on_local_process(local_process_index=2)
+ def print_something():
+ print(f"Printed on process {accelerator.local_process_index}")
+
+
+ print_something()
+ # On server 1:
+ "Printed on process 2"
+ # On server 2:
+ "Printed on process 2"
+ ```
+ """
+ if function is None:
+ return partial(self.on_local_process, local_process_index=local_process_index)
+ if (self.local_process_index == local_process_index) or (not self.use_distributed):
+ return function
+ return do_nothing
+
+ def print(self, *args, **kwargs):
+ if self.is_local_main_process:
+ print(*args, **kwargs)
+
+ @property
+ def default_device(self) -> torch.device:
+ """
+ Returns the default device which is:
+ - MPS if `torch.backends.mps.is_available()` and `torch.backends.mps.is_built()` both return True.
+ - CUDA if `torch.cuda.is_available()`
+ - MLU if `is_mlu_available()`
+ - MUSA if `is_musa_available()`
+ - NPU if `is_npu_available()`
+ - CPU otherwise
+ """
+ if is_mps_available():
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
+ return torch.device("mps")
+ elif is_mlu_available():
+ return torch.device("mlu")
+ elif is_musa_available():
+ return torch.device("musa")
+ # NPU should be checked before CUDA when using `transfer_to_npu`
+ # See issue #3020: https://github.com/huggingface/accelerate/issues/3020
+ elif is_npu_available():
+ return torch.device("npu")
+ elif torch.cuda.is_available():
+ return torch.device("cuda")
+ elif is_xpu_available():
+ return torch.device("xpu")
+ else:
+ return torch.device("cpu")
+
+ def _prepare_backend(
+ self, cpu: bool = False, sagemaker_dp=False, backend: str = None
+ ) -> tuple[str, DistributedType]:
+ "Prepares any imports needed before initializing the distributed backend and sets `self.backend` properly"
+ distributed_type = None
+ if sagemaker_dp:
+ import smdistributed.dataparallel.torch.torch_smddp # noqa
+
+ backend = "smddp"
+ distributed_type = DistributedType.MULTI_GPU
+ elif is_torch_xla_available():
+ backend = "xla"
+ distributed_type = DistributedType.XLA
+ elif int(os.environ.get("LOCAL_RANK", -1)) != -1 and not cpu:
+ if is_mlu_available():
+ backend = "cncl"
+ distributed_type = DistributedType.MULTI_MLU
+ elif is_musa_available():
+ backend = "mccl"
+ distributed_type = DistributedType.MULTI_MUSA
+ # NPU should be checked before CUDA when using `transfer_to_npu`
+ # See issue #3020: https://github.com/huggingface/accelerate/issues/3020
+ elif is_npu_available():
+ backend = "hccl"
+ distributed_type = DistributedType.MULTI_NPU
+ elif torch.cuda.is_available():
+ if backend is None:
+ backend = "nccl"
+ distributed_type = DistributedType.MULTI_GPU
+
+ if distributed_type is None and (
+ int(os.environ.get("LOCAL_RANK", -1)) != -1
+ or get_int_from_env(["PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "MV2_COMM_WORLD_SIZE", "WORLD_SIZE"], 1) > 1
+ ):
+ if not cpu and is_xpu_available():
+ distributed_type = DistributedType.MULTI_XPU
+ else:
+ distributed_type = DistributedType.MULTI_CPU
+
+ if (
+ backend in (None, "ccl")
+ and is_ccl_available()
+ and (get_int_from_env(["CCL_WORKER_COUNT"], 0) > 0 or distributed_type == DistributedType.MULTI_XPU)
+ ):
+ if get_ccl_version() >= "1.12":
+ import oneccl_bindings_for_pytorch # noqa: F401
+ else:
+ import torch_ccl # noqa: F401
+
+ backend = "ccl"
+ elif backend in (None, "mpi") and torch.distributed.is_mpi_available():
+ backend = "mpi"
+ else:
+ backend = "gloo"
+ if distributed_type is None:
+ distributed_type = DistributedType.NO
+
+ return backend, distributed_type
+
+ def set_device(self):
+ """
+ Sets the device in `self.device` to the current distributed environment.
+ """
+ if self.device is not None:
+ return
+ if self.distributed_type == DistributedType.NO:
+ self.device = torch.device("cpu") if self._cpu else self.default_device
+ return
+ device = str(self.distributed_type).split(".")[-1].replace("MULTI_", "").lower()
+ if device not in ("cpu", "gpu", "mlu", "musa", "npu", "xpu", "xla"):
+ raise ValueError(
+ f"Can't set device for {self.distributed_type} ({device}), verify we should be calling `_set_device()` for it!"
+ )
+ if device == "xla":
+ self.device = xm.xla_device()
+ else:
+ if device == "gpu":
+ device = "cuda"
+ device_module = getattr(torch, device)
+ device_index = self.local_process_index % device_module.device_count()
+ self.device = torch.device(device, device_index)
+ device_module.set_device(self.device)
+
+ def destroy_process_group(self, group=None):
+ """
+ Destroys the process group. If one is not specified, the default process group is destroyed.
+ """
+ if self.fork_launched and group is None:
+ return
+ # needed when using torch.distributed.init_process_group
+ if torch.distributed.is_initialized():
+ torch.distributed.destroy_process_group(group)
+
+ def __getattr__(self, name: str):
+ # By this point we know that no attributes of `self` contain `name`,
+ # so we just modify the error message
+ if name in self._known_attrs:
+ raise AttributeError(
+ f"`PartialState` object has no attribute `{name}`. "
+ "This happens if `PartialState._reset_state()` was called and "
+ "an `Accelerator` or `PartialState` was not reinitialized."
+ )
+ # Raise a typical AttributeError
+ raise AttributeError(f"'PartialState' object has no attribute '{name}'")
+
+
+class AcceleratorState:
+ """
+ Singleton class that has information about the current training environment.
+
+ **Available attributes:**
+
+ - **device** (`torch.device`) -- The device to use.
+ - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently
+ in use.
+ - **initialized** (`bool`) -- Whether or not the `AcceleratorState` has been initialized from `Accelerator`.
+ - **local_process_index** (`int`) -- The index of the current process on the current server.
+ - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type
+ of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8').
+ - **num_processes** (`int`) -- The number of processes currently launched in parallel.
+ - **process_index** (`int`) -- The index of the current process.
+ - **is_last_process** (`bool`) -- Whether or not the current process is the last one.
+ - **is_main_process** (`bool`) -- Whether or not the current process is the main one.
+ - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node.
+ - **debug** (`bool`) -- Whether or not the current script is being run in debug mode.
+ """
+
+ _shared_state = SharedDict()
+ _known_attrs = PartialState._known_attrs + [
+ "deepspeed_plugin",
+ "use_ipex",
+ "fsdp_plugin",
+ "megatron_lm_plugin",
+ "dynamo_plugin",
+ ]
+
+ def __init__(
+ self,
+ mixed_precision: str = None,
+ cpu: bool = False,
+ dynamo_plugin=None,
+ deepspeed_plugin=None,
+ fsdp_plugin=None,
+ megatron_lm_plugin=None,
+ _from_accelerator: bool = False,
+ **kwargs,
+ ):
+ self.__dict__ = self._shared_state
+ if parse_flag_from_env("ACCELERATE_USE_CPU"):
+ cpu = True
+ if PartialState._shared_state == {}:
+ PartialState(cpu, **kwargs)
+ self.__dict__.update(PartialState._shared_state)
+ self._check_initialized(mixed_precision, cpu)
+ if not self.initialized:
+ self.deepspeed_plugins = None
+ self.use_ipex = None
+ mixed_precision = (
+ parse_choice_from_env("ACCELERATE_MIXED_PRECISION", "no")
+ if mixed_precision is None
+ else mixed_precision.lower()
+ )
+ if mixed_precision == "fp8":
+ if not is_fp8_available():
+ raise ValueError(
+ "Using `fp8` precision requires `transformer_engine` or `MS-AMP` to be installed."
+ )
+ elif not check_fp8_capability():
+ logger.warning(
+ f"The current device has compute capability of {torch.cuda.get_device_capability()} which is "
+ "insufficient for FP8 mixed precision training (requires a GPU Hopper/Ada Lovelace "
+ "or higher, compute capability of 8.9 or higher). Will use FP16 instead."
+ )
+ mixed_precision = "fp16"
+
+ self.dynamo_plugin = dynamo_plugin
+ if not _from_accelerator:
+ raise ValueError(
+ "Please make sure to properly initialize your accelerator via `accelerator = Accelerator()` "
+ "before using any functionality from the `accelerate` library."
+ )
+ # deepspeed handles mixed_precision using deepspeed_config
+ self._mixed_precision = "no" if self.distributed_type == DistributedType.DEEPSPEED else mixed_precision
+ if self.distributed_type == DistributedType.XLA and is_torch_xla_available(check_is_tpu=True):
+ if mixed_precision == "bf16":
+ if os.environ.get("ACCELERATE_DOWNCAST_BF16"):
+ os.environ["XLA_USE_BF16"] = str(0)
+ os.environ["XLA_DOWNCAST_BF16"] = str(1)
+ self.downcast_bfloat = True
+ else:
+ os.environ["XLA_USE_BF16"] = str(1)
+ os.environ["XLA_DOWNCAST_BF16"] = str(0)
+ self.downcast_bfloat = False
+ elif os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true" and not cpu:
+ self.deepspeed_plugins = deepspeed_plugin
+ self.distributed_type = DistributedType.DEEPSPEED
+ elif self.distributed_type in [
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_XPU,
+ ]:
+ if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true" or fsdp_plugin is not None:
+ self.distributed_type = DistributedType.FSDP
+ if self._mixed_precision != "no":
+ fsdp_plugin.set_mixed_precision(self._mixed_precision)
+ self.fsdp_plugin = fsdp_plugin
+ if os.environ.get("ACCELERATE_USE_MEGATRON_LM", "false") == "true" and self.distributed_type not in [
+ DistributedType.MULTI_XPU,
+ ]:
+ self.distributed_type = DistributedType.MEGATRON_LM
+ megatron_lm_plugin.set_mixed_precision(self._mixed_precision)
+ self.megatron_lm_plugin = megatron_lm_plugin
+ elif self.distributed_type in [DistributedType.MULTI_CPU, DistributedType.MULTI_XPU, DistributedType.NO]:
+ if is_ipex_available():
+ # check if user disables it explicitly
+ self.use_ipex = parse_flag_from_env("ACCELERATE_USE_IPEX", default=True)
+ else:
+ self.use_ipex = False
+ if (
+ self.dynamo_plugin.backend != DynamoBackend.NO
+ and self._mixed_precision == "no"
+ and self.device.type == "cuda"
+ ):
+ torch.backends.cuda.matmul.allow_tf32 = True
+ if (
+ self.dynamo_plugin.backend != DynamoBackend.NO
+ and self._mixed_precision == "no"
+ and self.device.type == "musa"
+ ):
+ torch.backends.musa.matmul.allow_tf32 = True
+ PartialState._shared_state["distributed_type"] = self.distributed_type
+
+ @property
+ def initialized(self) -> bool:
+ return self._shared_state != PartialState._shared_state
+
+ def __repr__(self):
+ repr = PartialState().__repr__() + f"\nMixed precision type: {self.mixed_precision}\n"
+ if self.distributed_type == DistributedType.DEEPSPEED:
+ repr += f"ds_config: {self.deepspeed_plugin.deepspeed_config}\n"
+ return repr
+
+ def _check_initialized(self, mixed_precision=None, cpu=None):
+ "Checks if a modification is trying to be made and the `AcceleratorState` has already been initialized"
+ if self.initialized:
+ err = "AcceleratorState has already been initialized and cannot be changed, restart your runtime completely and pass `{flag}` to `Accelerator()`."
+ if cpu and self.device.type != "cpu":
+ raise ValueError(err.format(flag="cpu=True"))
+ if (
+ mixed_precision is not None
+ and mixed_precision != self._mixed_precision
+ and self.distributed_type != DistributedType.DEEPSPEED
+ ):
+ raise ValueError(err.format(flag=f"mixed_precision='{mixed_precision}'"))
+
+ @property
+ def mixed_precision(self):
+ if self.distributed_type == DistributedType.DEEPSPEED:
+ config = self.deepspeed_plugin.deepspeed_config
+ if config.get("fp16", {}).get("enabled", False):
+ mixed_precision = "fp16"
+ elif config.get("bf16", {}).get("enabled", False):
+ mixed_precision = "bf16"
+ else:
+ mixed_precision = "no"
+ else:
+ mixed_precision = self._mixed_precision
+ return mixed_precision
+
+ @staticmethod
+ def _reset_state(reset_partial_state: bool = False):
+ "Resets `_shared_state`, is used internally and should not be called"
+ AcceleratorState._shared_state.clear()
+ if reset_partial_state:
+ PartialState._reset_state()
+
+ def destroy_process_group(self, group=None):
+ """
+ Destroys the process group. If one is not specified, the default process group is destroyed.
+
+ If `self.fork_lauched` is `True` and `group` is `None`, nothing happens.
+ """
+ PartialState().destroy_process_group(group)
+
+ @property
+ def fork_launched(self):
+ return PartialState().fork_launched
+
+ @property
+ def use_distributed(self):
+ """
+ Whether the Accelerator is configured for distributed training
+ """
+ return PartialState().use_distributed
+
+ @property
+ def is_last_process(self) -> bool:
+ "Returns whether the current process is the last one"
+ return PartialState().is_last_process
+
+ @property
+ def is_main_process(self) -> bool:
+ "Returns whether the current process is the main process"
+ return PartialState().is_main_process
+
+ @property
+ def is_local_main_process(self) -> bool:
+ "Returns whether the current process is the main process on the local node"
+ return PartialState().is_local_main_process
+
+ def wait_for_everyone(self):
+ PartialState().wait_for_everyone()
+
+ @contextmanager
+ def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False):
+ """
+ Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
+ distributed inference, such as with different prompts.
+
+ Note that when using a `dict`, all keys need to have the same number of elements.
+
+ Args:
+ inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`):
+ The input to split between processes.
+ apply_padding (`bool`, `optional`, defaults to `False`):
+ Whether to apply padding by repeating the last element of the input so that all processes have the same
+ number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing
+ in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.
+
+
+ Example:
+
+ ```python
+ # Assume there are two processes
+ from accelerate.state import AcceleratorState
+
+ state = AcceleratorState()
+ with state.split_between_processes(["A", "B", "C"]) as inputs:
+ print(inputs)
+ # Process 0
+ ["A", "B"]
+ # Process 1
+ ["C"]
+
+ with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
+ print(inputs)
+ # Process 0
+ ["A", "B"]
+ # Process 1
+ ["C", "C"]
+ ```
+ """
+ with PartialState().split_between_processes(inputs, apply_padding=apply_padding) as inputs:
+ yield inputs
+
+ @contextmanager
+ def main_process_first(self):
+ """
+ Lets the main process go first inside a with block.
+
+ The other processes will enter the with block after the main process exits.
+ """
+ with PartialState().main_process_first():
+ yield
+
+ @contextmanager
+ def local_main_process_first(self):
+ """
+ Lets the local main process go inside a with block.
+
+ The other processes will enter the with block after the main process exits.
+ """
+ with PartialState().local_main_process_first():
+ yield
+
+ @property
+ def deepspeed_plugin(self):
+ """
+ Returns the currently active DeepSpeedPlugin.
+
+ If not using deepspeed, returns `None`.
+ """
+ # To maintain original behavior, return None if not using deepspeed.
+ if self.distributed_type != DistributedType.DEEPSPEED:
+ return None
+ from accelerate.utils.deepspeed import get_active_deepspeed_plugin
+
+ return get_active_deepspeed_plugin(self)
+
+ @deepspeed_required
+ def get_deepspeed_plugin(self, name: str):
+ """
+ Returns the DeepSpeedPlugin with the given plugin_key.
+ """
+ return self.deepspeed_plugins[name]
+
+ @deepspeed_required
+ def select_deepspeed_plugin(self, name: str = None):
+ """
+ Activates the DeepSpeedPlugin with the given `name`, and will disable all other plugins.
+ """
+ for key, plugin in self.deepspeed_plugins.items():
+ if key != name:
+ plugin._unselect()
+ self.deepspeed_plugins[name].select(_from_accelerator_state=True)
+
+ def print(self, *args, **kwargs):
+ PartialState().print(*args, **kwargs)
+
+ def __getattr__(self, name: str):
+ # By this point we know that no attributes of `self` contain `name`,
+ # so we just modify the error message
+ if name in self._known_attrs:
+ raise AttributeError(
+ f"`AcceleratorState` object has no attribute `{name}`. "
+ "This happens if `AcceleratorState._reset_state()` was called and "
+ "an `Accelerator` or `PartialState` was not reinitialized."
+ )
+ # Raise a typical AttributeError
+ raise AttributeError(f"'AcceleratorState' object has no attribute '{name}'")
+
+
+class GradientState:
+ """
+ Singleton class that has information related to gradient synchronization for gradient accumulation
+
+ **Available attributes:**
+
+ - **end_of_dataloader** (`bool`) -- Whether we have reached the end the current dataloader
+ - **remainder** (`int`) -- The number of extra samples that were added from padding the dataloader
+ - **sync_gradients** (`bool`) -- Whether the gradients should be synced across all devices
+ - **active_dataloader** (`Optional[DataLoader]`) -- The dataloader that is currently being iterated over
+ - **dataloader_references** (`List[Optional[DataLoader]]`) -- A list of references to the dataloaders that are
+ being iterated over
+ - **num_steps** (`int`) -- The number of steps to accumulate over
+ - **adjust_scheduler** (`bool`) -- Whether the scheduler should be adjusted to account for the gradient
+ accumulation
+ - **sync_with_dataloader** (`bool`) -- Whether the gradients should be synced at the end of the dataloader
+ iteration and the number of total steps reset
+ - **is_xla_gradients_synced** (`bool`) -- Whether the XLA gradients have been synchronized. It is initialized
+ as false. Once gradients have been reduced before the optimizer step, this flag is set to true. Subsequently,
+ after each step, the flag is reset to false. FSDP will always synchronize the gradients, hence
+ is_xla_gradients_synced is always true.
+ """
+
+ _shared_state = SharedDict()
+
+ def __init__(self, gradient_accumulation_plugin: Optional[GradientAccumulationPlugin] = None):
+ self.__dict__ = self._shared_state
+ if not self.initialized:
+ self.sync_gradients = True
+ self.active_dataloader = None
+ self.dataloader_references = [None]
+ self.plugin_kwargs = (
+ gradient_accumulation_plugin.to_kwargs() if gradient_accumulation_plugin is not None else {}
+ )
+ self._is_xla_gradients_synced = False
+
+ # Plugin args are different and can be updated
+ if gradient_accumulation_plugin is not None and self.plugin_kwargs != gradient_accumulation_plugin.to_kwargs():
+ self.plugin_kwargs = gradient_accumulation_plugin.to_kwargs()
+
+ @property
+ def num_steps(self) -> int:
+ "Returns the number of steps to accumulate over"
+ return self.plugin_kwargs.get("num_steps", 1)
+
+ @property
+ def adjust_scheduler(self) -> bool:
+ "Returns whether the scheduler should be adjusted"
+ return self.plugin_kwargs.get("adjust_scheduler", False)
+
+ @property
+ def sync_with_dataloader(self) -> bool:
+ "Returns whether the gradients should be synced at the end of the dataloader iteration and the number of total steps reset"
+ return self.plugin_kwargs.get("sync_with_dataloader", True)
+
+ @property
+ def initialized(self) -> bool:
+ "Returns whether the `GradientState` has been initialized"
+ return GradientState._shared_state != {}
+
+ @property
+ def end_of_dataloader(self) -> bool:
+ "Returns whether we have reached the end of the current dataloader"
+ if not self.in_dataloader:
+ return False
+ return self.active_dataloader.end_of_dataloader
+
+ @property
+ def remainder(self) -> int:
+ "Returns the number of extra samples that were added from padding the dataloader"
+ if not self.in_dataloader:
+ return -1
+ return self.active_dataloader.remainder
+
+ def __repr__(self):
+ return (
+ f"Sync Gradients: {self.sync_gradients}\n"
+ f"At end of current dataloader: {self.end_of_dataloader}\n"
+ f"Extra samples added: {self.remainder}\n"
+ f"Gradient accumulation plugin: {self.plugin_kwargs}\n"
+ )
+
+ @property
+ def is_xla_gradients_synced(self):
+ "Returns the value of is_xla_gradients_synced. FSDP will always synchronize the gradients, hence is_xla_gradients_synced is always true."
+ if parse_flag_from_env("ACCELERATE_USE_FSDP", default=False):
+ return True
+ return self._is_xla_gradients_synced
+
+ @is_xla_gradients_synced.setter
+ def is_xla_gradients_synced(self, is_synced):
+ "Set the _is_xla_gradients_synced attribute."
+ self._is_xla_gradients_synced = is_synced
+
+ def _set_sync_gradients(self, sync_gradients):
+ "Private function that sets whether gradients should be synchronized. Users should not have to call this."
+ self.sync_gradients = sync_gradients
+ # Allow grad-sync to automatically work on TPUs
+ if (
+ self.sync_gradients
+ and is_torch_xla_available(check_is_tpu=True)
+ and PartialState().distributed_type == DistributedType.XLA
+ ):
+ xm.mark_step()
+
+ def _add_dataloader(self, dataloader):
+ "Private function that adds a dataloader to `self.dataloader_references` and sets `in_dataloader` to `True`. Users should not have to call this."
+ self.active_dataloader = dataloader
+ self.dataloader_references.append(self.active_dataloader)
+
+ def _remove_dataloader(self, dataloader):
+ "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."
+ self.dataloader_references.remove(dataloader)
+ self.active_dataloader = self.dataloader_references[-1]
+
+ @property
+ def in_dataloader(self) -> bool:
+ "Returns whether the current process is in a dataloader"
+ return self.active_dataloader is not None
+
+ @staticmethod
+ def _reset_state():
+ "Resets `_shared_state`, is used internally and should not be called"
+ GradientState._shared_state.clear()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/__init__.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e07f52647694a813fbaf1e043d350f65001cae73
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/__init__.py
@@ -0,0 +1,54 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from .testing import (
+ DEFAULT_LAUNCH_COMMAND,
+ are_the_same_tensors,
+ assert_exception,
+ capture_call_output,
+ device_count,
+ execute_subprocess_async,
+ get_launch_command,
+ memory_allocated_func,
+ path_in_accelerate_package,
+ require_bnb,
+ require_cpu,
+ require_cuda,
+ require_huggingface_suite,
+ require_mlu,
+ require_mps,
+ require_multi_device,
+ require_multi_gpu,
+ require_multi_xpu,
+ require_musa,
+ require_non_cpu,
+ require_non_torch_xla,
+ require_non_xpu,
+ require_npu,
+ require_pippy,
+ require_single_device,
+ require_single_gpu,
+ require_single_xpu,
+ require_torch_min_version,
+ require_torchvision,
+ require_tpu,
+ require_transformer_engine,
+ require_xpu,
+ skip,
+ slow,
+ torch_device,
+)
+from .training import RegressionDataset, RegressionModel, RegressionModel4XPU
+
+
+from .scripts import test_script, test_sync, test_ops # isort: skip
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/examples.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/examples.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed41d38c9092385ba9730472aa10b5208f48c67b
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/examples.py
@@ -0,0 +1,146 @@
+#!/usr/bin/env python
+
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+A collection of utilities for comparing `examples/complete_*_example.py` scripts with the capabilities inside of each
+`examples/by_feature` example. `compare_against_test` is the main function that should be used when testing, while the
+others are used to either get the code that matters, or to preprocess them (such as stripping comments)
+"""
+
+import os
+from typing import List
+
+
+def get_function_contents_by_name(lines: List[str], name: str):
+ """
+ Extracts a function from `lines` of segmented source code with the name `name`.
+
+ Args:
+ lines (`List[str]`):
+ Source code of a script seperated by line.
+ name (`str`):
+ The name of the function to extract. Should be either `training_function` or `main`
+ """
+ if name != "training_function" and name != "main":
+ raise ValueError(f"Incorrect function name passed: {name}, choose either 'main' or 'training_function'")
+ good_lines, found_start = [], False
+ for line in lines:
+ if not found_start and f"def {name}" in line:
+ found_start = True
+ good_lines.append(line)
+ continue
+ if found_start:
+ if name == "training_function" and "def main" in line:
+ return good_lines
+ if name == "main" and "if __name__" in line:
+ return good_lines
+ good_lines.append(line)
+
+
+def clean_lines(lines: List[str]):
+ """
+ Filters `lines` and removes any entries that start with a comment ('#') or is just a newline ('\n')
+
+ Args:
+ lines (`List[str]`):
+ Source code of a script seperated by line.
+ """
+ return [line for line in lines if not line.lstrip().startswith("#") and line != "\n"]
+
+
+def compare_against_test(base_filename: str, feature_filename: str, parser_only: bool, secondary_filename: str = None):
+ """
+ Tests whether the additional code inside of `feature_filename` was implemented in `base_filename`. This should be
+ used when testing to see if `complete_*_.py` examples have all of the implementations from each of the
+ `examples/by_feature/*` scripts.
+
+ It utilizes `nlp_example.py` to extract out all of the repeated training code, so that only the new additional code
+ is examined and checked. If something *other* than `nlp_example.py` should be used, such as `cv_example.py` for the
+ `complete_cv_example.py` script, it should be passed in for the `secondary_filename` parameter.
+
+ Args:
+ base_filename (`str` or `os.PathLike`):
+ The filepath of a single "complete" example script to test, such as `examples/complete_cv_example.py`
+ feature_filename (`str` or `os.PathLike`):
+ The filepath of a single feature example script. The contents of this script are checked to see if they
+ exist in `base_filename`
+ parser_only (`bool`):
+ Whether to compare only the `main()` sections in both files, or to compare the contents of
+ `training_loop()`
+ secondary_filename (`str`, *optional*):
+ A potential secondary filepath that should be included in the check. This function extracts the base
+ functionalities off of "examples/nlp_example.py", so if `base_filename` is a script other than
+ `complete_nlp_example.py`, the template script should be included here. Such as `examples/cv_example.py`
+ """
+ with open(base_filename) as f:
+ base_file_contents = f.readlines()
+ with open(os.path.abspath(os.path.join("examples", "nlp_example.py"))) as f:
+ full_file_contents = f.readlines()
+ with open(feature_filename) as f:
+ feature_file_contents = f.readlines()
+ if secondary_filename is not None:
+ with open(secondary_filename) as f:
+ secondary_file_contents = f.readlines()
+
+ # This is our base, we remove all the code from here in our `full_filename` and `feature_filename` to find the new content
+ if parser_only:
+ base_file_func = clean_lines(get_function_contents_by_name(base_file_contents, "main"))
+ full_file_func = clean_lines(get_function_contents_by_name(full_file_contents, "main"))
+ feature_file_func = clean_lines(get_function_contents_by_name(feature_file_contents, "main"))
+ if secondary_filename is not None:
+ secondary_file_func = clean_lines(get_function_contents_by_name(secondary_file_contents, "main"))
+ else:
+ base_file_func = clean_lines(get_function_contents_by_name(base_file_contents, "training_function"))
+ full_file_func = clean_lines(get_function_contents_by_name(full_file_contents, "training_function"))
+ feature_file_func = clean_lines(get_function_contents_by_name(feature_file_contents, "training_function"))
+ if secondary_filename is not None:
+ secondary_file_func = clean_lines(
+ get_function_contents_by_name(secondary_file_contents, "training_function")
+ )
+
+ _dl_line = "train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)\n"
+
+ # Specific code in our script that differs from the full version, aka what is new
+ new_feature_code = []
+ passed_idxs = [] # We keep track of the idxs just in case it's a repeated statement
+ it = iter(feature_file_func)
+ for i in range(len(feature_file_func) - 1):
+ if i not in passed_idxs:
+ line = next(it)
+ if (line not in full_file_func) and (line.lstrip() != _dl_line):
+ if "TESTING_MOCKED_DATALOADERS" not in line:
+ new_feature_code.append(line)
+ passed_idxs.append(i)
+ else:
+ # Skip over the `config['num_epochs'] = 2` statement
+ _ = next(it)
+
+ # Extract out just the new parts from the full_file_training_func
+ new_full_example_parts = []
+ passed_idxs = [] # We keep track of the idxs just in case it's a repeated statement
+ for i, line in enumerate(base_file_func):
+ if i not in passed_idxs:
+ if (line not in full_file_func) and (line.lstrip() != _dl_line):
+ if "TESTING_MOCKED_DATALOADERS" not in line:
+ new_full_example_parts.append(line)
+ passed_idxs.append(i)
+
+ # Finally, get the overall diff
+ diff_from_example = [line for line in new_feature_code if line not in new_full_example_parts]
+ if secondary_filename is not None:
+ diff_from_two = [line for line in full_file_contents if line not in secondary_file_func]
+ diff_from_example = [line for line in diff_from_example if line not in diff_from_two]
+
+ return diff_from_example
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/__init__.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9cbe26c257b515f657c05e1996d517e69613972
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/__init__.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9cbe26c257b515f657c05e1996d517e69613972
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b86a40b20721699bd3df4e9969d5823d7b3d9e3
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py
@@ -0,0 +1,269 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import json
+import os
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, model_name: str = "bert-base-cased"):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ model_name (`str`, *optional*):
+ """
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ tokenized_datasets = datasets.map(
+ tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ if accelerator.distributed_type == DistributedType.XLA:
+ return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt")
+ return tokenizer.pad(examples, padding="longest", return_tensors="pt")
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+def evaluation_loop(accelerator, model, eval_dataloader, metric):
+ model.eval()
+ samples_seen = 0
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ # It is slightly faster to call this once, than multiple times
+ predictions, references = accelerator.gather(
+ (predictions, batch["labels"])
+ ) # If we are in a multiprocess environment, the last batch has duplicates
+ if accelerator.use_distributed:
+ if step == len(eval_dataloader) - 1:
+ predictions = predictions[: len(eval_dataloader.dataset) - samples_seen]
+ references = references[: len(eval_dataloader.dataset) - samples_seen]
+ else:
+ samples_seen += references.shape[0]
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ return eval_metric["accuracy"]
+
+
+def training_function(config, args):
+ # Initialize accelerator
+ accelerator = Accelerator()
+
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+ model_name = args.model_name_or_path
+
+ set_seed(seed)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name)
+
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True)
+
+ # Instantiate optimizer
+ optimizer_cls = (
+ AdamW
+ if accelerator.state.deepspeed_plugin is None
+ or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
+ else DummyOptim
+ )
+ optimizer = optimizer_cls(params=model.parameters(), lr=lr)
+
+ if accelerator.state.deepspeed_plugin is not None:
+ gradient_accumulation_steps = accelerator.state.deepspeed_plugin.deepspeed_config[
+ "gradient_accumulation_steps"
+ ]
+ else:
+ gradient_accumulation_steps = 1
+ max_training_steps = (len(train_dataloader) * num_epochs) // gradient_accumulation_steps
+
+ # Instantiate scheduler
+ if (
+ accelerator.state.deepspeed_plugin is None
+ or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
+ ):
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=max_training_steps,
+ )
+ else:
+ lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0)
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # We need to keep track of how many total steps we have iterated over
+ overall_step = 0
+ # We also need to keep track of the stating epoch so files are named properly
+ starting_epoch = 0
+ metric = evaluate.load("glue", "mrpc")
+ ending_epoch = num_epochs
+
+ if args.partial_train_epoch is not None:
+ ending_epoch = args.partial_train_epoch
+
+ if args.resume_from_checkpoint:
+ accelerator.load_state(args.resume_from_checkpoint)
+ epoch_string = args.resume_from_checkpoint.split("epoch_")[1]
+ state_epoch_num = ""
+ for char in epoch_string:
+ if char.isdigit():
+ state_epoch_num += char
+ else:
+ break
+ starting_epoch = int(state_epoch_num) + 1
+ accuracy = evaluation_loop(accelerator, model, eval_dataloader, metric)
+ accelerator.print("resumed checkpoint performance:", accuracy)
+ accelerator.print("resumed checkpoint's scheduler's lr:", lr_scheduler.get_lr()[0])
+ accelerator.print("resumed optimizers's lr:", optimizer.param_groups[0]["lr"])
+ with open(os.path.join(args.output_dir, f"state_{starting_epoch - 1}.json")) as f:
+ resumed_state = json.load(f)
+ assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed"
+ assert (
+ resumed_state["lr"] == lr_scheduler.get_lr()[0]
+ ), "Scheduler learning rate mismatch, loading from checkpoint failed"
+ assert (
+ resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"]
+ ), "Optimizer learning rate mismatch, loading from checkpoint failed"
+ assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed"
+ return
+
+ # Now we train the model
+ state = {}
+ for epoch in range(starting_epoch, ending_epoch):
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ outputs = model(**batch)
+ loss = outputs.loss
+ loss = loss / gradient_accumulation_steps
+ accelerator.backward(loss)
+ if step % gradient_accumulation_steps == 0:
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ overall_step += 1
+ output_dir = f"epoch_{epoch}"
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+ accuracy = evaluation_loop(accelerator, model, eval_dataloader, metric)
+ state["accuracy"] = accuracy
+ state["lr"] = lr_scheduler.get_lr()[0]
+ state["optimizer_lr"] = optimizer.param_groups[0]["lr"]
+ state["epoch"] = epoch
+ state["step"] = overall_step
+ accelerator.print(f"epoch {epoch}:", state)
+
+ accelerator.wait_for_everyone()
+ if accelerator.is_main_process:
+ with open(os.path.join(args.output_dir, f"state_{epoch}.json"), "w") as f:
+ json.dump(state, f)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.")
+ parser.add_argument(
+ "--model_name_or_path",
+ type=str,
+ default="bert-base-cased",
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
+ required=False,
+ )
+ parser.add_argument(
+ "--output_dir",
+ type=str,
+ default=".",
+ help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
+ )
+ parser.add_argument(
+ "--resume_from_checkpoint",
+ type=str,
+ default=None,
+ help="If the training should continue from a checkpoint folder.",
+ )
+ parser.add_argument(
+ "--partial_train_epoch",
+ type=int,
+ default=None,
+ help="If passed, the training will stop after this number of epochs.",
+ )
+ parser.add_argument(
+ "--num_epochs",
+ type=int,
+ default=2,
+ help="Number of train epochs.",
+ )
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16}
+
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_ds_multiple_model.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_ds_multiple_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..3729ecf4c72190bf865d620b6941206ab904818c
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_ds_multiple_model.py
@@ -0,0 +1,332 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+Test script for verifying multiple models can be utilized with Accelerate + DeepSpeed:
+
+Scenario 1: One model is training, another model is being used for inference/logits to impact training in some form.
+Scenario 2: Two models are training simultaneously, which means two optimizers, etc.
+"""
+
+import argparse
+from pathlib import Path
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup
+
+from accelerate import Accelerator, DeepSpeedPlugin, DistributedType
+from accelerate.state import AcceleratorState
+from accelerate.utils.deepspeed import get_active_deepspeed_plugin
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+class NoiseModel(torch.nn.Module):
+ def __init__(self, noise_factor=0.1):
+ super().__init__()
+ self.noise_factor = torch.nn.Parameter(torch.tensor(noise_factor, dtype=torch.float32))
+
+ def forward(self, loss):
+ return loss * self.noise_factor
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, model_name: str = "bert-base-cased"):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ model_name (`str`, *optional*):
+ """
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ tokenized_datasets = datasets.map(
+ tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ if accelerator.distributed_type == DistributedType.XLA:
+ return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt")
+ return tokenizer.pad(examples, padding="longest", return_tensors="pt")
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+test_file_path = __file__
+path = Path(test_file_path).resolve()
+test_file_dir_str = str(path.parent.parent.parent.parent.parent.parent)
+
+# Create our DS plugins
+# We use custom schedulers and optimizers, hence `model_only`
+ds_config_file = dict(
+ zero2=f"{test_file_dir_str}/tests/deepspeed/ds_config_zero2_model_only.json",
+ zero3=f"{test_file_dir_str}/tests/deepspeed/ds_config_zero3_model_only.json",
+)
+
+
+def single_model_training(config, args):
+ # Training a single model, we have a `noise` model that is untrainable used to inject some noise into the training process
+ num_epochs = config["num_epochs"]
+ zero2_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero2"])
+ zero3_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero3"])
+
+ deepspeed_plugins = {"training": zero2_plugin, "inference": zero3_plugin}
+
+ # Initialize accelerator
+ accelerator = Accelerator(
+ deepspeed_plugins=deepspeed_plugins,
+ mixed_precision="bf16",
+ )
+
+ # Initialize model under zero2 plugin
+ assert get_active_deepspeed_plugin(accelerator.state) is zero2_plugin
+ train_model = AutoModelForSequenceClassification.from_pretrained(args.model_name_or_path)
+ train_dataloader, eval_dataloader = get_dataloaders(
+ accelerator, batch_size=config["batch_size"], model_name=args.model_name_or_path
+ )
+ max_training_steps = len(train_dataloader) * config["num_epochs"]
+ optimizer = AdamW(train_model.parameters(), lr=config["lr"])
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer, num_warmup_steps=0, num_training_steps=max_training_steps
+ )
+
+ train_dataloader, eval_dataloader, train_model, optimizer, lr_scheduler = accelerator.prepare(
+ train_dataloader, eval_dataloader, train_model, optimizer, lr_scheduler
+ )
+
+ # Now prepare the model under zero3 plugin
+ accelerator.state.select_deepspeed_plugin("inference")
+ assert get_active_deepspeed_plugin(accelerator.state) is zero3_plugin
+ inference_model = NoiseModel()
+ inference_model = accelerator.prepare(inference_model)
+ inference_model.eval()
+
+ # Run training loop
+ accelerator.state.select_deepspeed_plugin("training")
+ # We also need to keep track of the stating epoch so files are named properly
+ starting_epoch = 0
+
+ # Now we train the model
+ best_performance = 0
+ metric = evaluate.load("glue", "mrpc")
+ performance_metric = {}
+ for epoch in range(starting_epoch, num_epochs):
+ train_model.train()
+ inference_model.train()
+ for step, batch in enumerate(train_dataloader):
+ with accelerator.accumulate(train_model):
+ outputs_1 = train_model(**batch)
+ with torch.no_grad():
+ outputs_2 = inference_model(outputs_1.loss)
+ # Combine the losses
+ loss = outputs_1.loss + outputs_2
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ train_model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ with torch.no_grad():
+ outputs = train_model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ # It is slightly faster to call this once, than multiple times
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+ performance_metric[f"epoch-{epoch}"] = eval_metric["accuracy"]
+
+ if best_performance < eval_metric["accuracy"]:
+ best_performance = eval_metric["accuracy"]
+ assert best_performance > performance_metric["epoch-0"]
+
+
+def multiple_model_training(config, args):
+ # This will essentially be like a k-fold model, but one model is Zero-2 and another model is Zero-3
+ num_epochs = config["num_epochs"]
+ zero2_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero2"])
+ zero3_plugin = DeepSpeedPlugin(hf_ds_config=ds_config_file["zero3"])
+
+ deepspeed_plugins = {"zero2": zero2_plugin, "zero3": zero3_plugin}
+
+ # Initialize accelerator
+ zero2_accelerator = Accelerator(
+ deepspeed_plugins=deepspeed_plugins,
+ mixed_precision="bf16",
+ )
+
+ # Since an `AcceleratorState` has already been made, we can just reuse it here
+ zero3_accelerator = Accelerator()
+
+ # Initialize model under zero2 plugin
+ assert get_active_deepspeed_plugin(zero2_accelerator.state) is zero2_plugin
+ zero2_model = AutoModelForSequenceClassification.from_pretrained(args.model_name_or_path)
+ train_dataloader, eval_dataloader = get_dataloaders(
+ zero2_accelerator, batch_size=config["batch_size"], model_name=args.model_name_or_path
+ )
+ max_training_steps = len(train_dataloader) * config["num_epochs"]
+ zero2_optimizer = AdamW(zero2_model.parameters(), lr=config["lr"])
+ zero2_lr_scheduler = get_linear_schedule_with_warmup(
+ zero2_optimizer, num_warmup_steps=0, num_training_steps=max_training_steps
+ )
+
+ train_dataloader, eval_dataloader, zero2_model, zero2_optimizer, zero2_lr_scheduler = zero2_accelerator.prepare(
+ train_dataloader, eval_dataloader, zero2_model, zero2_optimizer, zero2_lr_scheduler
+ )
+ assert zero2_accelerator.deepspeed_engine_wrapped.engine is zero2_model
+
+ # now do Zero3
+ zero3_accelerator.state.select_deepspeed_plugin("zero3")
+ zero3_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = zero2_plugin.deepspeed_config[
+ "train_micro_batch_size_per_gpu"
+ ]
+ assert get_active_deepspeed_plugin(zero3_accelerator.state) is zero3_plugin
+ zero3_model = AutoModelForSequenceClassification.from_pretrained(args.model_name_or_path)
+ zero3_optimizer = AdamW(zero3_model.parameters(), lr=config["lr"])
+ zero3_lr_scheduler = get_linear_schedule_with_warmup(
+ zero3_optimizer, num_warmup_steps=0, num_training_steps=max_training_steps
+ )
+ zero3_model, zero3_optimizer, zero3_lr_scheduler = zero3_accelerator.prepare(
+ zero3_model, zero3_optimizer, zero3_lr_scheduler
+ )
+ assert zero3_accelerator.deepspeed_engine_wrapped.engine is zero3_model
+
+ # Run training loop
+ starting_epoch = 0
+
+ # Now we train the model
+ best_performance_a = 0
+ best_performance_b = 0
+ metric_a = evaluate.load("glue", "mrpc")
+ metric_b = evaluate.load("glue", "mrpc")
+ performance_metric_a = {}
+ performance_metric_b = {}
+ for epoch in range(starting_epoch, num_epochs):
+ zero2_model.train()
+ zero3_model.train()
+ for step, batch in enumerate(train_dataloader):
+ with zero2_accelerator.accumulate(zero2_model, zero3_model):
+ outputs_1 = zero2_model(**batch)
+ zero2_accelerator.backward(outputs_1.loss)
+ zero2_optimizer.step()
+ zero2_lr_scheduler.step()
+ zero2_optimizer.zero_grad()
+ outputs_2 = zero3_model(**batch)
+ zero3_accelerator.backward(outputs_2.loss)
+ zero3_optimizer.step()
+ zero3_lr_scheduler.step()
+ zero3_optimizer.zero_grad()
+
+ zero2_model.eval()
+ zero3_model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ with torch.no_grad():
+ logits_a = zero2_model(**batch).logits
+ logits_b = zero3_model(**batch).logits
+ # Combine the logits from both models
+ predictions_a = logits_a.argmax(dim=-1)
+ predictions_b = logits_b.argmax(dim=-1)
+ # It is slightly faster to call this once, than multiple times
+ predictions_a, predictions_b, references = zero2_accelerator.gather_for_metrics(
+ (predictions_a, predictions_b, batch["labels"])
+ )
+ metric_a.add_batch(
+ predictions=predictions_a,
+ references=references,
+ )
+ metric_b.add_batch(
+ predictions=predictions_b,
+ references=references,
+ )
+
+ eval_metric_a = metric_a.compute()
+ eval_metric_b = metric_b.compute()
+ # Use accelerator.print to print only on the main process.
+ zero2_accelerator.print(f"epoch {epoch}:", eval_metric_a, eval_metric_b)
+ performance_metric_a[f"epoch-{epoch}"] = eval_metric_a["accuracy"]
+ performance_metric_b[f"epoch-{epoch}"] = eval_metric_b["accuracy"]
+
+ if best_performance_a < eval_metric_a["accuracy"]:
+ best_performance_a = eval_metric_a["accuracy"]
+ if best_performance_b < eval_metric_b["accuracy"]:
+ best_performance_b = eval_metric_b["accuracy"]
+ assert best_performance_a > performance_metric_a["epoch-0"]
+ assert best_performance_b > performance_metric_b["epoch-0"]
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.")
+ parser.add_argument(
+ "--model_name_or_path",
+ type=str,
+ default="bert-base-cased",
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
+ required=False,
+ )
+ parser.add_argument(
+ "--performance_lower_bound",
+ type=float,
+ default=None,
+ help="Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.",
+ )
+ parser.add_argument(
+ "--num_epochs",
+ type=int,
+ default=2,
+ help="Number of train epochs.",
+ )
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16}
+ single_model_training(config, args)
+ AcceleratorState._reset_state(True)
+ multiple_model_training(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_metrics.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..dfbf5c9f90ce0727523e3b43a1dce1600a514961
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_metrics.py
@@ -0,0 +1,307 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import logging
+import math
+import os
+from copy import deepcopy
+
+import datasets
+import evaluate
+import torch
+import transformers
+from datasets import load_dataset
+from torch.utils.data import DataLoader, IterableDataset
+from transformers import AutoModelForSequenceClassification, AutoTokenizer
+
+from accelerate import Accelerator, DataLoaderConfiguration, DistributedType
+from accelerate.data_loader import DataLoaderDispatcher
+from accelerate.test_utils import RegressionDataset, RegressionModel, torch_device
+from accelerate.utils import is_torch_xla_available, set_seed
+
+
+os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true"
+
+
+class ListHandler(logging.Handler):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.logs = []
+
+ def emit(self, record):
+ self.logs.append(record)
+
+
+def get_basic_setup(accelerator, num_samples=82, batch_size=16):
+ "Returns everything needed to perform basic training"
+ set_seed(42)
+ model = RegressionModel()
+ ddp_model = deepcopy(model)
+ dset = RegressionDataset(length=num_samples)
+ dataloader = DataLoader(dset, batch_size=batch_size)
+ model.to(accelerator.device)
+ ddp_model, dataloader = accelerator.prepare(ddp_model, dataloader)
+ return model, ddp_model, dataloader
+
+
+def get_dataloader(accelerator: Accelerator, use_longest=False):
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/mrpc-bert-base-cased")
+ dataset = load_dataset("glue", "mrpc", split="validation")
+
+ def tokenize_function(examples):
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ with accelerator.main_process_first():
+ tokenized_datasets = dataset.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ if use_longest:
+ return tokenizer.pad(examples, padding="longest", return_tensors="pt")
+ return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt")
+
+ return DataLoader(tokenized_datasets, shuffle=False, collate_fn=collate_fn, batch_size=16)
+
+
+def get_mrpc_setup(dispatch_batches, split_batches):
+ dataloader_config = DataLoaderConfiguration(dispatch_batches=dispatch_batches, split_batches=split_batches)
+ accelerator = Accelerator(dataloader_config=dataloader_config)
+ dataloader = get_dataloader(accelerator, not dispatch_batches)
+ model = AutoModelForSequenceClassification.from_pretrained(
+ "hf-internal-testing/mrpc-bert-base-cased", return_dict=True
+ )
+ ddp_model, ddp_dataloader = accelerator.prepare(model, dataloader)
+ return {
+ "ddp": [ddp_model, ddp_dataloader, torch_device],
+ "no": [model, dataloader, accelerator.device],
+ }, accelerator
+
+
+def generate_predictions(model, dataloader, accelerator):
+ logits_and_targets = []
+ for batch in dataloader:
+ input, target = batch.values()
+ with torch.no_grad():
+ logit = model(input)
+ logit, target = accelerator.gather_for_metrics((logit, target))
+ logits_and_targets.append((logit, target))
+ logits, targs = [], []
+ for logit, targ in logits_and_targets:
+ logits.append(logit)
+ targs.append(targ)
+ logits, targs = torch.cat(logits), torch.cat(targs)
+ return logits, targs
+
+
+def test_torch_metrics(
+ accelerator: Accelerator, num_samples=82, dispatch_batches=False, split_batches=False, batch_size=16
+):
+ _, ddp_model, dataloader = get_basic_setup(accelerator, num_samples, batch_size)
+ logits, _ = generate_predictions(ddp_model, dataloader, accelerator)
+ assert (
+ len(logits) == num_samples
+ ), f"Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(logits)}"
+
+
+def test_mrpc(dispatch_batches: bool = False, split_batches: bool = False):
+ metric = evaluate.load("glue", "mrpc")
+ setup, accelerator = get_mrpc_setup(dispatch_batches, split_batches)
+ # First do baseline
+ model, dataloader, device = setup["no"]
+ model.to(device)
+ model.eval()
+ for batch in dataloader:
+ batch.to(device)
+ with torch.inference_mode():
+ outputs = model(**batch)
+ preds = outputs.logits.argmax(dim=-1)
+ metric.add_batch(predictions=preds, references=batch["labels"])
+ baseline = metric.compute()
+
+ # Then do distributed
+ model, dataloader, device = setup["ddp"]
+ model.eval()
+ for batch in dataloader:
+ with torch.inference_mode():
+ outputs = model(**batch)
+ preds = outputs.logits.argmax(dim=-1)
+ references = batch["labels"]
+ preds, references = accelerator.gather_for_metrics((preds, references))
+ metric.add_batch(predictions=preds, references=references)
+ distributed = metric.compute()
+
+ for key in "accuracy f1".split():
+ assert math.isclose(
+ baseline[key], distributed[key]
+ ), f"Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n"
+
+
+def test_gather_for_metrics_with_non_tensor_objects_iterable_dataset():
+ class DummyIterableDataset(IterableDataset):
+ def __init__(self, data):
+ self.data = data
+
+ def __len__(self):
+ return len(self.data)
+
+ def __iter__(self):
+ yield from self.data
+
+ iterable_dataset = DummyIterableDataset([n for n in range(30)])
+ dataloader = DataLoader(iterable_dataset, batch_size=4)
+ accelerator = Accelerator()
+ prepared_dataloader = accelerator.prepare(dataloader)
+
+ if accelerator.is_main_process:
+ logger = logging.root.manager.loggerDict["accelerate.accelerator"]
+ list_handler = ListHandler()
+ logger.addHandler(list_handler)
+
+ batches_for_metrics = []
+ for batch in prepared_dataloader:
+ batches_for_metrics.append(accelerator.gather_for_metrics(batch))
+
+ assert torch.cat(batches_for_metrics).size(0) == 30
+
+ if accelerator.is_main_process:
+ assert len(list_handler.logs) == 0
+ logger.removeHandler(list_handler)
+
+
+def test_gather_for_metrics_with_iterable_dataset():
+ class DummyIterableDataset(IterableDataset):
+ def __init__(self, data):
+ self.data = data
+
+ def __len__(self):
+ return len(self.data)
+
+ def __iter__(self):
+ yield from self.data
+
+ iterable_dataset = DummyIterableDataset(torch.as_tensor(range(30)))
+ dataloader = DataLoader(iterable_dataset, batch_size=4)
+
+ accelerator = Accelerator()
+ prepared_dataloader = accelerator.prepare(dataloader)
+
+ assert isinstance(prepared_dataloader, DataLoaderDispatcher)
+
+ if accelerator.is_main_process:
+ logger = logging.root.manager.loggerDict["accelerate.accelerator"]
+ list_handler = ListHandler()
+ logger.addHandler(list_handler)
+
+ batches_for_metrics = []
+ for batch in prepared_dataloader:
+ batches_for_metrics.append(accelerator.gather_for_metrics(batch))
+
+ assert torch.cat(batches_for_metrics).size(0) == 30
+
+ if accelerator.is_main_process:
+ assert len(list_handler.logs) == 0
+
+ logger.removeHandler(list_handler)
+
+
+def test_gather_for_metrics_drop_last():
+ accelerator = Accelerator()
+ per_device_batch_size = 5
+ num_items = (10 * accelerator.num_processes) + 1
+ dataloader = DataLoader(range(num_items), batch_size=per_device_batch_size, drop_last=True)
+ dataloader = accelerator.prepare(dataloader)
+
+ iterator = iter(dataloader)
+ next(iterator) # Skip first batch tensor([0, 1, 2, 3, 4], device='cuda:0')
+ batch = next(iterator)
+ gathered_items = accelerator.gather_for_metrics(batch)
+
+ # Should return a full set of complete batches from each GPU
+ num_expected_items = per_device_batch_size * accelerator.num_processes
+ assert gathered_items.size(0) == (
+ num_expected_items
+ ), f"Expected number of items: {num_expected_items}, Actual: {gathered_items.size(0)}"
+
+
+def main():
+ dataloader_config = DataLoaderConfiguration(split_batches=False, dispatch_batches=False)
+ accelerator = Accelerator(dataloader_config=dataloader_config)
+ if accelerator.is_local_main_process:
+ datasets.utils.logging.set_verbosity_warning()
+ transformers.utils.logging.set_verbosity_warning()
+ else:
+ datasets.utils.logging.set_verbosity_error()
+ transformers.utils.logging.set_verbosity_error()
+ # TorchXLA does not support batch dispatching. 'put_on_device' is always False for
+ # TorchXLA, which can cause a value error in 'prepare_data_loader' function.
+ dispatch_batches_options = [False] if accelerator.state.distributed_type == DistributedType.XLA else [True, False]
+
+ # Temporarily close this test for TorchXLA due to the 'Cannot set version_counter for
+ # inference tensor' error in inference mode. Reopen it after TorchXLA fixes this bug.
+ # These are a bit slower so they should only be ran on the GPU or TPU
+ if accelerator.device.type != "cpu" and not is_torch_xla_available():
+ if accelerator.is_local_main_process:
+ print("**Testing gather_for_metrics**")
+ for split_batches in [True, False]:
+ for dispatch_batches in dispatch_batches_options:
+ if accelerator.is_local_main_process:
+ print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`")
+ test_mrpc(dispatch_batches, split_batches)
+ accelerator.state._reset_state()
+ print("test_gather_for_metrics_with_iterable_dataset")
+ test_gather_for_metrics_with_iterable_dataset()
+ print("test gather_for_metrics_with_non_tensor_objects_iterable_dataset")
+ test_gather_for_metrics_with_non_tensor_objects_iterable_dataset()
+
+ # MpDeviceLoader in TorchXLA is an asynchronous loader that preloads several batches into cache.
+ # This can cause the 'end_of_dataloader' of DataLoaderStateMixin to be set earlier than intended.
+ # Skip this test when TorchXLA is enabled.
+ if accelerator.state.distributed_type != DistributedType.XLA:
+ if accelerator.is_local_main_process:
+ print("**Test torch metrics**")
+ for split_batches in [True, False]:
+ for dispatch_batches in dispatch_batches_options:
+ dataloader_config = DataLoaderConfiguration(
+ split_batches=split_batches, dispatch_batches=dispatch_batches
+ )
+ accelerator = Accelerator(dataloader_config=dataloader_config)
+ if accelerator.is_local_main_process:
+ print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99")
+ test_torch_metrics(accelerator, 99)
+ accelerator.state._reset_state()
+ if accelerator.is_local_main_process:
+ print("**Test last batch is not dropped when perfectly divisible**")
+ accelerator = Accelerator()
+ test_torch_metrics(accelerator, 512)
+ accelerator.state._reset_state()
+ if accelerator.is_local_main_process:
+ print("**Test that `drop_last` is taken into account**")
+ test_gather_for_metrics_drop_last()
+ accelerator.end_training()
+ accelerator.state._reset_state()
+
+
+def _mp_fn(index):
+ # For xla_spawn (TPUs)
+ main()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..93e3a34ffb152dc250e764a60520d43f04b3b1f8
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py
@@ -0,0 +1,291 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import gc
+import json
+import os
+
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+from accelerate.utils import is_mlu_available, is_musa_available, is_npu_available, is_xpu_available
+from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+# Converting Bytes to Megabytes
+def b2mb(x):
+ return int(x / 2**20)
+
+
+# This context manager is used to track the peak memory usage of the process
+class TorchTracemalloc:
+ def __enter__(self):
+ gc.collect()
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
+ self.begin = torch.cuda.memory_allocated()
+ elif is_mlu_available():
+ torch.mlu.empty_cache()
+ torch.mlu.reset_max_memory_allocated() # reset the peak gauge to zero
+ self.begin = torch.mlu.memory_allocated()
+ elif is_musa_available():
+ torch.musa.empty_cache()
+ torch.musa.reset_max_memory_allocated() # reset the peak gauge to zero
+ self.begin = torch.musa.memory_allocated()
+ elif is_npu_available():
+ torch.npu.empty_cache()
+ torch.npu.reset_max_memory_allocated() # reset the peak gauge to zero
+ self.begin = torch.npu.memory_allocated()
+ elif is_xpu_available():
+ torch.xpu.empty_cache()
+ torch.xpu.reset_max_memory_allocated() # reset the peak gauge to zero
+ self.begin = torch.xpu.memory_allocated()
+ return self
+
+ def __exit__(self, *exc):
+ gc.collect()
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ self.end = torch.cuda.memory_allocated()
+ self.peak = torch.cuda.max_memory_allocated()
+ elif is_mlu_available():
+ torch.mlu.empty_cache()
+ torch.mlu.memory_allocated() # reset the peak gauge to zero
+ self.begin = torch.mlu.max_memory_allocated()
+ elif is_musa_available():
+ torch.musa.empty_cache()
+ torch.musa.memory_allocated() # reset the peak gauge to zero
+ self.begin = torch.musa.max_memory_allocated()
+ elif is_npu_available():
+ torch.npu.empty_cache()
+ self.end = torch.npu.memory_allocated()
+ self.peak = torch.npu.max_memory_allocated()
+ elif is_xpu_available():
+ torch.xpu.empty_cache()
+ self.end = torch.xpu.memory_allocated()
+ self.peak = torch.xpu.max_memory_allocated()
+ self.used = b2mb(self.end - self.begin)
+ self.peaked = b2mb(self.peak - self.begin)
+ # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")
+
+
+def get_dataloaders(
+ accelerator: Accelerator,
+ batch_size: int = 16,
+ model_name: str = "bert-base-cased",
+ n_train: int = 320,
+ n_val: int = 160,
+):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ model_name (`str`, *optional*):
+ The name of the model to use.
+ n_train (`int`, *optional*):
+ The number of training examples to use.
+ n_val (`int`, *optional*):
+ The number of validation examples to use.
+ """
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ datasets = load_dataset(
+ "glue", "mrpc", split={"train": f"train[:{n_train}]", "validation": f"validation[:{n_val}]"}
+ )
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ tokenized_datasets = datasets.map(
+ tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ if accelerator.distributed_type == DistributedType.XLA:
+ return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt")
+ return tokenizer.pad(examples, padding="longest", return_tensors="pt")
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+def training_function(config, args):
+ # Initialize accelerator
+ accelerator = Accelerator()
+
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+ model_name = args.model_name_or_path
+
+ set_seed(seed)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name, args.n_train, args.n_val)
+
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True)
+
+ # Instantiate optimizer
+ optimizer_cls = (
+ AdamW
+ if accelerator.state.deepspeed_plugin is None
+ or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
+ else DummyOptim
+ )
+ optimizer = optimizer_cls(params=model.parameters(), lr=lr)
+
+ if accelerator.state.deepspeed_plugin is not None:
+ gradient_accumulation_steps = accelerator.state.deepspeed_plugin.deepspeed_config[
+ "gradient_accumulation_steps"
+ ]
+ else:
+ gradient_accumulation_steps = 1
+ max_training_steps = (len(train_dataloader) * num_epochs) // gradient_accumulation_steps
+
+ # Instantiate scheduler
+ if (
+ accelerator.state.deepspeed_plugin is None
+ or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
+ ):
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=max_training_steps,
+ )
+ else:
+ lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0)
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # We need to keep track of how many total steps we have iterated over
+ overall_step = 0
+ # We also need to keep track of the stating epoch so files are named properly
+ starting_epoch = 0
+
+ # Now we train the model
+ train_total_peak_memory = {}
+ for epoch in range(starting_epoch, num_epochs):
+ with TorchTracemalloc() as tracemalloc:
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ outputs = model(**batch)
+ loss = outputs.loss
+ loss = loss / gradient_accumulation_steps
+ accelerator.backward(loss)
+ if step % gradient_accumulation_steps == 0:
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ overall_step += 1
+
+ # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
+ accelerator.print(f"Memory before entering the train : {b2mb(tracemalloc.begin)}")
+ accelerator.print(f"Memory consumed at the end of the train (end-begin): {tracemalloc.used}")
+ accelerator.print(f"Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}")
+ accelerator.print(
+ f"Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
+ )
+ train_total_peak_memory[f"epoch-{epoch}"] = tracemalloc.peaked + b2mb(tracemalloc.begin)
+ if args.peak_memory_upper_bound is not None:
+ assert (
+ train_total_peak_memory[f"epoch-{epoch}"] <= args.peak_memory_upper_bound
+ ), "Peak memory usage exceeded the upper bound"
+
+ accelerator.wait_for_everyone()
+ if accelerator.is_main_process:
+ with open(os.path.join(args.output_dir, "peak_memory_utilization.json"), "w") as f:
+ json.dump(train_total_peak_memory, f)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.")
+ parser.add_argument(
+ "--model_name_or_path",
+ type=str,
+ default="bert-base-cased",
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
+ required=False,
+ )
+ parser.add_argument(
+ "--output_dir",
+ type=str,
+ default=".",
+ help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
+ )
+ parser.add_argument(
+ "--peak_memory_upper_bound",
+ type=float,
+ default=None,
+ help="The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.",
+ )
+ parser.add_argument(
+ "--n_train",
+ type=int,
+ default=320,
+ help="Number of training examples to use.",
+ )
+ parser.add_argument(
+ "--n_val",
+ type=int,
+ default=160,
+ help="Number of validation examples to use.",
+ )
+ parser.add_argument(
+ "--num_epochs",
+ type=int,
+ default=1,
+ help="Number of train epochs.",
+ )
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_performance.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_performance.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1f7ddd579f1761777de488673dbf55ea3fc182d
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_performance.py
@@ -0,0 +1,244 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import json
+import os
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, model_name: str = "bert-base-cased"):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ model_name (`str`, *optional*):
+ """
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ tokenized_datasets = datasets.map(
+ tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ if accelerator.distributed_type == DistributedType.XLA:
+ return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt")
+ return tokenizer.pad(examples, padding="longest", return_tensors="pt")
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+def training_function(config, args):
+ # Initialize accelerator
+ accelerator = Accelerator()
+
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+ model_name = args.model_name_or_path
+
+ set_seed(seed)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name)
+
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True)
+
+ # Instantiate optimizer
+ optimizer_cls = (
+ AdamW
+ if accelerator.state.deepspeed_plugin is None
+ or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
+ else DummyOptim
+ )
+ optimizer = optimizer_cls(params=model.parameters(), lr=lr)
+
+ max_training_steps = len(train_dataloader) * num_epochs
+
+ # Instantiate scheduler
+ linear_decay_scheduler = False
+ if (
+ accelerator.state.deepspeed_plugin is None
+ or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
+ ):
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=max_training_steps,
+ )
+ linear_decay_scheduler = True
+ else:
+ lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0)
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # We also need to keep track of the stating epoch so files are named properly
+ starting_epoch = 0
+
+ # Now we train the model
+ metric = evaluate.load("glue", "mrpc")
+ best_performance = 0
+ performance_metric = {}
+ expected_lr_after_first_optim_step = lr * (
+ 1 - 1 / (max_training_steps / accelerator.num_processes / accelerator.gradient_accumulation_steps)
+ )
+ lr_scheduler_check_completed = False
+ for epoch in range(starting_epoch, num_epochs):
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ with accelerator.accumulate(model):
+ outputs = model(**batch)
+ loss = outputs.loss
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ # assert the learning rate after first optimizer step
+ if (
+ accelerator.sync_gradients
+ and not lr_scheduler_check_completed
+ and linear_decay_scheduler
+ and accelerator.state.mixed_precision == "no"
+ ):
+ assert (
+ lr_scheduler.get_last_lr()[0] == expected_lr_after_first_optim_step
+ ), f"Wrong lr found at second step, expected {expected_lr_after_first_optim_step}, got {lr_scheduler.get_last_lr()[0]}"
+ lr_scheduler_check_completed = True
+
+ model.eval()
+ samples_seen = 0
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ # It is slightly faster to call this once, than multiple times
+ predictions, references = accelerator.gather(
+ (predictions, batch["labels"])
+ ) # If we are in a multiprocess environment, the last batch has duplicates
+ if accelerator.use_distributed:
+ if step == len(eval_dataloader) - 1:
+ predictions = predictions[: len(eval_dataloader.dataset) - samples_seen]
+ references = references[: len(eval_dataloader.dataset) - samples_seen]
+ else:
+ samples_seen += references.shape[0]
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+ performance_metric[f"epoch-{epoch}"] = eval_metric["accuracy"]
+
+ if best_performance < eval_metric["accuracy"]:
+ best_performance = eval_metric["accuracy"]
+
+ # check that the LR is 0
+ if linear_decay_scheduler and accelerator.state.mixed_precision == "no":
+ assert (
+ lr_scheduler.get_last_lr()[0] == 0
+ ), f"Wrong lr found at last step, expected 0, got {lr_scheduler.get_last_lr()[0]}"
+
+ if args.performance_lower_bound is not None:
+ assert (
+ args.performance_lower_bound <= best_performance
+ ), f"Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}"
+
+ accelerator.wait_for_everyone()
+ if accelerator.is_main_process:
+ with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
+ json.dump(performance_metric, f)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.")
+ parser.add_argument(
+ "--model_name_or_path",
+ type=str,
+ default="bert-base-cased",
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
+ required=False,
+ )
+ parser.add_argument(
+ "--output_dir",
+ type=str,
+ default=".",
+ help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
+ )
+ parser.add_argument(
+ "--performance_lower_bound",
+ type=float,
+ default=None,
+ help="Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.",
+ )
+ parser.add_argument(
+ "--num_epochs",
+ type=int,
+ default=3,
+ help="Number of train epochs.",
+ )
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_pippy.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_pippy.py
new file mode 100644
index 0000000000000000000000000000000000000000..389b963e0cb544c4b9eb08ad72f871ecead30f01
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_pippy.py
@@ -0,0 +1,116 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import torch
+from transformers import (
+ BertConfig,
+ BertForMaskedLM,
+ GPT2Config,
+ GPT2ForSequenceClassification,
+)
+
+from accelerate import PartialState
+from accelerate.inference import prepare_pippy
+from accelerate.utils import DistributedType, set_seed
+
+
+model_to_config = {
+ "bert": (BertForMaskedLM, BertConfig, 512),
+ "gpt2": (GPT2ForSequenceClassification, GPT2Config, 1024),
+}
+
+
+def get_model_and_data_for_text(model_name, device, num_processes: int = 2):
+ initializer, config, seq_len = model_to_config[model_name]
+ config_args = {}
+ # Eventually needed for batch inference tests on gpt-2 when bs != 1
+ # if model_name == "gpt2":
+ # config_args["pad_token_id"] = 0
+ model_config = config(**config_args)
+ model = initializer(model_config)
+ kwargs = dict(low=0, high=model_config.vocab_size, device=device, dtype=torch.int64, requires_grad=False)
+ trace_input = torch.randint(size=(1, seq_len), **kwargs)
+ inference_inputs = torch.randint(size=(num_processes, seq_len), **kwargs)
+ return model, trace_input, inference_inputs
+
+
+def test_bert(batch_size: int = 2):
+ set_seed(42)
+ state = PartialState()
+ model, trace_input, inference_inputs = get_model_and_data_for_text("bert", "cpu", batch_size)
+ model = prepare_pippy(model, example_args=(trace_input,), no_split_module_classes=model._no_split_modules)
+ # For inference args need to be a tuple
+ inputs = inference_inputs.to("cuda")
+ with torch.no_grad():
+ output = model(inputs)
+ # Zach: Check that we just grab the real outputs we need at the end
+ if not state.is_last_process:
+ assert output is None, "Output was not generated on just the last process!"
+ else:
+ assert output is not None, "Output was not generated in the last process!"
+
+
+def test_gpt2(batch_size: int = 2):
+ set_seed(42)
+ state = PartialState()
+ model, trace_input, inference_inputs = get_model_and_data_for_text("gpt2", "cpu", batch_size)
+ model = prepare_pippy(model, example_args=(trace_input,), no_split_module_classes=model._no_split_modules)
+ # For inference args need to be a tuple
+ inputs = inference_inputs.to("cuda")
+ with torch.no_grad():
+ output = model(inputs)
+ # Zach: Check that we just grab the real outputs we need at the end
+ if not state.is_last_process:
+ assert output is None, "Output was not generated on just the last process!"
+ else:
+ assert output is not None, "Output was not generated in the last process!"
+
+
+# Currently disabled, enable again once PyTorch pippy interface can trace a resnet34
+# def test_resnet(batch_size: int = 2):
+# set_seed(42)
+# state = PartialState()
+# model = resnet34()
+# input_tensor = torch.rand(1, 3, 224, 224)
+# model = prepare_pippy(
+# model,
+# example_args=(input_tensor,),
+# )
+# inference_inputs = torch.rand(batch_size, 3, 224, 224)
+# inputs = send_to_device(inference_inputs, "cuda:0")
+# with torch.no_grad():
+# output = model(inputs)
+# # Zach: Check that we just grab the real outputs we need at the end
+# if not state.is_last_process:
+# assert output is None, "Output was not generated on just the last process!"
+# else:
+# assert output is not None, "Output was not generated in the last process!"
+
+
+if __name__ == "__main__":
+ state = PartialState()
+ state.print("Testing pippy integration...")
+ try:
+ if state.distributed_type == DistributedType.MULTI_GPU:
+ state.print("Testing GPT2...")
+ test_gpt2()
+ # Issue: When modifying the tokenizer for batch GPT2 inference, there's an issue
+ # due to references
+ # NameError: cannot access free variable 'chunk_args_list' where it is not associated with a value in enclosing scope
+ # test_gpt2(3)
+ state.print("Testing BERT...")
+ test_bert()
+ else:
+ print("Less than two GPUs found, not running tests!")
+ finally:
+ state.destroy_process_group()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bbb324c8cde4611a53cb94b721e0258c6ba7f56
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py
@@ -0,0 +1,53 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import torch.distributed
+
+from accelerate.test_utils import require_huggingface_suite, torch_device
+from accelerate.utils import is_transformers_available
+
+
+if is_transformers_available():
+ from transformers import AutoModel, TrainingArguments
+
+
+GPT2_TINY = "sshleifer/tiny-gpt2"
+
+
+@require_huggingface_suite
+def init_torch_dist_then_launch_deepspeed():
+ backend = "ccl" if torch_device == "xpu" else "nccl"
+ torch.distributed.init_process_group(backend=backend)
+ deepspeed_config = {
+ "zero_optimization": {
+ "stage": 3,
+ },
+ "train_batch_size": "auto",
+ "train_micro_batch_size_per_gpu": "auto",
+ }
+ train_args = TrainingArguments(
+ output_dir="./",
+ deepspeed=deepspeed_config,
+ )
+ model = AutoModel.from_pretrained(GPT2_TINY)
+ assert train_args is not None
+ assert model is not None
+
+
+def main():
+ init_torch_dist_then_launch_deepspeed()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_cli.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..c85828cd49624372ae1866082e5580c60f8c9293
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_cli.py
@@ -0,0 +1,26 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import torch
+
+
+def main():
+ if torch.cuda.is_available():
+ num_gpus = torch.cuda.device_count()
+ else:
+ num_gpus = 0
+ print(f"Successfully ran on {num_gpus} GPUs")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_ddp_comm_hook.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_ddp_comm_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..01c939db15bebf59c3666e56706b7225e63e8342
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_ddp_comm_hook.py
@@ -0,0 +1,78 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import torch
+
+from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs, PartialState
+
+
+class MockModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ torch.manual_seed(0)
+ self.p = torch.nn.Parameter(torch.randn(40, 20))
+
+ def forward(self, x, rank):
+ return self.p * (x ** (1 + rank))
+
+
+def _run_and_get_grads(model, rank):
+ torch.manual_seed(2024)
+ input = torch.randn(40, 20)
+ output = model(input, rank)
+ output.mean().backward()
+ param = next(model.parameters())
+ return param.grad
+
+
+def test_ddp_comm_hook(comm_hook, comm_wrapper, comm_state_option):
+ ddp_kwargs = DistributedDataParallelKwargs(
+ comm_hook=comm_hook,
+ comm_wrapper=comm_wrapper,
+ comm_state_option=comm_state_option,
+ )
+ accelerator = Accelerator(kwargs_handlers=[ddp_kwargs])
+
+ model = accelerator.prepare(MockModel())
+ hook_grads = _run_and_get_grads(model, accelerator.local_process_index)
+
+ reference_model = torch.nn.parallel.DistributedDataParallel(
+ MockModel().to(accelerator.device),
+ device_ids=[accelerator.local_process_index],
+ output_device=accelerator.local_process_index,
+ )
+ reference_grads = _run_and_get_grads(reference_model, accelerator.local_process_index)
+
+ torch.testing.assert_close(hook_grads, reference_grads, rtol=1e-2, atol=1e-2)
+
+
+def main():
+ for comm_hook, comm_wrapper, comm_state_option in [
+ (DDPCommunicationHookType.NO, DDPCommunicationHookType.NO, {}),
+ (DDPCommunicationHookType.FP16, DDPCommunicationHookType.NO, {}),
+ (DDPCommunicationHookType.BF16, DDPCommunicationHookType.NO, {}),
+ (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.NO, {}),
+ (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.FP16, {}),
+ (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.BF16, {}),
+ (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.NO, {"matrix_approximation_rank": 2}),
+ (DDPCommunicationHookType.BATCHED_POWER_SGD, DDPCommunicationHookType.NO, {}),
+ (DDPCommunicationHookType.BATCHED_POWER_SGD, DDPCommunicationHookType.FP16, {}),
+ (DDPCommunicationHookType.BATCHED_POWER_SGD, DDPCommunicationHookType.BF16, {}),
+ ]:
+ print(f"Test DDP comm hook: {comm_hook}, comm wrapper: {comm_wrapper}")
+ test_ddp_comm_hook(comm_hook, comm_wrapper, comm_state_option)
+ PartialState().destroy_process_group()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_distributed_data_loop.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_distributed_data_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..899dc6e3f876bad23207a7d74552de17cd0c9336
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_distributed_data_loop.py
@@ -0,0 +1,410 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import pickle
+import tempfile
+import warnings
+from typing import List
+from unittest.mock import Mock
+
+import torch
+from torch.utils.data import (
+ BatchSampler,
+ DataLoader,
+ Dataset,
+ IterableDataset,
+ RandomSampler,
+ TensorDataset,
+ default_collate,
+)
+
+from accelerate.accelerator import Accelerator, DataLoaderConfiguration
+from accelerate.utils.dataclasses import DistributedType
+
+
+NUM_ELEMENTS = 22
+NUM_WORKERS = 4
+BATCH_SIZE = 4
+
+
+class DummyDataset(Dataset):
+ def __len__(self):
+ return NUM_ELEMENTS
+
+ def __getitem__(self, index):
+ squeeze = False
+
+ if isinstance(index, int):
+ index = [index]
+ squeeze = True
+ elif isinstance(index, slice):
+ index = list(range(*index.indices(self.size)))
+ else:
+ index = list(index)
+
+ batch = [{"index": i, "label": i % 2, "random_augmentation": torch.rand(1).item()} for i in index]
+
+ if squeeze:
+ batch = batch[0]
+
+ return batch
+
+
+class DummyIterableDataset(IterableDataset):
+ def __init__(self, data):
+ self.data = data
+
+ def __iter__(self):
+ yield from self.data
+
+
+def create_accelerator(even_batches=True):
+ dataloader_config = DataLoaderConfiguration(even_batches=even_batches)
+ accelerator = Accelerator(dataloader_config=dataloader_config)
+ assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
+ return accelerator
+
+
+def create_dataloader(
+ accelerator: Accelerator, dataset_size: int, batch_size: int, iterable: bool = False, shuffle: bool = False
+):
+ """
+ Create a simple DataLoader to use during the test cases
+ """
+ values = torch.as_tensor(range(dataset_size))
+ if shuffle:
+ values = values[torch.randperm(values.size(0))]
+ if iterable:
+ dataset = DummyIterableDataset(values)
+ else:
+ dataset = TensorDataset(torch.as_tensor(range(dataset_size)))
+
+ dl = DataLoader(dataset, batch_size=batch_size)
+ dl = accelerator.prepare(dl)
+
+ return dl
+
+
+def verify_dataloader_batch_sizes(
+ accelerator: Accelerator,
+ dataset_size: int,
+ batch_size: int,
+ process_0_expected_batch_sizes: List[int],
+ process_1_expected_batch_sizes: List[int],
+):
+ """
+ A helper function for verifying the batch sizes coming from a prepared dataloader in each process
+ """
+ dl = create_dataloader(accelerator=accelerator, dataset_size=dataset_size, batch_size=batch_size)
+
+ batch_sizes = [len(batch[0]) for batch in dl]
+
+ if accelerator.process_index == 0:
+ assert batch_sizes == process_0_expected_batch_sizes
+ elif accelerator.process_index == 1:
+ assert batch_sizes == process_1_expected_batch_sizes
+
+
+def test_default_ensures_even_batch_sizes():
+ accelerator = create_accelerator()
+
+ # without padding, we would expect a different number of batches
+ verify_dataloader_batch_sizes(
+ accelerator,
+ dataset_size=3,
+ batch_size=1,
+ process_0_expected_batch_sizes=[1, 1],
+ process_1_expected_batch_sizes=[1, 1],
+ )
+
+ # without padding, we would expect the same number of batches, but different sizes
+ verify_dataloader_batch_sizes(
+ accelerator,
+ dataset_size=7,
+ batch_size=2,
+ process_0_expected_batch_sizes=[2, 2],
+ process_1_expected_batch_sizes=[2, 2],
+ )
+
+
+def test_can_disable_even_batches():
+ accelerator = create_accelerator(even_batches=False)
+
+ verify_dataloader_batch_sizes(
+ accelerator,
+ dataset_size=3,
+ batch_size=1,
+ process_0_expected_batch_sizes=[1, 1],
+ process_1_expected_batch_sizes=[1],
+ )
+
+ verify_dataloader_batch_sizes(
+ accelerator,
+ dataset_size=7,
+ batch_size=2,
+ process_0_expected_batch_sizes=[2, 2],
+ process_1_expected_batch_sizes=[2, 1],
+ )
+
+
+def test_can_join_uneven_inputs():
+ accelerator = create_accelerator(even_batches=False)
+
+ model = torch.nn.Linear(1, 1)
+ ddp_model = accelerator.prepare(model)
+
+ dl = create_dataloader(accelerator, dataset_size=3, batch_size=1)
+
+ batch_idxs = []
+ with accelerator.join_uneven_inputs([ddp_model]):
+ for batch_idx, batch in enumerate(dl):
+ output = ddp_model(batch[0].float())
+ loss = output.sum()
+ loss.backward()
+ batch_idxs.append(batch_idx)
+
+ accelerator.wait_for_everyone()
+
+ if accelerator.process_index == 0:
+ assert batch_idxs == [0, 1]
+ elif accelerator.process_index == 1:
+ assert batch_idxs == [0]
+
+
+def test_join_raises_warning_for_non_ddp_distributed(accelerator):
+ with warnings.catch_warnings(record=True) as w:
+ with accelerator.join_uneven_inputs([Mock()]):
+ pass
+
+ assert issubclass(w[-1].category, UserWarning)
+ assert "only supported for multi-GPU" in str(w[-1].message)
+
+
+def test_join_can_override_even_batches():
+ default_even_batches = True
+ overridden_even_batches = False
+ accelerator = create_accelerator(even_batches=default_even_batches)
+ model = torch.nn.Linear(1, 1)
+ ddp_model = accelerator.prepare(model)
+ train_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1)
+ valid_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1)
+
+ with accelerator.join_uneven_inputs([ddp_model], even_batches=overridden_even_batches):
+ train_dl_overridden_value = train_dl.batch_sampler.even_batches
+ valid_dl_overridden_value = valid_dl.batch_sampler.even_batches
+
+ assert train_dl_overridden_value == overridden_even_batches
+ assert valid_dl_overridden_value == overridden_even_batches
+ assert train_dl.batch_sampler.even_batches == default_even_batches
+ assert valid_dl.batch_sampler.even_batches == default_even_batches
+
+
+def test_join_can_override_for_mixed_type_dataloaders():
+ default_even_batches = True
+ overridden_even_batches = False
+ accelerator = create_accelerator(even_batches=default_even_batches)
+ model = torch.nn.Linear(1, 1)
+ ddp_model = accelerator.prepare(model)
+ create_dataloader(accelerator, dataset_size=3, batch_size=1, iterable=True)
+ batch_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore")
+ try:
+ with accelerator.join_uneven_inputs([ddp_model], even_batches=overridden_even_batches):
+ batch_dl_overridden_value = batch_dl.batch_sampler.even_batches
+ except AttributeError:
+ # ensure attribute error is not raised when processing iterable dl
+ raise AssertionError
+
+ assert batch_dl_overridden_value == overridden_even_batches
+ assert batch_dl.batch_sampler.even_batches == default_even_batches
+
+
+def test_join_raises_warning_for_iterable_when_overriding_even_batches():
+ accelerator = create_accelerator()
+ model = torch.nn.Linear(1, 1)
+ ddp_model = accelerator.prepare(model)
+ create_dataloader(accelerator, dataset_size=3, batch_size=1, iterable=True)
+
+ with warnings.catch_warnings(record=True) as w:
+ with accelerator.join_uneven_inputs([ddp_model], even_batches=False):
+ pass
+
+ assert issubclass(w[-1].category, UserWarning)
+ assert "only supported for map-style datasets" in str(w[-1].message)
+
+
+def test_pickle_accelerator():
+ accelerator = create_accelerator()
+ data_loader = create_dataloader(accelerator, dataset_size=32, batch_size=4)
+ _ = accelerator.prepare(data_loader)
+ pickled_accelerator = pickle.dumps(accelerator)
+ unpickled_accelerator = pickle.loads(pickled_accelerator)
+ # TODO: Maybe this should be implemented as __eq__ for AcceleratorState?
+ assert accelerator.state.__dict__ == unpickled_accelerator.state.__dict__
+
+
+def test_data_loader(data_loader, accelerator):
+ # Prepare the DataLoader
+ data_loader = accelerator.prepare(data_loader)
+
+ all_examples = []
+ for i, batch in enumerate(data_loader):
+ index, _ = accelerator.gather_for_metrics((batch["index"], batch["label"]))
+ all_examples.extend(index.detach().cpu().numpy().tolist())
+
+ # Sort the examples
+ sorted_all_examples = sorted(all_examples)
+
+ # Check if all elements are present in the sorted list of iterated samples
+ assert (
+ len(set(sorted_all_examples)) == NUM_ELEMENTS
+ ), "Not all the dataset elements have been iterated in an epoch due to duplication of samples across processes."
+
+
+def test_stateful_dataloader(accelerator):
+ """
+ Tests that a stateful dataloader can be iterated over, saved after a few batches using `load_state_dict`, and then
+ resumed from the saved state.
+
+ The result should be the same as the rest of the data that iterated over after saving.
+ """
+ old_dataloader_config = accelerator.dataloader_config
+ try:
+ accelerator.dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=True)
+ prepared_dl = create_dataloader(
+ accelerator, dataset_size=32 * accelerator.num_processes, batch_size=4, iterable=True, shuffle=True
+ )
+ untrained_batches = []
+ # Calculate what step that will be
+ total_batches = 32 * accelerator.num_processes // (4 * accelerator.num_processes)
+ last_batch_num = total_batches - 1
+ for step, batch in enumerate(prepared_dl):
+ # Step just before
+ if step == last_batch_num - 1:
+ state_dict = prepared_dl.state_dict()
+ if step >= last_batch_num:
+ # Otherwise grab the "unseen" batches
+ untrained_batches.append(batch)
+ not_skipped_batches = accelerator.gather(untrained_batches)
+ prepared_dl.load_state_dict(state_dict)
+ resumed_batches = []
+ for batch in prepared_dl:
+ resumed_batches.append(batch)
+ resumed_batches = accelerator.gather(resumed_batches)
+ for b1, b2 in zip(not_skipped_batches, resumed_batches):
+ for v1, v2 in zip(b1, b2):
+ assert torch.equal(v1, v2), f"Batch {b1} and {b2} are not equal"
+ finally:
+ accelerator.dataloader_config = old_dataloader_config
+
+
+def test_stateful_dataloader_save_state(accelerator):
+ """
+ Tests that a stateful dataloader can be iterated over, saved after a few batches using `Accelerator.save_state`,
+ and then resumed from the saved state.
+
+ The result should be the same as the rest of the data that iterated over after saving.
+ """
+ old_dataloader_config = accelerator.dataloader_config
+ try:
+ with tempfile.TemporaryDirectory() as tmpdir:
+ accelerator.dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=True)
+ prepared_dl = create_dataloader(
+ accelerator, dataset_size=32 * accelerator.num_processes, batch_size=4, iterable=True, shuffle=True
+ )
+ untrained_batches = []
+ # Calculate what step that will be
+ total_batches = 32 * accelerator.num_processes // (4 * accelerator.num_processes)
+ last_batch_num = total_batches - 1
+ for step, batch in enumerate(prepared_dl):
+ # Step just before
+ if step == last_batch_num - 1:
+ accelerator.save_state(tmpdir)
+ if step >= last_batch_num:
+ # Otherwise grab the "unseen" batches
+ untrained_batches.append(batch)
+ not_skipped_batches = accelerator.gather(untrained_batches)
+ accelerator.load_state(tmpdir)
+ resumed_batches = []
+ for batch in prepared_dl:
+ resumed_batches.append(batch)
+ resumed_batches = accelerator.gather(resumed_batches)
+ for b1, b2 in zip(not_skipped_batches, resumed_batches):
+ for v1, v2 in zip(b1, b2):
+ assert torch.equal(v1, v2), f"Batch {b1} and {b2} are not equal"
+ finally:
+ accelerator.dataloader_config = old_dataloader_config
+
+
+def main():
+ accelerator = create_accelerator()
+ torch.manual_seed(accelerator.process_index)
+
+ accelerator.print("Test that even_batches variable ensures uniform batches across processes")
+ test_default_ensures_even_batch_sizes()
+
+ accelerator.print("Run tests with even_batches disabled")
+ test_can_disable_even_batches()
+
+ accelerator.print("Test joining uneven inputs")
+ test_can_join_uneven_inputs()
+
+ accelerator.print("Test overriding even_batches when joining uneven inputs")
+ test_join_can_override_even_batches()
+
+ accelerator.print("Test overriding even_batches for mixed dataloader types")
+ test_join_can_override_for_mixed_type_dataloaders()
+
+ accelerator.print("Test overriding even_batches raises a warning for iterable dataloaders")
+ test_join_raises_warning_for_iterable_when_overriding_even_batches()
+
+ accelerator.print("Test join with non DDP distributed raises warning")
+ original_state = accelerator.state.distributed_type
+ accelerator.state.distributed_type = DistributedType.FSDP
+ test_join_raises_warning_for_non_ddp_distributed(accelerator)
+ accelerator.state.distributed_type = original_state
+
+ accelerator.print("Test pickling an accelerator")
+ test_pickle_accelerator()
+
+ dataset = DummyDataset()
+ # Conventional Dataloader with shuffle=False
+ loader = DataLoader(dataset, shuffle=False, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS)
+ test_data_loader(loader, accelerator)
+
+ # Conventional Dataloader with shuffle=True
+ loader = DataLoader(dataset, shuffle=True, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS)
+ test_data_loader(loader, accelerator)
+
+ # Dataloader with batch_sampler
+ sampler = BatchSampler(RandomSampler(dataset), batch_size=BATCH_SIZE, drop_last=False)
+ loader = DataLoader(dataset, batch_sampler=sampler, num_workers=NUM_WORKERS)
+ test_data_loader(loader, accelerator)
+
+ # Dataloader with sampler as an instance of `BatchSampler`
+ sampler = BatchSampler(RandomSampler(dataset), batch_size=BATCH_SIZE, drop_last=False)
+ loader = DataLoader(dataset, sampler=sampler, batch_size=None, collate_fn=default_collate, num_workers=NUM_WORKERS)
+ test_data_loader(loader, accelerator)
+ test_stateful_dataloader(accelerator)
+ test_stateful_dataloader_save_state(accelerator)
+
+ accelerator.end_training()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_merge_weights.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_merge_weights.py
new file mode 100644
index 0000000000000000000000000000000000000000..a13908640476137b35011ed3f8dc36916c808fce
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_merge_weights.py
@@ -0,0 +1,161 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import gc
+import logging
+import shutil
+from pathlib import Path
+
+import torch
+from safetensors.torch import load_file
+from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy, StateDictType
+from torch.utils.data import DataLoader
+
+from accelerate import Accelerator, FullyShardedDataParallelPlugin
+from accelerate.commands.merge import merge_command, merge_command_parser
+from accelerate.state import AcceleratorState
+from accelerate.test_utils.training import RegressionDataset
+from accelerate.utils import merge_fsdp_weights, patch_environment, save_fsdp_model
+
+
+logging.basicConfig(level=logging.INFO)
+
+parser = merge_command_parser()
+
+
+class TinyModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = torch.nn.Linear(16, 16)
+ self.activation = torch.nn.ReLU()
+ self.linear2 = torch.nn.Linear(16, 16)
+ self.softmax = torch.nn.Softmax()
+
+ def forward(self, x):
+ return self.linear2(self.activation(self.linear1(x)))
+
+
+def setup():
+ if AcceleratorState._shared_state != {}:
+ AcceleratorState()._reset_state()
+ plugin = FullyShardedDataParallelPlugin(
+ sharding_strategy=ShardingStrategy.FULL_SHARD, state_dict_type=StateDictType.SHARDED_STATE_DICT
+ )
+ model = TinyModel()
+ with patch_environment(fsdp_auto_wrap_policy="SIZE_BASED_WRAP"):
+ plugin.set_auto_wrap_policy(model)
+ accelerator = Accelerator(fsdp_plugin=plugin)
+ model = accelerator.prepare(model)
+ return model, plugin, accelerator
+
+
+def mock_training(accelerator, model):
+ train_set = RegressionDataset(length=128, seed=42)
+ train_dl = DataLoader(train_set, batch_size=16, shuffle=False)
+ optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
+
+ train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer)
+ for _ in range(3):
+ for batch in train_dl:
+ model.zero_grad()
+ output = model(batch["x"])
+ loss = torch.nn.functional.mse_loss(output, batch["y"])
+ accelerator.backward(loss)
+ optimizer.step()
+ return model
+
+
+def check_weights(operation, state_1, state_2):
+ for weight_1, weight_2 in zip(state_1.values(), state_2.values()):
+ if str(weight_1.device) != "cuda":
+ weight_1 = weight_1.to("cuda")
+ if str(weight_2.device) != "cuda":
+ weight_2 = weight_2.to("cuda")
+ if operation == "same":
+ assert torch.allclose(weight_1, weight_2)
+ else:
+ assert not torch.allclose(weight_1, weight_2)
+
+
+def check_safetensors_weights(path, model):
+ safe_state_dict = load_file(path / "model.safetensors")
+ safe_loaded_model = TinyModel()
+ check_weights("diff", model.state_dict(), safe_loaded_model.state_dict())
+ safe_loaded_model.load_state_dict(safe_state_dict)
+ check_weights("same", model.state_dict(), safe_loaded_model.state_dict())
+
+
+def check_pytorch_weights(path, model):
+ nonsafe_state_dict = torch.load(path / "pytorch_model.bin")
+ nonsafe_loaded_model = TinyModel()
+ check_weights("diff", model.state_dict(), nonsafe_loaded_model.state_dict())
+ nonsafe_loaded_model.load_state_dict(nonsafe_state_dict)
+ check_weights("same", model.state_dict(), nonsafe_loaded_model.state_dict())
+
+
+def test_merge_weights_safetensors(model, path):
+ # Should now be saved at `path/merged.safetensors`
+ merge_fsdp_weights(path / "pytorch_model_fsdp_0", path, safe_serialization=True)
+ check_safetensors_weights(path, model)
+
+
+def test_merge_weights_command_safetensors(model, path):
+ args = parser.parse_args([str(path / "pytorch_model_fsdp_0"), str(path)])
+ merge_command(args)
+ check_safetensors_weights(path, model)
+
+
+def test_merge_weights_pytorch(model, path):
+ # Should now be saved at `path/merged.bin`
+ merge_fsdp_weights(path / "pytorch_model_fsdp_0", path, safe_serialization=False)
+ check_pytorch_weights(path, model)
+
+
+def test_merge_weights_command_pytorch(model, path):
+ args = parser.parse_args([str(path / "pytorch_model_fsdp_0"), str(path), "--unsafe_serialization"])
+ merge_command(args)
+ check_pytorch_weights(path, model)
+
+
+if __name__ == "__main__":
+ # Note this test requires at least two accelerators!
+ model, plugin, accelerator = setup()
+ if accelerator.num_processes > 1:
+ try:
+ # Initial setup for things
+ out_path = Path("test_merge_weights_fsdp_weights")
+ if not out_path.exists():
+ out_path.mkdir(parents=True, exist_ok=True)
+
+ # Train briefly once weights aren't the baseline
+ model = mock_training(accelerator, model)
+ accelerator.wait_for_everyone()
+
+ gc.collect() # Needed for some lingering refs after training
+ save_fsdp_model(plugin, accelerator, model, out_path)
+ accelerator.wait_for_everyone()
+
+ # Finally we can test
+ test_merge_weights_safetensors(model, out_path)
+ test_merge_weights_command_safetensors(model, out_path)
+ test_merge_weights_pytorch(model, out_path)
+ test_merge_weights_command_pytorch(model, out_path)
+ except Exception:
+ raise
+ finally:
+ # Cleanup in case of any failures
+ if accelerator.is_main_process:
+ shutil.rmtree(out_path)
+ accelerator.wait_for_everyone()
+ accelerator.end_training()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_notebook.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_notebook.py
new file mode 100644
index 0000000000000000000000000000000000000000..267c11b50b22250e781f94e3643b8895cc6aeb02
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_notebook.py
@@ -0,0 +1,118 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Test file to ensure that in general certain situational setups for notebooks work.
+"""
+
+import os
+import time
+from multiprocessing import Queue
+
+from pytest import mark, raises
+from torch.distributed.elastic.multiprocessing.errors import ChildFailedError
+
+from accelerate import PartialState, notebook_launcher
+from accelerate.test_utils import require_bnb
+from accelerate.utils import is_bnb_available
+
+
+def basic_function():
+ # Just prints the PartialState
+ print(f"PartialState:\n{PartialState()}")
+
+
+def tough_nut_function(queue: Queue):
+ if queue.empty():
+ return
+ trial = queue.get()
+ if trial > 0:
+ queue.put(trial - 1)
+ raise RuntimeError("The nut hasn't cracked yet! Try again.")
+
+ print(f"PartialState:\n{PartialState()}")
+
+
+def bipolar_sleep_function(sleep_sec: int):
+ state = PartialState()
+ if state.process_index % 2 == 0:
+ raise RuntimeError("I'm an even process. I don't like to sleep.")
+ else:
+ time.sleep(sleep_sec)
+
+
+NUM_PROCESSES = int(os.environ.get("ACCELERATE_NUM_PROCESSES", 1))
+
+
+def test_can_initialize():
+ notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES)
+
+
+@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test static rendezvous backends")
+def test_static_rdzv_backend():
+ notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES, rdzv_backend="static")
+
+
+@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test c10d rendezvous backends")
+def test_c10d_rdzv_backend():
+ notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES, rdzv_backend="c10d")
+
+
+@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test fault tolerance")
+def test_fault_tolerant(max_restarts: int = 3):
+ queue = Queue()
+ queue.put(max_restarts)
+ notebook_launcher(tough_nut_function, (queue,), num_processes=NUM_PROCESSES, max_restarts=max_restarts)
+
+
+@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test monitoring")
+def test_monitoring(monitor_interval: float = 0.01, sleep_sec: int = 100):
+ start_time = time.time()
+ with raises(ChildFailedError, match="I'm an even process. I don't like to sleep."):
+ notebook_launcher(
+ bipolar_sleep_function,
+ (sleep_sec,),
+ num_processes=NUM_PROCESSES,
+ monitor_interval=monitor_interval,
+ )
+ assert time.time() - start_time < sleep_sec, "Monitoring did not stop the process in time."
+
+
+@require_bnb
+def test_problematic_imports():
+ with raises(RuntimeError, match="Please keep these imports"):
+ import bitsandbytes as bnb # noqa: F401
+
+ notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES)
+
+
+def main():
+ print("Test basic notebook can be ran")
+ test_can_initialize()
+ print("Test static rendezvous backend")
+ test_static_rdzv_backend()
+ print("Test c10d rendezvous backend")
+ test_c10d_rdzv_backend()
+ print("Test fault tolerant")
+ test_fault_tolerant()
+ print("Test monitoring")
+ test_monitoring()
+ if is_bnb_available():
+ print("Test problematic imports (bnb)")
+ test_problematic_imports()
+ if NUM_PROCESSES > 1:
+ PartialState().destroy_process_group()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_ops.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..e70d0fe504f2bba38394f15c26262baccce26bfd
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_ops.py
@@ -0,0 +1,180 @@
+#!/usr/bin/env python
+
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import torch
+
+from accelerate import PartialState
+from accelerate.test_utils.testing import assert_exception
+from accelerate.utils.dataclasses import DistributedType
+from accelerate.utils.operations import (
+ DistributedOperationException,
+ broadcast,
+ copy_tensor_to_devices,
+ gather,
+ gather_object,
+ pad_across_processes,
+ reduce,
+)
+
+
+def create_tensor(state):
+ return (torch.arange(state.num_processes) + 1.0 + (state.num_processes * state.process_index)).to(state.device)
+
+
+def test_gather(state):
+ tensor = create_tensor(state)
+ gathered_tensor = gather(tensor)
+ assert gathered_tensor.tolist() == list(range(1, state.num_processes**2 + 1))
+
+
+def test_gather_object(state):
+ # Gather objects in TorchXLA is not supported.
+ if state.distributed_type == DistributedType.XLA:
+ return
+ obj = [state.process_index]
+ gathered_obj = gather_object(obj)
+ assert len(gathered_obj) == state.num_processes, f"{gathered_obj}, {len(gathered_obj)} != {state.num_processes}"
+ assert gathered_obj == list(range(state.num_processes)), f"{gathered_obj} != {list(range(state.num_processes))}"
+
+
+def test_gather_non_contigous(state):
+ # Skip this test because the 'is_contiguous' function of XLA tensor always returns True.
+ if state.distributed_type == DistributedType.XLA:
+ return
+ # Create a non-contiguous tensor
+ tensor = torch.arange(12).view(4, 3).t().to(state.device)
+ assert not tensor.is_contiguous()
+ # Shouldn't error out
+ _ = gather(tensor)
+
+
+def test_broadcast(state):
+ tensor = create_tensor(state)
+ broadcasted_tensor = broadcast(tensor)
+ assert broadcasted_tensor.shape == torch.Size([state.num_processes])
+ assert broadcasted_tensor.tolist() == list(range(1, state.num_processes + 1))
+
+
+def test_pad_across_processes(state):
+ # We need to pad the tensor with one more element if we are the main process
+ # to ensure that we can pad
+ if state.is_main_process:
+ tensor = torch.arange(state.num_processes + 1).to(state.device)
+ else:
+ tensor = torch.arange(state.num_processes).to(state.device)
+ padded_tensor = pad_across_processes(tensor)
+ assert padded_tensor.shape == torch.Size([state.num_processes + 1])
+ if not state.is_main_process:
+ assert padded_tensor.tolist() == list(range(0, state.num_processes)) + [0]
+
+
+def test_reduce_sum(state):
+ # For now runs on only two processes
+ if state.num_processes != 2:
+ return
+ tensor = create_tensor(state)
+ reduced_tensor = reduce(tensor, "sum")
+ truth_tensor = torch.tensor([4.0, 6]).to(state.device)
+ assert torch.allclose(reduced_tensor, truth_tensor), f"{reduced_tensor} != {truth_tensor}"
+
+
+def test_reduce_mean(state):
+ # For now runs on only two processes
+ if state.num_processes != 2:
+ return
+ tensor = create_tensor(state)
+ reduced_tensor = reduce(tensor, "mean")
+ truth_tensor = torch.tensor([2.0, 3]).to(state.device)
+ assert torch.allclose(reduced_tensor, truth_tensor), f"{reduced_tensor} != {truth_tensor}"
+
+
+def test_op_checker(state):
+ # Must be in a distributed state, and gathering is currently not supported in TorchXLA.
+ if state.distributed_type in [DistributedType.NO, DistributedType.XLA]:
+ return
+ state.debug = True
+ # `pad_across_processes`
+ if state.process_index == 0:
+ data = {"tensor": torch.tensor([[0.0, 1, 2, 3, 4]]).to(state.device)}
+ else:
+ data = {"tensor": torch.tensor([[[0.0, 1, 2, 3, 4, 5]]]).to(state.device)}
+
+ with assert_exception(DistributedOperationException):
+ pad_across_processes(data, dim=0)
+
+ # `reduce`
+ if state.process_index == 0:
+ data = {"tensor": torch.tensor([[0.0, 1, 2, 3, 4]]).to(state.device)}
+ else:
+ data = {"tensor": torch.tensor([[[0.0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]]).to(state.device)}
+
+ with assert_exception(DistributedOperationException):
+ reduce(data)
+
+ # `broadcast`
+ if state.process_index == 0:
+ data = {"tensor": torch.tensor([[0.0, 1, 2, 3, 4]]).to(state.device)}
+ else:
+ data = {"tensor": torch.tensor([[[0.0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]]).to(state.device)}
+
+ with assert_exception(DistributedOperationException):
+ broadcast(data)
+
+ state.debug = False
+
+
+def test_copy_tensor_to_devices(state):
+ if state.distributed_type not in [DistributedType.MULTI_GPU, DistributedType.XLA]:
+ return
+ if state.is_main_process:
+ tensor = torch.tensor([1, 2, 3], dtype=torch.int).to(state.device)
+ else:
+ tensor = None
+ tensor = copy_tensor_to_devices(tensor)
+ assert torch.allclose(tensor, torch.tensor([1, 2, 3], dtype=torch.int, device=state.device))
+
+
+def _mp_fn(index):
+ # For xla_spawn (TPUs)
+ main()
+
+
+def main():
+ state = PartialState()
+ state.print(f"State: {state}")
+ state.print("testing gather")
+ test_gather(state)
+ state.print("testing gather_object")
+ test_gather_object(state)
+ state.print("testing gather non-contigous")
+ test_gather_non_contigous(state)
+ state.print("testing broadcast")
+ test_broadcast(state)
+ state.print("testing pad_across_processes")
+ test_pad_across_processes(state)
+ state.print("testing reduce_sum")
+ test_reduce_sum(state)
+ state.print("testing reduce_mean")
+ test_reduce_mean(state)
+ state.print("testing op_checker")
+ test_op_checker(state)
+ state.print("testing sending tensors across devices")
+ test_copy_tensor_to_devices(state)
+ state.destroy_process_group()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_script.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_script.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d54d098a6331608ccba3834b184184002ce6a0c
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_script.py
@@ -0,0 +1,829 @@
+#!/usr/bin/env python
+
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import contextlib
+import io
+import math
+import time
+from copy import deepcopy
+from pathlib import Path
+
+import numpy as np
+import torch
+from torch.utils.data import DataLoader, Dataset
+
+from accelerate import Accelerator
+from accelerate.data_loader import SeedableRandomSampler, prepare_data_loader
+from accelerate.state import AcceleratorState
+from accelerate.test_utils import RegressionDataset, are_the_same_tensors
+from accelerate.utils import (
+ DataLoaderConfiguration,
+ DistributedType,
+ gather,
+ is_bf16_available,
+ is_datasets_available,
+ is_ipex_available,
+ is_mlu_available,
+ is_musa_available,
+ is_npu_available,
+ is_pytest_available,
+ is_xpu_available,
+ set_seed,
+ synchronize_rng_states,
+)
+
+
+# TODO: remove RegressionModel4XPU once ccl support empty buffer in broadcasting.
+if is_xpu_available():
+ from accelerate.test_utils import RegressionModel4XPU as RegressionModel
+else:
+ from accelerate.test_utils import RegressionModel
+
+
+def generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler=False):
+ "Creates a dataloader that can also use the `SeedableRandomSampler`"
+ if use_seedable_sampler:
+ # The SeedableRandomSampler is needed during distributed setups
+ # for full reproducability across processes with the `DataLoader`
+ sampler = SeedableRandomSampler(
+ generator=generator,
+ data_source=train_set,
+ num_samples=len(train_set),
+ )
+ return DataLoader(train_set, batch_size=batch_size, sampler=sampler)
+ else:
+ return DataLoader(train_set, batch_size=batch_size, shuffle=True, generator=generator)
+
+
+def print_main(state):
+ print(f"Printing from the main process {state.process_index}")
+
+
+def print_local_main(state):
+ print(f"Printing from the local main process {state.local_process_index}")
+
+
+def print_last(state):
+ print(f"Printing from the last process {state.process_index}")
+
+
+def print_on(state, process_idx):
+ print(f"Printing from process {process_idx}: {state.process_index}")
+
+
+def process_execution_check():
+ accelerator = Accelerator()
+ num_processes = accelerator.num_processes
+ # Test main_process_first context manager
+ path = Path("check_main_process_first.txt")
+ with accelerator.main_process_first():
+ if accelerator.is_main_process:
+ time.sleep(0.1) # ensure main process takes longest
+ with open(path, "a+") as f:
+ f.write("Currently in the main process\n")
+ else:
+ with open(path, "a+") as f:
+ f.write("Now on another process\n")
+ accelerator.wait_for_everyone()
+
+ if accelerator.is_main_process:
+ with open(path) as f:
+ text = "".join(f.readlines())
+ try:
+ assert text.startswith("Currently in the main process\n"), "Main process was not first"
+ if num_processes > 1:
+ assert text.endswith("Now on another process\n"), "Main process was not first"
+ assert (
+ text.count("Now on another process\n") == accelerator.num_processes - 1
+ ), f"Only wrote to file {text.count('Now on another process') + 1} times, not {accelerator.num_processes}"
+ except AssertionError:
+ path.unlink()
+ raise
+
+ if accelerator.is_main_process and path.exists():
+ path.unlink()
+ accelerator.wait_for_everyone()
+ # Test the decorators
+ f = io.StringIO()
+ with contextlib.redirect_stdout(f):
+ accelerator.on_main_process(print_main)(accelerator.state)
+ result = f.getvalue().rstrip()
+ if accelerator.is_main_process:
+ assert result == "Printing from the main process 0", f"{result} != Printing from the main process 0"
+ else:
+ assert f.getvalue().rstrip() == "", f'{result} != ""'
+ f.truncate(0)
+ f.seek(0)
+
+ with contextlib.redirect_stdout(f):
+ accelerator.on_local_main_process(print_local_main)(accelerator.state)
+ if accelerator.is_local_main_process:
+ assert f.getvalue().rstrip() == "Printing from the local main process 0"
+ else:
+ assert f.getvalue().rstrip() == ""
+ f.truncate(0)
+ f.seek(0)
+
+ with contextlib.redirect_stdout(f):
+ accelerator.on_last_process(print_last)(accelerator.state)
+ if accelerator.is_last_process:
+ assert f.getvalue().rstrip() == f"Printing from the last process {accelerator.state.num_processes - 1}"
+ else:
+ assert f.getvalue().rstrip() == ""
+ f.truncate(0)
+ f.seek(0)
+
+ for process_idx in range(num_processes):
+ with contextlib.redirect_stdout(f):
+ accelerator.on_process(print_on, process_index=process_idx)(accelerator.state, process_idx)
+ if accelerator.process_index == process_idx:
+ assert f.getvalue().rstrip() == f"Printing from process {process_idx}: {accelerator.process_index}"
+ else:
+ assert f.getvalue().rstrip() == ""
+ f.truncate(0)
+ f.seek(0)
+
+
+def init_state_check():
+ # Test we can instantiate this twice in a row.
+ state = AcceleratorState()
+ if state.local_process_index == 0:
+ print("Testing, testing. 1, 2, 3.")
+ print(state)
+
+
+def rng_sync_check():
+ state = AcceleratorState()
+ synchronize_rng_states(["torch"])
+ assert are_the_same_tensors(torch.get_rng_state()), "RNG states improperly synchronized on CPU."
+ if state.distributed_type == DistributedType.MULTI_GPU:
+ synchronize_rng_states(["cuda"])
+ assert are_the_same_tensors(torch.cuda.get_rng_state()), "RNG states improperly synchronized on GPU."
+ elif state.distributed_type == DistributedType.MULTI_XPU:
+ synchronize_rng_states(["xpu"])
+ assert are_the_same_tensors(torch.xpu.get_rng_state()), "RNG states improperly synchronized on XPU."
+ generator = torch.Generator()
+ synchronize_rng_states(["generator"], generator=generator)
+ assert are_the_same_tensors(generator.get_state()), "RNG states improperly synchronized in generator."
+
+ if state.local_process_index == 0:
+ print("All rng are properly synched.")
+
+
+def dl_preparation_check():
+ state = AcceleratorState()
+ length = 32 * state.num_processes
+
+ dl = DataLoader(range(length), batch_size=8)
+ dl = prepare_data_loader(dl, state.device, state.num_processes, state.process_index, put_on_device=True)
+ result = []
+ for batch in dl:
+ result.append(gather(batch))
+ result = torch.cat(result)
+
+ print(state.process_index, result, type(dl))
+ assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result."
+
+ dl = DataLoader(range(length), batch_size=8)
+ dl = prepare_data_loader(
+ dl,
+ state.device,
+ state.num_processes,
+ state.process_index,
+ put_on_device=True,
+ split_batches=True,
+ )
+ result = []
+ for batch in dl:
+ result.append(gather(batch))
+ result = torch.cat(result)
+ assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result."
+
+ if state.process_index == 0:
+ print("Non-shuffled dataloader passing.")
+
+ dl = DataLoader(range(length), batch_size=8, shuffle=True)
+ dl = prepare_data_loader(dl, state.device, state.num_processes, state.process_index, put_on_device=True)
+ result = []
+ for batch in dl:
+ result.append(gather(batch))
+ result = torch.cat(result).tolist()
+ result.sort()
+ assert result == list(range(length)), "Wrong shuffled dataloader result."
+
+ dl = DataLoader(range(length), batch_size=8, shuffle=True)
+ dl = prepare_data_loader(
+ dl,
+ state.device,
+ state.num_processes,
+ state.process_index,
+ put_on_device=True,
+ split_batches=True,
+ )
+ result = []
+ for batch in dl:
+ result.append(gather(batch))
+ result = torch.cat(result).tolist()
+ result.sort()
+ assert result == list(range(length)), "Wrong shuffled dataloader result."
+
+ if state.local_process_index == 0:
+ print("Shuffled dataloader passing.")
+
+
+def central_dl_preparation_check():
+ state = AcceleratorState()
+ length = 32 * state.num_processes
+
+ dl = DataLoader(range(length), batch_size=8)
+ dl = prepare_data_loader(
+ dl, state.device, state.num_processes, state.process_index, put_on_device=True, dispatch_batches=True
+ )
+ result = []
+ for batch in dl:
+ result.append(gather(batch))
+ result = torch.cat(result)
+ assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result."
+
+ dl = DataLoader(range(length), batch_size=8)
+ dl = prepare_data_loader(
+ dl,
+ state.device,
+ state.num_processes,
+ state.process_index,
+ put_on_device=True,
+ split_batches=True,
+ dispatch_batches=True,
+ )
+ result = []
+ for batch in dl:
+ result.append(gather(batch))
+ result = torch.cat(result)
+ assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result."
+
+ if state.process_index == 0:
+ print("Non-shuffled central dataloader passing.")
+
+ dl = DataLoader(range(length), batch_size=8, shuffle=True)
+ dl = prepare_data_loader(
+ dl, state.device, state.num_processes, state.process_index, put_on_device=True, dispatch_batches=True
+ )
+ result = []
+ for batch in dl:
+ result.append(gather(batch))
+ result = torch.cat(result).tolist()
+ result.sort()
+ assert result == list(range(length)), "Wrong shuffled dataloader result."
+
+ dl = DataLoader(range(length), batch_size=8, shuffle=True)
+ dl = prepare_data_loader(
+ dl,
+ state.device,
+ state.num_processes,
+ state.process_index,
+ put_on_device=True,
+ split_batches=True,
+ dispatch_batches=True,
+ )
+ result = []
+ for batch in dl:
+ result.append(gather(batch))
+ result = torch.cat(result).tolist()
+ result.sort()
+ assert result == list(range(length)), "Wrong shuffled dataloader result."
+
+ if state.local_process_index == 0:
+ print("Shuffled central dataloader passing.")
+
+
+def custom_sampler_check():
+ state = AcceleratorState()
+
+ class CustomDataset(Dataset):
+ def __init__(self, data):
+ self.data = data
+
+ def __len__(self):
+ return len(self.data)
+
+ def __getitem__(self, index):
+ return self.data[index]
+
+ class CustomBatchSampler:
+ def __init__(self, dataset_length: int, batch_size: int, shuffle: bool = True):
+ self.batch_size = batch_size
+ self.data_index = np.arange(dataset_length)
+ self.shuffle = shuffle
+
+ def __iter__(self):
+ num_batches = len(self)
+ if self.shuffle:
+ index = np.random.permutation(self.data_index)
+ else:
+ index = self.data_index
+ output = np.array_split(index, num_batches)
+ yield from output
+
+ def __len__(self):
+ return math.ceil(len(self.data_index) / self.batch_size)
+
+ dataset = CustomDataset(range(32 * state.num_processes))
+ sampler = CustomBatchSampler(len(dataset), batch_size=8)
+ dl = DataLoader(dataset, batch_sampler=sampler)
+ dl = prepare_data_loader(dl, state.device, state.num_processes, state.process_index)
+ # We need just ensure that `dl.batch_sampler` (or `dl.batch_sampler.batch_sampler` is indeed the old batch sampler
+ if hasattr(dl.batch_sampler, "batch_sampler"):
+ assert isinstance(
+ dl.batch_sampler.batch_sampler, CustomBatchSampler
+ ), "Custom sampler was changed after calling `prepare_data_loader`"
+ else:
+ assert isinstance(
+ dl.batch_sampler, CustomBatchSampler
+ ), "Custom sampler was changed after calling `prepare_data_loader`"
+
+
+def check_seedable_sampler():
+ # Set seed
+ set_seed(42)
+ train_set = RegressionDataset(length=10, seed=42)
+ train_dl = DataLoader(train_set, batch_size=2, shuffle=True)
+
+ config = DataLoaderConfiguration(use_seedable_sampler=True)
+ accelerator = Accelerator(dataloader_config=config)
+ train_dl = accelerator.prepare(train_dl)
+ original_items = []
+ for _ in range(3):
+ for batch in train_dl:
+ original_items.append(batch["x"])
+ original_items = torch.cat(original_items)
+
+ # Set seed again and the epoch
+ set_seed(42)
+ train_dl.set_epoch(0)
+ new_items = []
+ for _ in range(3):
+ for batch in train_dl:
+ new_items.append(batch["x"])
+ new_items = torch.cat(new_items)
+ assert torch.allclose(original_items, new_items), "Did not obtain the same items with the same seed and epoch."
+
+
+def check_seedable_sampler_in_batch_sampler_shard():
+ set_seed(42)
+
+ config = DataLoaderConfiguration(use_seedable_sampler=True)
+ accelerator = Accelerator(dataloader_config=config)
+ assert accelerator.num_processes > 1, "This test requires more than one process."
+
+ dataloader = DataLoader(list(range(10)), batch_size=1, shuffle=True)
+ prepared_data_loader = prepare_data_loader(
+ dataloader=dataloader,
+ use_seedable_sampler=True,
+ )
+
+ target_sampler = prepared_data_loader.batch_sampler.batch_sampler.sampler
+ assert isinstance(
+ target_sampler, SeedableRandomSampler
+ ), "Sampler in BatchSamplerShard is not SeedableRandomSampler."
+
+
+def mock_training(length, batch_size, generator, use_seedable_sampler=False):
+ set_seed(42)
+ generator.manual_seed(42)
+ train_set = RegressionDataset(length=length, seed=42)
+
+ train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler)
+ model = RegressionModel()
+ optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
+ for epoch in range(3):
+ for batch in train_dl:
+ model.zero_grad()
+ output = model(batch["x"])
+ loss = torch.nn.functional.mse_loss(output, batch["y"])
+ loss.backward()
+ optimizer.step()
+ return train_set, model
+
+
+def training_check(use_seedable_sampler=False):
+ state = AcceleratorState()
+ generator = torch.Generator()
+ batch_size = 8
+ length = batch_size * 4 * state.num_processes
+
+ train_set, old_model = mock_training(length, batch_size * state.num_processes, generator, use_seedable_sampler)
+ assert are_the_same_tensors(old_model.a), "Did not obtain the same model on both processes."
+ assert are_the_same_tensors(old_model.b), "Did not obtain the same model on both processes."
+
+ accelerator = Accelerator()
+ train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler)
+ model = RegressionModel()
+ optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
+
+ train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer)
+ set_seed(42)
+ generator.manual_seed(42)
+ for _ in range(3):
+ for batch in train_dl:
+ model.zero_grad()
+ output = model(batch["x"])
+ loss = torch.nn.functional.mse_loss(output, batch["y"])
+ accelerator.backward(loss)
+ optimizer.step()
+
+ model = accelerator.unwrap_model(model).cpu()
+ assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on CPU or distributed training."
+ assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on CPU or distributed training."
+
+ accelerator.print("Training yielded the same results on one CPU or distributed setup with no batch split.")
+
+ dataloader_config = DataLoaderConfiguration(split_batches=True, use_seedable_sampler=use_seedable_sampler)
+ accelerator = Accelerator(dataloader_config=dataloader_config)
+ train_dl = generate_baseline_dataloader(
+ train_set, generator, batch_size * state.num_processes, use_seedable_sampler
+ )
+ model = RegressionModel()
+ optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
+
+ train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer)
+ set_seed(42)
+ generator.manual_seed(42)
+ for _ in range(3):
+ for batch in train_dl:
+ model.zero_grad()
+ output = model(batch["x"])
+ loss = torch.nn.functional.mse_loss(output, batch["y"])
+ accelerator.backward(loss)
+ optimizer.step()
+
+ model = accelerator.unwrap_model(model).cpu()
+ assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on CPU or distributed training."
+ assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on CPU or distributed training."
+
+ accelerator.print("Training yielded the same results on one CPU or distributes setup with batch split.")
+
+ if torch.cuda.is_available() or is_npu_available() or is_mlu_available() or is_musa_available():
+ # Mostly a test that FP16 doesn't crash as the operation inside the model is not converted to FP16
+ print("FP16 training check.")
+ AcceleratorState._reset_state()
+ dataloader_config = DataLoaderConfiguration(use_seedable_sampler=use_seedable_sampler)
+ accelerator = Accelerator(mixed_precision="fp16", dataloader_config=dataloader_config)
+ train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler)
+ model = RegressionModel()
+ optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
+
+ train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer)
+ set_seed(42)
+ generator.manual_seed(42)
+ for _ in range(3):
+ for batch in train_dl:
+ model.zero_grad()
+ output = model(batch["x"])
+ loss = torch.nn.functional.mse_loss(output, batch["y"])
+ accelerator.backward(loss)
+ optimizer.step()
+
+ model = accelerator.unwrap_model(model).cpu()
+ assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on CPU or distributed training."
+ assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on CPU or distributed training."
+
+ if torch.cuda.is_available():
+ # Mostly a test that model.forward will have autocast when running unwrap_model(model, keep_fp32_wrapper=True)
+ print("Keep fp32 wrapper check.")
+ AcceleratorState._reset_state()
+ accelerator = Accelerator(mixed_precision="fp16")
+
+ model = torch.nn.Linear(2, 4)
+ model = accelerator.prepare(model)
+ model_with_fp32_wrapper = accelerator.unwrap_model(model, keep_fp32_wrapper=True)
+
+ # Run forward with fp16 as input.
+ # When the model is with mixed precision wrapper, no error will be raised.
+ input_tensor = torch.Tensor([1, 2]).to(dtype=torch.float16, device=accelerator.device)
+ output = model_with_fp32_wrapper(input_tensor)
+
+ # BF16 support is only for CPU + TPU, and some GPU
+ if is_bf16_available():
+ # Mostly a test that BF16 doesn't crash as the operation inside the model is not converted to BF16
+ print("BF16 training check.")
+ AcceleratorState._reset_state()
+ dataloader_config = DataLoaderConfiguration(use_seedable_sampler=use_seedable_sampler)
+ accelerator = Accelerator(mixed_precision="bf16", dataloader_config=dataloader_config)
+ train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler)
+ model = RegressionModel()
+ optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
+
+ train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer)
+ set_seed(42)
+ generator.manual_seed(42)
+ for _ in range(3):
+ for batch in train_dl:
+ model.zero_grad()
+ output = model(batch["x"])
+ loss = torch.nn.functional.mse_loss(output, batch["y"])
+ accelerator.backward(loss)
+ optimizer.step()
+
+ model = accelerator.unwrap_model(model).cpu()
+ assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on CPU or distributed training."
+ assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on CPU or distributed training."
+
+ # IPEX support is only for CPU
+ if is_ipex_available():
+ print("ipex BF16 training check.")
+ AcceleratorState._reset_state()
+ dataloader_config = DataLoaderConfiguration(use_seedable_sampler=use_seedable_sampler)
+ accelerator = Accelerator(mixed_precision="bf16", cpu=True, dataloader_config=dataloader_config)
+ train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler)
+ model = RegressionModel()
+ optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
+
+ train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer)
+ set_seed(42)
+ generator.manual_seed(42)
+ for _ in range(3):
+ for batch in train_dl:
+ model.zero_grad()
+ output = model(batch["x"])
+ loss = torch.nn.functional.mse_loss(output, batch["y"])
+ accelerator.backward(loss)
+ optimizer.step()
+
+ model = accelerator.unwrap_model(model).cpu()
+ assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on CPU or distributed training."
+ assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on CPU or distributed training."
+
+ # XPU support is only for XPU
+ if is_xpu_available():
+ print("xpu BF16 training check.")
+ AcceleratorState._reset_state()
+ dataloader_config = DataLoaderConfiguration(use_seedable_sampler=use_seedable_sampler)
+ accelerator = Accelerator(mixed_precision="bf16", cpu=False, dataloader_config=dataloader_config)
+ train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler)
+ model = RegressionModel()
+ optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
+
+ train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer)
+ set_seed(42)
+ generator.manual_seed(42)
+ for _ in range(3):
+ for batch in train_dl:
+ model.zero_grad()
+ output = model(batch["x"])
+ loss = torch.nn.functional.mse_loss(output, batch["y"])
+ accelerator.backward(loss)
+ optimizer.step()
+
+ model = accelerator.unwrap_model(model).cpu()
+ assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on XPU or distributed training."
+ assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on XPU or distributed training."
+
+
+def test_split_between_processes_dataset(datasets_Dataset):
+ state = AcceleratorState()
+ data = datasets_Dataset.from_list([dict(k=v) for v in range(2 * state.num_processes)])
+ with state.split_between_processes(data, apply_padding=False) as results:
+ assert (
+ len(results) == 2
+ ), f"Each process did not have two items. Process index: {state.process_index}; Length: {len(results)}"
+
+ data = datasets_Dataset.from_list([dict(k=v) for v in range(2 * state.num_processes - 1)])
+ with state.split_between_processes(data, apply_padding=False) as results:
+ if state.is_last_process:
+ assert (
+ len(results) == 1
+ ), f"Last process did not receive a single item. Process index: {state.process_index}; Length: {len(results)}"
+ else:
+ assert (
+ len(results) == 2
+ ), f"One of the intermediate processes did not receive two items. Process index: {state.process_index}; Length: {len(results)}"
+
+ data = datasets_Dataset.from_list([dict(k=v) for v in range(2 * state.num_processes - 1)])
+ with state.split_between_processes(data, apply_padding=True) as results:
+ if state.num_processes == 1:
+ assert (
+ len(results) == 1
+ ), f"Single process did not receive a single item. Process index: {state.process_index}; Length: {len(results)}"
+ else:
+ assert (
+ len(results) == 2
+ ), f"Each process did not have two items. Process index: {state.process_index}; Length: {len(results)}"
+
+ state.wait_for_everyone()
+
+
+def test_split_between_processes_list():
+ state = AcceleratorState()
+ data = list(range(0, 2 * state.num_processes))
+ with state.split_between_processes(data) as results:
+ assert (
+ len(results) == 2
+ ), f"Each process did not have two items. Process index: {state.process_index}; Length: {len(results)}"
+
+ data = list(range(0, (3 * state.num_processes) - 1))
+ with state.split_between_processes(data, apply_padding=True) as results:
+ if state.is_last_process:
+ # Test that the last process gets the extra item(s)
+ num_samples_per_device = math.ceil(len(data) / state.num_processes)
+ assert (
+ len(results) == num_samples_per_device
+ ), f"Last process did not get the extra item(s). Process index: {state.process_index}; Length: {len(results)}"
+ state.wait_for_everyone()
+
+
+def test_split_between_processes_nested_dict():
+ state = AcceleratorState()
+ a = [1, 2, 3, 4, 5, 6, 7, 8]
+ b = ["a", "b", "c", "d", "e", "f", "g", "h"]
+ c = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8])
+ if state.num_processes in (1, 2, 4):
+ data = {"a": a, "b": b, "c": c}
+ data_copy = deepcopy(data)
+ with state.split_between_processes(data) as results:
+ if state.process_index == 0:
+ assert results["a"] == data_copy["a"][: 8 // state.num_processes]
+ elif state.num_processes == 2:
+ assert results["a"] == data_copy["a"][4:]
+ elif state.process_index == 3:
+ # We return a list each time
+ assert results["a"] == data_copy["a"][-2:], f'Expected: {data_copy["a"][-2]}, Actual: {results["a"]}'
+ if state.process_index == 0:
+ assert results["b"] == data_copy["b"][: 8 // state.num_processes]
+ elif state.num_processes == 2:
+ assert results["b"] == data_copy["b"][4:]
+ elif state.process_index == 3:
+ assert results["b"] == data_copy["b"][-2:]
+ if state.process_index == 0:
+ assert torch.allclose(
+ results["c"], data_copy["c"][: 8 // state.num_processes]
+ ), f"Did not obtain expected values on process 0, expected `{data['c'][:8 // state.num_processes]}`, received: {results['c']}"
+ elif state.num_processes == 2:
+ assert torch.allclose(
+ results["c"], data_copy["c"][4:]
+ ), f"Did not obtain expected values on process 2, expected `{data['c'][4:]}`, received: {results['c']}"
+ elif state.process_index == 3:
+ assert torch.allclose(
+ results["c"], data_copy["c"][-2:]
+ ), f"Did not obtain expected values on process 4, expected `{data['c'][-2:]}`, received: {results['c']}"
+
+ state.wait_for_everyone()
+
+
+def test_split_between_processes_tensor():
+ state = AcceleratorState()
+ if state.num_processes > 1:
+ data = torch.tensor([[0, 1, 2, 3], [4, 5, 6, 7]]).to(state.device)
+ with state.split_between_processes(data) as results:
+ if state.process_index == 0:
+ assert torch.allclose(results, torch.tensor([0, 1, 2, 3]).to(state.device))
+ else:
+ assert torch.allclose(results, torch.tensor([4, 5, 6, 7]).to(state.device))
+ state.wait_for_everyone()
+
+
+def test_split_between_processes_evenly():
+ state = AcceleratorState()
+ if state.num_processes in (1, 2, 4, 8):
+ data = list(range(17))
+ num_samples_per_process = len(data) // state.num_processes
+ num_extras = len(data) % state.num_processes
+ with state.split_between_processes(data) as results:
+ if state.process_index < num_extras:
+ assert (
+ len(results) == num_samples_per_process + 1
+ ), f"Each Process should have even elements. Expected: {num_samples_per_process + 1}, Actual: {len(results)}"
+ else:
+ assert (
+ len(results) == num_samples_per_process
+ ), f"Each Process should have even elements. Expected: {num_samples_per_process}, Actual: {len(results)}"
+ state.wait_for_everyone()
+
+
+def test_trigger():
+ accelerator = Accelerator()
+ # should start with being false
+ assert accelerator.check_trigger() is False
+
+ # set a breakpoint on the main process
+ if accelerator.is_main_process:
+ accelerator.set_trigger()
+
+ # check it's been activated across all processes
+ # calls `all_reduce` and triggers a sync
+ assert accelerator.check_trigger() is True
+
+ # check it's been reset after the sync
+ assert accelerator.check_trigger() is False
+
+
+def test_reinstantiated_state():
+ import pytest
+
+ AcceleratorState._reset_state()
+ simple_model = torch.nn.Linear(1, 1)
+ # First define an accelerator
+ accelerator = Accelerator()
+ # Then call `reset_state`, breaking the state existing in the accelerator
+ AcceleratorState._reset_state()
+ # Now try and prepare a simple model, should raise the custom error early
+ with pytest.raises(AttributeError) as cm:
+ accelerator.prepare(simple_model)
+ assert "`AcceleratorState` object has no attribute" in str(cm.value.args[0])
+ assert "This happens if `AcceleratorState._reset_state()`" in str(cm.value.args[0])
+
+
+def main():
+ accelerator = Accelerator()
+ state = accelerator.state
+ if state.local_process_index == 0:
+ print("**Initialization**")
+ init_state_check()
+ state.wait_for_everyone()
+
+ if state.distributed_type == DistributedType.MULTI_GPU:
+ num_processes_per_node = torch.cuda.device_count()
+ else:
+ num_processes_per_node = state.num_processes
+
+ # We only run this test on non-multinode
+ if num_processes_per_node == state.num_processes:
+ if state.process_index == 0:
+ print("\n**Test process execution**")
+ process_execution_check()
+
+ if state.process_index == 0:
+ print("\n**Test split between processes as a list**")
+ test_split_between_processes_list()
+
+ if state.process_index == 0:
+ print("\n**Test split between processes as a dict**")
+ test_split_between_processes_nested_dict()
+
+ if state.process_index == 0:
+ print("\n**Test split between processes as a tensor**")
+ test_split_between_processes_tensor()
+
+ if state.process_index == 0:
+ print("\n**Test split between processes evenly**")
+ test_split_between_processes_evenly()
+
+ if state.process_index == 0:
+ print("\n**Test split between processes as a datasets.Dataset**")
+ if is_datasets_available():
+ from datasets import Dataset as datasets_Dataset
+
+ test_split_between_processes_dataset(datasets_Dataset)
+ else:
+ print("Skipped because Hugging Face datasets is not available")
+
+ if state.local_process_index == 0:
+ print("\n**Test random number generator synchronization**")
+ rng_sync_check()
+
+ if state.local_process_index == 0:
+ print("\n**DataLoader integration test**")
+ dl_preparation_check()
+ if state.distributed_type != DistributedType.XLA:
+ central_dl_preparation_check()
+ custom_sampler_check()
+ check_seedable_sampler()
+
+ if state.num_processes > 1:
+ check_seedable_sampler_in_batch_sampler_shard()
+
+ # Trainings are not exactly the same in DeepSpeed and CPU mode
+ if state.distributed_type == DistributedType.DEEPSPEED:
+ return
+
+ if state.local_process_index == 0:
+ print("\n**Training integration test**")
+ training_check(use_seedable_sampler=False)
+ training_check(use_seedable_sampler=True)
+
+ if state.local_process_index == 0:
+ print("\n**Breakpoint trigger test**")
+ test_trigger()
+
+ if is_pytest_available():
+ if state.local_process_index == 0:
+ print("\n**Test reinstantiated state**")
+ test_reinstantiated_state()
+
+ state.destroy_process_group()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_sync.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_sync.py
new file mode 100644
index 0000000000000000000000000000000000000000..b80b5db5b48c5ccfd64e41567274eb88d2af6814
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/scripts/test_sync.py
@@ -0,0 +1,404 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from copy import deepcopy
+
+import torch
+import torch.nn.functional as F
+from torch.optim import AdamW
+from torch.optim.lr_scheduler import LambdaLR
+from torch.utils.data import DataLoader
+
+from accelerate.accelerator import Accelerator, DataLoaderConfiguration, GradientAccumulationPlugin
+from accelerate.state import GradientState
+from accelerate.test_utils import RegressionDataset, RegressionModel
+from accelerate.utils import DistributedType, set_seed
+
+
+def check_model_parameters(model_a, model_b, did_step, iteration, **kwargs):
+ for param, grad_param in zip(model_a.parameters(), model_b.parameters()):
+ if not param.requires_grad:
+ continue
+ if not did_step:
+ # Grads should not be in sync
+ assert (
+ torch.allclose(param.grad, grad_param.grad, **kwargs) is False
+ ), f"Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})"
+ else:
+ # Grads should be in sync
+ assert (
+ torch.allclose(param.grad, grad_param.grad, **kwargs) is True
+ ), f"Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})"
+
+
+def step_model(model, input, target, accelerator, do_backward=True):
+ model.train()
+ output = model(input)
+ loss = F.mse_loss(output, target.to(output.device))
+ if not do_backward:
+ loss /= accelerator.gradient_accumulation_steps
+ loss.backward()
+ else:
+ accelerator.backward(loss)
+
+
+def get_training_setup(accelerator, sched=False):
+ "Returns everything needed to perform basic training"
+ set_seed(42)
+ model = RegressionModel()
+ ddp_model = deepcopy(model)
+ dset = RegressionDataset(length=80)
+ dataloader = DataLoader(dset, batch_size=16)
+ model.to(accelerator.device)
+ if sched:
+ opt = AdamW(params=model.parameters(), lr=1e-3)
+ ddp_opt = AdamW(params=ddp_model.parameters(), lr=1e-3)
+ sched = LambdaLR(opt, lr_lambda=lambda epoch: epoch**0.65)
+ ddp_sched = LambdaLR(ddp_opt, lr_lambda=lambda epoch: epoch**0.65)
+ # Make a copy of `model`
+ if sched:
+ ddp_model, ddp_opt, ddp_sched, dataloader = accelerator.prepare(ddp_model, ddp_opt, ddp_sched, dataloader)
+ else:
+ ddp_model, dataloader = accelerator.prepare(ddp_model, dataloader)
+ if sched:
+ return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched)
+ return model, ddp_model, dataloader
+
+
+def test_noop_sync(accelerator):
+ # Test when on a single CPU or GPU that the context manager does nothing
+ model, ddp_model, dataloader = get_training_setup(accelerator)
+ # Use a single batch
+ ddp_input, ddp_target = next(iter(dataloader)).values()
+ for iteration in range(3):
+ # Gather the distributed inputs and targs for the base model
+ input, target = accelerator.gather((ddp_input, ddp_target))
+ input, target = input.to(accelerator.device), target.to(accelerator.device)
+ # Perform our initial ground truth step in non "DDP"
+ step_model(model, input, target, accelerator)
+ # Do "gradient accumulation" (noop)
+ if iteration % 2 == 0:
+ # Accumulate grads locally
+ with accelerator.no_sync(ddp_model):
+ step_model(ddp_model, ddp_input, ddp_target, accelerator)
+ else:
+ # Sync grads
+ step_model(ddp_model, ddp_input, ddp_target, accelerator)
+
+ # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync
+ check_model_parameters(model, ddp_model, True, iteration)
+ for param, ddp_param in zip(model.parameters(), ddp_model.parameters()):
+ if not param.requires_grad:
+ continue
+ assert torch.allclose(
+ param.grad, ddp_param.grad
+ ), f"Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})"
+
+ # Shuffle ddp_input on each iteration
+ torch.manual_seed(1337 + iteration)
+ ddp_input = ddp_input[torch.randperm(len(ddp_input))]
+
+
+def test_distributed_sync(accelerator):
+ # Test on distributed setup that context manager behaves properly
+ model, ddp_model, dataloader = get_training_setup(accelerator)
+ # Use a single batch
+ ddp_input, ddp_target = next(iter(dataloader)).values()
+ for iteration in range(3):
+ # Gather the distributed inputs and targs for the base model
+ input, target = accelerator.gather((ddp_input, ddp_target))
+ input, target = input.to(accelerator.device), target.to(accelerator.device)
+ # Perform our initial ground truth step in non "DDP"
+ step_model(model, input, target, accelerator)
+ # Do "gradient accumulation" (noop)
+ if iteration % 2 == 0:
+ # Accumulate grads locally
+ with accelerator.no_sync(ddp_model):
+ step_model(ddp_model, ddp_input, ddp_target, accelerator)
+ else:
+ # Sync grads
+ step_model(ddp_model, ddp_input, ddp_target, accelerator)
+
+ # DDP model and model should only be in sync when not (iteration % 2 == 0)
+ for param, ddp_param in zip(model.parameters(), ddp_model.parameters()):
+ if not param.requires_grad:
+ continue
+ if iteration % 2 == 0:
+ # Grads should not be in sync
+ assert (
+ torch.allclose(param.grad, ddp_param.grad) is False
+ ), f"Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})"
+ else:
+ # Grads should be in sync
+ assert (
+ torch.allclose(param.grad, ddp_param.grad) is True
+ ), f"Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})"
+
+ # Shuffle ddp_input on each iteration
+ torch.manual_seed(1337 + iteration)
+ ddp_input = ddp_input[torch.randperm(len(ddp_input))]
+
+
+def test_distributed_sync_multiple_fwd(accelerator):
+ # Test on distributed setup that context manager behaves properly when used with multiple forwards followed by multiple backwards
+ model, ddp_model, dataloader = get_training_setup(accelerator)
+ # Do multiple forwards
+ losses = []
+ num_iterations = 3
+ for iteration in range(num_iterations):
+ ddp_input, ddp_target = next(iter(dataloader)).values()
+
+ # Gather the distributed inputs and targs for the base model
+ input, target = accelerator.gather((ddp_input, ddp_target))
+ input, target = input.to(accelerator.device), target.to(accelerator.device)
+
+ # Perform our initial ground truth step in non "DDP"
+ step_model(model, input, target, accelerator)
+
+ # Accumulate grads locally
+ with accelerator.no_sync(ddp_model):
+ ddp_output = ddp_model(ddp_input)
+ loss = F.mse_loss(ddp_output, ddp_target.to(ddp_output.device))
+ losses.append(loss)
+
+ # Do multiple backwards and sync only at the last backward
+ for iteration in range(num_iterations):
+ loss = losses[iteration]
+
+ if iteration < num_iterations - 1:
+ # Accumulate grads locally
+ accelerator.backward(loss)
+
+ # DDP model and model should only be in sync after last backward
+ for param, ddp_param in zip(model.parameters(), ddp_model.parameters()):
+ if not param.requires_grad:
+ continue
+ # Grads should not be in sync
+ assert (
+ torch.allclose(param.grad, ddp_param.grad) is False
+ ), f"Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})"
+
+ else:
+ # Sync grads if last backward
+ with accelerator.trigger_sync_in_backward(ddp_model):
+ accelerator.backward(loss)
+
+ # DDP model and model should only be in sync after last backward
+ for param, ddp_param in zip(model.parameters(), ddp_model.parameters()):
+ if not param.requires_grad:
+ continue
+ # Grads should be in sync
+ assert (
+ torch.allclose(param.grad, ddp_param.grad) is True
+ ), f"Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})"
+
+
+def test_gradient_accumulation(split_batches=False, dispatch_batches=False, sync_each_batch=False):
+ gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2, sync_each_batch=sync_each_batch)
+ dataloader_config = DataLoaderConfiguration(split_batches=split_batches, dispatch_batches=dispatch_batches)
+ accelerator = Accelerator(
+ dataloader_config=dataloader_config,
+ gradient_accumulation_plugin=gradient_accumulation_plugin,
+ )
+ # Test that context manager behaves properly
+ model, ddp_model, dataloader = get_training_setup(accelerator)
+ for iteration, batch in enumerate(dataloader):
+ ddp_input, ddp_target = batch.values()
+ # Gather the distributed inputs and targs for the base model
+ input, target = accelerator.gather((ddp_input, ddp_target))
+ input, target = input.to(accelerator.device), target.to(accelerator.device)
+ # Perform our initial ground truth step in non "DDP"
+ step_model(model, input, target, accelerator, False)
+ # Do "gradient accumulation" (noop)
+ with accelerator.accumulate(ddp_model):
+ step_model(ddp_model, ddp_input, ddp_target, accelerator)
+
+ # DDP model and model should only be in sync when not (iteration % 2 == 0)
+ for param, ddp_param in zip(model.parameters(), ddp_model.parameters()):
+ if not param.requires_grad:
+ continue
+ if ((iteration + 1) % 2 == 0) or (iteration == len(dataloader) - 1) or sync_each_batch:
+ # Grads should be in sync
+ assert (
+ torch.allclose(param.grad, ddp_param.grad) is True
+ ), f"Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})"
+ else:
+ # Grads should not be in sync
+ assert (
+ torch.allclose(param.grad, ddp_param.grad) is False
+ ), f"Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})"
+
+ # Shuffle ddp_input on each iteration
+ torch.manual_seed(1337 + iteration)
+ ddp_input = ddp_input[torch.randperm(len(ddp_input))]
+ GradientState._reset_state()
+
+
+def test_gradient_accumulation_with_opt_and_scheduler(
+ split_batches=False, dispatch_batches=False, sync_each_batch=False
+):
+ gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2, sync_each_batch=sync_each_batch)
+ dataloader_config = DataLoaderConfiguration(split_batches=split_batches, dispatch_batches=dispatch_batches)
+ accelerator = Accelerator(
+ dataloader_config=dataloader_config,
+ gradient_accumulation_plugin=gradient_accumulation_plugin,
+ )
+ # Test that context manager behaves properly
+ model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched = get_training_setup(accelerator, True)
+ for iteration, batch in enumerate(dataloader):
+ ddp_input, ddp_target = batch.values()
+ # Gather the distributed inputs and targs for the base model
+ input, target = accelerator.gather((ddp_input, ddp_target))
+ input, target = input.to(accelerator.device), target.to(accelerator.device)
+ # Perform our initial ground truth step in non "DDP"
+ model.train()
+ ddp_model.train()
+ step_model(model, input, target, accelerator, False)
+ opt.step()
+
+ if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(dataloader)):
+ if split_batches:
+ sched.step()
+ else:
+ for _ in range(accelerator.num_processes):
+ sched.step()
+
+ # Perform gradient accumulation under wrapper
+ with accelerator.accumulate(ddp_model):
+ step_model(ddp_model, ddp_input, ddp_target, accelerator)
+ ddp_opt.step()
+ ddp_sched.step()
+
+ # Learning rates should be the same
+ assert (
+ opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"]
+ ), f'Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]["lr"]}\nDDP opt: {ddp_opt.param_groups[0]["lr"]}\n'
+ did_step = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(dataloader))
+ if accelerator.num_processes > 1:
+ check_model_parameters(
+ model,
+ ddp_model,
+ did_step or sync_each_batch, # syncs at each grad_accum interval of if sync_each_batch==True
+ iteration,
+ rtol=1e-3, # needs a relative tolerance due to roundoff errors
+ )
+
+ if did_step:
+ opt.zero_grad() # flush gradients every accum step
+ ddp_opt.zero_grad()
+
+ # Shuffle ddp_input on each iteration
+ torch.manual_seed(1337 + iteration)
+ GradientState._reset_state()
+
+
+def test_dataloader_break():
+ accelerator = Accelerator()
+ first_dset = RegressionDataset(length=80)
+ first_dataloader = DataLoader(first_dset, batch_size=16)
+ second_dset = RegressionDataset(length=96)
+ second_dataloader = DataLoader(second_dset, batch_size=16)
+ first_dataloader, second_dataloader = accelerator.prepare(first_dataloader, second_dataloader)
+
+ assert accelerator.gradient_state.active_dataloader is None
+ for iteration, _ in enumerate(first_dataloader):
+ assert id(accelerator.gradient_state.active_dataloader) == id(first_dataloader)
+ if iteration < len(first_dataloader) - 1:
+ assert not accelerator.gradient_state.end_of_dataloader
+ if iteration == 1:
+ for batch_num, _ in enumerate(second_dataloader):
+ assert id(accelerator.gradient_state.active_dataloader) == id(second_dataloader)
+ if batch_num < len(second_dataloader) - 1:
+ assert not accelerator.gradient_state.end_of_dataloader
+ else:
+ assert accelerator.gradient_state.end_of_dataloader
+ else:
+ assert accelerator.gradient_state.end_of_dataloader
+ assert accelerator.gradient_state.active_dataloader is None
+
+
+def main():
+ accelerator = Accelerator()
+ state = accelerator.state
+ if state.local_process_index == 0:
+ print("**Test `accumulate` gradient accumulation with dataloader break**")
+ if state.distributed_type != DistributedType.XLA:
+ test_dataloader_break()
+ if state.distributed_type == DistributedType.NO:
+ if state.local_process_index == 0:
+ print("**Test NOOP `no_sync` context manager**")
+ test_noop_sync(accelerator)
+ if state.distributed_type in (
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_CPU,
+ ):
+ if state.local_process_index == 0:
+ print("**Test Distributed `no_sync` context manager**")
+ test_distributed_sync(accelerator)
+ if state.local_process_index == 0:
+ print("**Test Distributed `no_sync` context manager with multiple forwards**")
+ test_distributed_sync_multiple_fwd(accelerator)
+ if state.distributed_type in (
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ ):
+ for split_batch in [True, False]:
+ for dispatch_batches in [True, False]:
+ for sync_each_batch in [True, False]:
+ if state.local_process_index == 0:
+ print(
+ "**Test `accumulate` gradient accumulation, ",
+ f"`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}` and `sync_each_batch={sync_each_batch}`**",
+ )
+ test_gradient_accumulation(split_batch, dispatch_batches, sync_each_batch)
+
+ # Currently will break on torch 2.0 +, need to investigate why
+ if state.local_process_index == 0:
+ print(
+ "**Test `accumulate` gradient accumulation with optimizer and scheduler, ",
+ "`split_batches=False`, `dispatch_batches=False`, `sync_each_batch=False`**",
+ )
+ test_gradient_accumulation_with_opt_and_scheduler()
+ if state.distributed_type in (
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ ):
+ for split_batch in [True, False]:
+ for dispatch_batches in [True, False]:
+ for sync_each_batch in [True, False]:
+ if not split_batch and not dispatch_batches and not sync_each_batch:
+ continue
+ if state.local_process_index == 0:
+ print(
+ "**Test `accumulate` gradient accumulation with optimizer and scheduler, ",
+ f"`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}` and `sync_each_batch={sync_each_batch}`**",
+ )
+ test_gradient_accumulation_with_opt_and_scheduler(split_batch, dispatch_batches, sync_each_batch)
+ state.destroy_process_group()
+
+
+def _mp_fn(index):
+ # For xla_spawn (TPUs)
+ main()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/testing.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b9305c5c9b759dab37e87b284848e69517e9f41
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/testing.py
@@ -0,0 +1,689 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import asyncio
+import inspect
+import io
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from contextlib import contextmanager
+from functools import partial
+from pathlib import Path
+from typing import List, Union
+from unittest import mock
+
+import torch
+
+import accelerate
+
+from ..state import AcceleratorState, PartialState
+from ..utils import (
+ gather,
+ is_bnb_available,
+ is_clearml_available,
+ is_comet_ml_available,
+ is_cuda_available,
+ is_datasets_available,
+ is_deepspeed_available,
+ is_dvclive_available,
+ is_import_timer_available,
+ is_mlu_available,
+ is_mps_available,
+ is_musa_available,
+ is_npu_available,
+ is_pandas_available,
+ is_pippy_available,
+ is_schedulefree_available,
+ is_tensorboard_available,
+ is_timm_available,
+ is_torch_version,
+ is_torch_xla_available,
+ is_torchdata_stateful_dataloader_available,
+ is_torchvision_available,
+ is_transformer_engine_available,
+ is_transformers_available,
+ is_triton_available,
+ is_wandb_available,
+ is_xpu_available,
+ str_to_bool,
+)
+
+
+def get_backend():
+ if is_torch_xla_available():
+ return "xla", torch.cuda.device_count(), torch.cuda.memory_allocated
+ elif is_cuda_available():
+ return "cuda", torch.cuda.device_count(), torch.cuda.memory_allocated
+ elif is_mps_available(min_version="2.0"):
+ return "mps", 1, torch.mps.current_allocated_memory
+ elif is_mps_available():
+ return "mps", 1, lambda: 0
+ elif is_mlu_available():
+ return "mlu", torch.mlu.device_count(), torch.mlu.memory_allocated
+ elif is_musa_available():
+ return "musa", torch.musa.device_count(), torch.musa.memory_allocated
+ elif is_npu_available():
+ return "npu", torch.npu.device_count(), torch.npu.memory_allocated
+ elif is_xpu_available():
+ return "xpu", torch.xpu.device_count(), torch.xpu.memory_allocated
+ else:
+ return "cpu", 1, lambda: 0
+
+
+torch_device, device_count, memory_allocated_func = get_backend()
+
+
+def get_launch_command(**kwargs) -> list:
+ """
+ Wraps around `kwargs` to help simplify launching from `subprocess`.
+
+ Example:
+ ```python
+ # returns ['accelerate', 'launch', '--num_processes=2', '--device_count=2']
+ get_launch_command(num_processes=2, device_count=2)
+ ```
+ """
+ command = ["accelerate", "launch"]
+ for k, v in kwargs.items():
+ if isinstance(v, bool) and v:
+ command.append(f"--{k}")
+ elif v is not None:
+ command.append(f"--{k}={v}")
+ return command
+
+
+DEFAULT_LAUNCH_COMMAND = get_launch_command(num_processes=device_count, monitor_interval=0.1)
+
+
+def parse_flag_from_env(key, default=False):
+ try:
+ value = os.environ[key]
+ except KeyError:
+ # KEY isn't set, default to `default`.
+ _value = default
+ else:
+ # KEY is set, convert it to True or False.
+ try:
+ _value = str_to_bool(value)
+ except ValueError:
+ # More values are supported, but let's keep the message simple.
+ raise ValueError(f"If set, {key} must be yes or no.")
+ return _value
+
+
+_run_slow_tests = parse_flag_from_env("RUN_SLOW", default=False)
+
+
+def skip(test_case):
+ "Decorator that skips a test unconditionally"
+ return unittest.skip("Test was skipped")(test_case)
+
+
+def slow(test_case):
+ """
+ Decorator marking a test as slow. Slow tests are skipped by default. Set the RUN_SLOW environment variable to a
+ truthy value to run them.
+ """
+ return unittest.skipUnless(_run_slow_tests, "test is slow")(test_case)
+
+
+def require_cpu(test_case):
+ """
+ Decorator marking a test that must be only ran on the CPU. These tests are skipped when a GPU is available.
+ """
+ return unittest.skipUnless(torch_device == "cpu", "test requires only a CPU")(test_case)
+
+
+def require_non_cpu(test_case):
+ """
+ Decorator marking a test that requires a hardware accelerator backend. These tests are skipped when there are no
+ hardware accelerator available.
+ """
+ return unittest.skipUnless(torch_device != "cpu", "test requires a GPU")(test_case)
+
+
+def require_cuda(test_case):
+ """
+ Decorator marking a test that requires CUDA. These tests are skipped when there are no GPU available or when
+ TorchXLA is available.
+ """
+ return unittest.skipUnless(is_cuda_available() and not is_torch_xla_available(), "test requires a GPU")(test_case)
+
+
+def require_xpu(test_case):
+ """
+ Decorator marking a test that requires XPU. These tests are skipped when there are no XPU available.
+ """
+ return unittest.skipUnless(is_xpu_available(), "test requires a XPU")(test_case)
+
+
+def require_non_xpu(test_case):
+ """
+ Decorator marking a test that should be skipped for XPU.
+ """
+ return unittest.skipUnless(torch_device != "xpu", "test requires a non-XPU")(test_case)
+
+
+def require_mlu(test_case):
+ """
+ Decorator marking a test that requires MLU. These tests are skipped when there are no MLU available.
+ """
+ return unittest.skipUnless(is_mlu_available(), "test require a MLU")(test_case)
+
+
+def require_musa(test_case):
+ """
+ Decorator marking a test that requires MUSA. These tests are skipped when there are no MUSA available.
+ """
+ return unittest.skipUnless(is_musa_available(), "test require a MUSA")(test_case)
+
+
+def require_npu(test_case):
+ """
+ Decorator marking a test that requires NPU. These tests are skipped when there are no NPU available.
+ """
+ return unittest.skipUnless(is_npu_available(), "test require a NPU")(test_case)
+
+
+def require_mps(test_case):
+ """
+ Decorator marking a test that requires MPS backend. These tests are skipped when torch doesn't support `mps`
+ backend.
+ """
+ return unittest.skipUnless(is_mps_available(), "test requires a `mps` backend support in `torch`")(test_case)
+
+
+def require_huggingface_suite(test_case):
+ """
+ Decorator marking a test that requires transformers and datasets. These tests are skipped when they are not.
+ """
+ return unittest.skipUnless(
+ is_transformers_available() and is_datasets_available(),
+ "test requires the Hugging Face suite",
+ )(test_case)
+
+
+def require_transformers(test_case):
+ """
+ Decorator marking a test that requires transformers. These tests are skipped when they are not.
+ """
+ return unittest.skipUnless(is_transformers_available(), "test requires the transformers library")(test_case)
+
+
+def require_timm(test_case):
+ """
+ Decorator marking a test that requires timm. These tests are skipped when they are not.
+ """
+ return unittest.skipUnless(is_timm_available(), "test requires the timm library")(test_case)
+
+
+def require_torchvision(test_case):
+ """
+ Decorator marking a test that requires torchvision. These tests are skipped when they are not.
+ """
+ return unittest.skipUnless(is_torchvision_available(), "test requires the torchvision library")(test_case)
+
+
+def require_triton(test_case):
+ """
+ Decorator marking a test that requires triton. These tests are skipped when they are not.
+ """
+ return unittest.skipUnless(is_triton_available(), "test requires the triton library")(test_case)
+
+
+def require_schedulefree(test_case):
+ """
+ Decorator marking a test that requires schedulefree. These tests are skipped when they are not.
+ """
+ return unittest.skipUnless(is_schedulefree_available(), "test requires the schedulefree library")(test_case)
+
+
+def require_bnb(test_case):
+ """
+ Decorator marking a test that requires bitsandbytes. These tests are skipped when they are not.
+ """
+ return unittest.skipUnless(is_bnb_available(), "test requires the bitsandbytes library")(test_case)
+
+
+def require_tpu(test_case):
+ """
+ Decorator marking a test that requires TPUs. These tests are skipped when there are no TPUs available.
+ """
+ return unittest.skipUnless(is_torch_xla_available(check_is_tpu=True), "test requires TPU")(test_case)
+
+
+def require_non_torch_xla(test_case):
+ """
+ Decorator marking a test as requiring an environment without TorchXLA. These tests are skipped when TorchXLA is
+ available.
+ """
+ return unittest.skipUnless(not is_torch_xla_available(), "test requires an env without TorchXLA")(test_case)
+
+
+def require_single_device(test_case):
+ """
+ Decorator marking a test that requires a single device. These tests are skipped when there is no hardware
+ accelerator available or number of devices is more than one.
+ """
+ return unittest.skipUnless(torch_device != "cpu" and device_count == 1, "test requires a hardware accelerator")(
+ test_case
+ )
+
+
+def require_single_gpu(test_case):
+ """
+ Decorator marking a test that requires CUDA on a single GPU. These tests are skipped when there are no GPU
+ available or number of GPUs is more than one.
+ """
+ return unittest.skipUnless(torch.cuda.device_count() == 1, "test requires a GPU")(test_case)
+
+
+def require_single_xpu(test_case):
+ """
+ Decorator marking a test that requires CUDA on a single XPU. These tests are skipped when there are no XPU
+ available or number of xPUs is more than one.
+ """
+ return unittest.skipUnless(torch.xpu.device_count() == 1, "test requires a XPU")(test_case)
+
+
+def require_multi_device(test_case):
+ """
+ Decorator marking a test that requires a multi-device setup. These tests are skipped on a machine without multiple
+ devices.
+ """
+ return unittest.skipUnless(device_count > 1, "test requires multiple hardware accelerators")(test_case)
+
+
+def require_multi_gpu(test_case):
+ """
+ Decorator marking a test that requires a multi-GPU setup. These tests are skipped on a machine without multiple
+ GPUs.
+ """
+ return unittest.skipUnless(torch.cuda.device_count() > 1, "test requires multiple GPUs")(test_case)
+
+
+def require_multi_xpu(test_case):
+ """
+ Decorator marking a test that requires a multi-XPU setup. These tests are skipped on a machine without multiple
+ XPUs.
+ """
+ return unittest.skipUnless(torch.xpu.device_count() > 1, "test requires multiple XPUs")(test_case)
+
+
+def require_deepspeed(test_case):
+ """
+ Decorator marking a test that requires DeepSpeed installed. These tests are skipped when DeepSpeed isn't installed
+ """
+ return unittest.skipUnless(is_deepspeed_available(), "test requires DeepSpeed")(test_case)
+
+
+def require_fsdp(test_case):
+ """
+ Decorator marking a test that requires FSDP installed. These tests are skipped when FSDP isn't installed
+ """
+ return unittest.skipUnless(is_torch_version(">=", "1.12.0"), "test requires torch version >= 1.12.0")(test_case)
+
+
+def require_torch_min_version(test_case=None, version=None):
+ """
+ Decorator marking that a test requires a particular torch version to be tested. These tests are skipped when an
+ installed torch version is less than the required one.
+ """
+ if test_case is None:
+ return partial(require_torch_min_version, version=version)
+ return unittest.skipUnless(is_torch_version(">=", version), f"test requires torch version >= {version}")(test_case)
+
+
+def require_tensorboard(test_case):
+ """
+ Decorator marking a test that requires tensorboard installed. These tests are skipped when tensorboard isn't
+ installed
+ """
+ return unittest.skipUnless(is_tensorboard_available(), "test requires Tensorboard")(test_case)
+
+
+def require_wandb(test_case):
+ """
+ Decorator marking a test that requires wandb installed. These tests are skipped when wandb isn't installed
+ """
+ return unittest.skipUnless(is_wandb_available(), "test requires wandb")(test_case)
+
+
+def require_comet_ml(test_case):
+ """
+ Decorator marking a test that requires comet_ml installed. These tests are skipped when comet_ml isn't installed
+ """
+ return unittest.skipUnless(is_comet_ml_available(), "test requires comet_ml")(test_case)
+
+
+def require_clearml(test_case):
+ """
+ Decorator marking a test that requires clearml installed. These tests are skipped when clearml isn't installed
+ """
+ return unittest.skipUnless(is_clearml_available(), "test requires clearml")(test_case)
+
+
+def require_dvclive(test_case):
+ """
+ Decorator marking a test that requires dvclive installed. These tests are skipped when dvclive isn't installed
+ """
+ return unittest.skipUnless(is_dvclive_available(), "test requires dvclive")(test_case)
+
+
+def require_pandas(test_case):
+ """
+ Decorator marking a test that requires pandas installed. These tests are skipped when pandas isn't installed
+ """
+ return unittest.skipUnless(is_pandas_available(), "test requires pandas")(test_case)
+
+
+def require_pippy(test_case):
+ """
+ Decorator marking a test that requires pippy installed. These tests are skipped when pippy isn't installed
+ """
+ return unittest.skipUnless(is_pippy_available(), "test requires pippy")(test_case)
+
+
+def require_import_timer(test_case):
+ """
+ Decorator marking a test that requires tuna interpreter installed. These tests are skipped when tuna isn't
+ installed
+ """
+ return unittest.skipUnless(is_import_timer_available(), "test requires tuna interpreter")(test_case)
+
+
+def require_transformer_engine(test_case):
+ """
+ Decorator marking a test that requires transformers engine installed. These tests are skipped when transformers
+ engine isn't installed
+ """
+ return unittest.skipUnless(is_transformer_engine_available(), "test requires transformers engine")(test_case)
+
+
+_atleast_one_tracker_available = (
+ any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
+)
+
+
+def require_trackers(test_case):
+ """
+ Decorator marking that a test requires at least one tracking library installed. These tests are skipped when none
+ are installed
+ """
+ return unittest.skipUnless(
+ _atleast_one_tracker_available,
+ "test requires at least one tracker to be available and for `comet_ml` to not be installed",
+ )(test_case)
+
+
+def require_torchdata_stateful_dataloader(test_case):
+ """
+ Decorator marking a test that requires torchdata.stateful_dataloader.
+
+ These tests are skipped when torchdata with stateful_dataloader module isn't installed.
+
+ """
+ return unittest.skipUnless(
+ is_torchdata_stateful_dataloader_available(), "test requires torchdata.stateful_dataloader"
+ )(test_case)
+
+
+class TempDirTestCase(unittest.TestCase):
+ """
+ A TestCase class that keeps a single `tempfile.TemporaryDirectory` open for the duration of the class, wipes its
+ data at the start of a test, and then destroyes it at the end of the TestCase.
+
+ Useful for when a class or API requires a single constant folder throughout it's use, such as Weights and Biases
+
+ The temporary directory location will be stored in `self.tmpdir`
+ """
+
+ clear_on_setup = True
+
+ @classmethod
+ def setUpClass(cls):
+ "Creates a `tempfile.TemporaryDirectory` and stores it in `cls.tmpdir`"
+ cls.tmpdir = Path(tempfile.mkdtemp())
+
+ @classmethod
+ def tearDownClass(cls):
+ "Remove `cls.tmpdir` after test suite has finished"
+ if os.path.exists(cls.tmpdir):
+ shutil.rmtree(cls.tmpdir)
+
+ def setUp(self):
+ "Destroy all contents in `self.tmpdir`, but not `self.tmpdir`"
+ if self.clear_on_setup:
+ for path in self.tmpdir.glob("**/*"):
+ if path.is_file():
+ path.unlink()
+ elif path.is_dir():
+ shutil.rmtree(path)
+
+
+class AccelerateTestCase(unittest.TestCase):
+ """
+ A TestCase class that will reset the accelerator state at the end of every test. Every test that checks or utilizes
+ the `AcceleratorState` class should inherit from this to avoid silent failures due to state being shared between
+ tests.
+ """
+
+ def tearDown(self):
+ super().tearDown()
+ # Reset the state of the AcceleratorState singleton.
+ AcceleratorState._reset_state()
+ PartialState._reset_state()
+
+
+class MockingTestCase(unittest.TestCase):
+ """
+ A TestCase class designed to dynamically add various mockers that should be used in every test, mimicking the
+ behavior of a class-wide mock when defining one normally will not do.
+
+ Useful when a mock requires specific information available only initialized after `TestCase.setUpClass`, such as
+ setting an environment variable with that information.
+
+ The `add_mocks` function should be ran at the end of a `TestCase`'s `setUp` function, after a call to
+ `super().setUp()` such as:
+ ```python
+ def setUp(self):
+ super().setUp()
+ mocks = mock.patch.dict(os.environ, {"SOME_ENV_VAR", "SOME_VALUE"})
+ self.add_mocks(mocks)
+ ```
+ """
+
+ def add_mocks(self, mocks: Union[mock.Mock, List[mock.Mock]]):
+ """
+ Add custom mocks for tests that should be repeated on each test. Should be called during
+ `MockingTestCase.setUp`, after `super().setUp()`.
+
+ Args:
+ mocks (`mock.Mock` or list of `mock.Mock`):
+ Mocks that should be added to the `TestCase` after `TestCase.setUpClass` has been run
+ """
+ self.mocks = mocks if isinstance(mocks, (tuple, list)) else [mocks]
+ for m in self.mocks:
+ m.start()
+ self.addCleanup(m.stop)
+
+
+def are_the_same_tensors(tensor):
+ state = AcceleratorState()
+ tensor = tensor[None].clone().to(state.device)
+ tensors = gather(tensor).cpu()
+ tensor = tensor[0].cpu()
+ for i in range(tensors.shape[0]):
+ if not torch.equal(tensors[i], tensor):
+ return False
+ return True
+
+
+class _RunOutput:
+ def __init__(self, returncode, stdout, stderr):
+ self.returncode = returncode
+ self.stdout = stdout
+ self.stderr = stderr
+
+
+async def _read_stream(stream, callback):
+ while True:
+ line = await stream.readline()
+ if line:
+ callback(line)
+ else:
+ break
+
+
+async def _stream_subprocess(cmd, env=None, stdin=None, timeout=None, quiet=False, echo=False) -> _RunOutput:
+ if echo:
+ print("\nRunning: ", " ".join(cmd))
+
+ p = await asyncio.create_subprocess_exec(
+ cmd[0],
+ *cmd[1:],
+ stdin=stdin,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ env=env,
+ )
+
+ # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
+ # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
+ #
+ # If it starts hanging, will need to switch to the following code. The problem is that no data
+ # will be seen until it's done and if it hangs for example there will be no debug info.
+ # out, err = await p.communicate()
+ # return _RunOutput(p.returncode, out, err)
+
+ out = []
+ err = []
+
+ def tee(line, sink, pipe, label=""):
+ line = line.decode("utf-8").rstrip()
+ sink.append(line)
+ if not quiet:
+ print(label, line, file=pipe)
+
+ # XXX: the timeout doesn't seem to make any difference here
+ await asyncio.wait(
+ [
+ asyncio.create_task(_read_stream(p.stdout, lambda l: tee(l, out, sys.stdout, label="stdout:"))),
+ asyncio.create_task(_read_stream(p.stderr, lambda l: tee(l, err, sys.stderr, label="stderr:"))),
+ ],
+ timeout=timeout,
+ )
+ return _RunOutput(await p.wait(), out, err)
+
+
+def execute_subprocess_async(cmd: list, env=None, stdin=None, timeout=180, quiet=False, echo=True) -> _RunOutput:
+ # Cast every path in `cmd` to a string
+ for i, c in enumerate(cmd):
+ if isinstance(c, Path):
+ cmd[i] = str(c)
+ loop = asyncio.get_event_loop()
+ result = loop.run_until_complete(
+ _stream_subprocess(cmd, env=env, stdin=stdin, timeout=timeout, quiet=quiet, echo=echo)
+ )
+
+ cmd_str = " ".join(cmd)
+ if result.returncode > 0:
+ stderr = "\n".join(result.stderr)
+ raise RuntimeError(
+ f"'{cmd_str}' failed with returncode {result.returncode}\n\n"
+ f"The combined stderr from workers follows:\n{stderr}"
+ )
+
+ return result
+
+
+class SubprocessCallException(Exception):
+ pass
+
+
+def run_command(command: List[str], return_stdout=False, env=None):
+ """
+ Runs `command` with `subprocess.check_output` and will potentially return the `stdout`. Will also properly capture
+ if an error occured while running `command`
+ """
+ # Cast every path in `command` to a string
+ for i, c in enumerate(command):
+ if isinstance(c, Path):
+ command[i] = str(c)
+ if env is None:
+ env = os.environ.copy()
+ try:
+ output = subprocess.check_output(command, stderr=subprocess.STDOUT, env=env)
+ if return_stdout:
+ if hasattr(output, "decode"):
+ output = output.decode("utf-8")
+ return output
+ except subprocess.CalledProcessError as e:
+ raise SubprocessCallException(
+ f"Command `{' '.join(command)}` failed with the following error:\n\n{e.output.decode()}"
+ ) from e
+
+
+def path_in_accelerate_package(*components: str) -> Path:
+ """
+ Get a path within the `accelerate` package's directory.
+
+ Args:
+ *components: Components of the path to join after the package directory.
+
+ Returns:
+ `Path`: The path to the requested file or directory.
+ """
+
+ accelerate_package_dir = Path(inspect.getfile(accelerate)).parent
+ return accelerate_package_dir.joinpath(*components)
+
+
+@contextmanager
+def assert_exception(exception_class: Exception, msg: str = None) -> bool:
+ """
+ Context manager to assert that the right `Exception` class was raised.
+
+ If `msg` is provided, will check that the message is contained in the raised exception.
+ """
+ was_ran = False
+ try:
+ yield
+ was_ran = True
+ except Exception as e:
+ assert isinstance(e, exception_class), f"Expected exception of type {exception_class} but got {type(e)}"
+ if msg is not None:
+ assert msg in str(e), f"Expected message '{msg}' to be in exception but got '{str(e)}'"
+ if was_ran:
+ raise AssertionError(f"Expected exception of type {exception_class} but ran without issue.")
+
+
+def capture_call_output(func, *args, **kwargs):
+ """
+ Takes in a `func` with `args` and `kwargs` and returns the captured stdout as a string
+ """
+ captured_output = io.StringIO()
+ original_stdout = sys.stdout
+ try:
+ sys.stdout = captured_output
+ func(*args, **kwargs)
+ except Exception as e:
+ raise e
+ finally:
+ sys.stdout = original_stdout
+ return captured_output.getvalue()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/training.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/training.py
new file mode 100644
index 0000000000000000000000000000000000000000..d89cfd3c71546871d00cb9c2a5cd07494c46cbfe
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/test_utils/training.py
@@ -0,0 +1,101 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import numpy as np
+import torch
+from torch.utils.data import DataLoader
+
+from accelerate.utils.dataclasses import DistributedType
+
+
+class RegressionDataset:
+ def __init__(self, a=2, b=3, length=64, seed=None):
+ rng = np.random.default_rng(seed)
+ self.length = length
+ self.x = rng.normal(size=(length,)).astype(np.float32)
+ self.y = a * self.x + b + rng.normal(scale=0.1, size=(length,)).astype(np.float32)
+
+ def __len__(self):
+ return self.length
+
+ def __getitem__(self, i):
+ return {"x": self.x[i], "y": self.y[i]}
+
+
+class RegressionModel4XPU(torch.nn.Module):
+ def __init__(self, a=0, b=0, double_output=False):
+ super().__init__()
+ self.a = torch.nn.Parameter(torch.tensor([2, 3]).float())
+ self.b = torch.nn.Parameter(torch.tensor([2, 3]).float())
+ self.first_batch = True
+
+ def forward(self, x=None):
+ if self.first_batch:
+ print(f"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}")
+ self.first_batch = False
+ return x * self.a[0] + self.b[0]
+
+
+class RegressionModel(torch.nn.Module):
+ def __init__(self, a=0, b=0, double_output=False):
+ super().__init__()
+ self.a = torch.nn.Parameter(torch.tensor(a).float())
+ self.b = torch.nn.Parameter(torch.tensor(b).float())
+ self.first_batch = True
+
+ def forward(self, x=None):
+ if self.first_batch:
+ print(f"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}")
+ self.first_batch = False
+ return x * self.a + self.b
+
+
+def mocked_dataloaders(accelerator, batch_size: int = 16):
+ from datasets import load_dataset
+ from transformers import AutoTokenizer
+
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ data_files = {"train": "tests/test_samples/MRPC/train.csv", "validation": "tests/test_samples/MRPC/dev.csv"}
+ datasets = load_dataset("csv", data_files=data_files)
+ label_list = datasets["train"].unique("label")
+
+ label_to_id = {v: i for i, v in enumerate(label_list)}
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(
+ examples["sentence1"], examples["sentence2"], truncation=True, max_length=None, padding="max_length"
+ )
+ if "label" in examples:
+ outputs["labels"] = [label_to_id[l] for l in examples["label"]]
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["sentence1", "sentence2", "label"],
+ )
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ if accelerator.distributed_type == DistributedType.XLA:
+ return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt")
+ return tokenizer.pad(examples, padding="longest", return_tensors="pt")
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=2)
+ eval_dataloader = DataLoader(tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=1)
+
+ return train_dataloader, eval_dataloader
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/tracking.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/tracking.py
new file mode 100644
index 0000000000000000000000000000000000000000..5efba19bc6769d9c70ea8b17b8da784b908f529f
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/tracking.py
@@ -0,0 +1,1023 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Expectation:
+# Provide a project dir name, then each type of logger gets stored in project/{`logging_dir`}
+
+import json
+import os
+import time
+from functools import wraps
+from typing import Any, Dict, List, Optional, Union
+
+import yaml
+
+from .logging import get_logger
+from .state import PartialState
+from .utils import (
+ LoggerType,
+ is_aim_available,
+ is_clearml_available,
+ is_comet_ml_available,
+ is_dvclive_available,
+ is_mlflow_available,
+ is_tensorboard_available,
+ is_wandb_available,
+ listify,
+)
+
+
+_available_trackers = []
+
+if is_tensorboard_available():
+ _available_trackers.append(LoggerType.TENSORBOARD)
+
+if is_wandb_available():
+ _available_trackers.append(LoggerType.WANDB)
+
+if is_comet_ml_available():
+ _available_trackers.append(LoggerType.COMETML)
+
+if is_aim_available():
+ _available_trackers.append(LoggerType.AIM)
+
+if is_mlflow_available():
+ _available_trackers.append(LoggerType.MLFLOW)
+
+if is_clearml_available():
+ _available_trackers.append(LoggerType.CLEARML)
+
+if is_dvclive_available():
+ _available_trackers.append(LoggerType.DVCLIVE)
+
+logger = get_logger(__name__)
+
+
+def on_main_process(function):
+ """
+ Decorator to selectively run the decorated function on the main process only based on the `main_process_only`
+ attribute in a class.
+
+ Checks at function execution rather than initialization time, not triggering the initialization of the
+ `PartialState`.
+ """
+
+ @wraps(function)
+ def execute_on_main_process(self, *args, **kwargs):
+ if getattr(self, "main_process_only", False):
+ return PartialState().on_main_process(function)(self, *args, **kwargs)
+ else:
+ return function(self, *args, **kwargs)
+
+ return execute_on_main_process
+
+
+def get_available_trackers():
+ "Returns a list of all supported available trackers in the system"
+ return _available_trackers
+
+
+class GeneralTracker:
+ """
+ A base Tracker class to be used for all logging integration implementations.
+
+ Each function should take in `**kwargs` that will automatically be passed in from a base dictionary provided to
+ [`Accelerator`].
+
+ Should implement `name`, `requires_logging_directory`, and `tracker` properties such that:
+
+ `name` (`str`): String representation of the tracker class name, such as "TensorBoard" `requires_logging_directory`
+ (`bool`): Whether the logger requires a directory to store their logs. `tracker` (`object`): Should return internal
+ tracking mechanism used by a tracker class (such as the `run` for wandb)
+
+ Implementations can also include a `main_process_only` (`bool`) attribute to toggle if relevent logging, init, and
+ other functions should occur on the main process or across all processes (by default will use `True`)
+ """
+
+ main_process_only = True
+
+ def __init__(self, _blank=False):
+ if not _blank:
+ err = ""
+ if not hasattr(self, "name"):
+ err += "`name`"
+ if not hasattr(self, "requires_logging_directory"):
+ if len(err) > 0:
+ err += ", "
+ err += "`requires_logging_directory`"
+
+ # as tracker is a @property that relies on post-init
+ if "tracker" not in dir(self):
+ if len(err) > 0:
+ err += ", "
+ err += "`tracker`"
+ if len(err) > 0:
+ raise NotImplementedError(
+ f"The implementation for this tracker class is missing the following "
+ f"required attributes. Please define them in the class definition: "
+ f"{err}"
+ )
+
+ def store_init_configuration(self, values: dict):
+ """
+ Logs `values` as hyperparameters for the run. Implementations should use the experiment configuration
+ functionality of a tracking API.
+
+ Args:
+ values (Dictionary `str` to `bool`, `str`, `float` or `int`):
+ Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
+ `str`, `float`, `int`, or `None`.
+ """
+ pass
+
+ def log(self, values: dict, step: Optional[int], **kwargs):
+ """
+ Logs `values` to the current run. Base `log` implementations of a tracking API should go in here, along with
+ special behavior for the `step parameter.
+
+ Args:
+ values (Dictionary `str` to `str`, `float`, or `int`):
+ Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`.
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ """
+ pass
+
+ def finish(self):
+ """
+ Should run any finalizing functions within the tracking API. If the API should not have one, just don't
+ overwrite that method.
+ """
+ pass
+
+
+class TensorBoardTracker(GeneralTracker):
+ """
+ A `Tracker` class that supports `tensorboard`. Should be initialized at the start of your script.
+
+ Args:
+ run_name (`str`):
+ The name of the experiment run
+ logging_dir (`str`, `os.PathLike`):
+ Location for TensorBoard logs to be stored.
+ **kwargs (additional keyword arguments, *optional*):
+ Additional key word arguments passed along to the `tensorboard.SummaryWriter.__init__` method.
+ """
+
+ name = "tensorboard"
+ requires_logging_directory = True
+
+ @on_main_process
+ def __init__(self, run_name: str, logging_dir: Union[str, os.PathLike], **kwargs):
+ try:
+ from torch.utils import tensorboard
+ except ModuleNotFoundError:
+ import tensorboardX as tensorboard
+ super().__init__()
+ self.run_name = run_name
+ self.logging_dir = os.path.join(logging_dir, run_name)
+ self.writer = tensorboard.SummaryWriter(self.logging_dir, **kwargs)
+ logger.debug(f"Initialized TensorBoard project {self.run_name} logging to {self.logging_dir}")
+ logger.debug(
+ "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
+ )
+
+ @property
+ def tracker(self):
+ return self.writer
+
+ @on_main_process
+ def store_init_configuration(self, values: dict):
+ """
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the
+ hyperparameters in a yaml file for future use.
+
+ Args:
+ values (Dictionary `str` to `bool`, `str`, `float` or `int`):
+ Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
+ `str`, `float`, `int`, or `None`.
+ """
+ self.writer.add_hparams(values, metric_dict={})
+ self.writer.flush()
+ project_run_name = time.time()
+ dir_name = os.path.join(self.logging_dir, str(project_run_name))
+ os.makedirs(dir_name, exist_ok=True)
+ with open(os.path.join(dir_name, "hparams.yml"), "w") as outfile:
+ try:
+ yaml.dump(values, outfile)
+ except yaml.representer.RepresenterError:
+ logger.error("Serialization to store hyperparameters failed")
+ raise
+ logger.debug("Stored initial configuration hyperparameters to TensorBoard and hparams yaml file")
+
+ @on_main_process
+ def log(self, values: dict, step: Optional[int] = None, **kwargs):
+ """
+ Logs `values` to the current run.
+
+ Args:
+ values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
+ Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
+ `str` to `float`/`int`.
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ kwargs:
+ Additional key word arguments passed along to either `SummaryWriter.add_scaler`,
+ `SummaryWriter.add_text`, or `SummaryWriter.add_scalers` method based on the contents of `values`.
+ """
+ values = listify(values)
+ for k, v in values.items():
+ if isinstance(v, (int, float)):
+ self.writer.add_scalar(k, v, global_step=step, **kwargs)
+ elif isinstance(v, str):
+ self.writer.add_text(k, v, global_step=step, **kwargs)
+ elif isinstance(v, dict):
+ self.writer.add_scalars(k, v, global_step=step, **kwargs)
+ self.writer.flush()
+ logger.debug("Successfully logged to TensorBoard")
+
+ @on_main_process
+ def log_images(self, values: dict, step: Optional[int], **kwargs):
+ """
+ Logs `images` to the current run.
+
+ Args:
+ values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`):
+ Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ kwargs:
+ Additional key word arguments passed along to the `SummaryWriter.add_image` method.
+ """
+ for k, v in values.items():
+ self.writer.add_images(k, v, global_step=step, **kwargs)
+ logger.debug("Successfully logged images to TensorBoard")
+
+ @on_main_process
+ def finish(self):
+ """
+ Closes `TensorBoard` writer
+ """
+ self.writer.close()
+ logger.debug("TensorBoard writer closed")
+
+
+class WandBTracker(GeneralTracker):
+ """
+ A `Tracker` class that supports `wandb`. Should be initialized at the start of your script.
+
+ Args:
+ run_name (`str`):
+ The name of the experiment run.
+ **kwargs (additional keyword arguments, *optional*):
+ Additional key word arguments passed along to the `wandb.init` method.
+ """
+
+ name = "wandb"
+ requires_logging_directory = False
+ main_process_only = False
+
+ @on_main_process
+ def __init__(self, run_name: str, **kwargs):
+ super().__init__()
+ self.run_name = run_name
+
+ import wandb
+
+ self.run = wandb.init(project=self.run_name, **kwargs)
+ logger.debug(f"Initialized WandB project {self.run_name}")
+ logger.debug(
+ "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
+ )
+
+ @property
+ def tracker(self):
+ return self.run
+
+ @on_main_process
+ def store_init_configuration(self, values: dict):
+ """
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
+
+ Args:
+ values (Dictionary `str` to `bool`, `str`, `float` or `int`):
+ Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
+ `str`, `float`, `int`, or `None`.
+ """
+ import wandb
+
+ wandb.config.update(values, allow_val_change=True)
+ logger.debug("Stored initial configuration hyperparameters to WandB")
+
+ @on_main_process
+ def log(self, values: dict, step: Optional[int] = None, **kwargs):
+ """
+ Logs `values` to the current run.
+
+ Args:
+ values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
+ Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
+ `str` to `float`/`int`.
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ kwargs:
+ Additional key word arguments passed along to the `wandb.log` method.
+ """
+ self.run.log(values, step=step, **kwargs)
+ logger.debug("Successfully logged to WandB")
+
+ @on_main_process
+ def log_images(self, values: dict, step: Optional[int] = None, **kwargs):
+ """
+ Logs `images` to the current run.
+
+ Args:
+ values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`):
+ Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ kwargs:
+ Additional key word arguments passed along to the `wandb.log` method.
+ """
+ import wandb
+
+ for k, v in values.items():
+ self.log({k: [wandb.Image(image) for image in v]}, step=step, **kwargs)
+ logger.debug("Successfully logged images to WandB")
+
+ @on_main_process
+ def log_table(
+ self,
+ table_name: str,
+ columns: List[str] = None,
+ data: List[List[Any]] = None,
+ dataframe: Any = None,
+ step: Optional[int] = None,
+ **kwargs,
+ ):
+ """
+ Log a Table containing any object type (text, image, audio, video, molecule, html, etc). Can be defined either
+ with `columns` and `data` or with `dataframe`.
+
+ Args:
+ table_name (`str`):
+ The name to give to the logged table on the wandb workspace
+ columns (list of `str`, *optional*):
+ The name of the columns on the table
+ data (List of List of Any data type, *optional*):
+ The data to be logged in the table
+ dataframe (Any data type, *optional*):
+ The data to be logged in the table
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ """
+ import wandb
+
+ values = {table_name: wandb.Table(columns=columns, data=data, dataframe=dataframe)}
+ self.log(values, step=step, **kwargs)
+
+ @on_main_process
+ def finish(self):
+ """
+ Closes `wandb` writer
+ """
+ self.run.finish()
+ logger.debug("WandB run closed")
+
+
+class CometMLTracker(GeneralTracker):
+ """
+ A `Tracker` class that supports `comet_ml`. Should be initialized at the start of your script.
+
+ API keys must be stored in a Comet config file.
+
+ Args:
+ run_name (`str`):
+ The name of the experiment run.
+ **kwargs (additional keyword arguments, *optional*):
+ Additional key word arguments passed along to the `Experiment.__init__` method.
+ """
+
+ name = "comet_ml"
+ requires_logging_directory = False
+
+ @on_main_process
+ def __init__(self, run_name: str, **kwargs):
+ super().__init__()
+ self.run_name = run_name
+
+ from comet_ml import Experiment
+
+ self.writer = Experiment(project_name=run_name, **kwargs)
+ logger.debug(f"Initialized CometML project {self.run_name}")
+ logger.debug(
+ "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
+ )
+
+ @property
+ def tracker(self):
+ return self.writer
+
+ @on_main_process
+ def store_init_configuration(self, values: dict):
+ """
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
+
+ Args:
+ values (Dictionary `str` to `bool`, `str`, `float` or `int`):
+ Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
+ `str`, `float`, `int`, or `None`.
+ """
+ self.writer.log_parameters(values)
+ logger.debug("Stored initial configuration hyperparameters to CometML")
+
+ @on_main_process
+ def log(self, values: dict, step: Optional[int] = None, **kwargs):
+ """
+ Logs `values` to the current run.
+
+ Args:
+ values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
+ Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
+ `str` to `float`/`int`.
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ kwargs:
+ Additional key word arguments passed along to either `Experiment.log_metric`, `Experiment.log_other`,
+ or `Experiment.log_metrics` method based on the contents of `values`.
+ """
+ if step is not None:
+ self.writer.set_step(step)
+ for k, v in values.items():
+ if isinstance(v, (int, float)):
+ self.writer.log_metric(k, v, step=step, **kwargs)
+ elif isinstance(v, str):
+ self.writer.log_other(k, v, **kwargs)
+ elif isinstance(v, dict):
+ self.writer.log_metrics(v, step=step, **kwargs)
+ logger.debug("Successfully logged to CometML")
+
+ @on_main_process
+ def finish(self):
+ """
+ Closes `comet-ml` writer
+ """
+ self.writer.end()
+ logger.debug("CometML run closed")
+
+
+class AimTracker(GeneralTracker):
+ """
+ A `Tracker` class that supports `aim`. Should be initialized at the start of your script.
+
+ Args:
+ run_name (`str`):
+ The name of the experiment run.
+ **kwargs (additional keyword arguments, *optional*):
+ Additional key word arguments passed along to the `Run.__init__` method.
+ """
+
+ name = "aim"
+ requires_logging_directory = True
+
+ @on_main_process
+ def __init__(self, run_name: str, logging_dir: Optional[Union[str, os.PathLike]] = ".", **kwargs):
+ self.run_name = run_name
+
+ from aim import Run
+
+ self.writer = Run(repo=logging_dir, **kwargs)
+ self.writer.name = self.run_name
+ logger.debug(f"Initialized Aim project {self.run_name}")
+ logger.debug(
+ "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
+ )
+
+ @property
+ def tracker(self):
+ return self.writer
+
+ @on_main_process
+ def store_init_configuration(self, values: dict):
+ """
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
+
+ Args:
+ values (`dict`):
+ Values to be stored as initial hyperparameters as key-value pairs.
+ """
+ self.writer["hparams"] = values
+
+ @on_main_process
+ def log(self, values: dict, step: Optional[int], **kwargs):
+ """
+ Logs `values` to the current run.
+
+ Args:
+ values (`dict`):
+ Values to be logged as key-value pairs.
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ kwargs:
+ Additional key word arguments passed along to the `Run.track` method.
+ """
+ # Note: replace this with the dictionary support when merged
+ for key, value in values.items():
+ self.writer.track(value, name=key, step=step, **kwargs)
+
+ @on_main_process
+ def log_images(self, values: dict, step: Optional[int] = None, kwargs: Optional[Dict[str, dict]] = None):
+ """
+ Logs `images` to the current run.
+
+ Args:
+ values (`Dict[str, Union[np.ndarray, PIL.Image, Tuple[np.ndarray, str], Tuple[PIL.Image, str]]]`):
+ Values to be logged as key-value pairs. The values need to have type `np.ndarray` or PIL.Image. If a
+ tuple is provided, the first element should be the image and the second element should be the caption.
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ kwargs (`Dict[str, dict]`):
+ Additional key word arguments passed along to the `Run.Image` and `Run.track` method specified by the
+ keys `aim_image` and `track`, respectively.
+ """
+ import aim
+
+ aim_image_kw = {}
+ track_kw = {}
+
+ if kwargs is not None:
+ aim_image_kw = kwargs.get("aim_image", {})
+ track_kw = kwargs.get("track", {})
+
+ for key, value in values.items():
+ if isinstance(value, tuple):
+ img, caption = value
+ else:
+ img, caption = value, ""
+ aim_image = aim.Image(img, caption=caption, **aim_image_kw)
+ self.writer.track(aim_image, name=key, step=step, **track_kw)
+
+ @on_main_process
+ def finish(self):
+ """
+ Closes `aim` writer
+ """
+ self.writer.close()
+
+
+class MLflowTracker(GeneralTracker):
+ """
+ A `Tracker` class that supports `mlflow`. Should be initialized at the start of your script.
+
+ Args:
+ experiment_name (`str`, *optional*):
+ Name of the experiment. Environment variable MLFLOW_EXPERIMENT_NAME has priority over this argument.
+ logging_dir (`str` or `os.PathLike`, defaults to `"."`):
+ Location for mlflow logs to be stored.
+ run_id (`str`, *optional*):
+ If specified, get the run with the specified UUID and log parameters and metrics under that run. The run’s
+ end time is unset and its status is set to running, but the run’s other attributes (source_version,
+ source_type, etc.) are not changed. Environment variable MLFLOW_RUN_ID has priority over this argument.
+ tags (`Dict[str, str]`, *optional*):
+ An optional `dict` of `str` keys and values, or a `str` dump from a `dict`, to set as tags on the run. If a
+ run is being resumed, these tags are set on the resumed run. If a new run is being created, these tags are
+ set on the new run. Environment variable MLFLOW_TAGS has priority over this argument.
+ nested_run (`bool`, *optional*, defaults to `False`):
+ Controls whether run is nested in parent run. True creates a nested run. Environment variable
+ MLFLOW_NESTED_RUN has priority over this argument.
+ run_name (`str`, *optional*):
+ Name of new run (stored as a mlflow.runName tag). Used only when `run_id` is unspecified.
+ description (`str`, *optional*):
+ An optional string that populates the description box of the run. If a run is being resumed, the
+ description is set on the resumed run. If a new run is being created, the description is set on the new
+ run.
+ """
+
+ name = "mlflow"
+ requires_logging_directory = False
+
+ @on_main_process
+ def __init__(
+ self,
+ experiment_name: str = None,
+ logging_dir: Optional[Union[str, os.PathLike]] = None,
+ run_id: Optional[str] = None,
+ tags: Optional[Union[Dict[str, Any], str]] = None,
+ nested_run: Optional[bool] = False,
+ run_name: Optional[str] = None,
+ description: Optional[str] = None,
+ ):
+ experiment_name = os.environ.get("MLFLOW_EXPERIMENT_NAME", experiment_name)
+ run_id = os.environ.get("MLFLOW_RUN_ID", run_id)
+ tags = os.environ.get("MLFLOW_TAGS", tags)
+ if isinstance(tags, str):
+ tags = json.loads(tags)
+
+ nested_run = os.environ.get("MLFLOW_NESTED_RUN", nested_run)
+
+ import mlflow
+
+ exps = mlflow.search_experiments(filter_string=f"name = '{experiment_name}'")
+ if len(exps) > 0:
+ if len(exps) > 1:
+ logger.warning("Multiple experiments with the same name found. Using first one.")
+ experiment_id = exps[0].experiment_id
+ else:
+ experiment_id = mlflow.create_experiment(
+ name=experiment_name,
+ artifact_location=logging_dir,
+ tags=tags,
+ )
+
+ self.active_run = mlflow.start_run(
+ run_id=run_id,
+ experiment_id=experiment_id,
+ run_name=run_name,
+ nested=nested_run,
+ tags=tags,
+ description=description,
+ )
+
+ logger.debug(f"Initialized mlflow experiment {experiment_name}")
+ logger.debug(
+ "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
+ )
+
+ @property
+ def tracker(self):
+ return self.active_run
+
+ @on_main_process
+ def store_init_configuration(self, values: dict):
+ """
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
+
+ Args:
+ values (`dict`):
+ Values to be stored as initial hyperparameters as key-value pairs.
+ """
+ import mlflow
+
+ for name, value in list(values.items()):
+ # internally, all values are converted to str in MLflow
+ if len(str(value)) > mlflow.utils.validation.MAX_PARAM_VAL_LENGTH:
+ logger.warning_once(
+ f'Accelerate is attempting to log a value of "{value}" for key "{name}" as a parameter. MLflow\'s'
+ f" log_param() only accepts values no longer than {mlflow.utils.validation.MAX_PARAM_VAL_LENGTH} characters so we dropped this attribute."
+ )
+ del values[name]
+
+ values_list = list(values.items())
+
+ # MLflow cannot log more than 100 values in one go, so we have to split it
+ for i in range(0, len(values_list), mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH):
+ mlflow.log_params(dict(values_list[i : i + mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH]))
+
+ logger.debug("Stored initial configuration hyperparameters to MLflow")
+
+ @on_main_process
+ def log(self, values: dict, step: Optional[int]):
+ """
+ Logs `values` to the current run.
+
+ Args:
+ values (`dict`):
+ Values to be logged as key-value pairs.
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ """
+ metrics = {}
+ for k, v in values.items():
+ if isinstance(v, (int, float)):
+ metrics[k] = v
+ else:
+ logger.warning_once(
+ f'MLflowTracker is attempting to log a value of "{v}" of type {type(v)} for key "{k}" as a metric. '
+ "MLflow's log_metric() only accepts float and int types so we dropped this attribute."
+ )
+ import mlflow
+
+ mlflow.log_metrics(metrics, step=step)
+ logger.debug("Successfully logged to mlflow")
+
+ @on_main_process
+ def finish(self):
+ """
+ End the active MLflow run.
+ """
+ import mlflow
+
+ mlflow.end_run()
+
+
+class ClearMLTracker(GeneralTracker):
+ """
+ A `Tracker` class that supports `clearml`. Should be initialized at the start of your script.
+
+ Args:
+ run_name (`str`, *optional*):
+ Name of the experiment. Environment variables `CLEARML_PROJECT` and `CLEARML_TASK` have priority over this
+ argument.
+ **kwargs (additional keyword arguments, *optional*):
+ Kwargs passed along to the `Task.__init__` method.
+ """
+
+ name = "clearml"
+ requires_logging_directory = False
+
+ @on_main_process
+ def __init__(self, run_name: str = None, **kwargs):
+ from clearml import Task
+
+ current_task = Task.current_task()
+ self._initialized_externally = False
+ if current_task:
+ self._initialized_externally = True
+ self.task = current_task
+ return
+
+ kwargs.setdefault("project_name", os.environ.get("CLEARML_PROJECT", run_name))
+ kwargs.setdefault("task_name", os.environ.get("CLEARML_TASK", run_name))
+ self.task = Task.init(**kwargs)
+
+ @property
+ def tracker(self):
+ return self.task
+
+ @on_main_process
+ def store_init_configuration(self, values: dict):
+ """
+ Connect configuration dictionary to the Task object. Should be run at the beginning of your experiment.
+
+ Args:
+ values (`dict`):
+ Values to be stored as initial hyperparameters as key-value pairs.
+ """
+ return self.task.connect_configuration(values)
+
+ @on_main_process
+ def log(self, values: Dict[str, Union[int, float]], step: Optional[int] = None, **kwargs):
+ """
+ Logs `values` dictionary to the current run. The dictionary keys must be strings. The dictionary values must be
+ ints or floats
+
+ Args:
+ values (`Dict[str, Union[int, float]]`):
+ Values to be logged as key-value pairs. If the key starts with 'eval_'/'test_'/'train_', the value will
+ be reported under the 'eval'/'test'/'train' series and the respective prefix will be removed.
+ Otherwise, the value will be reported under the 'train' series, and no prefix will be removed.
+ step (`int`, *optional*):
+ If specified, the values will be reported as scalars, with the iteration number equal to `step`.
+ Otherwise they will be reported as single values.
+ kwargs:
+ Additional key word arguments passed along to the `clearml.Logger.report_single_value` or
+ `clearml.Logger.report_scalar` methods.
+ """
+ clearml_logger = self.task.get_logger()
+ for k, v in values.items():
+ if not isinstance(v, (int, float)):
+ logger.warning_once(
+ "Accelerator is attempting to log a value of "
+ f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
+ "This invocation of ClearML logger's report_scalar() "
+ "is incorrect so we dropped this attribute."
+ )
+ continue
+ if step is None:
+ clearml_logger.report_single_value(name=k, value=v, **kwargs)
+ continue
+ title, series = ClearMLTracker._get_title_series(k)
+ clearml_logger.report_scalar(title=title, series=series, value=v, iteration=step, **kwargs)
+
+ @on_main_process
+ def log_images(self, values: dict, step: Optional[int] = None, **kwargs):
+ """
+ Logs `images` to the current run.
+
+ Args:
+ values (`Dict[str, List[Union[np.ndarray, PIL.Image]]`):
+ Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ kwargs:
+ Additional key word arguments passed along to the `clearml.Logger.report_image` method.
+ """
+ clearml_logger = self.task.get_logger()
+ for k, v in values.items():
+ title, series = ClearMLTracker._get_title_series(k)
+ clearml_logger.report_image(title=title, series=series, iteration=step, image=v, **kwargs)
+
+ @on_main_process
+ def log_table(
+ self,
+ table_name: str,
+ columns: List[str] = None,
+ data: List[List[Any]] = None,
+ dataframe: Any = None,
+ step: Optional[int] = None,
+ **kwargs,
+ ):
+ """
+ Log a Table to the task. Can be defined eitherwith `columns` and `data` or with `dataframe`.
+
+ Args:
+ table_name (`str`):
+ The name of the table
+ columns (list of `str`, *optional*):
+ The name of the columns on the table
+ data (List of List of Any data type, *optional*):
+ The data to be logged in the table. If `columns` is not specified, then the first entry in data will be
+ the name of the columns of the table
+ dataframe (Any data type, *optional*):
+ The data to be logged in the table
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ kwargs:
+ Additional key word arguments passed along to the `clearml.Logger.report_table` method.
+ """
+ to_report = dataframe
+ if dataframe is None:
+ if data is None:
+ raise ValueError(
+ "`ClearMLTracker.log_table` requires that `data` to be supplied if `dataframe` is `None`"
+ )
+ to_report = [columns] + data if columns else data
+ title, series = ClearMLTracker._get_title_series(table_name)
+ self.task.get_logger().report_table(title=title, series=series, table_plot=to_report, iteration=step, **kwargs)
+
+ @on_main_process
+ def finish(self):
+ """
+ Close the ClearML task. If the task was initialized externally (e.g. by manually calling `Task.init`), this
+ function is a noop
+ """
+ if self.task and not self._initialized_externally:
+ self.task.close()
+
+ @staticmethod
+ def _get_title_series(name):
+ for prefix in ["eval", "test", "train"]:
+ if name.startswith(prefix + "_"):
+ return name[len(prefix) + 1 :], prefix
+ return name, "train"
+
+
+class DVCLiveTracker(GeneralTracker):
+ """
+ A `Tracker` class that supports `dvclive`. Should be initialized at the start of your script.
+
+ Args:
+ run_name (`str`, *optional*):
+ Ignored for dvclive. See `kwargs` instead.
+ kwargs:
+ Additional key word arguments passed along to [`dvclive.Live()`](https://dvc.org/doc/dvclive/live).
+
+ Example:
+
+ ```py
+ from accelerate import Accelerator
+
+ accelerator = Accelerator(log_with="dvclive")
+ accelerator.init_trackers(project_name="my_project", init_kwargs={"dvclive": {"dir": "my_directory"}})
+ ```
+ """
+
+ name = "dvclive"
+ requires_logging_directory = False
+
+ @on_main_process
+ def __init__(self, run_name: Optional[str] = None, live: Optional[Any] = None, **kwargs):
+ from dvclive import Live
+
+ super().__init__()
+ self.live = live if live is not None else Live(**kwargs)
+
+ @property
+ def tracker(self):
+ return self.live
+
+ @on_main_process
+ def store_init_configuration(self, values: dict):
+ """
+ Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the
+ hyperparameters in a yaml file for future use.
+
+ Args:
+ values (Dictionary `str` to `bool`, `str`, `float`, `int`, or a List or Dict of those types):
+ Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
+ `str`, `float`, or `int`.
+ """
+ self.live.log_params(values)
+
+ @on_main_process
+ def log(self, values: dict, step: Optional[int] = None, **kwargs):
+ """
+ Logs `values` to the current run.
+
+ Args:
+ values (Dictionary `str` to `str`, `float`, or `int`):
+ Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`.
+ step (`int`, *optional*):
+ The run step. If included, the log will be affiliated with this step.
+ kwargs:
+ Additional key word arguments passed along to `dvclive.Live.log_metric()`.
+ """
+ from dvclive.plots import Metric
+
+ if step is not None:
+ self.live.step = step
+ for k, v in values.items():
+ if Metric.could_log(v):
+ self.live.log_metric(k, v, **kwargs)
+ else:
+ logger.warning_once(
+ "Accelerator attempted to log a value of "
+ f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
+ "This invocation of DVCLive's Live.log_metric() "
+ "is incorrect so we dropped this attribute."
+ )
+ self.live.next_step()
+
+ @on_main_process
+ def finish(self):
+ """
+ Closes `dvclive.Live()`.
+ """
+ self.live.end()
+
+
+LOGGER_TYPE_TO_CLASS = {
+ "aim": AimTracker,
+ "comet_ml": CometMLTracker,
+ "mlflow": MLflowTracker,
+ "tensorboard": TensorBoardTracker,
+ "wandb": WandBTracker,
+ "clearml": ClearMLTracker,
+ "dvclive": DVCLiveTracker,
+}
+
+
+def filter_trackers(
+ log_with: List[Union[str, LoggerType, GeneralTracker]],
+ logging_dir: Union[str, os.PathLike] = None,
+):
+ """
+ Takes in a list of potential tracker types and checks that:
+ - The tracker wanted is available in that environment
+ - Filters out repeats of tracker types
+ - If `all` is in `log_with`, will return all trackers in the environment
+ - If a tracker requires a `logging_dir`, ensures that `logging_dir` is not `None`
+
+ Args:
+ log_with (list of `str`, [`~utils.LoggerType`] or [`~tracking.GeneralTracker`], *optional*):
+ A list of loggers to be setup for experiment tracking. Should be one or several of:
+
+ - `"all"`
+ - `"tensorboard"`
+ - `"wandb"`
+ - `"comet_ml"`
+ - `"mlflow"`
+ - `"dvclive"`
+ If `"all"` is selected, will pick up all available trackers in the environment and initialize them. Can
+ also accept implementations of `GeneralTracker` for custom trackers, and can be combined with `"all"`.
+ logging_dir (`str`, `os.PathLike`, *optional*):
+ A path to a directory for storing logs of locally-compatible loggers.
+ """
+ loggers = []
+ if log_with is not None:
+ if not isinstance(log_with, (list, tuple)):
+ log_with = [log_with]
+ if "all" in log_with or LoggerType.ALL in log_with:
+ loggers = [o for o in log_with if issubclass(type(o), GeneralTracker)] + get_available_trackers()
+ else:
+ for log_type in log_with:
+ if log_type not in LoggerType and not issubclass(type(log_type), GeneralTracker):
+ raise ValueError(f"Unsupported logging capability: {log_type}. Choose between {LoggerType.list()}")
+ if issubclass(type(log_type), GeneralTracker):
+ loggers.append(log_type)
+ else:
+ log_type = LoggerType(log_type)
+ if log_type not in loggers:
+ if log_type in get_available_trackers():
+ tracker_init = LOGGER_TYPE_TO_CLASS[str(log_type)]
+ if tracker_init.requires_logging_directory:
+ if logging_dir is None:
+ raise ValueError(
+ f"Logging with `{log_type}` requires a `logging_dir` to be passed in."
+ )
+ loggers.append(log_type)
+ else:
+ logger.debug(f"Tried adding logger {log_type}, but package is unavailable in the system.")
+
+ return loggers
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/__init__.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..324fcd17886902b3509e3889c0fdc844d5349cf0
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/__init__.py
@@ -0,0 +1,265 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from .constants import (
+ MITA_PROFILING_AVAILABLE_PYTORCH_VERSION,
+ MODEL_NAME,
+ OPTIMIZER_NAME,
+ PROFILE_PATTERN_NAME,
+ RNG_STATE_NAME,
+ SAFE_MODEL_NAME,
+ SAFE_WEIGHTS_INDEX_NAME,
+ SAFE_WEIGHTS_NAME,
+ SAFE_WEIGHTS_PATTERN_NAME,
+ SAMPLER_NAME,
+ SCALER_NAME,
+ SCHEDULER_NAME,
+ TORCH_DISTRIBUTED_OPERATION_TYPES,
+ TORCH_LAUNCH_PARAMS,
+ WEIGHTS_INDEX_NAME,
+ WEIGHTS_NAME,
+ WEIGHTS_PATTERN_NAME,
+ XPU_PROFILING_AVAILABLE_PYTORCH_VERSION,
+)
+from .dataclasses import (
+ AutocastKwargs,
+ BnbQuantizationConfig,
+ ComputeEnvironment,
+ CustomDtype,
+ DataLoaderConfiguration,
+ DDPCommunicationHookType,
+ DeepSpeedPlugin,
+ DistributedDataParallelKwargs,
+ DistributedType,
+ DynamoBackend,
+ FP8RecipeKwargs,
+ FullyShardedDataParallelPlugin,
+ GradientAccumulationPlugin,
+ GradScalerKwargs,
+ InitProcessGroupKwargs,
+ KwargsHandler,
+ LoggerType,
+ MegatronLMPlugin,
+ PrecisionType,
+ ProfileKwargs,
+ ProjectConfiguration,
+ RNGType,
+ SageMakerDistributedType,
+ TensorInformation,
+ TorchDynamoPlugin,
+ add_model_config_to_megatron_parser,
+)
+from .environment import (
+ are_libraries_initialized,
+ check_cuda_p2p_ib_support,
+ check_fp8_capability,
+ convert_dict_to_env_variables,
+ get_cpu_distributed_information,
+ get_gpu_info,
+ get_int_from_env,
+ parse_choice_from_env,
+ parse_flag_from_env,
+ set_numa_affinity,
+ str_to_bool,
+)
+from .imports import (
+ deepspeed_required,
+ get_ccl_version,
+ is_4bit_bnb_available,
+ is_8bit_bnb_available,
+ is_aim_available,
+ is_bf16_available,
+ is_bitsandbytes_multi_backend_available,
+ is_bnb_available,
+ is_boto3_available,
+ is_ccl_available,
+ is_clearml_available,
+ is_comet_ml_available,
+ is_cuda_available,
+ is_datasets_available,
+ is_deepspeed_available,
+ is_dvclive_available,
+ is_fp8_available,
+ is_import_timer_available,
+ is_ipex_available,
+ is_lomo_available,
+ is_megatron_lm_available,
+ is_mlflow_available,
+ is_mlu_available,
+ is_mps_available,
+ is_msamp_available,
+ is_musa_available,
+ is_npu_available,
+ is_pandas_available,
+ is_peft_available,
+ is_pippy_available,
+ is_pynvml_available,
+ is_pytest_available,
+ is_rich_available,
+ is_sagemaker_available,
+ is_schedulefree_available,
+ is_tensorboard_available,
+ is_timm_available,
+ is_torch_xla_available,
+ is_torchdata_available,
+ is_torchdata_stateful_dataloader_available,
+ is_torchvision_available,
+ is_transformer_engine_available,
+ is_transformers_available,
+ is_triton_available,
+ is_wandb_available,
+ is_xpu_available,
+)
+from .modeling import (
+ calculate_maximum_sizes,
+ check_device_map,
+ check_tied_parameters_in_config,
+ check_tied_parameters_on_same_device,
+ compute_module_sizes,
+ convert_file_size_to_int,
+ dtype_byte_size,
+ find_tied_parameters,
+ get_balanced_memory,
+ get_max_layer_size,
+ get_max_memory,
+ get_mixed_precision_context_manager,
+ id_tensor_storage,
+ infer_auto_device_map,
+ is_peft_model,
+ load_checkpoint_in_model,
+ load_offloaded_weights,
+ load_state_dict,
+ named_module_tensors,
+ retie_parameters,
+ set_module_tensor_to_device,
+)
+from .offload import (
+ OffloadedWeightsLoader,
+ PrefixedDataset,
+ extract_submodules_state_dict,
+ load_offloaded_weight,
+ offload_state_dict,
+ offload_weight,
+ save_offload_index,
+)
+from .operations import (
+ CannotPadNestedTensorWarning,
+ GatheredParameters,
+ broadcast,
+ broadcast_object_list,
+ concatenate,
+ convert_outputs_to_fp32,
+ convert_to_fp32,
+ copy_tensor_to_devices,
+ find_batch_size,
+ find_device,
+ gather,
+ gather_object,
+ get_data_structure,
+ honor_type,
+ ignorant_find_batch_size,
+ initialize_tensors,
+ is_namedtuple,
+ is_tensor_information,
+ is_torch_tensor,
+ listify,
+ pad_across_processes,
+ pad_input_tensors,
+ recursively_apply,
+ reduce,
+ send_to_device,
+ slice_tensors,
+)
+from .versions import compare_versions, is_torch_version
+
+
+if is_deepspeed_available():
+ from .deepspeed import (
+ DeepSpeedEngineWrapper,
+ DeepSpeedOptimizerWrapper,
+ DeepSpeedSchedulerWrapper,
+ DummyOptim,
+ DummyScheduler,
+ HfDeepSpeedConfig,
+ get_active_deepspeed_plugin,
+ )
+
+from .bnb import has_4bit_bnb_layers, load_and_quantize_model
+from .fsdp_utils import (
+ disable_fsdp_ram_efficient_loading,
+ enable_fsdp_ram_efficient_loading,
+ load_fsdp_model,
+ load_fsdp_optimizer,
+ merge_fsdp_weights,
+ save_fsdp_model,
+ save_fsdp_optimizer,
+)
+from .launch import (
+ PrepareForLaunch,
+ _filter_args,
+ prepare_deepspeed_cmd_env,
+ prepare_multi_gpu_env,
+ prepare_sagemager_args_inputs,
+ prepare_simple_launcher_cmd_env,
+ prepare_tpu,
+)
+
+# For docs
+from .megatron_lm import (
+ AbstractTrainStep,
+ BertTrainStep,
+ GPTTrainStep,
+ MegatronLMDummyDataLoader,
+ MegatronLMDummyScheduler,
+ T5TrainStep,
+ avg_losses_across_data_parallel_group,
+)
+
+
+if is_megatron_lm_available():
+ from .megatron_lm import (
+ MegatronEngine,
+ MegatronLMOptimizerWrapper,
+ MegatronLMSchedulerWrapper,
+ gather_across_data_parallel_groups,
+ )
+ from .megatron_lm import initialize as megatron_lm_initialize
+ from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader
+ from .megatron_lm import prepare_model_optimizer_scheduler as megatron_lm_prepare_model_optimizer_scheduler
+ from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer
+ from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler
+from .memory import find_executable_batch_size, release_memory
+from .other import (
+ check_os_kernel,
+ clean_state_dict_for_safetensors,
+ clear_environment,
+ convert_bytes,
+ extract_model_from_parallel,
+ get_pretty_name,
+ is_port_in_use,
+ merge_dicts,
+ patch_environment,
+ recursive_getattr,
+ save,
+ wait_for_everyone,
+ write_basic_config,
+)
+from .random import set_seed, synchronize_rng_state, synchronize_rng_states
+from .torch_xla import install_xla
+from .tqdm import tqdm
+from .transformer_engine import (
+ apply_fp8_autowrap,
+ contextual_fp8_autocast,
+ convert_model,
+ has_transformer_engine_layers,
+)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/bnb.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/bnb.py
new file mode 100644
index 0000000000000000000000000000000000000000..284ee5df6e89171948745255dd33a3b2b91123a2
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/bnb.py
@@ -0,0 +1,467 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import logging
+import os
+from copy import deepcopy
+from typing import Dict, List, Optional, Union
+
+import torch
+import torch.nn as nn
+
+from accelerate.utils.imports import (
+ is_4bit_bnb_available,
+ is_8bit_bnb_available,
+)
+
+from ..big_modeling import dispatch_model, init_empty_weights
+from .dataclasses import BnbQuantizationConfig
+from .modeling import (
+ find_tied_parameters,
+ get_balanced_memory,
+ infer_auto_device_map,
+ load_checkpoint_in_model,
+ offload_weight,
+ set_module_tensor_to_device,
+)
+
+
+logger = logging.getLogger(__name__)
+
+
+def load_and_quantize_model(
+ model: torch.nn.Module,
+ bnb_quantization_config: BnbQuantizationConfig,
+ weights_location: Union[str, os.PathLike] = None,
+ device_map: Optional[Dict[str, Union[int, str, torch.device]]] = None,
+ no_split_module_classes: Optional[List[str]] = None,
+ max_memory: Optional[Dict[Union[int, str], Union[int, str]]] = None,
+ offload_folder: Optional[Union[str, os.PathLike]] = None,
+ offload_state_dict: bool = False,
+):
+ """
+ This function will quantize the input model with the associated config passed in `bnb_quantization_config`. If the
+ model is in the meta device, we will load and dispatch the weights according to the `device_map` passed. If the
+ model is already loaded, we will quantize the model and put the model on the GPU,
+
+ Args:
+ model (`torch.nn.Module`):
+ Input model. The model can be already loaded or on the meta device
+ bnb_quantization_config (`BnbQuantizationConfig`):
+ The bitsandbytes quantization parameters
+ weights_location (`str` or `os.PathLike`):
+ The folder weights_location to load. It can be:
+ - a path to a file containing a whole model state dict
+ - a path to a `.json` file containing the index to a sharded checkpoint
+ - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint.
+ - a path to a folder containing a unique pytorch_model.bin file.
+ device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*):
+ A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer
+ name, once a given module name is inside, every submodule of it will be sent to the same device.
+ no_split_module_classes (`List[str]`, *optional*):
+ A list of layer class names that should never be split across device (for instance any layer that has a
+ residual connection).
+ max_memory (`Dict`, *optional*):
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available if unset.
+ offload_folder (`str` or `os.PathLike`, *optional*):
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
+ offload_state_dict (`bool`, *optional*, defaults to `False`):
+ If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if
+ the weight of the CPU state dict + the biggest shard does not fit.
+
+ Returns:
+ `torch.nn.Module`: The quantized model
+ """
+
+ load_in_4bit = bnb_quantization_config.load_in_4bit
+ load_in_8bit = bnb_quantization_config.load_in_8bit
+
+ if load_in_8bit and not is_8bit_bnb_available():
+ raise ImportError(
+ "You have a version of `bitsandbytes` that is not compatible with 8bit quantization,"
+ " make sure you have the latest version of `bitsandbytes` installed."
+ )
+ if load_in_4bit and not is_4bit_bnb_available():
+ raise ValueError(
+ "You have a version of `bitsandbytes` that is not compatible with 4bit quantization,"
+ "make sure you have the latest version of `bitsandbytes` installed."
+ )
+
+ modules_on_cpu = []
+ # custom device map
+ if isinstance(device_map, dict) and len(device_map.keys()) > 1:
+ modules_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
+
+ # We keep some modules such as the lm_head in their original dtype for numerical stability reasons
+ if bnb_quantization_config.skip_modules is None:
+ bnb_quantization_config.skip_modules = get_keys_to_not_convert(model)
+
+ # add cpu modules to skip modules only for 4-bit modules
+ if load_in_4bit:
+ bnb_quantization_config.skip_modules.extend(modules_on_cpu)
+ modules_to_not_convert = bnb_quantization_config.skip_modules
+
+ # We add the modules we want to keep in full precision
+ if bnb_quantization_config.keep_in_fp32_modules is None:
+ bnb_quantization_config.keep_in_fp32_modules = []
+ keep_in_fp32_modules = bnb_quantization_config.keep_in_fp32_modules
+ modules_to_not_convert.extend(keep_in_fp32_modules)
+
+ # compatibility with peft
+ model.is_loaded_in_4bit = load_in_4bit
+ model.is_loaded_in_8bit = load_in_8bit
+
+ model_device = get_parameter_device(model)
+ if model_device.type != "meta":
+ # quantization of an already loaded model
+ logger.warning(
+ "It is not recommended to quantize a loaded model. "
+ "The model should be instantiated under the `init_empty_weights` context manager."
+ )
+ model = replace_with_bnb_layers(model, bnb_quantization_config, modules_to_not_convert=modules_to_not_convert)
+ # convert param to the right dtype
+ dtype = bnb_quantization_config.torch_dtype
+ for name, param in model.state_dict().items():
+ if any(module_to_keep_in_fp32 in name for module_to_keep_in_fp32 in keep_in_fp32_modules):
+ param.to(torch.float32)
+ if param.dtype != torch.float32:
+ name = name.replace(".weight", "").replace(".bias", "")
+ param = getattr(model, name, None)
+ if param is not None:
+ param.to(torch.float32)
+ elif torch.is_floating_point(param):
+ param.to(dtype)
+ if model_device.type == "cuda":
+ # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
+ model.cuda(torch.cuda.current_device())
+ torch.cuda.empty_cache()
+ elif torch.cuda.is_available():
+ model.to(torch.cuda.current_device())
+ else:
+ raise RuntimeError("No GPU found. A GPU is needed for quantization.")
+ logger.info(
+ f"The model device type is {model_device.type}. However, cuda is needed for quantization."
+ "We move the model to cuda."
+ )
+ return model
+
+ elif weights_location is None:
+ raise RuntimeError(
+ f"`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} "
+ )
+
+ else:
+ with init_empty_weights():
+ model = replace_with_bnb_layers(
+ model, bnb_quantization_config, modules_to_not_convert=modules_to_not_convert
+ )
+
+ device_map = get_quantized_model_device_map(
+ model,
+ bnb_quantization_config,
+ device_map,
+ max_memory=max_memory,
+ no_split_module_classes=no_split_module_classes,
+ )
+ if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
+ offload_state_dict = True
+
+ offload = any(x in list(device_map.values()) for x in ["cpu", "disk"])
+
+ load_checkpoint_in_model(
+ model,
+ weights_location,
+ device_map,
+ dtype=bnb_quantization_config.torch_dtype,
+ offload_folder=offload_folder,
+ offload_state_dict=offload_state_dict,
+ keep_in_fp32_modules=bnb_quantization_config.keep_in_fp32_modules,
+ offload_8bit_bnb=load_in_8bit and offload,
+ )
+ return dispatch_model(model, device_map=device_map, offload_dir=offload_folder)
+
+
+def get_quantized_model_device_map(
+ model, bnb_quantization_config, device_map=None, max_memory=None, no_split_module_classes=None
+):
+ if device_map is None:
+ if torch.cuda.is_available():
+ device_map = {"": torch.cuda.current_device()}
+ else:
+ raise RuntimeError("No GPU found. A GPU is needed for quantization.")
+ logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`.")
+
+ if isinstance(device_map, str):
+ if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
+ raise ValueError(
+ "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or "
+ "'sequential'."
+ )
+
+ special_dtypes = {}
+ special_dtypes.update(
+ {
+ name: bnb_quantization_config.torch_dtype
+ for name, _ in model.named_parameters()
+ if any(m in name for m in bnb_quantization_config.skip_modules)
+ }
+ )
+ special_dtypes.update(
+ {
+ name: torch.float32
+ for name, _ in model.named_parameters()
+ if any(m in name for m in bnb_quantization_config.keep_in_fp32_modules)
+ }
+ )
+
+ kwargs = {}
+ kwargs["special_dtypes"] = special_dtypes
+ kwargs["no_split_module_classes"] = no_split_module_classes
+ kwargs["dtype"] = bnb_quantization_config.target_dtype
+
+ # get max_memory for each device.
+ if device_map != "sequential":
+ max_memory = get_balanced_memory(
+ model,
+ low_zero=(device_map == "balanced_low_0"),
+ max_memory=max_memory,
+ **kwargs,
+ )
+
+ kwargs["max_memory"] = max_memory
+ device_map = infer_auto_device_map(model, **kwargs)
+
+ if isinstance(device_map, dict):
+ # check if don't have any quantized module on the cpu
+ modules_not_to_convert = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fp32_modules
+
+ device_map_without_some_modules = {
+ key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
+ }
+ for device in ["cpu", "disk"]:
+ if device in device_map_without_some_modules.values():
+ if bnb_quantization_config.load_in_4bit:
+ raise ValueError(
+ """
+ Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit
+ the quantized model. If you want to dispatch the model on the CPU or the disk while keeping
+ these modules in `torch_dtype`, you need to pass a custom `device_map` to
+ `load_and_quantize_model`. Check
+ https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk
+ for more details.
+ """
+ )
+ else:
+ logger.info(
+ "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit"
+ )
+ del device_map_without_some_modules
+ return device_map
+
+
+def replace_with_bnb_layers(model, bnb_quantization_config, modules_to_not_convert=None, current_key_name=None):
+ """
+ A helper function to replace all `torch.nn.Linear` modules by `bnb.nn.Linear8bit` modules or by `bnb.nn.Linear4bit`
+ modules from the `bitsandbytes`library. The function will be run recursively and replace `torch.nn.Linear` modules.
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model or `torch.nn.Module` as the function is run recursively.
+ modules_to_not_convert (`List[str]`):
+ Names of the modules to not quantize convert. In practice we keep the `lm_head` in full precision for
+ numerical stability reasons.
+ current_key_name (`List[str]`, *optional*):
+ An array to track the current key of the recursion. This is used to check whether the current key (part of
+ it) is not in the list of modules to not convert.
+ """
+
+ if modules_to_not_convert is None:
+ modules_to_not_convert = []
+
+ model, has_been_replaced = _replace_with_bnb_layers(
+ model, bnb_quantization_config, modules_to_not_convert, current_key_name
+ )
+ if not has_been_replaced:
+ logger.warning(
+ "You are loading your model in 8bit or 4bit but no linear modules were found in your model."
+ " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers."
+ " Please double check your model architecture, or submit an issue on github if you think this is"
+ " a bug."
+ )
+ return model
+
+
+def _replace_with_bnb_layers(
+ model,
+ bnb_quantization_config,
+ modules_to_not_convert=None,
+ current_key_name=None,
+):
+ """
+ Private method that wraps the recursion for module replacement.
+
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
+ """
+ # bitsandbytes will initialize CUDA on import, so it needs to be imported lazily
+ import bitsandbytes as bnb
+
+ has_been_replaced = False
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+ if isinstance(module, nn.Linear) and name not in modules_to_not_convert:
+ # Check if the current key is not in the `modules_to_not_convert`
+ current_key_name_str = ".".join(current_key_name)
+ proceed = True
+ for key in modules_to_not_convert:
+ if (
+ (key in current_key_name_str) and (key + "." in current_key_name_str)
+ ) or key == current_key_name_str:
+ proceed = False
+ break
+ if proceed:
+ # Load bnb module with empty weight and replace ``nn.Linear` module
+ if bnb_quantization_config.load_in_8bit:
+ bnb_module = bnb.nn.Linear8bitLt(
+ module.in_features,
+ module.out_features,
+ module.bias is not None,
+ has_fp16_weights=False,
+ threshold=bnb_quantization_config.llm_int8_threshold,
+ )
+ elif bnb_quantization_config.load_in_4bit:
+ bnb_module = bnb.nn.Linear4bit(
+ module.in_features,
+ module.out_features,
+ module.bias is not None,
+ bnb_quantization_config.bnb_4bit_compute_dtype,
+ compress_statistics=bnb_quantization_config.bnb_4bit_use_double_quant,
+ quant_type=bnb_quantization_config.bnb_4bit_quant_type,
+ )
+ else:
+ raise ValueError("load_in_8bit and load_in_4bit can't be both False")
+ bnb_module.weight.data = module.weight.data
+ if module.bias is not None:
+ bnb_module.bias.data = module.bias.data
+ bnb_module.requires_grad_(False)
+ setattr(model, name, bnb_module)
+ has_been_replaced = True
+ if len(list(module.children())) > 0:
+ _, _has_been_replaced = _replace_with_bnb_layers(
+ module, bnb_quantization_config, modules_to_not_convert, current_key_name
+ )
+ has_been_replaced = has_been_replaced | _has_been_replaced
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+def get_keys_to_not_convert(model):
+ r"""
+ An utility function to get the key of the module to keep in full precision if any For example for CausalLM modules
+ we may want to keep the lm_head in full precision for numerical stability reasons. For other architectures, we want
+ to keep the tied weights of the model. The function will return a list of the keys of the modules to not convert in
+ int8.
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model
+ """
+ # Create a copy of the model
+ with init_empty_weights():
+ tied_model = deepcopy(model) # this has 0 cost since it is done inside `init_empty_weights` context manager`
+
+ tied_params = find_tied_parameters(tied_model)
+ # For compatibility with Accelerate < 0.18
+ if isinstance(tied_params, dict):
+ tied_keys = sum(list(tied_params.values()), []) + list(tied_params.keys())
+ else:
+ tied_keys = sum(tied_params, [])
+ has_tied_params = len(tied_keys) > 0
+
+ # Check if it is a base model
+ is_base_model = False
+ if hasattr(model, "base_model_prefix"):
+ is_base_model = not hasattr(model, model.base_model_prefix)
+
+ # Ignore this for base models (BertModel, GPT2Model, etc.)
+ if (not has_tied_params) and is_base_model:
+ return []
+
+ # otherwise they have an attached head
+ list_modules = list(model.named_children())
+ list_last_module = [list_modules[-1][0]]
+
+ # add last module together with tied weights
+ intersection = set(list_last_module) - set(tied_keys)
+ list_untouched = list(set(tied_keys)) + list(intersection)
+
+ # remove ".weight" from the keys
+ names_to_remove = [".weight", ".bias"]
+ filtered_module_names = []
+ for name in list_untouched:
+ for name_to_remove in names_to_remove:
+ if name_to_remove in name:
+ name = name.replace(name_to_remove, "")
+ filtered_module_names.append(name)
+
+ return filtered_module_names
+
+
+def has_4bit_bnb_layers(model):
+ """Check if we have `bnb.nn.Linear4bit` or `bnb.nn.Linear8bitLt` layers inside our model"""
+ # bitsandbytes will initialize CUDA on import, so it needs to be imported lazily
+ import bitsandbytes as bnb
+
+ for m in model.modules():
+ if isinstance(m, bnb.nn.Linear4bit):
+ return True
+ return False
+
+
+def get_parameter_device(parameter: nn.Module):
+ return next(parameter.parameters()).device
+
+
+def quantize_and_offload_8bit(model, param, param_name, new_dtype, offload_folder, offload_index, fp16_statistics):
+ # if it is not quantized, we quantize and offload the quantized weights and the SCB stats
+ if fp16_statistics is None:
+ set_module_tensor_to_device(model, param_name, 0, dtype=new_dtype, value=param)
+ tensor_name = param_name
+ module = model
+ if "." in tensor_name:
+ splits = tensor_name.split(".")
+ for split in splits[:-1]:
+ new_module = getattr(module, split)
+ if new_module is None:
+ raise ValueError(f"{module} has no attribute {split}.")
+ module = new_module
+ tensor_name = splits[-1]
+ # offload weights
+ module._parameters[tensor_name].requires_grad = False
+ offload_weight(module._parameters[tensor_name], param_name, offload_folder, index=offload_index)
+ if hasattr(module._parameters[tensor_name], "SCB"):
+ offload_weight(
+ module._parameters[tensor_name].SCB,
+ param_name.replace("weight", "SCB"),
+ offload_folder,
+ index=offload_index,
+ )
+ else:
+ offload_weight(param, param_name, offload_folder, index=offload_index)
+ offload_weight(fp16_statistics, param_name.replace("weight", "SCB"), offload_folder, index=offload_index)
+
+ set_module_tensor_to_device(model, param_name, "meta", dtype=new_dtype, value=torch.empty(*param.size()))
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/constants.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6d7d262678054311e2d0ca6c5ccc60758fc134a
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/constants.py
@@ -0,0 +1,86 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import operator as op
+
+
+SCALER_NAME = "scaler.pt"
+MODEL_NAME = "pytorch_model"
+SAFE_MODEL_NAME = "model"
+RNG_STATE_NAME = "random_states"
+OPTIMIZER_NAME = "optimizer"
+SCHEDULER_NAME = "scheduler"
+SAMPLER_NAME = "sampler"
+PROFILE_PATTERN_NAME = "profile_{suffix}.json"
+WEIGHTS_NAME = f"{MODEL_NAME}.bin"
+WEIGHTS_PATTERN_NAME = "pytorch_model{suffix}.bin"
+WEIGHTS_INDEX_NAME = f"{WEIGHTS_NAME}.index.json"
+SAFE_WEIGHTS_NAME = f"{SAFE_MODEL_NAME}.safetensors"
+SAFE_WEIGHTS_PATTERN_NAME = "model{suffix}.safetensors"
+SAFE_WEIGHTS_INDEX_NAME = f"{SAFE_WEIGHTS_NAME}.index.json"
+SAGEMAKER_PYTORCH_VERSION = "1.10.2"
+SAGEMAKER_PYTHON_VERSION = "py38"
+SAGEMAKER_TRANSFORMERS_VERSION = "4.17.0"
+SAGEMAKER_PARALLEL_EC2_INSTANCES = ["ml.p3.16xlarge", "ml.p3dn.24xlarge", "ml.p4dn.24xlarge"]
+FSDP_SHARDING_STRATEGY = ["FULL_SHARD", "SHARD_GRAD_OP", "NO_SHARD", "HYBRID_SHARD", "HYBRID_SHARD_ZERO2"]
+FSDP_AUTO_WRAP_POLICY = ["TRANSFORMER_BASED_WRAP", "SIZE_BASED_WRAP", "NO_WRAP"]
+FSDP_BACKWARD_PREFETCH = ["BACKWARD_PRE", "BACKWARD_POST", "NO_PREFETCH"]
+FSDP_STATE_DICT_TYPE = ["FULL_STATE_DICT", "LOCAL_STATE_DICT", "SHARDED_STATE_DICT"]
+FSDP_PYTORCH_VERSION = (
+ "2.1.0.a0+32f93b1" # Technically should be 2.1.0, but MS-AMP uses this specific prerelease in their Docker image.
+)
+FSDP_MODEL_NAME = "pytorch_model_fsdp"
+DEEPSPEED_MULTINODE_LAUNCHERS = ["pdsh", "standard", "openmpi", "mvapich", "mpich"]
+TORCH_DYNAMO_MODES = ["default", "reduce-overhead", "max-autotune"]
+ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION = "2.2.0"
+XPU_PROFILING_AVAILABLE_PYTORCH_VERSION = "2.4.0"
+MITA_PROFILING_AVAILABLE_PYTORCH_VERSION = "2.1.0"
+
+STR_OPERATION_TO_FUNC = {">": op.gt, ">=": op.ge, "==": op.eq, "!=": op.ne, "<=": op.le, "<": op.lt}
+
+# These are the args for `torch.distributed.launch` for pytorch < 1.9
+TORCH_LAUNCH_PARAMS = [
+ "nnodes",
+ "nproc_per_node",
+ "rdzv_backend",
+ "rdzv_endpoint",
+ "rdzv_id",
+ "rdzv_conf",
+ "standalone",
+ "max_restarts",
+ "monitor_interval",
+ "start_method",
+ "role",
+ "module",
+ "m",
+ "no_python",
+ "run_path",
+ "log_dir",
+ "r",
+ "redirects",
+ "t",
+ "tee",
+ "node_rank",
+ "master_addr",
+ "master_port",
+]
+
+CUDA_DISTRIBUTED_TYPES = ["DEEPSPEED", "MULTI_GPU", "FSDP", "MEGATRON_LM"]
+TORCH_DISTRIBUTED_OPERATION_TYPES = CUDA_DISTRIBUTED_TYPES + [
+ "MULTI_NPU",
+ "MULTI_MLU",
+ "MULTI_MUSA",
+ "MULTI_XPU",
+ "MULTI_CPU",
+]
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/dataclasses.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/dataclasses.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e09c7ea9a080f09ec364782195e932d3692f0f7
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/dataclasses.py
@@ -0,0 +1,2528 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+General namespace and dataclass related classes
+"""
+
+import argparse
+import copy
+import enum
+import functools
+import os
+import warnings
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from datetime import timedelta
+from typing import Any, Callable, Dict, Iterable, List, Literal, Optional, Tuple, Union, get_args
+
+import torch
+
+from .constants import (
+ FSDP_AUTO_WRAP_POLICY,
+ FSDP_BACKWARD_PREFETCH,
+ FSDP_SHARDING_STRATEGY,
+ MITA_PROFILING_AVAILABLE_PYTORCH_VERSION,
+ XPU_PROFILING_AVAILABLE_PYTORCH_VERSION,
+)
+from .environment import parse_flag_from_env, str_to_bool
+from .imports import (
+ is_cuda_available,
+ is_mlu_available,
+ is_msamp_available,
+ is_npu_available,
+ is_transformer_engine_available,
+ is_xpu_available,
+)
+from .versions import compare_versions, is_torch_version
+
+
+class KwargsHandler:
+ """
+ Internal mixin that implements a `to_kwargs()` method for a dataclass.
+ """
+
+ def to_dict(self):
+ return copy.deepcopy(self.__dict__)
+
+ def to_kwargs(self):
+ """
+ Returns a dictionary containing the attributes with values different from the default of this class.
+ """
+ # import clear_environment here to avoid circular import problem
+ from .other import clear_environment
+
+ with clear_environment():
+ default_dict = self.__class__().to_dict()
+ this_dict = self.to_dict()
+ return {k: v for k, v in this_dict.items() if default_dict[k] != v}
+
+
+class EnumWithContains(enum.EnumMeta):
+ "A metaclass that adds the ability to check if `self` contains an item with the `in` operator"
+
+ def __contains__(cls, item):
+ try:
+ cls(item)
+ except ValueError:
+ return False
+ return True
+
+
+class BaseEnum(enum.Enum, metaclass=EnumWithContains):
+ "An enum class that can get the value of an item with `str(Enum.key)`"
+
+ def __str__(self):
+ return self.value
+
+ @classmethod
+ def list(cls):
+ "Method to list all the possible items in `cls`"
+ return list(map(str, cls))
+
+
+@dataclass
+class AutocastKwargs(KwargsHandler):
+ """
+ Use this object in your [`Accelerator`] to customize how `torch.autocast` behaves. Please refer to the
+ documentation of this [context manager](https://pytorch.org/docs/stable/amp.html#torch.autocast) for more
+ information on each argument.
+
+ Example:
+
+ ```python
+ from accelerate import Accelerator
+ from accelerate.utils import AutocastKwargs
+
+ kwargs = AutocastKwargs(cache_enabled=True)
+ accelerator = Accelerator(kwargs_handlers=[kwargs])
+ ```
+ """
+
+ enabled: bool = True
+ cache_enabled: bool = None
+
+
+class DDPCommunicationHookType(BaseEnum):
+ """
+ Represents a type of communication hook used in DDP.
+
+ Values:
+
+ - **NO** -- no communication hook
+ - **FP16** -- DDP communication hook to compress the gradients in FP16
+ - **BF16** -- DDP communication hook to compress the gradients in BF16
+ - **POWER_SGD** -- DDP communication hook to use PowerSGD
+ - **BATCHED_POWER_SGD** -- DDP communication hook to use batched PowerSGD
+ """
+
+ NO = "no"
+ FP16 = "fp16"
+ BF16 = "bf16"
+ POWER_SGD = "power_sgd"
+ BATCHED_POWER_SGD = "batched_power_sgd"
+
+
+@dataclass
+class DistributedDataParallelKwargs(KwargsHandler):
+ """
+ Use this object in your [`Accelerator`] to customize how your model is wrapped in a
+ `torch.nn.parallel.DistributedDataParallel`. Please refer to the documentation of this
+ [wrapper](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) for more
+ information on each argument.
+
+
+
+ `gradient_as_bucket_view` is only available in PyTorch 1.7.0 and later versions.
+
+ `static_graph` is only available in PyTorch 1.11.0 and later versions.
+
+
+
+ Example:
+
+ ```python
+ from accelerate import Accelerator
+ from accelerate.utils import DistributedDataParallelKwargs
+
+ kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
+ accelerator = Accelerator(kwargs_handlers=[kwargs])
+ ```
+ """
+
+ dim: int = 0
+ broadcast_buffers: bool = True
+ bucket_cap_mb: int = 25
+ find_unused_parameters: bool = False
+ check_reduction: bool = False
+ gradient_as_bucket_view: bool = False
+ static_graph: bool = False
+
+ comm_hook: DDPCommunicationHookType = DDPCommunicationHookType.NO
+ comm_wrapper: Literal[
+ DDPCommunicationHookType.NO, DDPCommunicationHookType.FP16, DDPCommunicationHookType.BF16
+ ] = DDPCommunicationHookType.NO
+ comm_state_option: dict = field(default_factory=dict)
+
+ def to_dict(self, ignore_keys=("comm_hook", "comm_wrapper", "comm_state_option")):
+ return {k: v for k, v in super().to_dict().items() if k not in ignore_keys}
+
+ def register_comm_hook(self, model):
+ from torch.distributed.algorithms.ddp_comm_hooks import default_hooks, powerSGD_hook
+
+ hook_map: Dict[DDPCommunicationHookType, Callable] = {
+ DDPCommunicationHookType.FP16: default_hooks.fp16_compress_hook,
+ DDPCommunicationHookType.BF16: default_hooks.bf16_compress_hook,
+ DDPCommunicationHookType.POWER_SGD: powerSGD_hook.powerSGD_hook,
+ DDPCommunicationHookType.BATCHED_POWER_SGD: powerSGD_hook.batched_powerSGD_hook,
+ }
+
+ wrapper_map: Dict[DDPCommunicationHookType, Callable] = {
+ DDPCommunicationHookType.FP16: default_hooks.fp16_compress_wrapper,
+ DDPCommunicationHookType.BF16: default_hooks.bf16_compress_wrapper,
+ }
+
+ hook: Optional[Callable] = hook_map.get(self.comm_hook)
+ wrapper: Optional[Callable] = wrapper_map.get(self.comm_wrapper)
+
+ if hook and wrapper:
+ hook = wrapper(hook)
+
+ if hook:
+ state = (
+ powerSGD_hook.PowerSGDState(None, **self.comm_state_option)
+ if self.comm_hook in (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.BATCHED_POWER_SGD)
+ else None
+ )
+ model.register_comm_hook(
+ state=state,
+ hook=hook,
+ )
+
+
+@dataclass
+class GradScalerKwargs(KwargsHandler):
+ """
+ Use this object in your [`Accelerator`] to customize the behavior of mixed precision, specifically how the
+ `torch.cuda.amp.GradScaler` used is created. Please refer to the documentation of this
+ [scaler](https://pytorch.org/docs/stable/amp.html?highlight=gradscaler) for more information on each argument.
+
+
+
+ `GradScaler` is only available in PyTorch 1.5.0 and later versions.
+
+
+
+ Example:
+
+ ```python
+ from accelerate import Accelerator
+ from accelerate.utils import GradScalerKwargs
+
+ kwargs = GradScalerKwargs(backoff_filter=0.25)
+ accelerator = Accelerator(kwargs_handlers=[kwargs])
+ ```
+ """
+
+ init_scale: float = 65536.0
+ growth_factor: float = 2.0
+ backoff_factor: float = 0.5
+ growth_interval: int = 2000
+ enabled: bool = True
+
+
+@dataclass
+class InitProcessGroupKwargs(KwargsHandler):
+ """
+ Use this object in your [`Accelerator`] to customize the initialization of the distributed processes. Please refer
+ to the documentation of this
+ [method](https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more
+ information on each argument.
+
+ Note: If `timeout` is set to `None`, the default will be based upon how `backend` is set.
+
+ ```python
+ from datetime import timedelta
+ from accelerate import Accelerator
+ from accelerate.utils import InitProcessGroupKwargs
+
+ kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=800))
+ accelerator = Accelerator(kwargs_handlers=[kwargs])
+ ```
+ """
+
+ backend: Optional[str] = "nccl"
+ init_method: Optional[str] = None
+ timeout: Optional[timedelta] = None
+
+ def __post_init__(self):
+ if self.timeout is None:
+ seconds = 1800 if self.backend != "nccl" else 600
+ self.timeout = timedelta(seconds=seconds)
+
+
+# Literals
+Backend = Literal["MSAMP", "TE"]
+OptLevel = Literal["O1", "O2"]
+FP8Format = Literal["E4M3", "HYBRID"]
+AmaxComputeAlgorithm = Literal["max", "most_recent"]
+
+
+@dataclass
+class FP8RecipeKwargs(KwargsHandler):
+ """
+ Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision
+ training with `transformer-engine` or `ms-amp`.
+
+
+
+ For more information on `transformer-engine` args, please refer to the API
+ [documentation](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/common.html).
+
+ For more information on the `ms-amp` args, please refer to the Optimization Level
+ [documentation](https://azure.github.io/MS-AMP/docs/user-tutorial/optimization-level).
+
+
+
+ ```python
+ from accelerate import Accelerator
+ from accelerate.utils import FP8RecipeKwargs
+
+ kwargs = FP8RecipeKwargs(backend="te", fp8_format="HYBRID")
+ accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[kwargs])
+ ```
+
+ To use MS-AMP as an engine, pass `backend="msamp"` and the `optimization_level`:
+
+ ```python
+ kwargs = FP8RecipeKwargs(backend="msamp", optimization_level="02")
+ ```
+
+ Args:
+ backend (`str`, *optional*):
+ Which FP8 engine to use. Must be one of `"msamp"` (MS-AMP) or `"te"` (TransformerEngine). If not passed,
+ will use whichever is available in the environment, prioritizing MS-AMP.
+ use_autocast_during_eval (`bool`, *optional*, default to `False`):
+ Whether to use FP8 autocast during eval mode. Generally better metrics are found when this is `False`.
+ margin (`int`, *optional*, default to 0):
+ The margin to use for the gradient scaling.
+ interval (`int`, *optional*, default to 1):
+ The interval to use for how often the scaling factor is recomputed.
+ fp8_format (`str`, *optional*, default to "HYBRID"):
+ The format to use for the FP8 recipe. Must be one of `HYBRID` or `E4M3`. (Generally `HYBRID` for training,
+ `E4M3` for evaluation)
+ amax_history_len (`int`, *optional*, default to 1024):
+ The length of the history to use for the scaling factor computation
+ amax_compute_algo (`str`, *optional*, default to "most_recent"):
+ The algorithm to use for the scaling factor computation. Must be one of `max` or `most_recent`.
+ override_linear_precision (`tuple` of three `bool`, *optional*, default to `(False, False, False)`):
+ Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision.
+ optimization_level (`str`), one of `O1`, `O2`. (default is `O2`):
+ What level of 8-bit collective communication should be used with MS-AMP. In general:
+ * O1: Weight gradients and `all_reduce` communications are done in fp8, reducing GPU
+ memory usage and communication bandwidth
+ * O2: First-order optimizer states are in 8-bit, and second order states are in FP16.
+ Only available when using Adam or AdamW. This maintains accuracy and can potentially save the
+ highest memory.
+ * 03: Specifically for DeepSpeed, implements capabilities so weights and master weights of models
+ are stored in FP8. If `fp8` is selected and deepspeed is enabled, will be used by default. (Not
+ available currently).
+ """
+
+ backend: Backend = None
+ use_autocast_during_eval: bool = None
+ opt_level: OptLevel = None
+ margin: int = None
+ interval: int = None
+ fp8_format: FP8Format = None
+ amax_history_len: int = None
+ amax_compute_algo: AmaxComputeAlgorithm = None
+ override_linear_precision: Tuple[bool, bool, bool] = None
+
+ def __post_init__(self):
+ env_prefix = "ACCELERATE_FP8_"
+ default_backend = "msamp" if is_msamp_available() else "te"
+ if self.backend is None:
+ self.backend = os.environ.get(env_prefix + "BACKEND", default_backend)
+ self.backend = self.backend.upper()
+ if self.backend not in get_args(Backend):
+ raise ValueError("`backend` must be 'MSAMP' or 'TE' (TransformerEngine).")
+ # Check TE args
+ if self.backend == "TE":
+ if not is_transformer_engine_available():
+ raise ValueError(
+ "TransformerEngine is not available. Please either install it, or use the 'MSAMP' backend (if installed)."
+ )
+ if self.use_autocast_during_eval is None:
+ self.use_autocast_during_eval = parse_flag_from_env(env_prefix + "USE_AUTOCAST_DURING_EVAL")
+ if self.margin is None:
+ self.margin = int(os.environ.get(env_prefix + "MARGIN", 0))
+ if self.interval is None:
+ self.interval = int(os.environ.get(env_prefix + "INTERVAL", 1))
+ if self.fp8_format is None:
+ self.fp8_format = os.environ.get(env_prefix + "FORMAT", "HYBRID")
+ self.fp8_format = self.fp8_format.upper()
+ if self.fp8_format not in get_args(FP8Format):
+ raise ValueError(f"`fp8_format` must be one of {' or '.join(get_args(FP8Format))}.")
+ if self.amax_compute_algo is None:
+ self.amax_compute_algo = os.environ.get(env_prefix + "AMAX_COMPUTE_ALGO", "most_recent")
+ self.amax_compute_algo = self.amax_compute_algo.lower()
+ if self.amax_compute_algo not in get_args(AmaxComputeAlgorithm):
+ raise ValueError(f"`amax_compute_algo` must be one of {' or '.join(get_args(AmaxComputeAlgorithm))}")
+ if self.amax_history_len is None:
+ self.amax_history_len = int(os.environ.get(env_prefix + "AMAX_HISTORY_LEN", 1024))
+ if self.override_linear_precision is None:
+ fprop = parse_flag_from_env(env_prefix + "OVERRIDE_FPROP")
+ dgrad = parse_flag_from_env(env_prefix + "OVERRIDE_DGRAD")
+ wgrad = parse_flag_from_env(env_prefix + "OVERRIDE_WGRAD")
+ self.override_linear_precision = (fprop, dgrad, wgrad)
+ elif self.backend == "MSAMP":
+ if not is_msamp_available():
+ raise ValueError(
+ "MS-AMP is not available. Please either install it, or use the 'TE' backend (if installed)."
+ )
+ if self.opt_level is None:
+ self.opt_level = os.environ.get(env_prefix + "OPT_LEVEL", "O2")
+ if self.opt_level not in get_args(OptLevel):
+ raise ValueError(f"`optimization_level` must be one of {' or '.join(get_args(OptLevel))}")
+
+
+# Literal
+ProfilerActivity = Literal["cpu", "xpu", "mtia", "cuda"]
+
+
+@dataclass
+class ProfileKwargs(KwargsHandler):
+ """
+ Use this object in your [`Accelerator`] to customize the initialization of the profiler. Please refer to the
+ documentation of this [context manager](https://pytorch.org/docs/stable/profiler.html#torch.profiler.profile) for
+ more information on each argument.
+
+
+
+ `torch.profiler` is only available in PyTorch 1.8.1 and later versions.
+
+
+
+ Example:
+
+ ```python
+ from accelerate import Accelerator
+ from accelerate.utils import ProfileKwargs
+
+ kwargs = ProfileKwargs(activities=["cpu", "cuda"])
+ accelerator = Accelerator(kwargs_handlers=[kwargs])
+ ```
+
+ Args:
+ activities (`List[str]`, *optional*, default to `None`):
+ The list of activity groups to use in profiling. Must be one of `"cpu"`, `"xpu"`, `"mtia"`, or `"cuda"`.
+ schedule_option (`Dict[str, int]`, *optional*, default to `None`):
+ The schedule option to use for the profiler. Available keys are `wait`, `warmup`, `active`, `repeat` and
+ `skip_first`. The profiler will skip the first `skip_first` steps, then wait for `wait` steps, then do the
+ warmup for the next `warmup` steps, then do the active recording for the next `active` steps and then
+ repeat the cycle starting with `wait` steps. The optional number of cycles is specified with the `repeat`
+ parameter, the zero value means that the cycles will continue until the profiling is finished.
+ on_trace_ready (`Callable`, *optional*, default to `None`):
+ Callable that is called at each step when schedule returns `ProfilerAction.RECORD_AND_SAVE` during the
+ profiling.
+ record_shapes (`bool`, *optional*, default to `False`):
+ Save information about operator’s input shapes.
+ profile_memory (`bool`, *optional*, default to `False`):
+ Track tensor memory allocation/deallocation
+ with_stack (`bool`, *optional*, default to `False`):
+ Record source information (file and line number) for the ops.
+ with_flops (`bool`, *optional*, default to `False`):
+ Use formula to estimate the FLOPS of specific operators
+ with_modules (`bool`, *optional*, default to `False`):
+ Record module hierarchy (including function names) corresponding to the callstack of the op.
+ output_trace_dir (`str`, *optional*, default to `None`):
+ Exports the collected trace in Chrome JSON format. Chrome use 'chrome://tracing' view json file. Defaults
+ to None, which means profiling does not store json files.
+ """
+
+ activities: Optional[List[ProfilerActivity]] = None
+ schedule_option: Optional[Dict[str, int]] = None
+ on_trace_ready: Optional[Callable] = None
+ record_shapes: bool = False
+ profile_memory: bool = False
+ with_stack: bool = False
+ with_flops: bool = False
+ with_modules: bool = False
+ output_trace_dir: Optional[str] = None
+
+ def _get_profiler_activity(self, activity: ProfilerActivity) -> torch.profiler.ProfilerActivity:
+ """Get the profiler activity from the string.
+
+ Args:
+ activity (str): The profiler activity name.
+
+ Returns:
+ torch.profiler.ProfilerActivity: The profiler activity.
+ """
+
+ profiler_activity_map: dict[str, torch.profiler.ProfilerActivity] = {
+ "cpu": torch.profiler.ProfilerActivity.CPU,
+ "cuda": torch.profiler.ProfilerActivity.CUDA,
+ }
+
+ if is_torch_version(">=", XPU_PROFILING_AVAILABLE_PYTORCH_VERSION):
+ profiler_activity_map["xpu"] = torch.profiler.ProfilerActivity.XPU
+
+ if is_torch_version(">=", MITA_PROFILING_AVAILABLE_PYTORCH_VERSION):
+ profiler_activity_map["mtia"] = torch.profiler.ProfilerActivity.MTIA
+
+ if activity not in profiler_activity_map:
+ raise ValueError(f"Invalid profiler activity: {activity}. Must be one of {list(profiler_activity_map)}.")
+ return profiler_activity_map[activity]
+
+ def build(self) -> torch.profiler.profile:
+ """
+ Build a profiler object with the current configuration.
+
+ Returns:
+ torch.profiler.profile: The profiler object.
+ """
+ activities: Optional[List[ProfilerActivity]] = None
+ if self.activities is not None:
+ activities = [self._get_profiler_activity(activity) for activity in self.activities]
+ schedule: Optional[torch.profiler.schedule] = None
+ if self.schedule_option is not None:
+ schedule = torch.profiler.schedule(**self.schedule_option)
+
+ return torch.profiler.profile(
+ activities=activities,
+ schedule=schedule,
+ on_trace_ready=self.on_trace_ready,
+ record_shapes=self.record_shapes,
+ profile_memory=self.profile_memory,
+ with_stack=self.with_stack,
+ with_flops=self.with_flops,
+ with_modules=self.with_modules,
+ )
+
+
+class DistributedType(str, enum.Enum):
+ """
+ Represents a type of distributed environment.
+
+ Values:
+
+ - **NO** -- Not a distributed environment, just a single process.
+ - **MULTI_CPU** -- Distributed on multiple CPU nodes.
+ - **MULTI_GPU** -- Distributed on multiple GPUs.
+ - **MULTI_MLU** -- Distributed on multiple MLUs.
+ - **MULTI_MUSA** -- Distributed on multiple MUSAs.
+ - **MULTI_NPU** -- Distributed on multiple NPUs.
+ - **MULTI_XPU** -- Distributed on multiple XPUs.
+ - **DEEPSPEED** -- Using DeepSpeed.
+ - **XLA** -- Using TorchXLA.
+ """
+
+ # Subclassing str as well as Enum allows the `DistributedType` to be JSON-serializable out of the box.
+ NO = "NO"
+ MULTI_CPU = "MULTI_CPU"
+ MULTI_GPU = "MULTI_GPU"
+ MULTI_NPU = "MULTI_NPU"
+ MULTI_MLU = "MULTI_MLU"
+ MULTI_MUSA = "MULTI_MUSA"
+ MULTI_XPU = "MULTI_XPU"
+ DEEPSPEED = "DEEPSPEED"
+ FSDP = "FSDP"
+ XLA = "XLA"
+ MEGATRON_LM = "MEGATRON_LM"
+
+
+class SageMakerDistributedType(str, enum.Enum):
+ """
+ Represents a type of distributed environment.
+
+ Values:
+
+ - **NO** -- Not a distributed environment, just a single process.
+ - **DATA_PARALLEL** -- using sagemaker distributed data parallelism.
+ - **MODEL_PARALLEL** -- using sagemaker distributed model parallelism.
+ """
+
+ # Subclassing str as well as Enum allows the `SageMakerDistributedType` to be JSON-serializable out of the box.
+ NO = "NO"
+ DATA_PARALLEL = "DATA_PARALLEL"
+ MODEL_PARALLEL = "MODEL_PARALLEL"
+
+
+class FP8BackendType(str, enum.Enum):
+ """
+ Represents the backend used for FP8.
+
+ Values:
+
+ - **TE** -- using TransformerEngine.
+ - **MSAMP** -- using msamp.
+ """
+
+ # Subclassing str as well as Enum allows the `FP8BackendType` to be JSON-serializable out of the box.
+ TE = "TE"
+ MSAMP = "MSAMP"
+
+
+class ComputeEnvironment(str, enum.Enum):
+ """
+ Represents a type of the compute environment.
+
+ Values:
+
+ - **LOCAL_MACHINE** -- private/custom cluster hardware.
+ - **AMAZON_SAGEMAKER** -- Amazon SageMaker as compute environment.
+ """
+
+ # Subclassing str as well as Enum allows the `ComputeEnvironment` to be JSON-serializable out of the box.
+ LOCAL_MACHINE = "LOCAL_MACHINE"
+ AMAZON_SAGEMAKER = "AMAZON_SAGEMAKER"
+
+
+class DynamoBackend(str, BaseEnum):
+ """
+ Represents a dynamo backend (see https://pytorch.org/docs/stable/torch.compiler.html).
+
+ Values:
+
+ - **NO** -- Do not use torch dynamo.
+ - **EAGER** -- Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo
+ issues.
+ - **AOT_EAGER** -- Uses AotAutograd with no compiler, i.e, just using PyTorch eager for the AotAutograd's
+ extracted forward and backward graphs. This is useful for debugging, and unlikely to give speedups.
+ - **INDUCTOR** -- Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton
+ kernels. [Read
+ more](https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747)
+ - **AOT_TS_NVFUSER** -- nvFuser with AotAutograd/TorchScript. [Read
+ more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593)
+ - **NVPRIMS_NVFUSER** -- nvFuser with PrimTorch. [Read
+ more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593)
+ - **CUDAGRAPHS** -- cudagraphs with AotAutograd. [Read more](https://github.com/pytorch/torchdynamo/pull/757)
+ - **OFI** -- Uses Torchscript optimize_for_inference. Inference only. [Read
+ more](https://pytorch.org/docs/stable/generated/torch.jit.optimize_for_inference.html)
+ - **FX2TRT** -- Uses Nvidia TensorRT for inference optimizations. Inference only. [Read
+ more](https://github.com/pytorch/TensorRT/blob/master/docsrc/tutorials/getting_started_with_fx_path.rst)
+ - **ONNXRT** -- Uses ONNXRT for inference on CPU/GPU. Inference only. [Read more](https://onnxruntime.ai/)
+ - **TENSORRT** -- Uses ONNXRT to run TensorRT for inference optimizations. [Read
+ more](https://github.com/onnx/onnx-tensorrt)
+ - **AOT_TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for training. [Read
+ more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md)
+ - **TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for inference. [Read
+ more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md)
+ - **IPEX** -- Uses IPEX for inference on CPU. Inference only. [Read
+ more](https://github.com/intel/intel-extension-for-pytorch).
+ - **TVM** -- Uses Apach TVM for inference optimizations. [Read more](https://tvm.apache.org/)
+
+ """
+
+ # Subclassing str as well as Enum allows the `SageMakerDistributedType` to be JSON-serializable out of the box.
+ NO = "NO"
+ EAGER = "EAGER"
+ AOT_EAGER = "AOT_EAGER"
+ INDUCTOR = "INDUCTOR"
+ AOT_TS_NVFUSER = "AOT_TS_NVFUSER"
+ NVPRIMS_NVFUSER = "NVPRIMS_NVFUSER"
+ CUDAGRAPHS = "CUDAGRAPHS"
+ OFI = "OFI"
+ FX2TRT = "FX2TRT"
+ ONNXRT = "ONNXRT"
+ TENSORRT = "TENSORRT"
+ AOT_TORCHXLA_TRACE_ONCE = "AOT_TORCHXLA_TRACE_ONCE"
+ TORCHXLA_TRACE_ONCE = "TORCHXLA_TRACE_ONCE"
+ IPEX = "IPEX"
+ TVM = "TVM"
+
+
+class LoggerType(BaseEnum):
+ """Represents a type of supported experiment tracker
+
+ Values:
+
+ - **ALL** -- all available trackers in the environment that are supported
+ - **TENSORBOARD** -- TensorBoard as an experiment tracker
+ - **WANDB** -- wandb as an experiment tracker
+ - **COMETML** -- comet_ml as an experiment tracker
+ - **DVCLIVE** -- dvclive as an experiment tracker
+ """
+
+ ALL = "all"
+ AIM = "aim"
+ TENSORBOARD = "tensorboard"
+ WANDB = "wandb"
+ COMETML = "comet_ml"
+ MLFLOW = "mlflow"
+ CLEARML = "clearml"
+ DVCLIVE = "dvclive"
+
+
+class PrecisionType(str, BaseEnum):
+ """Represents a type of precision used on floating point values
+
+ Values:
+
+ - **NO** -- using full precision (FP32)
+ - **FP16** -- using half precision
+ - **BF16** -- using brain floating point precision
+ """
+
+ NO = "no"
+ FP8 = "fp8"
+ FP16 = "fp16"
+ BF16 = "bf16"
+
+
+class RNGType(BaseEnum):
+ TORCH = "torch"
+ CUDA = "cuda"
+ MLU = "mlu"
+ MUSA = "musa"
+ NPU = "npu"
+ XLA = "xla"
+ XPU = "xpu"
+ GENERATOR = "generator"
+
+
+class CustomDtype(enum.Enum):
+ r"""
+ An enum that contains multiple custom dtypes that can be used for `infer_auto_device_map`.
+ """
+
+ FP8 = "fp8"
+ INT4 = "int4"
+ INT2 = "int2"
+
+
+# data classes
+
+
+@dataclass
+class TensorInformation:
+ shape: torch.Size
+ dtype: torch.dtype
+
+
+@dataclass
+class DataLoaderConfiguration:
+ """
+ Configuration for dataloader-related items when calling `accelerator.prepare`.
+
+ Args:
+ split_batches (`bool`, defaults to `False`):
+ Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If
+ `True`, the actual batch size used will be the same on any kind of distributed processes, but it must be a
+ round multiple of `num_processes` you are using. If `False`, actual batch size used will be the one set in
+ your script multiplied by the number of processes.
+ dispatch_batches (`bool`, defaults to `None`):
+ If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process
+ and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose
+ underlying dataset is an `IterableDataset`, `False` otherwise.
+ even_batches (`bool`, defaults to `True`):
+ If set to `True`, in cases where the total batch size across all processes does not exactly divide the
+ dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among
+ all workers.
+ use_seedable_sampler (`bool`, defaults to `False`):
+ Whether or not use a fully seedable random sampler ([`data_loader.SeedableRandomSampler`]). Ensures
+ training results are fully reproducable using a different sampling technique. While seed-to-seed results
+ may differ, on average the differences are neglible when using multiple different seeds to compare. Should
+ also be ran with [`~utils.set_seed`] for the best results.
+ non_blocking (`bool`, defaults to `False`):
+ If set to `True`, the dataloader prepared by the Accelerator will utilize non-blocking host-to-device
+ transfers, allowing for better overlap between dataloader communication and computation. Recommended that
+ the prepared dataloader has `pin_memory` set to `True` to work properly.
+ use_stateful_dataloader (`bool`, defaults to `False`):
+ If set to `True`, the dataloader prepared by the Accelerator will be backed by
+ [torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader).
+ This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed.
+ """
+
+ split_batches: bool = field(
+ default=False,
+ metadata={
+ "help": "Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If"
+ " `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a"
+ " round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set"
+ " in your script multiplied by the number of processes."
+ },
+ )
+ dispatch_batches: bool = field(
+ default=None,
+ metadata={
+ "help": "If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process"
+ " and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose"
+ " underlying dataset is an `IterableDataset`, `False` otherwise."
+ },
+ )
+ even_batches: bool = field(
+ default=True,
+ metadata={
+ "help": "If set to `True`, in cases where the total batch size across all processes does not exactly divide the"
+ " dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among"
+ " all workers."
+ },
+ )
+ use_seedable_sampler: bool = field(
+ default=False,
+ metadata={
+ "help": "Whether or not use a fully seedable random sampler ([`data_loader.SeedableRandomSampler`])."
+ "Ensures training results are fully reproducable using a different sampling technique. "
+ "While seed-to-seed results may differ, on average the differences are neglible when using"
+ "multiple different seeds to compare. Should also be ran with [`~utils.set_seed`] for the best results."
+ },
+ )
+ non_blocking: bool = field(
+ default=False,
+ metadata={
+ "help": "If set to `True`, the dataloader prepared by the Accelerator will utilize non-blocking host-to-device"
+ " transfers, allowing for better overlap between dataloader communication and computation. Recommended that the"
+ " prepared dataloader has `pin_memory` set to `True` to work properly."
+ },
+ )
+ use_stateful_dataloader: bool = field(
+ default=False,
+ metadata={
+ "help": "If set to `True`, the dataloader prepared by the Accelerator will be backed by "
+ "[torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader). This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed."
+ },
+ )
+
+
+@dataclass
+class ProjectConfiguration:
+ """
+ Configuration for the Accelerator object based on inner-project needs.
+
+ Args:
+ project_dir (`str`, defaults to `None`):
+ A path to a directory for storing data.
+ logging_dir (`str`, defaults to `None`):
+ A path to a directory for storing logs of locally-compatible loggers. If None, defaults to `project_dir`.
+ automatic_checkpoint_naming (`bool`, defaults to `False`):
+ Whether saved states should be automatically iteratively named.
+ total_limit (`int`, defaults to `None`):
+ The maximum number of total saved states to keep.
+ iteration (`int`, defaults to `0`):
+ The current save iteration.
+ save_on_each_node (`bool`, defaults to `False`):
+ When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on
+ the main one.
+ """
+
+ project_dir: str = field(default=None, metadata={"help": "A path to a directory for storing data."})
+ logging_dir: str = field(
+ default=None,
+ metadata={
+ "help": "A path to a directory for storing logs of locally-compatible loggers. If None, defaults to `project_dir`."
+ },
+ )
+ automatic_checkpoint_naming: bool = field(
+ default=False,
+ metadata={"help": "Whether saved states should be automatically iteratively named."},
+ )
+
+ total_limit: int = field(
+ default=None,
+ metadata={"help": "The maximum number of total saved states to keep."},
+ )
+
+ iteration: int = field(
+ default=0,
+ metadata={"help": "The current save iteration."},
+ )
+
+ save_on_each_node: bool = field(
+ default=False,
+ metadata={
+ "help": (
+ "When doing multi-node distributed training, whether to save models and checkpoints on each node, or"
+ " only on the main one"
+ )
+ },
+ )
+
+ def set_directories(self, project_dir: str = None):
+ "Sets `self.project_dir` and `self.logging_dir` to the appropriate values."
+ self.project_dir = project_dir
+ if self.logging_dir is None:
+ self.logging_dir = project_dir
+
+ def __post_init__(self):
+ self.set_directories(self.project_dir)
+
+
+@dataclass
+class GradientAccumulationPlugin(KwargsHandler):
+ """
+ A plugin to configure gradient accumulation behavior. You can only pass one of `gradient_accumulation_plugin` or
+ `gradient_accumulation_steps` to [`Accelerator`]. Passing both raises an error.
+
+ Parameters:
+ num_steps (`int`):
+ The number of steps to accumulate gradients for.
+ adjust_scheduler (`bool`, *optional*, defaults to `True`):
+ Whether to adjust the scheduler steps to account for the number of steps being accumulated. Should be
+ `True` if the used scheduler was not adjusted for gradient accumulation.
+ sync_with_dataloader (`bool`, *optional*, defaults to `True`):
+ Whether to synchronize setting the gradients when at the end of the dataloader.
+ sync_each_batch (`bool`, *optional*):
+ Whether to synchronize setting the gradients at each data batch. Seting to `True` may reduce memory
+ requirements when using gradient accumulation with distributed training, at expense of speed.
+
+ Example:
+
+ ```python
+ from accelerate.utils import GradientAccumulationPlugin
+
+ gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2)
+ accelerator = Accelerator(gradient_accumulation_plugin=gradient_accumulation_plugin)
+ ```
+ """
+
+ num_steps: int = field(default=None, metadata={"help": "The number of steps to accumulate gradients for."})
+ adjust_scheduler: bool = field(
+ default=True,
+ metadata={
+ "help": "Whether to adjust the scheduler steps to account for the number of steps being accumulated. Should be `True` if the used scheduler was not adjusted for gradient accumulation."
+ },
+ )
+ sync_with_dataloader: bool = field(
+ default=True,
+ metadata={
+ "help": "Whether to synchronize setting the gradients when at the end of the dataloader. Should only be set to `False` if you know what you're doing."
+ },
+ )
+ sync_each_batch: bool = field(
+ default=False,
+ metadata={
+ "help": "Whether to synchronize setting the gradients at each data batch. Setting to `True` may reduce memory requirements when using gradient accumulation with distributed training, at expense of speed."
+ },
+ )
+
+
+@dataclass
+class TorchDynamoPlugin(KwargsHandler):
+ """
+ This plugin is used to compile a model with PyTorch 2.0
+
+ Args:
+ backend (`DynamoBackend`, defaults to `None`):
+ A valid Dynamo backend. See https://pytorch.org/docs/stable/torch.compiler.html for more details.
+ mode (`str`, defaults to `None`):
+ Possible options are 'default', 'reduce-overhead' or 'max-autotune'.
+ fullgraph (`bool`, defaults to `None`):
+ Whether it is ok to break model into several subgraphs.
+ dynamic (`bool`, defaults to `None`):
+ Whether to use dynamic shape for tracing.
+ options (`Any`, defaults to `None`):
+ A dictionary of options to pass to the backend.
+ disable (`bool`, defaults to `False`):
+ Turn torch.compile() into a no-op for testing
+ """
+
+ backend: DynamoBackend = field(
+ default=None,
+ metadata={"help": f"Possible options are {[b.value.lower() for b in DynamoBackend]}"},
+ )
+ mode: str = field(
+ default=None, metadata={"help": "Possible options are 'default', 'reduce-overhead' or 'max-autotune'"}
+ )
+ fullgraph: bool = field(default=None, metadata={"help": "Whether it is ok to break model into several subgraphs"})
+ dynamic: bool = field(default=None, metadata={"help": "Whether to use dynamic shape for tracing"})
+ options: Any = field(default=None, metadata={"help": "A dictionary of options to pass to the backend."})
+ disable: bool = field(default=False, metadata={"help": "Turn torch.compile() into a no-op for testing"})
+
+ def __post_init__(self):
+ prefix = "ACCELERATE_DYNAMO_"
+ if self.backend is None:
+ self.backend = os.environ.get(prefix + "BACKEND", "no")
+ self.backend = DynamoBackend(self.backend.upper())
+ if self.mode is None:
+ self.mode = os.environ.get(prefix + "MODE", "default")
+ if self.fullgraph is None:
+ self.fullgraph = str_to_bool(os.environ.get(prefix + "USE_FULLGRAPH", "False")) == 1
+ if self.dynamic is None:
+ self.dynamic = str_to_bool(os.environ.get(prefix + "USE_DYNAMIC", "False")) == 1
+
+ def to_dict(self):
+ dynamo_config = copy.deepcopy(self.__dict__)
+ dynamo_config["backend"] = dynamo_config["backend"].value.lower()
+ return dynamo_config
+
+
+@dataclass
+class DeepSpeedPlugin:
+ """
+ This plugin is used to integrate DeepSpeed.
+
+ Args:
+ hf_ds_config (`Any`, defaults to `None`):
+ Path to DeepSpeed config file or dict or an object of class `accelerate.utils.deepspeed.HfDeepSpeedConfig`.
+ gradient_accumulation_steps (`int`, defaults to `None`):
+ Number of steps to accumulate gradients before updating optimizer states. If not set, will use the value
+ from the `Accelerator` directly.
+ gradient_clipping (`float`, defaults to `None`):
+ Enable gradient clipping with value.
+ zero_stage (`int`, defaults to `None`):
+ Possible options are 0, 1, 2, 3. Default will be taken from environment variable.
+ is_train_batch_min (`bool`, defaults to `True`):
+ If both train & eval dataloaders are specified, this will decide the `train_batch_size`.
+ offload_optimizer_device (`str`, defaults to `None`):
+ Possible options are none|cpu|nvme. Only applicable with ZeRO Stages 2 and 3.
+ offload_param_device (`str`, defaults to `None`):
+ Possible options are none|cpu|nvme. Only applicable with ZeRO Stage 3.
+ offload_optimizer_nvme_path (`str`, defaults to `None`):
+ Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3.
+ offload_param_nvme_path (`str`, defaults to `None`):
+ Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3.
+ zero3_init_flag (`bool`, defaults to `None`):
+ Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3.
+ zero3_save_16bit_model (`bool`, defaults to `None`):
+ Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3.
+ transformer_moe_cls_names (`str`, defaults to `None`):
+ Comma-separated list of Transformers MoE layer class names (case-sensitive). For example,
+ `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention`, `JetMoEBlock`, etc.
+ enable_msamp (`bool`, defaults to `None`):
+ Flag to indicate whether to enable MS-AMP backend for FP8 training.
+ msasmp_opt_level (`Optional[Literal["O1", "O2"]]`, defaults to `None`):
+ Optimization level for MS-AMP (defaults to 'O1'). Only applicable if `enable_msamp` is True. Should be one
+ of ['O1' or 'O2'].
+ """
+
+ hf_ds_config: Any = field(
+ default=None,
+ metadata={
+ "help": "path to DeepSpeed config file or dict or an object of class `accelerate.utils.deepspeed.HfDeepSpeedConfig`."
+ },
+ )
+ gradient_accumulation_steps: int = field(
+ default=None,
+ metadata={
+ "help": "Number of steps to accumulate gradients before updating optimizer states. If not set, will use the value from the `Accelerator` directly."
+ },
+ )
+ gradient_clipping: float = field(default=None, metadata={"help": "Enable gradient clipping with value"})
+ zero_stage: int = field(
+ default=None,
+ metadata={"help": "Possible options are 0,1,2,3; Default will be taken from environment variable"},
+ )
+ is_train_batch_min: bool = field(
+ default=True,
+ metadata={"help": "If both train & eval dataloaders are specified, this will decide the train_batch_size"},
+ )
+ offload_optimizer_device: str = field(
+ default=None,
+ metadata={"help": "Possible options are none|cpu|nvme. Only applicable with ZeRO Stages 2 and 3."},
+ )
+ offload_param_device: str = field(
+ default=None,
+ metadata={"help": "Possible options are none|cpu|nvme. Only applicable with ZeRO Stage 3."},
+ )
+ offload_optimizer_nvme_path: str = field(
+ default=None,
+ metadata={"help": "Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3."},
+ )
+ offload_param_nvme_path: str = field(
+ default=None,
+ metadata={"help": "Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3."},
+ )
+ zero3_init_flag: bool = field(
+ default=None,
+ metadata={
+ "help": "Flag to indicate whether to enable `deepspeed.zero.Init` for constructing massive models."
+ "Only applicable with ZeRO Stage-3."
+ },
+ )
+ zero3_save_16bit_model: bool = field(
+ default=None,
+ metadata={"help": "Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3."},
+ )
+ transformer_moe_cls_names: str = field(
+ default=None,
+ metadata={
+ "help": "comma-separated list of transformers MoE layer class names (case-sensitive), e.g : "
+ " `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ..."
+ },
+ )
+ enable_msamp: bool = field(
+ default=None,
+ metadata={"help": "Flag to indicate whether to enable MS-AMP backend for FP8 training."},
+ )
+ msamp_opt_level: Optional[Literal["O1", "O2"]] = field(
+ default=None,
+ metadata={
+ "help": "Optimization level for MS-AMP (defaults to 'O1'). Only applicable if `enable_msamp` is True. Should be one of ['O1' or 'O2']."
+ },
+ )
+
+ def __post_init__(self):
+ from .deepspeed import HfDeepSpeedConfig
+
+ if self.gradient_accumulation_steps is None:
+ gas = os.environ.get("ACCELERATE_GRADIENT_ACCUMULATION_STEPS", "auto")
+ self.gradient_accumulation_steps = int(gas) if gas.isdigit() else gas
+
+ if self.gradient_clipping is None:
+ gradient_clipping = os.environ.get("ACCELERATE_GRADIENT_CLIPPING", "auto")
+ self.gradient_clipping = gradient_clipping if gradient_clipping == "auto" else float(gradient_clipping)
+
+ if self.zero_stage is None:
+ self.zero_stage = int(os.environ.get("ACCELERATE_DEEPSPEED_ZERO_STAGE", 2))
+
+ if self.offload_optimizer_device is None:
+ self.offload_optimizer_device = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE", "none")
+
+ if self.offload_param_device is None:
+ self.offload_param_device = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE", "none")
+
+ if self.offload_optimizer_nvme_path is None:
+ self.offload_optimizer_nvme_path = os.environ.get(
+ "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_NVME_PATH", "none"
+ )
+
+ if self.offload_param_nvme_path is None:
+ self.offload_param_nvme_path = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_NVME_PATH", "none")
+
+ if self.zero3_save_16bit_model is None:
+ self.zero3_save_16bit_model = (
+ os.environ.get("ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL", "false") == "true"
+ )
+ if self.enable_msamp is None:
+ self.enable_msamp = os.environ.get("ACCELERATE_FP8_BACKEND", None) == "MSAMP"
+
+ if self.msamp_opt_level is None:
+ self.msamp_opt_level = os.environ.get("ACCELERATE_FP8_OPT_LEVEL", "O1")
+
+ if self.hf_ds_config is None:
+ self.hf_ds_config = os.environ.get("ACCELERATE_DEEPSPEED_CONFIG_FILE", "none")
+ if (
+ isinstance(self.hf_ds_config, dict)
+ or (isinstance(self.hf_ds_config, str) and self.hf_ds_config != "none")
+ or isinstance(self.hf_ds_config, HfDeepSpeedConfig)
+ ):
+ if not isinstance(self.hf_ds_config, HfDeepSpeedConfig):
+ self.hf_ds_config = HfDeepSpeedConfig(self.hf_ds_config)
+ if "gradient_accumulation_steps" not in self.hf_ds_config.config:
+ self.hf_ds_config.config["gradient_accumulation_steps"] = 1
+ if "zero_optimization" not in self.hf_ds_config.config:
+ raise ValueError("Please specify the ZeRO optimization config in the DeepSpeed config.")
+
+ self._deepspeed_config_checks()
+ plugin_to_config_mapping = {
+ "gradient_accumulation_steps": "gradient_accumulation_steps",
+ "gradient_clipping": "gradient_clipping",
+ "zero_stage": "zero_optimization.stage",
+ "offload_optimizer_device": "zero_optimization.offload_optimizer.device",
+ "offload_param_device": "zero_optimization.offload_param.device",
+ "offload_param_nvme_path": "zero_optimization.offload_param.nvme_path",
+ "offload_optimizer_nvme_path": "zero_optimization.offload_optimizer.nvme_path",
+ "zero3_save_16bit_model": "zero_optimization.stage3_gather_16bit_weights_on_model_save",
+ }
+ kwargs = {v: getattr(self, k) for k, v in plugin_to_config_mapping.items() if getattr(self, k) is not None}
+ for key in kwargs.keys():
+ self.fill_match(key, **kwargs, must_match=False)
+ self.hf_ds_config.set_stage_and_offload()
+
+ # filling the missing values in the class attributes from the DeepSpeed config
+ # when using the DeepSpeed config file.
+ for key, value in plugin_to_config_mapping.items():
+ config_value = self.hf_ds_config.get_value(value)
+ if config_value is not None and config_value != "auto":
+ setattr(self, key, config_value)
+ else:
+ config = {
+ "train_batch_size": "auto",
+ "train_micro_batch_size_per_gpu": "auto",
+ "gradient_accumulation_steps": self.gradient_accumulation_steps,
+ "zero_optimization": {
+ "stage": self.zero_stage,
+ "offload_optimizer": {
+ "device": self.offload_optimizer_device,
+ "nvme_path": self.offload_optimizer_nvme_path
+ if self.offload_optimizer_device == "nvme"
+ else None,
+ },
+ "offload_param": {
+ "device": self.offload_param_device,
+ "nvme_path": self.offload_param_nvme_path if self.offload_param_device == "nvme" else None,
+ },
+ "stage3_gather_16bit_weights_on_model_save": self.zero3_save_16bit_model,
+ },
+ }
+ if self.gradient_clipping:
+ config["gradient_clipping"] = self.gradient_clipping
+ self.hf_ds_config = HfDeepSpeedConfig(config)
+
+ self.deepspeed_config = self.hf_ds_config.config
+ self.deepspeed_config["steps_per_print"] = float("inf") # this will stop deepspeed from logging @ stdout
+ if self.zero3_init_flag is None:
+ self.zero3_init_flag = (
+ str_to_bool(os.environ.get("ACCELERATE_DEEPSPEED_ZERO3_INIT", str(self.hf_ds_config.is_zero3()))) == 1
+ )
+ if self.zero3_init_flag and not self.hf_ds_config.is_zero3():
+ warnings.warn("DeepSpeed Zero3 Init flag is only applicable for ZeRO Stage 3. Setting it to False.")
+ self.zero3_init_flag = False
+ # NOTE: Set to False by default, will be set to `True` automatically if it's the first plugin passed
+ # to the `Accelerator`'s `deepspeed_plugin` param, *or* `AcceleratorState().enable_deepspeed_plugin(plugin_key)` is manually called
+ self._set_selected(False)
+
+ # Ignore if it's already set
+ if self.enable_msamp and "msamp" not in self.deepspeed_config:
+ if self.zero_stage == 3:
+ raise NotImplementedError(
+ "MS-AMP is not supported for ZeRO Stage 3. Please use ZeRO Stage 0, 1, or 2 instead."
+ )
+ if self.msamp_opt_level not in ["O1", "O2"]:
+ raise ValueError("Invalid optimization level for MS-AMP. Please use one of ['O1' or'O2'].")
+ self.deepspeed_config["msamp"] = {"enabled": True, "opt_level": self.msamp_opt_level}
+
+ def fill_match(self, ds_key_long, mismatches=None, must_match=True, **kwargs):
+ mismatches = [] if mismatches is None else mismatches
+ config, ds_key = self.hf_ds_config.find_config_node(ds_key_long)
+ if config is None:
+ return
+
+ if config.get(ds_key) == "auto":
+ if ds_key_long in kwargs:
+ config[ds_key] = kwargs[ds_key_long]
+ return
+ else:
+ raise ValueError(
+ f"`{ds_key_long}` not found in kwargs. "
+ f"Please specify `{ds_key_long}` without `auto` (set to correct value) in the DeepSpeed config file or "
+ "pass it in kwargs."
+ )
+
+ if not must_match:
+ return
+
+ ds_val = config.get(ds_key)
+ if ds_val is not None and ds_key_long in kwargs:
+ if ds_val != kwargs[ds_key_long]:
+ mismatches.append(f"- ds {ds_key_long}={ds_val} vs arg {ds_key_long}={kwargs[ds_key_long]}")
+
+ def is_auto(self, ds_key_long):
+ val = self.hf_ds_config.get_value(ds_key_long)
+ if val is None:
+ return False
+ else:
+ return val == "auto"
+
+ def get_value(self, ds_key_long, default=None):
+ return self.hf_ds_config.get_value(ds_key_long, default)
+
+ def deepspeed_config_process(self, prefix="", mismatches=None, config=None, must_match=True, **kwargs):
+ """Process the DeepSpeed config with the values from the kwargs."""
+ mismatches = [] if mismatches is None else mismatches
+ if config is None:
+ config = self.deepspeed_config
+ for key, value in config.items():
+ if isinstance(value, dict):
+ self.deepspeed_config_process(
+ prefix=prefix + key + ".", mismatches=mismatches, config=value, must_match=must_match, **kwargs
+ )
+ else:
+ self.fill_match(prefix + key, mismatches, must_match=must_match, **kwargs)
+ if len(mismatches) > 0 and prefix == "":
+ mismatches_msg = "\n".join(mismatches)
+ raise ValueError(
+ "Please correct the following DeepSpeed config values that mismatch kwargs "
+ f" values:\n{mismatches_msg}\nThe easiest method is to set these DeepSpeed config values to 'auto'."
+ )
+
+ def set_mixed_precision(self, mixed_precision):
+ ds_config = self.deepspeed_config
+ kwargs = {
+ "fp16.enabled": mixed_precision == "fp16",
+ # When training in fp8, we still rely on bf16 autocast for the core mixed precision
+ "bf16.enabled": mixed_precision in ("bf16", "fp8"),
+ }
+ if mixed_precision == "fp16":
+ if "fp16" not in ds_config:
+ ds_config["fp16"] = {"enabled": True, "auto_cast": True}
+ elif mixed_precision in ("bf16", "fp8"):
+ if "bf16" not in ds_config:
+ ds_config["bf16"] = {"enabled": True}
+
+ if mixed_precision == "fp8" and self.enable_msamp:
+ if "msamp" not in ds_config:
+ ds_config["msamp"] = {"enabled": True, "opt_level": self.msamp_opt_level}
+
+ if mixed_precision != "no":
+ diff_dtype = "bf16" if mixed_precision == "fp16" else "fp16"
+ if str(ds_config.get(diff_dtype, {}).get("enabled", "False")).lower() == "true":
+ raise ValueError(
+ f"`--mixed_precision` arg cannot be set to `{mixed_precision}` when `{diff_dtype}` is set in the DeepSpeed config file."
+ )
+ for dtype in ["fp16", "bf16"]:
+ if dtype not in ds_config:
+ ds_config[dtype] = {"enabled": False}
+ self.fill_match("fp16.enabled", must_match=False, **kwargs)
+ self.fill_match("bf16.enabled", must_match=False, **kwargs)
+
+ def set_deepspeed_weakref(self):
+ from .imports import is_transformers_available
+
+ ds_config = copy.deepcopy(self.deepspeed_config)
+ if self.zero3_init_flag:
+ if not is_transformers_available():
+ raise Exception(
+ "When `zero3_init_flag` is set, it requires Transformers to be installed. "
+ "Please run `pip install transformers`."
+ )
+ if "gradient_accumulation_steps" not in ds_config or ds_config["gradient_accumulation_steps"] == "auto":
+ ds_config["gradient_accumulation_steps"] = 1
+ if (
+ "train_micro_batch_size_per_gpu" not in ds_config
+ or ds_config["train_micro_batch_size_per_gpu"] == "auto"
+ ):
+ ds_config["train_micro_batch_size_per_gpu"] = 1
+ if ds_config.get("train_batch_size", None) == "auto":
+ del ds_config["train_batch_size"]
+
+ if compare_versions("transformers", "<", "4.33"):
+ from transformers.deepspeed import HfDeepSpeedConfig, unset_hf_deepspeed_config
+ else:
+ from transformers.integrations import HfDeepSpeedConfig, unset_hf_deepspeed_config
+
+ unset_hf_deepspeed_config()
+ self.dschf = HfDeepSpeedConfig(ds_config) # keep this object alive # noqa
+
+ def is_zero3_init_enabled(self):
+ return self.zero3_init_flag
+
+ @contextmanager
+ def zero3_init_context_manager(self, enable=False):
+ old = self.zero3_init_flag
+ if old == enable:
+ yield
+ else:
+ self.zero3_init_flag = enable
+ self.dschf = None
+ self.set_deepspeed_weakref()
+ yield
+ self.zero3_init_flag = old
+ self.dschf = None
+ self.set_deepspeed_weakref()
+
+ def _deepspeed_config_checks(self):
+ env_variable_names_to_ignore = [
+ "ACCELERATE_GRADIENT_ACCUMULATION_STEPS",
+ "ACCELERATE_GRADIENT_CLIPPING",
+ "ACCELERATE_DEEPSPEED_ZERO_STAGE",
+ "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE",
+ "ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE",
+ "ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_NVME_PATH",
+ "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_NVME_PATH",
+ "ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL",
+ "ACCELERATE_MIXED_PRECISION",
+ ]
+ env_variable_names_to_ignore = [
+ name.replace("ACCELERATE_", "").replace("DEEPSPEED_", "").lower() for name in env_variable_names_to_ignore
+ ]
+
+ deepspeed_fields_from_accelerate_config = os.environ.get("ACCELERATE_CONFIG_DS_FIELDS", "").split(",")
+
+ if any(name in env_variable_names_to_ignore for name in deepspeed_fields_from_accelerate_config):
+ raise ValueError(
+ f"When using `deepspeed_config_file`, the following accelerate config variables will be ignored: {env_variable_names_to_ignore}.\n"
+ "Please specify them appropriately in the DeepSpeed config file.\n"
+ "If you are using an accelerate config file, remove others config variables mentioned in the above specified list.\n"
+ "The easiest method is to create a new config following the questionnaire via `accelerate config`.\n"
+ "It will only ask for the necessary config variables when using `deepspeed_config_file`."
+ )
+
+ def set_moe_leaf_modules(self, model):
+ if self.transformer_moe_cls_names is None:
+ self.transformer_moe_cls_names = os.environ.get("ACCELERATE_DEEPSPEED_MOE_LAYER_CLS_NAMES", None)
+ if self.transformer_moe_cls_names is not None:
+ if compare_versions("deepspeed", "<", "0.14.0"):
+ raise ImportError("DeepSpeed version must be >= 0.14.0 to use MOE support. Please update DeepSpeed.")
+ from deepspeed.utils import set_z3_leaf_modules
+
+ class_names = self.transformer_moe_cls_names.split(",")
+ transformer_moe_cls = []
+ for layer_class in class_names:
+ transformer_cls = get_module_class_from_name(model, layer_class)
+ if transformer_cls is None:
+ raise Exception(
+ f"Could not find a transformer layer class called '{layer_class}' to wrap in the model."
+ )
+ else:
+ transformer_moe_cls.append(transformer_cls)
+ set_z3_leaf_modules(model, transformer_moe_cls) # z3_leaf
+
+ def select(self, _from_accelerator_state: bool = False):
+ """
+ Sets the HfDeepSpeedWeakref to use the current deepspeed plugin configuration
+ """
+ if not _from_accelerator_state:
+ raise ValueError(
+ "A `DeepSpeedPlugin` object must be enabled manually by calling `AcceleratorState().enable_deepspeed_plugin(plugin_key)`."
+ )
+ self.set_deepspeed_weakref()
+ self._set_selected(True)
+
+ def _unselect(self):
+ self._set_selected(False)
+
+ def _set_selected(self, value: bool):
+ """
+ Private setter for the 'enabled' attribute.
+ """
+ self._selected = value
+
+ @property
+ def selected(self):
+ return self._selected
+
+ @selected.setter
+ def selected(self, value):
+ raise NotImplementedError(
+ "'enabled' can only be set through calling 'AcceleratorState().enable_deepspeed_plugin(key)'."
+ )
+
+
+@dataclass
+class FullyShardedDataParallelPlugin:
+ """
+ This plugin is used to enable fully sharded data parallelism.
+
+ Args:
+ sharding_strategy (`Union[str, torch.distributed.fsdp.ShardingStrategy]`, defaults to `'FULL_SHARD'`):
+ Sharding strategy to use. Should be either a `str` or an instance of
+ `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`.
+ backward_prefetch (`Union[str, torch.distributed.fsdp.BackwardPrefetch]`, defaults to `'NO_PREFETCH'`):
+ Backward prefetch strategy to use. Should be either a `str` or an instance of
+ `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch`.
+ mixed_precision_policy (`Optional[Union[dict, torch.distributed.fsdp.MixedPrecision]]`, defaults to `None`):
+ A config to enable mixed precision training with FullyShardedDataParallel. If passing in a `dict`, it
+ should have the following keys: `param_dtype`, `reduce_dtype`, and `buffer_dtype`.
+ auto_wrap_policy (`Optional(Union[Callable, Literal["transformer_based_wrap", "size_based_wrap", "no_wrap"]]), defaults to `NO_WRAP`):
+ A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one
+ of `transformer_based_wrap`, `size_based_wrap`, or `no_wrap`. See
+ `torch.distributed.fsdp.wrap.size_based_wrap_policy` for a direction on what it should look like.
+ cpu_offload (`Union[bool, torch.distributed.fsdp.CPUOffload]`, defaults to `False`):
+ Whether to offload parameters to CPU. Should be either a `bool` or an instance of
+ `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload`.
+ ignored_modules (`Optional[Iterable[torch.nn.Module]]`, defaults to `None`):
+ A list of modules to ignore when wrapping with FSDP.
+ state_dict_type (`Union[str, torch.distributed.fsdp.StateDictType]`, defaults to `'FULL_STATE_DICT'`):
+ State dict type to use. If a string, it must be one of `full_state_dict`, `local_state_dict`, or
+ `sharded_state_dict`.
+ state_dict_config (`Optional[Union[torch.distributed.fsdp.FullStateDictConfig, torch.distributed.fsdp.ShardedStateDictConfig]`, defaults to `None`):
+ State dict config to use. Is determined based on the `state_dict_type` if not passed in.
+ optim_state_dict_config (`Optional[Union[torch.distributed.fsdp.FullOptimStateDictConfig, torch.distributed.fsdp.ShardedOptimStateDictConfig]`, defaults to `None`):
+ Optim state dict config to use. Is determined based on the `state_dict_type` if not passed in.
+ limit_all_gathers (`bool`, defaults to `True`):
+ Whether to have FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. This
+ bool only affects the sharded strategies that schedule all-gathers. Enabling this can help lower the number
+ of CUDA malloc retries.
+ use_orig_params (`bool`, defaults to `False`):
+ Whether to use the original parameters for the optimizer.
+ param_init_fn (`Optional[Callable[[torch.nn.Module], None]`, defaults to `None`):
+ A `Callable[torch.nn.Module] -> None` that specifies how modules that are currently on the meta device
+ should be initialized onto an actual device. Only applicable when `sync_module_states` is `True`. By
+ default is a `lambda` which calls `to_empty` on the module.
+ sync_module_states (`bool`, defaults to `False`):
+ Whether each individually wrapped FSDP unit should broadcast module parameters from rank 0 to ensure they
+ are the same across all ranks after initialization. Defaults to `False` unless `cpu_ram_efficient_loading`
+ is `True`, then will be forcibly enabled.
+ forward_prefetch (`bool`, defaults to `False`):
+ Whether to have FSDP explicitly prefetches the next upcoming all-gather while executing in the forward
+ pass. only use with Static graphs.
+ activation_checkpointing (`bool`, defaults to `False`):
+ A technique to reduce memory usage by clearing activations of certain layers and recomputing them during a
+ backward pass. Effectively, this trades extra computation time for reduced memory usage.
+ cpu_ram_efficient_loading (`bool`, defaults to `None`):
+ If True, only the first process loads the pretrained model checkoint while all other processes have empty
+ weights. Only applicable for Transformers. When using this, `sync_module_states` needs to be `True`.
+ transformer_cls_names_to_wrap (`Optional[List[str]]`, defaults to `None`):
+ A list of transformer layer class names to wrap. Only applicable when `auto_wrap_policy` is
+ `transformer_based_wrap`.
+ min_num_params (`Optional[int]`, defaults to `None`):
+ The minimum number of parameters a module must have to be wrapped. Only applicable when `auto_wrap_policy`
+ is `size_based_wrap`.
+ """
+
+ sharding_strategy: Union[str, "torch.distributed.fsdp.ShardingStrategy"] = field(
+ default=None,
+ metadata={
+ "help": "Sharding strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Defaults to 'FULL_SHARD'"
+ },
+ )
+ backward_prefetch: Union[str, "torch.distributed.fsdp.BackwardPrefetch"] = field(
+ default=None,
+ metadata={
+ "help": "Backward prefetch strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch`. Defaults to 'NO_PREFETCH'"
+ },
+ )
+ mixed_precision_policy: Optional[Union[dict, "torch.distributed.fsdp.MixedPrecision"]] = field(
+ default=None,
+ metadata={
+ "help": "A config to enable mixed precision training with FullyShardedDataParallel. "
+ "If passing in a `dict`, it should have the following keys: `param_dtype`, `reduce_dtype`, and `buffer_dtype`."
+ },
+ )
+ auto_wrap_policy: Optional[Union[Callable, Literal["transformer_based_wrap", "size_based_wrap", "no_wrap"]]] = (
+ field(
+ default=None,
+ metadata={
+ "help": "A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one of `transformer_based_wrap`, `size_based_wrap`, or `no_wrap`. "
+ "Defaults to `NO_WRAP`. See `torch.distributed.fsdp.wrap.size_based_wrap_policy` for a direction on what it should look like"
+ },
+ )
+ )
+ cpu_offload: Union[bool, "torch.distributed.fsdp.CPUOffload"] = field(
+ default=None,
+ metadata={
+ "help": "Whether to offload parameters to CPU. Should be either a `bool` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload`. Defaults to `False`"
+ },
+ )
+ ignored_modules: Optional[Iterable[torch.nn.Module]] = field(
+ default=None,
+ metadata={"help": "A list of modules to ignore when wrapping with FSDP."},
+ )
+
+ state_dict_type: Union[str, "torch.distributed.fsdp.StateDictType"] = field(
+ default=None,
+ metadata={
+ "help": "State dict type to use. If a string, it must be one of `full_state_dict`, `local_state_dict`, or `sharded_state_dict`. Defaults to `FULL_STATE_DICT`"
+ },
+ )
+ state_dict_config: Optional[
+ Union[
+ "torch.distributed.fsdp.FullStateDictConfig",
+ "torch.distributed.fsdp.ShardedStateDictConfig",
+ ]
+ ] = field(
+ default=None,
+ metadata={"help": "State dict config to use. Is determined based on the `state_dict_type` if not passed in."},
+ )
+ optim_state_dict_config: Optional[
+ Union["torch.distributed.fsdp.FullOptimStateDictConfig", "torch.distributed.fsdp.ShardedOptimStateDictConfig"]
+ ] = field(
+ default=None,
+ metadata={
+ "help": "Optim state dict config to use. Is determined based on the `state_dict_type` if not passed in."
+ },
+ )
+ limit_all_gathers: bool = field(
+ default=True,
+ metadata={
+ "help": "Whether to have FSDP explicitly synchronizes the CPU thread to prevent "
+ "too many in-flight all-gathers. This bool only affects the sharded strategies that schedule all-gathers. "
+ "Enabling this can help lower the number of CUDA malloc retries."
+ },
+ )
+ use_orig_params: bool = field(
+ default=None,
+ metadata={"help": "Whether to use the original parameters for the optimizer. Defaults to `False`"},
+ )
+ param_init_fn: Optional[Callable[[torch.nn.Module], None]] = field(
+ default=None,
+ metadata={
+ "help": "A Callable[torch.nn.Module] -> None that specifies how modules "
+ "that are currently on the meta device should be initialized onto an actual device. "
+ "Only applicable when `sync_module_states` is `True`. By default is a `lambda` which calls `to_empty` on the module."
+ },
+ )
+ sync_module_states: bool = field(
+ default=None,
+ metadata={
+ "help": "Whether each individually wrapped FSDP unit should broadcast module parameters from rank 0 "
+ "to ensure they are the same across all ranks after initialization. Defaults to `False` unless "
+ "`cpu_ram_efficient_loading` is `True`, then will be forcibly enabled."
+ },
+ )
+ forward_prefetch: bool = field(
+ default=None,
+ metadata={
+ "help": "Whether to have FSDP explicitly prefetches the next upcoming "
+ "all-gather while executing in the forward pass. only use with Static graphs. Defaults to `False`"
+ },
+ )
+ activation_checkpointing: bool = field(
+ default=None,
+ metadata={
+ "help": "A technique to reduce memory usage by clearing activations of "
+ "certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time "
+ "for reduced memory usage. Defaults to `False`"
+ },
+ )
+ cpu_ram_efficient_loading: bool = field(
+ default=None,
+ metadata={
+ "help": "If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. "
+ "Only applicable for 🤗 Transformers. When using this, `sync_module_states` needs to be `True`. Defaults to `False`."
+ },
+ )
+ transformer_cls_names_to_wrap: Optional[List[str]] = field(
+ default=None,
+ metadata={
+ "help": "A list of transformer layer class names to wrap. Only applicable when `auto_wrap_policy` is `transformer_based_wrap`."
+ },
+ )
+ min_num_params: Optional[int] = field(
+ default=None,
+ metadata={
+ "help": "The minimum number of parameters a module must have to be wrapped. Only applicable when `auto_wrap_policy` is `size_based_wrap`."
+ },
+ )
+
+ def __post_init__(self):
+ from torch.distributed.fsdp import (
+ BackwardPrefetch,
+ CPUOffload,
+ ShardingStrategy,
+ )
+
+ env_prefix = "FSDP_"
+ # Strategy: By default we should always assume that values are passed in, else we check the environment variables
+ if self.sharding_strategy is None:
+ self.sharding_strategy = os.environ.get(env_prefix + "SHARDING_STRATEGY", "FULL_SHARD")
+ if isinstance(self.sharding_strategy, str):
+ # We need to remap based on custom enum values for user readability
+ if self.sharding_strategy.upper() in FSDP_SHARDING_STRATEGY:
+ self.sharding_strategy = FSDP_SHARDING_STRATEGY.index(self.sharding_strategy.upper()) + 1
+ if isinstance(self.sharding_strategy, int) or self.sharding_strategy.isdigit():
+ self.sharding_strategy = ShardingStrategy(int(self.sharding_strategy))
+ else:
+ self.sharding_strategy = ShardingStrategy[self.sharding_strategy.upper()]
+
+ if self.cpu_offload is None:
+ self.cpu_offload = str_to_bool(os.environ.get(env_prefix + "OFFLOAD_PARAMS", "False")) == 1
+ if isinstance(self.cpu_offload, bool):
+ self.cpu_offload = CPUOffload(offload_params=self.cpu_offload)
+
+ if self.backward_prefetch is None:
+ self.backward_prefetch = os.environ.get(env_prefix + "BACKWARD_PREFETCH", None)
+ if isinstance(self.backward_prefetch, str) and self.backward_prefetch.upper() == "NO_PREFETCH":
+ self.backward_prefetch = None
+ if self.backward_prefetch is not None and not isinstance(self.backward_prefetch, BackwardPrefetch):
+ if isinstance(self.backward_prefetch, str) and self.backward_prefetch.upper() in FSDP_BACKWARD_PREFETCH:
+ self.backward_prefetch = FSDP_BACKWARD_PREFETCH.index(self.backward_prefetch.upper()) + 1
+ if isinstance(self.backward_prefetch, int) or self.backward_prefetch.isdigit():
+ self.backward_prefetch = BackwardPrefetch(int(self.backward_prefetch))
+ else:
+ self.backward_prefetch = BackwardPrefetch[self.backward_prefetch.upper()]
+
+ self.set_state_dict_type()
+
+ if self.auto_wrap_policy is None:
+ self.auto_wrap_policy = os.environ.get(env_prefix + "AUTO_WRAP_POLICY", "NO_WRAP")
+ if isinstance(self.auto_wrap_policy, str):
+ if self.auto_wrap_policy.upper() not in FSDP_AUTO_WRAP_POLICY:
+ raise ValueError(
+ f"Invalid auto wrap policy: {self.auto_wrap_policy}. Must be one of {list(FSDP_AUTO_WRAP_POLICY.keys())}"
+ )
+ from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy, transformer_auto_wrap_policy
+
+ if self.auto_wrap_policy.upper() == "TRANSFORMER_BASED_WRAP":
+ self.auto_wrap_policy = transformer_auto_wrap_policy
+ if self.transformer_cls_names_to_wrap is None:
+ self.transformer_cls_names_to_wrap = os.environ.get(env_prefix + "TRANSFORMER_CLS_TO_WRAP", None)
+ if isinstance(self.transformer_cls_names_to_wrap, str):
+ self.transformer_cls_names_to_wrap = self.transformer_cls_names_to_wrap.split(",")
+ elif self.auto_wrap_policy.upper() == "SIZE_BASED_WRAP":
+ self.auto_wrap_policy = size_based_auto_wrap_policy
+ if self.min_num_params is None:
+ self.min_num_params = int(os.environ.get(env_prefix + "MIN_NUM_PARAMS", 0))
+ elif not isinstance(self.min_num_params, int):
+ raise ValueError(
+ f"`min_num_params` must be an integer. Got {self.min_num_params} of type {type(self.min_num_params)}"
+ )
+ elif self.auto_wrap_policy.upper() == "NO_WRAP":
+ self.auto_wrap_policy = None
+
+ if self.use_orig_params is None:
+ self.use_orig_params = str_to_bool(os.environ.get(env_prefix + "USE_ORIG_PARAMS", "False")) == 1
+
+ if self.sync_module_states is None:
+ self.sync_module_states = str_to_bool(os.environ.get(env_prefix + "SYNC_MODULE_STATES", "False")) == 1
+
+ if self.forward_prefetch is None:
+ self.forward_prefetch = str_to_bool(os.environ.get(env_prefix + "FORWARD_PREFETCH", "False")) == 1
+
+ if self.activation_checkpointing is None:
+ self.activation_checkpointing = (
+ str_to_bool(os.environ.get(env_prefix + "ACTIVATION_CHECKPOINTING", "False")) == 1
+ )
+
+ if self.cpu_ram_efficient_loading is None:
+ self.cpu_ram_efficient_loading = (
+ str_to_bool(os.environ.get(env_prefix + "CPU_RAM_EFFICIENT_LOADING", "False")) == 1
+ )
+
+ if self.cpu_ram_efficient_loading and not self.sync_module_states:
+ warnings.warn(
+ "sync_module_states cannot be False since efficient cpu ram loading enabled. "
+ "Setting sync_module_states to True."
+ )
+ self.sync_module_states = True
+
+ if isinstance(self.mixed_precision_policy, dict):
+ self.set_mixed_precision(self.mixed_precision_policy)
+
+ if self.sync_module_states:
+ if is_npu_available():
+ device = torch.npu.current_device()
+ elif is_mlu_available():
+ device = torch.mlu.current_device()
+ elif is_cuda_available():
+ device = torch.cuda.current_device()
+ elif is_xpu_available():
+ device = torch.xpu.current_device()
+ else:
+ raise RuntimeError(
+ "There are currently no available devices found, must be one of 'XPU', 'CUDA', or 'NPU'."
+ )
+ # Create a function that will be used to initialize the parameters of the model
+ # when using `sync_module_states`
+ self.param_init_fn = lambda x: x.to_empty(device=device, recurse=False)
+
+ def set_state_dict_type(self, state_dict_type=None):
+ """
+ Set the state dict config based on the `StateDictType`.
+ """
+ from torch.distributed.fsdp.fully_sharded_data_parallel import (
+ FullOptimStateDictConfig,
+ FullStateDictConfig,
+ ShardedOptimStateDictConfig,
+ ShardedStateDictConfig,
+ StateDictType,
+ )
+
+ # Override the state_dict_type if provided, typical use case:
+ # user trains with sharded, but final save is with full
+ if state_dict_type is not None:
+ self.state_dict_type = state_dict_type
+
+ if self.state_dict_type is None:
+ self.state_dict_type = os.environ.get("FSDP_STATE_DICT_TYPE", "FULL_STATE_DICT")
+ if isinstance(self.state_dict_type, str):
+ if self.state_dict_type.isdigit():
+ self.state_dict_type = StateDictType(int(self.state_dict_type))
+ else:
+ self.state_dict_type = StateDictType[self.state_dict_type.upper()]
+
+ if self.state_dict_type == StateDictType.FULL_STATE_DICT:
+ if self.state_dict_config is None:
+ self.state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)
+ if self.optim_state_dict_config is None:
+ self.optim_state_dict_config = FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=True)
+ elif self.state_dict_type == StateDictType.SHARDED_STATE_DICT:
+ if self.state_dict_config is None:
+ self.state_dict_config = ShardedStateDictConfig(offload_to_cpu=True)
+ if self.optim_state_dict_config is None:
+ self.optim_state_dict_config = ShardedOptimStateDictConfig(offload_to_cpu=True)
+
+ def set_auto_wrap_policy(self, model):
+ """
+ Given `model`, creates an `auto_wrap_policy` baesd on the passed in policy and if we can use the
+ `transformer_cls_to_wrap`
+ """
+ from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy, transformer_auto_wrap_policy
+
+ # First base off of `_no_split_modules`
+ no_split_modules = getattr(model, "_no_split_modules", None)
+ default_transformer_cls_names_to_wrap = list(no_split_modules) if no_split_modules is not None else []
+ if self.auto_wrap_policy == transformer_auto_wrap_policy:
+ if self.transformer_cls_names_to_wrap is None:
+ self.transformer_cls_names_to_wrap = default_transformer_cls_names_to_wrap
+ transformer_cls_to_wrap = set()
+ for layer_class in self.transformer_cls_names_to_wrap:
+ transformer_cls = get_module_class_from_name(model, layer_class)
+ if transformer_cls is None:
+ raise ValueError(f"Could not find the transformer layer class {layer_class} in the model.")
+ transformer_cls_to_wrap.add(transformer_cls)
+ # Finally we set the auto_wrap_policy to a callable
+ self.auto_wrap_policy = functools.partial(
+ self.auto_wrap_policy, transformer_layer_cls=transformer_cls_to_wrap
+ )
+
+ elif self.auto_wrap_policy == size_based_auto_wrap_policy:
+ # If zero, we silently ignore it.
+ if self.min_num_params > 0:
+ self.auto_wrap_policy = functools.partial(self.auto_wrap_policy, min_num_params=self.min_num_params)
+ else:
+ self.auto_wrap_policy = None
+
+ def set_mixed_precision(self, mixed_precision, buffer_autocast=False, override=False):
+ "Sets the mixed precision policy for FSDP"
+ mixed_precision_mapping = {
+ "fp8": torch.bfloat16,
+ "fp16": torch.float16,
+ "bf16": torch.bfloat16,
+ "fp32": torch.float32,
+ }
+ dtype = mixed_precision
+ if isinstance(mixed_precision, str):
+ dtype = mixed_precision_mapping.get(mixed_precision, None)
+ if dtype is None:
+ raise ValueError(
+ f"Invalid mixed precision: {mixed_precision}. Must be one of {list(mixed_precision_mapping.keys())}"
+ )
+ elif isinstance(mixed_precision, torch.dtype) and mixed_precision not in mixed_precision_mapping.values():
+ raise ValueError(
+ f"Invalid mixed precision: {mixed_precision}. Must be one of {list(mixed_precision_mapping.values())}"
+ )
+
+ buffer_type = torch.float32 if buffer_autocast else dtype
+
+ from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision
+
+ if override or self.mixed_precision_policy is None:
+ self.mixed_precision_policy = MixedPrecision(
+ param_dtype=dtype, reduce_dtype=dtype, buffer_dtype=buffer_type
+ )
+ elif isinstance(self.mixed_precision_policy, dict):
+ # Check for incompatible types
+ missing_keys = [
+ k for k in ["param_dtype", "reduce_dtype", "buffer_dtype"] if k not in self.mixed_precision_policy
+ ]
+ invalid_values = [
+ k for k, v in self.mixed_precision_policy.items() if v not in mixed_precision_mapping.values()
+ ]
+ if missing_keys or invalid_values:
+ raise ValueError(
+ f"Invalid mixed precision policy: {self.mixed_precision_policy}. "
+ f"Must be a `dict` with keys `param_dtype`, `reduce_dtype`, and `buffer_dtype`. "
+ f"Values must be one of {list(mixed_precision_mapping.values())}"
+ )
+ self.mixed_precision_policy = MixedPrecision(**self.mixed_precision_policy)
+
+
+@dataclass
+class MegatronLMPlugin:
+ """
+ Plugin for Megatron-LM to enable tensor, pipeline, sequence and data parallelism. Also to enable selective
+ activation recomputation and optimized fused kernels.
+
+ Args:
+ tp_degree (`int`, defaults to `None`):
+ Tensor parallelism degree.
+ pp_degree (`int`, defaults to `None`):
+ Pipeline parallelism degree.
+ num_micro_batches (`int`, defaults to `None`):
+ Number of micro-batches.
+ gradient_clipping (`float`, defaults to `None`):
+ Gradient clipping value based on global L2 Norm (0 to disable).
+ sequence_parallelism (`bool`, defaults to `None`):
+ Enable sequence parallelism.
+ recompute_activations (`bool`, defaults to `None`):
+ Enable selective activation recomputation.
+ use_distributed_optimizr (`bool`, defaults to `None`):
+ Enable distributed optimizer.
+ pipeline_model_parallel_split_rank (`int`, defaults to `None`):
+ Rank where encoder and decoder should be split.
+ num_layers_per_virtual_pipeline_stage (`int`, defaults to `None`):
+ Number of layers per virtual pipeline stage.
+ is_train_batch_min (`str`, defaults to `True`):
+ If both tran & eval dataloaders are specified, this will decide the `micro_batch_size`.
+ train_iters (`int`, defaults to `None`):
+ Total number of samples to train over all training runs. Note that either train-iters or train-samples
+ should be provided when using `MegatronLMDummyScheduler`.
+ train_samples (`int`, defaults to `None`):
+ Total number of samples to train over all training runs. Note that either train-iters or train-samples
+ should be provided when using `MegatronLMDummyScheduler`.
+ weight_decay_incr_style (`str`, defaults to `'constant'`):
+ Weight decay increment function. choices=["constant", "linear", "cosine"].
+ start_weight_decay (`float`, defaults to `None`):
+ Initial weight decay coefficient for L2 regularization.
+ end_weight_decay (`float`, defaults to `None`):
+ End of run weight decay coefficient for L2 regularization.
+ lr_decay_style (`str`, defaults to `'linear'`):
+ Learning rate decay function. choices=['constant', 'linear', 'cosine'].
+ lr_decay_iters (`int`, defaults to `None`):
+ Number of iterations for learning rate decay. If None defaults to `train_iters`.
+ lr_decay_samples (`int`, defaults to `None`):
+ Number of samples for learning rate decay. If None defaults to `train_samples`.
+ lr_warmup_iters (`int`, defaults to `None`):
+ Number of iterations to linearly warmup learning rate over.
+ lr_warmup_samples (`int`, defaults to `None`):
+ Number of samples to linearly warmup learning rate over.
+ lr_warmup_fraction (`float`, defaults to `None`):
+ Fraction of lr-warmup-(iters/samples) to linearly warmup learning rate over.
+ min_lr (`float`, defaults to `0`):
+ Minumum value for learning rate. The scheduler clip values below this threshold.
+ consumed_samples (`List`, defaults to `None`):
+ Number of samples consumed in the same order as the dataloaders to `accelerator.prepare` call.
+ no_wd_decay_cond (`Optional`, defaults to `None`):
+ Condition to disable weight decay.
+ scale_lr_cond (`Optional`, defaults to `None`):
+ Condition to scale learning rate.
+ lr_mult (`float`, defaults to `1.0`):
+ Learning rate multiplier.
+ megatron_dataset_flag (`bool`, defaults to `False`):
+ Whether the format of dataset follows Megatron-LM Indexed/Cached/MemoryMapped format.
+ seq_length (`int`, defaults to `None`):
+ Maximum sequence length to process.
+ encoder_seq_length (`int`, defaults to `None`):
+ Maximum sequence length to process for the encoder.
+ decoder_seq_length (`int`, defaults to `None`):
+ Maximum sequence length to process for the decoder.
+ tensorboard_dir (`str`, defaults to `None`):
+ Path to save tensorboard logs.
+ set_all_logging_options (`bool`, defaults to `False`):
+ Whether to set all logging options.
+ eval_iters (`int`, defaults to `100`):
+ Number of iterations to run for evaluation validation/test for.
+ eval_interval (`int`, defaults to `1000`):
+ Interval between running evaluation on validation set.
+ return_logits (`bool`, defaults to `False`):
+ Whether to return logits from the model.
+ custom_train_step_class (`Optional`, defaults to `None`):
+ Custom train step class.
+ custom_train_step_kwargs (`Optional`, defaults to `None`):
+ Custom train step kwargs.
+ custom_model_provider_function (`Optional`, defaults to `None`):
+ Custom model provider function.
+ custom_prepare_model_function (`Optional`, defaults to `None`):
+ Custom prepare model function.
+ custom_megatron_datasets_provider_function (`Optional`, defaults to `None`):
+ Custom megatron train_valid_test datasets provider function.
+ custom_get_batch_function (`Optional`, defaults to `None`):
+ Custom get batch function.
+ custom_loss_function (`Optional`, defaults to `None`):
+ Custom loss function.
+ other_megatron_args (`Optional`, defaults to `None`):
+ Other Megatron-LM arguments. Please refer Megatron-LM.
+ """
+
+ tp_degree: int = field(default=None, metadata={"help": "tensor parallelism degree."})
+ pp_degree: int = field(default=None, metadata={"help": "pipeline parallelism degree."})
+ num_micro_batches: int = field(default=None, metadata={"help": "number of micro-batches."})
+ gradient_clipping: float = field(
+ default=None, metadata={"help": "gradient clipping value based on global L2 Norm (0 to disable)"}
+ )
+ sequence_parallelism: bool = field(
+ default=None,
+ metadata={"help": "enable sequence parallelism"},
+ )
+ recompute_activations: bool = field(
+ default=None,
+ metadata={"help": "enable selective activation recomputation"},
+ )
+ use_distributed_optimizer: bool = field(
+ default=None,
+ metadata={"help": "enable distributed optimizer"},
+ )
+ pipeline_model_parallel_split_rank: int = field(
+ default=None, metadata={"help": "Rank where encoder and decoder should be split."}
+ )
+ num_layers_per_virtual_pipeline_stage: int = field(
+ default=None, metadata={"help": "Number of layers per virtual pipeline stage."}
+ )
+ is_train_batch_min: str = field(
+ default=True,
+ metadata={"help": "If both train & eval dataloaders are specified, this will decide the micro_batch_size"},
+ )
+ train_iters: int = field(
+ default=None,
+ metadata={
+ "help": "Total number of iterations to train over all training runs. "
+ "Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`"
+ },
+ )
+ train_samples: int = field(
+ default=None,
+ metadata={
+ "help": "Total number of samples to train over all training runs. "
+ "Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`"
+ },
+ )
+ weight_decay_incr_style: str = field(
+ default="constant",
+ metadata={"help": 'Weight decay increment function. choices=["constant", "linear", "cosine"]. '},
+ )
+ start_weight_decay: float = field(
+ default=None,
+ metadata={"help": "Initial weight decay coefficient for L2 regularization."},
+ )
+ end_weight_decay: float = field(
+ default=None,
+ metadata={"help": "End of run weight decay coefficient for L2 regularization."},
+ )
+ lr_decay_style: str = field(
+ default="linear",
+ metadata={"help": "Learning rate decay function. choices=['constant', 'linear', 'cosine']."},
+ )
+ lr_decay_iters: int = field(
+ default=None,
+ metadata={"help": "Number of iterations for learning rate decay. If None defaults to `train_iters`."},
+ )
+ lr_decay_samples: int = field(
+ default=None,
+ metadata={"help": "Number of samples for learning rate decay. If None defaults to `train_samples`."},
+ )
+ lr_warmup_iters: int = field(
+ default=None,
+ metadata={"help": "number of iterations to linearly warmup learning rate over."},
+ )
+ lr_warmup_samples: int = field(
+ default=None,
+ metadata={"help": "number of samples to linearly warmup learning rate over."},
+ )
+ lr_warmup_fraction: float = field(
+ default=None,
+ metadata={"help": "fraction of lr-warmup-(iters/samples) to linearly warmup learning rate over."},
+ )
+ min_lr: float = field(
+ default=0,
+ metadata={"help": "Minumum value for learning rate. The scheduler clip values below this threshold."},
+ )
+ consumed_samples: List[int] = field(
+ default=None,
+ metadata={
+ "help": "Number of samples consumed in the same order as the dataloaders to `accelerator.prepare` call."
+ },
+ )
+ no_wd_decay_cond: Optional[Callable] = field(default=None, metadata={"help": "Condition to disable weight decay."})
+ scale_lr_cond: Optional[Callable] = field(default=None, metadata={"help": "Condition to scale learning rate."})
+ lr_mult: float = field(default=1.0, metadata={"help": "Learning rate multiplier."})
+ megatron_dataset_flag: bool = field(
+ default=False,
+ metadata={"help": "Whether the format of dataset follows Megatron-LM Indexed/Cached/MemoryMapped format."},
+ )
+ seq_length: int = field(
+ default=None,
+ metadata={"help": "Maximum sequence length to process."},
+ )
+ encoder_seq_length: int = field(
+ default=None,
+ metadata={"help": "Maximum sequence length to process for the encoder."},
+ )
+ decoder_seq_length: int = field(
+ default=None,
+ metadata={"help": "Maximum sequence length to process for the decoder."},
+ )
+ tensorboard_dir: str = field(
+ default=None,
+ metadata={"help": "Path to save tensorboard logs."},
+ )
+ set_all_logging_options: bool = field(
+ default=False,
+ metadata={"help": "Whether to set all logging options."},
+ )
+ eval_iters: int = field(
+ default=100, metadata={"help": "Number of iterations to run for evaluation validation/test for."}
+ )
+ eval_interval: int = field(
+ default=1000, metadata={"help": "Interval between running evaluation on validation set."}
+ )
+ return_logits: bool = field(
+ default=False,
+ metadata={"help": "Whether to return logits from the model."},
+ )
+
+ # custom train step args
+ custom_train_step_class: Optional[Any] = field(
+ default=None,
+ metadata={"help": "Custom train step class."},
+ )
+ custom_train_step_kwargs: Optional[Dict[str, Any]] = field(
+ default=None,
+ metadata={"help": "Custom train step kwargs."},
+ )
+
+ # custom model args
+ custom_model_provider_function: Optional[Callable] = field(
+ default=None,
+ metadata={"help": "Custom model provider function."},
+ )
+ custom_prepare_model_function: Optional[Callable] = field(
+ default=None,
+ metadata={"help": "Custom prepare model function."},
+ )
+ custom_megatron_datasets_provider_function: Optional[Callable] = field(
+ default=None,
+ metadata={"help": "Custom megatron train_valid_test datasets provider function."},
+ )
+ custom_get_batch_function: Optional[Callable] = field(
+ default=None,
+ metadata={"help": "Custom get batch function."},
+ )
+ custom_loss_function: Optional[Callable] = field(
+ default=None,
+ metadata={"help": "Custom loss function."},
+ )
+
+ # remaining args such as enabling Alibi/ROPE positional embeddings,
+ # wandb logging, Multi-Query Attention, etc.
+ other_megatron_args: Optional[Dict[str, Any]] = field(
+ default=None,
+ metadata={"help": "Other Megatron-LM arguments. Please refer Megatron-LM"},
+ )
+
+ def __post_init__(self):
+ prefix = "MEGATRON_LM_"
+ if self.tp_degree is None:
+ self.tp_degree = int(os.environ.get(prefix + "TP_DEGREE", 1))
+ if self.pp_degree is None:
+ self.pp_degree = int(os.environ.get(prefix + "PP_DEGREE", 1))
+ if self.num_micro_batches is None:
+ self.num_micro_batches = int(os.environ.get(prefix + "NUM_MICRO_BATCHES", 1))
+ if self.gradient_clipping is None:
+ self.gradient_clipping = float(os.environ.get(prefix + "GRADIENT_CLIPPING", 1.0))
+ if self.recompute_activations is None:
+ self.recompute_activations = str_to_bool(os.environ.get(prefix + "RECOMPUTE_ACTIVATIONS", "False")) == 1
+ if self.use_distributed_optimizer is None:
+ self.use_distributed_optimizer = (
+ str_to_bool(os.environ.get(prefix + "USE_DISTRIBUTED_OPTIMIZER", "False")) == 1
+ )
+ if self.sequence_parallelism is None:
+ self.sequence_parallelism = str_to_bool(os.environ.get(prefix + "SEQUENCE_PARALLELISM", "False")) == 1
+
+ if self.pp_degree > 1 or self.use_distributed_optimizer:
+ self.DDP_impl = "local"
+ else:
+ self.DDP_impl = "torch"
+
+ if self.consumed_samples is not None:
+ if len(self.consumed_samples) == 1:
+ self.consumed_samples.extend([0, 0])
+ elif len(self.consumed_samples) == 2:
+ self.consumed_samples.append(0)
+
+ self.megatron_lm_default_args = {
+ "tensor_model_parallel_size": self.tp_degree,
+ "pipeline_model_parallel_size": self.pp_degree,
+ "pipeline_model_parallel_split_rank": self.pipeline_model_parallel_split_rank,
+ "num_layers_per_virtual_pipeline_stage": self.num_layers_per_virtual_pipeline_stage,
+ "DDP_impl": self.DDP_impl,
+ "use_distributed_optimizer": self.use_distributed_optimizer,
+ "sequence_parallel": self.sequence_parallelism,
+ "clip_grad": self.gradient_clipping,
+ "num_micro_batches": self.num_micro_batches,
+ "consumed_samples": self.consumed_samples,
+ "no_wd_decay_cond": self.no_wd_decay_cond,
+ "scale_lr_cond": self.scale_lr_cond,
+ "lr_mult": self.lr_mult,
+ "megatron_dataset_flag": self.megatron_dataset_flag,
+ "eval_iters": self.eval_iters,
+ "eval_interval": self.eval_interval,
+ }
+ if self.recompute_activations:
+ self.megatron_lm_default_args["recompute_granularity"] = "selective"
+ if self.tensorboard_dir is not None:
+ self.megatron_lm_default_args["tensorboard_dir"] = self.tensorboard_dir
+ if self.set_all_logging_options:
+ self.set_tensorboard_logging_options()
+ if self.other_megatron_args is not None:
+ self.megatron_lm_default_args.update(self.other_megatron_args)
+
+ def set_network_size_args(self, model, batch_data=None):
+ model_config_type = model.config.model_type.lower()
+ for model_type in MODEL_CONFIGS_TO_MEGATRON_PARSERS.keys():
+ if model_type in model_config_type:
+ MODEL_CONFIGS_TO_MEGATRON_PARSERS[model_type](self, model, batch_data)
+ return
+ raise ValueError(
+ f"Accelerate Megatron-LM integration not supports {model_config_type} model. "
+ "You can add your own model config parser."
+ )
+
+ def set_mixed_precision(self, mixed_precision):
+ if mixed_precision == "fp16":
+ self.megatron_lm_default_args["fp16"] = True
+ elif mixed_precision == "bf16":
+ self.megatron_lm_default_args["bf16"] = True
+ self.DDP_impl = "local"
+ self.megatron_lm_default_args["DDP_impl"] = self.DDP_impl
+
+ def set_training_args(self, micro_batch_size, dp_degree):
+ self.data_parallel_size = dp_degree
+ self.micro_batch_size = micro_batch_size
+ self.global_batch_size = dp_degree * micro_batch_size * self.num_micro_batches
+ self.megatron_lm_default_args["data_parallel_size"] = self.data_parallel_size
+ self.megatron_lm_default_args["micro_batch_size"] = self.micro_batch_size
+ self.megatron_lm_default_args["global_batch_size"] = self.global_batch_size
+
+ def set_optimizer_type(self, optimizer):
+ optimizer_name = optimizer.__class__.__name__.lower()
+ if "adam" in optimizer_name:
+ self.megatron_lm_default_args["optimizer"] = "adam"
+ self.megatron_lm_default_args["adam_beta1"] = optimizer.defaults["betas"][0]
+ self.megatron_lm_default_args["adam_beta2"] = optimizer.defaults["betas"][1]
+ self.megatron_lm_default_args["adam_eps"] = optimizer.defaults["eps"]
+ elif "sgd" in optimizer_name:
+ self.megatron_lm_default_args["optimizer"] = "sgd"
+ self.megatron_lm_default_args["sgd_momentum"] = optimizer.defaults["momentum"]
+ else:
+ raise ValueError(f"Optimizer {optimizer_name} is not supported by Megatron-LM")
+
+ self.megatron_lm_default_args["lr"] = optimizer.defaults["lr"]
+ self.megatron_lm_default_args["weight_decay"] = optimizer.defaults["weight_decay"]
+
+ def set_scheduler_args(self, scheduler):
+ if self.train_iters is None:
+ self.train_iters = scheduler.total_num_steps // self.megatron_lm_default_args["data_parallel_size"]
+ if self.train_samples is not None:
+ self.train_samples = None
+ warnings.warn(
+ "Ignoring `train_samples` as `train_iters` based on scheduler is being used for training."
+ )
+ if self.lr_warmup_iters is None:
+ self.lr_warmup_iters = scheduler.warmup_num_steps // self.megatron_lm_default_args["data_parallel_size"]
+ if self.lr_warmup_samples is not None:
+ warnings.warn(
+ "Ignoring `lr_warmup_samples` as `lr_warmup_iters` based on scheduler is being used for training."
+ )
+ self.lr_warmup_samples = 0
+
+ self.megatron_lm_default_args["train_iters"] = self.train_iters
+ self.megatron_lm_default_args["lr_warmup_iters"] = self.lr_warmup_iters
+ self.megatron_lm_default_args["train_samples"] = self.train_samples
+ self.megatron_lm_default_args["lr_warmup_samples"] = self.lr_warmup_samples
+ self.megatron_lm_default_args["lr_decay_iters"] = self.lr_decay_iters
+ self.megatron_lm_default_args["lr_decay_samples"] = self.lr_decay_samples
+ self.megatron_lm_default_args["lr_warmup_fraction"] = self.lr_warmup_fraction
+ self.megatron_lm_default_args["lr_decay_style"] = self.lr_decay_style
+ self.megatron_lm_default_args["weight_decay_incr_style"] = self.weight_decay_incr_style
+ self.megatron_lm_default_args["start_weight_decay"] = self.start_weight_decay
+ self.megatron_lm_default_args["end_weight_decay"] = self.end_weight_decay
+ self.megatron_lm_default_args["min_lr"] = self.min_lr
+
+ def set_tensorboard_logging_options(self):
+ from megatron.arguments import _add_logging_args
+
+ parser = argparse.ArgumentParser()
+ parser = _add_logging_args(parser)
+ logging_args = parser.parse_known_args()
+ self.dataset_args = vars(logging_args[0])
+ for key, value in self.dataset_args.items():
+ if key.startswith("log_"):
+ self.megatron_lm_default_args[key] = True
+ elif key.startswith("no_log_"):
+ self.megatron_lm_default_args[key.replace("no_", "")] = True
+
+
+MODEL_CONFIGS_TO_MEGATRON_PARSERS = {}
+
+
+def add_model_config_to_megatron_parser(model_type: str):
+ def add_model_config_parser_helper(func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ return func(*args, **kwargs)
+
+ MODEL_CONFIGS_TO_MEGATRON_PARSERS[model_type] = func
+ return wrapper
+
+ return add_model_config_parser_helper
+
+
+@add_model_config_to_megatron_parser("megatron-bert")
+def parse_bert_config(megatron_lm_plugin, model, batch_data):
+ model_type_name = "bert"
+ num_layers = model.config.num_hidden_layers
+ hidden_size = model.config.hidden_size
+ num_attention_heads = model.config.num_attention_heads
+ max_position_embeddings = model.config.max_position_embeddings
+ num_labels = model.config.num_labels
+ orig_vocab_size = model.config.vocab_size
+ pretraining_flag = False
+ if "maskedlm" in model.__class__.__name__.lower():
+ pretraining_flag = True
+ if megatron_lm_plugin.seq_length is not None:
+ if megatron_lm_plugin.encoder_seq_length is not None:
+ warnings.warn("Both `seq_length` and `encoder_seq_length` are set. Using `encoder_seq_length`.")
+ megatron_lm_plugin.seq_length = megatron_lm_plugin.encoder_seq_length
+ elif megatron_lm_plugin.encoder_seq_length is not None:
+ megatron_lm_plugin.seq_length = megatron_lm_plugin.encoder_seq_length
+ elif batch_data is not None:
+ megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1]
+ else:
+ megatron_lm_plugin.seq_length = max_position_embeddings
+ megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length
+ megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name
+ megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers
+ megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size
+ megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads
+ megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings
+ megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag
+ megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size
+ megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict
+ megatron_lm_plugin.megatron_lm_default_args["num_labels"] = num_labels
+
+
+@add_model_config_to_megatron_parser("gpt2")
+def parse_gpt2_config(megatron_lm_plugin, model, batch_data):
+ model_type_name = "gpt"
+ num_layers = model.config.n_layer
+ hidden_size = model.config.n_embd
+ num_attention_heads = model.config.n_head
+ max_position_embeddings = model.config.n_positions
+ orig_vocab_size = model.config.vocab_size
+ pretraining_flag = True
+ if megatron_lm_plugin.seq_length is not None:
+ if megatron_lm_plugin.decoder_seq_length is not None:
+ warnings.warn("Both `seq_length` and `decoder_seq_length` are set. Using `decoder_seq_length`.")
+ megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length
+ elif megatron_lm_plugin.decoder_seq_length is not None:
+ megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length
+ elif batch_data is not None:
+ megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1]
+ else:
+ megatron_lm_plugin.seq_length = max_position_embeddings
+ megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length
+ megatron_lm_plugin.megatron_lm_default_args["return_logits"] = megatron_lm_plugin.return_logits
+ megatron_lm_plugin.megatron_lm_default_args["tokenizer_type"] = "GPT2BPETokenizer"
+ megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name
+ megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers
+ megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size
+ megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads
+ megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings
+ megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag
+ megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size
+ megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict
+
+
+@add_model_config_to_megatron_parser("t5")
+def parse_t5_config(megatron_lm_plugin, model, batch_data):
+ model_type_name = "t5"
+ num_layers = model.config.num_layers
+ hidden_size = model.config.d_model
+ num_attention_heads = model.config.num_heads
+ max_position_embeddings = model.config.n_positions if hasattr(model.config, "n_positions") else 1024
+ orig_vocab_size = model.config.vocab_size
+ pretraining_flag = True
+ if megatron_lm_plugin.encoder_seq_length is None:
+ if batch_data is not None:
+ megatron_lm_plugin.encoder_seq_length = batch_data["input_ids"].shape[1]
+ else:
+ megatron_lm_plugin.encoder_seq_length = max_position_embeddings
+ if megatron_lm_plugin.decoder_seq_length is None:
+ if batch_data is not None:
+ megatron_lm_plugin.decoder_seq_length = batch_data["labels"].shape[1]
+ else:
+ megatron_lm_plugin.decoder_seq_length = max_position_embeddings
+ megatron_lm_plugin.megatron_lm_default_args["encoder_seq_length"] = megatron_lm_plugin.encoder_seq_length
+ megatron_lm_plugin.megatron_lm_default_args["decoder_seq_length"] = megatron_lm_plugin.decoder_seq_length
+ megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name
+ megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers
+ megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size
+ megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads
+ megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings
+ megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag
+ megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size
+ megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict
+
+
+@add_model_config_to_megatron_parser("llama")
+def parse_llama_config(megatron_lm_plugin, model, batch_data):
+ model_type_name = "gpt"
+ num_layers = model.config.num_hidden_layers
+ pretraining_flag = True
+ hidden_size = model.config.hidden_size
+ num_attention_heads = model.config.num_attention_heads
+ orig_vocab_size = model.config.vocab_size
+
+ max_position_embeddings = model.config.max_position_embeddings
+ seq_length = getattr(model.config, "max_sequence_length", None)
+ if megatron_lm_plugin.seq_length is None:
+ if seq_length is not None:
+ megatron_lm_plugin.seq_length = seq_length
+ elif megatron_lm_plugin.decoder_seq_length is not None:
+ megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length
+ elif batch_data is not None:
+ megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1]
+ else:
+ megatron_lm_plugin.seq_length = max_position_embeddings
+
+ megatron_lm_plugin.megatron_lm_default_args["return_logits"] = megatron_lm_plugin.return_logits
+ megatron_lm_plugin.megatron_lm_default_args["tokenizer_type"] = "Llama2Tokenizer"
+ megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name
+ megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers
+ megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag
+ megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size
+ megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads
+ megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size
+ megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings
+ megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length
+ megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict
+
+
+@dataclass
+class BnbQuantizationConfig:
+ """
+ A plugin to enable BitsAndBytes 4bit and 8bit quantization
+
+ Args:
+ load_in_8bit (`bool`, defaults to `False`):
+ Enable 8bit quantization.
+ llm_int8_threshold (`float`, defaults to `6.0`):
+ Value of the outliner threshold. Only relevant when `load_in_8bit=True`.
+ load_in_4_bit (`bool`, defaults to `False`):
+ Enable 4bit quantization.
+ bnb_4bit_quant_type (`str`, defaults to `fp4`):
+ Set the quantization data type in the `bnb.nn.Linear4Bit` layers. Options are {'fp4','np4'}.
+ bnb_4bit_use_double_quant (`bool`, defaults to `False`):
+ Enable nested quantization where the quantization constants from the first quantization are quantized
+ again.
+ bnb_4bit_compute_dtype (`bool`, defaults to `fp16`):
+ This sets the computational type which might be different than the input time. For example, inputs might be
+ fp32, but computation can be set to bf16 for speedups. Options are {'fp32','fp16','bf16'}.
+ torch_dtype (`torch.dtype`, defaults to `None`):
+ This sets the dtype of the remaining non quantized layers. `bitsandbytes` library suggests to set the value
+ to `torch.float16` for 8 bit model and use the same dtype as the compute dtype for 4 bit model.
+ skip_modules (`List[str]`, defaults to `None`):
+ An explicit list of the modules that we don't quantize. The dtype of these modules will be `torch_dtype`.
+ keep_in_fp32_modules (`List`, defaults to `None`):
+ An explicit list of the modules that we don't quantize. We keep them in `torch.float32`.
+ """
+
+ load_in_8bit: bool = field(default=False, metadata={"help": "enable 8bit quantization."})
+
+ llm_int8_threshold: float = field(
+ default=6.0, metadata={"help": "value of the outliner threshold. only relevant when load_in_8bit=True"}
+ )
+
+ load_in_4bit: bool = field(default=False, metadata={"help": "enable 4bit quantization."})
+
+ bnb_4bit_quant_type: str = field(
+ default="fp4",
+ metadata={
+ "help": "set the quantization data type in the `bnb.nn.Linear4Bit` layers. Options are {'fp4','np4'}."
+ },
+ )
+
+ bnb_4bit_use_double_quant: bool = field(
+ default=False,
+ metadata={
+ "help": "enable nested quantization where the quantization constants from the first quantization are quantized again."
+ },
+ )
+
+ bnb_4bit_compute_dtype: bool = field(
+ default="fp16",
+ metadata={
+ "help": "This sets the computational type which might be different than the input time. For example, inputs might be "
+ "fp32, but computation can be set to bf16 for speedups. Options are {'fp32','fp16','bf16'}."
+ },
+ )
+
+ torch_dtype: torch.dtype = field(
+ default=None,
+ metadata={
+ "help": "this sets the dtype of the remaining non quantized layers. `bitsandbytes` library suggests to set the value"
+ "to `torch.float16` for 8 bit model and use the same dtype as the compute dtype for 4 bit model "
+ },
+ )
+
+ skip_modules: List[str] = field(
+ default=None,
+ metadata={
+ "help": "an explicit list of the modules that we don't quantize. The dtype of these modules will be `torch_dtype`."
+ },
+ )
+
+ keep_in_fp32_modules: List[str] = field(
+ default=None,
+ metadata={"help": "an explicit list of the modules that we don't quantize. We keep them in `torch.float32`."},
+ )
+
+ def __post_init__(self):
+ """
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if not isinstance(self.load_in_8bit, bool):
+ raise ValueError("load_in_8bit must be a boolean")
+
+ if not isinstance(self.load_in_4bit, bool):
+ raise ValueError("load_in_4bit must be a boolean")
+
+ if self.load_in_4bit and self.load_in_8bit:
+ raise ValueError("load_in_4bit and load_in_8 can't be both True")
+
+ if not self.load_in_4bit and not self.load_in_8bit:
+ raise ValueError("load_in_4bit and load_in_8 can't be both False")
+
+ if not isinstance(self.llm_int8_threshold, (int, float)):
+ raise ValueError("llm_int8_threshold must be a float or an int")
+
+ if not isinstance(self.bnb_4bit_quant_type, str):
+ raise ValueError("bnb_4bit_quant_type must be a string")
+ elif self.bnb_4bit_quant_type not in ["fp4", "nf4"]:
+ raise ValueError(f"bnb_4bit_quant_type must be in ['fp4','nf4'] but found {self.bnb_4bit_quant_type}")
+
+ if not isinstance(self.bnb_4bit_use_double_quant, bool):
+ raise ValueError("bnb_4bit_use_double_quant must be a boolean")
+
+ if isinstance(self.bnb_4bit_compute_dtype, str):
+ if self.bnb_4bit_compute_dtype == "fp32":
+ self.bnb_4bit_compute_dtype = torch.float32
+ elif self.bnb_4bit_compute_dtype == "fp16":
+ self.bnb_4bit_compute_dtype = torch.float16
+ elif self.bnb_4bit_compute_dtype == "bf16":
+ self.bnb_4bit_compute_dtype = torch.bfloat16
+ else:
+ raise ValueError(
+ f"bnb_4bit_compute_dtype must be in ['fp32','fp16','bf16'] but found {self.bnb_4bit_compute_dtype}"
+ )
+ elif not isinstance(self.bnb_4bit_compute_dtype, torch.dtype):
+ raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype")
+
+ if self.skip_modules is not None and not isinstance(self.skip_modules, list):
+ raise ValueError("skip_modules must be a list of strings")
+
+ if self.keep_in_fp32_modules is not None and not isinstance(self.keep_in_fp32_modules, list):
+ raise ValueError("keep_in_fp_32_modules must be a list of strings")
+
+ if self.load_in_4bit:
+ self.target_dtype = CustomDtype.INT4
+
+ if self.load_in_8bit:
+ self.target_dtype = torch.int8
+
+ if self.load_in_4bit and self.llm_int8_threshold != 6.0:
+ warnings.warn("llm_int8_threshold can only be used for model loaded in 8bit")
+
+ if isinstance(self.torch_dtype, str):
+ if self.torch_dtype == "fp32":
+ self.torch_dtype = torch.float32
+ elif self.torch_dtype == "fp16":
+ self.torch_dtype = torch.float16
+ elif self.torch_dtype == "bf16":
+ self.torch_dtype = torch.bfloat16
+ else:
+ raise ValueError(f"torch_dtype must be in ['fp32','fp16','bf16'] but found {self.torch_dtype}")
+ if self.load_in_8bit and self.torch_dtype is None:
+ self.torch_dtype = torch.float16
+
+ if self.load_in_4bit and self.torch_dtype is None:
+ self.torch_dtype = self.bnb_4bit_compute_dtype
+
+ if not isinstance(self.torch_dtype, torch.dtype):
+ raise ValueError("torch_dtype must be a torch.dtype")
+
+
+def get_module_class_from_name(module, name):
+ """
+ Gets a class from a module by its name.
+
+ Args:
+ module (`torch.nn.Module`): The module to get the class from.
+ name (`str`): The name of the class.
+ """
+ modules_children = list(module.children())
+ if module.__class__.__name__ == name:
+ return module.__class__
+ elif len(modules_children) == 0:
+ return
+ else:
+ for child_module in modules_children:
+ module_class = get_module_class_from_name(child_module, name)
+ if module_class is not None:
+ return module_class
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/deepspeed.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/deepspeed.py
new file mode 100644
index 0000000000000000000000000000000000000000..4712daee30a106bdd20ec132189e36b4e35f37ad
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/deepspeed.py
@@ -0,0 +1,291 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import base64
+import json
+import os
+from copy import deepcopy
+
+from ..optimizer import AcceleratedOptimizer
+from ..scheduler import AcceleratedScheduler
+from .dataclasses import DistributedType
+
+
+def get_active_deepspeed_plugin(state):
+ """
+ Returns the currently active DeepSpeedPlugin.
+
+ Raises:
+ ValueError: If DeepSpeed was not enabled and this function is called.
+ """
+ if state.distributed_type != DistributedType.DEEPSPEED:
+ raise ValueError(
+ "Couldn't retrieve the active `DeepSpeedPlugin` as none were enabled. "
+ "Please make sure that either `Accelerator` is configured for `deepspeed` "
+ "or make sure that the desired `DeepSpeedPlugin` has been enabled (`AcceleratorState().select_deepspeed_plugin(name)`) "
+ "before calling this function."
+ )
+ if not isinstance(state.deepspeed_plugins, dict):
+ return state.deepspeed_plugins
+ return next(plugin for plugin in state.deepspeed_plugins.values() if plugin.selected)
+
+
+class HfDeepSpeedConfig:
+ """
+ This object contains a DeepSpeed configuration dictionary and can be quickly queried for things like zero stage.
+
+ A `weakref` of this object is stored in the module's globals to be able to access the config from areas where
+ things like the Trainer object is not available (e.g. `from_pretrained` and `_get_resized_embeddings`). Therefore
+ it's important that this object remains alive while the program is still running.
+
+ [`Trainer`] uses the `HfTrainerDeepSpeedConfig` subclass instead. That subclass has logic to sync the configuration
+ with values of [`TrainingArguments`] by replacing special placeholder values: `"auto"`. Without this special logic
+ the DeepSpeed configuration is not modified in any way.
+
+ Args:
+ config_file_or_dict (`Union[str, Dict]`): path to DeepSpeed config file or dict.
+
+ """
+
+ def __init__(self, config_file_or_dict):
+ if isinstance(config_file_or_dict, dict):
+ # Don't modify user's data should they want to reuse it (e.g. in tests), because once we
+ # modified it, it will not be accepted here again, since `auto` values would have been overridden
+ config = deepcopy(config_file_or_dict)
+ elif os.path.exists(config_file_or_dict):
+ with open(config_file_or_dict, encoding="utf-8") as f:
+ config = json.load(f)
+ else:
+ try:
+ config_decoded = base64.urlsafe_b64decode(config_file_or_dict).decode("utf-8")
+ config = json.loads(config_decoded)
+ except (UnicodeDecodeError, AttributeError, ValueError):
+ raise ValueError(
+ f"Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}"
+ )
+
+ self.config = config
+
+ self.set_stage_and_offload()
+
+ def set_stage_and_offload(self):
+ # zero stage - this is done as early as possible, before model is created, to allow
+ # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object
+ # during ``zero.Init()`` which needs to know the dtype, and some other hparams.
+ self._stage = self.get_value("zero_optimization.stage", -1)
+
+ # offload
+ self._offload = False
+ if self.is_zero2() or self.is_zero3():
+ offload_devices_valid = set(["cpu", "nvme"])
+ offload_devices = set(
+ [
+ self.get_value("zero_optimization.offload_optimizer.device"),
+ self.get_value("zero_optimization.offload_param.device"),
+ ]
+ )
+ if len(offload_devices & offload_devices_valid) > 0:
+ self._offload = True
+
+ def find_config_node(self, ds_key_long):
+ config = self.config
+
+ # find the config node of interest if it exists
+ nodes = ds_key_long.split(".")
+ ds_key = nodes.pop()
+ for node in nodes:
+ config = config.get(node)
+ if config is None:
+ return None, ds_key
+
+ return config, ds_key
+
+ def get_value(self, ds_key_long, default=None):
+ """
+ Returns the set value or `default` if no value is set
+ """
+ config, ds_key = self.find_config_node(ds_key_long)
+ if config is None:
+ return default
+ return config.get(ds_key, default)
+
+ def del_config_sub_tree(self, ds_key_long, must_exist=False):
+ """
+ Deletes a sub-section of the config file if it's found.
+
+ Unless `must_exist` is `True` the section doesn't have to exist.
+ """
+ config = self.config
+
+ # find the config node of interest if it exists
+ nodes = ds_key_long.split(".")
+ for node in nodes:
+ parent_config = config
+ config = config.get(node)
+ if config is None:
+ if must_exist:
+ raise ValueError(f"Can't find {ds_key_long} entry in the config: {self.config}")
+ else:
+ return
+
+ # if found remove it
+ if parent_config is not None:
+ parent_config.pop(node)
+
+ def is_true(self, ds_key_long):
+ """
+ Returns `True`/``False` only if the value is set, always `False` otherwise. So use this method to ask the very
+ specific question of whether the value is set to `True` (and it's not set to `False`` or isn't set).
+
+ """
+ value = self.get_value(ds_key_long)
+ return False if value is None else bool(value)
+
+ def is_false(self, ds_key_long):
+ """
+ Returns `True`/``False` only if the value is set, always `False` otherwise. So use this method to ask the very
+ specific question of whether the value is set to `False` (and it's not set to `True`` or isn't set).
+ """
+ value = self.get_value(ds_key_long)
+ return False if value is None else not bool(value)
+
+ def is_zero2(self):
+ return self._stage == 2
+
+ def is_zero3(self):
+ return self._stage == 3
+
+ def is_offload(self):
+ return self._offload
+
+
+class DeepSpeedEngineWrapper:
+ """
+ Internal wrapper for deepspeed.runtime.engine.DeepSpeedEngine. This is used to follow conventional training loop.
+
+ Args:
+ engine (deepspeed.runtime.engine.DeepSpeedEngine): deepspeed engine to wrap
+ """
+
+ def __init__(self, engine):
+ self.engine = engine
+
+ def backward(self, loss, **kwargs):
+ # runs backpropagation and handles mixed precision
+ self.engine.backward(loss, **kwargs)
+
+ # Deepspeed's `engine.step` performs the following operations:
+ # - gradient accumulation check
+ # - gradient clipping
+ # - optimizer step
+ # - zero grad
+ # - checking overflow
+ # - lr_scheduler step (only if engine.lr_scheduler is not None)
+ self.engine.step()
+ # and this plugin overrides the above calls with no-ops when Accelerate runs under
+ # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple
+ # training loop that works transparently under many training regimes.
+
+
+class DeepSpeedOptimizerWrapper(AcceleratedOptimizer):
+ """
+ Internal wrapper around a deepspeed optimizer.
+
+ Args:
+ optimizer (`torch.optim.optimizer.Optimizer`):
+ The optimizer to wrap.
+ """
+
+ def __init__(self, optimizer):
+ super().__init__(optimizer, device_placement=False, scaler=None)
+ self.__has_overflow__ = hasattr(self.optimizer, "overflow")
+
+ def zero_grad(self, set_to_none=None):
+ pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed
+
+ def step(self):
+ pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed
+
+ @property
+ def step_was_skipped(self):
+ """Whether or not the optimizer step was done, or skipped because of gradient overflow."""
+ if self.__has_overflow__:
+ return self.optimizer.overflow
+ return False
+
+
+class DeepSpeedSchedulerWrapper(AcceleratedScheduler):
+ """
+ Internal wrapper around a deepspeed scheduler.
+
+ Args:
+ scheduler (`torch.optim.lr_scheduler.LambdaLR`):
+ The scheduler to wrap.
+ optimizers (one or a list of `torch.optim.Optimizer`):
+ """
+
+ def __init__(self, scheduler, optimizers):
+ super().__init__(scheduler, optimizers)
+
+ def step(self):
+ pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed
+
+
+class DummyOptim:
+ """
+ Dummy optimizer presents model parameters or param groups, this is primarily used to follow conventional training
+ loop when optimizer config is specified in the deepspeed config file.
+
+ Args:
+ lr (float):
+ Learning rate.
+ params (iterable): iterable of parameters to optimize or dicts defining
+ parameter groups
+ weight_decay (float):
+ Weight decay.
+ **kwargs (additional keyword arguments, *optional*):
+ Other arguments.
+ """
+
+ def __init__(self, params, lr=0.001, weight_decay=0, **kwargs):
+ self.params = params
+ self.lr = lr
+ self.weight_decay = weight_decay
+ self.kwargs = kwargs
+
+
+class DummyScheduler:
+ """
+ Dummy scheduler presents model parameters or param groups, this is primarily used to follow conventional training
+ loop when scheduler config is specified in the deepspeed config file.
+
+ Args:
+ optimizer (`torch.optim.optimizer.Optimizer`):
+ The optimizer to wrap.
+ total_num_steps (int, *optional*):
+ Total number of steps.
+ warmup_num_steps (int, *optional*):
+ Number of steps for warmup.
+ lr_scheduler_callable (callable, *optional*):
+ A callable function that creates an LR Scheduler. It accepts only one argument `optimizer`.
+ **kwargs (additional keyword arguments, *optional*):
+ Other arguments.
+ """
+
+ def __init__(self, optimizer, total_num_steps=None, warmup_num_steps=0, lr_scheduler_callable=None, **kwargs):
+ self.optimizer = optimizer
+ self.total_num_steps = total_num_steps
+ self.warmup_num_steps = warmup_num_steps
+ self.lr_scheduler_callable = lr_scheduler_callable
+ self.kwargs = kwargs
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/environment.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/environment.py
new file mode 100644
index 0000000000000000000000000000000000000000..34fa7e2ae29a9ceb54bec4a1b6a1eda3b3b0d8d4
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/environment.py
@@ -0,0 +1,274 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import logging
+import math
+import os
+import platform
+import subprocess
+import sys
+from dataclasses import dataclass, field
+from functools import lru_cache
+from shutil import which
+from typing import List, Optional
+
+import torch
+from packaging.version import parse
+
+
+logger = logging.getLogger(__name__)
+
+
+def convert_dict_to_env_variables(current_env: dict):
+ """
+ Verifies that all keys and values in `current_env` do not contain illegal keys or values, and returns a list of
+ strings as the result.
+
+ Example:
+ ```python
+ >>> from accelerate.utils.environment import verify_env
+
+ >>> env = {"ACCELERATE_DEBUG_MODE": "1", "BAD_ENV_NAME": ">> valid_env_items = verify_env(env)
+ >>> print(valid_env_items)
+ ["ACCELERATE_DEBUG_MODE=1\n", "OTHER_ENV=2\n"]
+ ```
+ """
+ forbidden_chars = [";", "\n", "<", ">", " "]
+ valid_env_items = []
+ for key, value in current_env.items():
+ if all(char not in (key + value) for char in forbidden_chars) and len(key) >= 1 and len(value) >= 1:
+ valid_env_items.append(f"{key}={value}\n")
+ else:
+ logger.warning(f"WARNING: Skipping {key}={value} as it contains forbidden characters or missing values.")
+ return valid_env_items
+
+
+def str_to_bool(value) -> int:
+ """
+ Converts a string representation of truth to `True` (1) or `False` (0).
+
+ True values are `y`, `yes`, `t`, `true`, `on`, and `1`; False value are `n`, `no`, `f`, `false`, `off`, and `0`;
+ """
+ value = value.lower()
+ if value in ("y", "yes", "t", "true", "on", "1"):
+ return 1
+ elif value in ("n", "no", "f", "false", "off", "0"):
+ return 0
+ else:
+ raise ValueError(f"invalid truth value {value}")
+
+
+def get_int_from_env(env_keys, default):
+ """Returns the first positive env value found in the `env_keys` list or the default."""
+ for e in env_keys:
+ val = int(os.environ.get(e, -1))
+ if val >= 0:
+ return val
+ return default
+
+
+def parse_flag_from_env(key, default=False):
+ """Returns truthy value for `key` from the env if available else the default."""
+ value = os.environ.get(key, str(default))
+ return str_to_bool(value) == 1 # As its name indicates `str_to_bool` actually returns an int...
+
+
+def parse_choice_from_env(key, default="no"):
+ value = os.environ.get(key, str(default))
+ return value
+
+
+def are_libraries_initialized(*library_names: str) -> List[str]:
+ """
+ Checks if any of `library_names` are imported in the environment. Will return any names that are.
+ """
+ return [lib_name for lib_name in library_names if lib_name in sys.modules.keys()]
+
+
+def _nvidia_smi():
+ """
+ Returns the right nvidia-smi command based on the system.
+ """
+ if platform.system() == "Windows":
+ # If platform is Windows and nvidia-smi can't be found in path
+ # try from systemd drive with default installation path
+ command = which("nvidia-smi")
+ if command is None:
+ command = f"{os.environ['systemdrive']}\\Program Files\\NVIDIA Corporation\\NVSMI\\nvidia-smi.exe"
+ else:
+ command = "nvidia-smi"
+ return command
+
+
+def get_gpu_info():
+ """
+ Gets GPU count and names using `nvidia-smi` instead of torch to not initialize CUDA.
+
+ Largely based on the `gputil` library.
+ """
+ # Returns as list of `n` GPUs and their names
+ output = subprocess.check_output(
+ [_nvidia_smi(), "--query-gpu=count,name", "--format=csv,noheader"], universal_newlines=True
+ )
+ output = output.strip()
+ gpus = output.split(os.linesep)
+ # Get names from output
+ gpu_count = len(gpus)
+ gpu_names = [gpu.split(",")[1].strip() for gpu in gpus]
+ return gpu_names, gpu_count
+
+
+def get_driver_version():
+ """
+ Returns the driver version
+
+ In the case of multiple GPUs, will return the first.
+ """
+ output = subprocess.check_output(
+ [_nvidia_smi(), "--query-gpu=driver_version", "--format=csv,noheader"], universal_newlines=True
+ )
+ output = output.strip()
+ return output.split(os.linesep)[0]
+
+
+def check_cuda_p2p_ib_support():
+ """
+ Checks if the devices being used have issues with P2P and IB communications, namely any consumer GPU hardware after
+ the 3090.
+
+ Noteably uses `nvidia-smi` instead of torch to not initialize CUDA.
+ """
+ try:
+ device_names, device_count = get_gpu_info()
+ # As new consumer GPUs get released, add them to `unsupported_devices``
+ unsupported_devices = {"RTX 40"}
+ if device_count > 1:
+ if any(
+ unsupported_device in device_name
+ for device_name in device_names
+ for unsupported_device in unsupported_devices
+ ):
+ # Check if they have the right driver version
+ acceptable_driver_version = "550.40.07"
+ current_driver_version = get_driver_version()
+ if parse(current_driver_version) < parse(acceptable_driver_version):
+ return False
+ return True
+ except Exception:
+ pass
+ return True
+
+
+def check_fp8_capability():
+ """
+ Checks if all the current GPUs available support FP8.
+
+ Notably must initialize `torch.cuda` to check.
+ """
+ cuda_device_capacity = torch.cuda.get_device_capability()
+ return cuda_device_capacity >= (8, 9)
+
+
+@dataclass
+class CPUInformation:
+ """
+ Stores information about the CPU in a distributed environment. It contains the following attributes:
+ - rank: The rank of the current process.
+ - world_size: The total number of processes in the world.
+ - local_rank: The rank of the current process on the local node.
+ - local_world_size: The total number of processes on the local node.
+ """
+
+ rank: int = field(default=0, metadata={"help": "The rank of the current process."})
+ world_size: int = field(default=1, metadata={"help": "The total number of processes in the world."})
+ local_rank: int = field(default=0, metadata={"help": "The rank of the current process on the local node."})
+ local_world_size: int = field(default=1, metadata={"help": "The total number of processes on the local node."})
+
+
+def get_cpu_distributed_information() -> CPUInformation:
+ """
+ Returns various information about the environment in relation to CPU distributed training as a `CPUInformation`
+ dataclass.
+ """
+ information = {}
+ information["rank"] = get_int_from_env(["RANK", "PMI_RANK", "OMPI_COMM_WORLD_RANK", "MV2_COMM_WORLD_RANK"], 0)
+ information["world_size"] = get_int_from_env(
+ ["WORLD_SIZE", "PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "MV2_COMM_WORLD_SIZE"], 1
+ )
+ information["local_rank"] = get_int_from_env(
+ ["LOCAL_RANK", "MPI_LOCALRANKID", "OMPI_COMM_WORLD_LOCAL_RANK", "MV2_COMM_WORLD_LOCAL_RANK"], 0
+ )
+ information["local_world_size"] = get_int_from_env(
+ ["LOCAL_WORLD_SIZE", "MPI_LOCALNRANKS", "OMPI_COMM_WORLD_LOCAL_SIZE", "MV2_COMM_WORLD_LOCAL_SIZE"],
+ 1,
+ )
+ return CPUInformation(**information)
+
+
+def override_numa_affinity(local_process_index: int, verbose: Optional[bool] = None) -> None:
+ """
+ Overrides whatever NUMA affinity is set for the current process. This is very taxing and requires recalculating the
+ affinity to set, ideally you should use `utils.environment.set_numa_affinity` instead.
+
+ Args:
+ local_process_index (int):
+ The index of the current process on the current server.
+ verbose (bool, *optional*):
+ Whether to log out the assignment of each CPU. If `ACCELERATE_DEBUG_MODE` is enabled, will default to True.
+ """
+ if verbose is None:
+ verbose = parse_flag_from_env("ACCELERATE_DEBUG_MODE", False)
+ if torch.cuda.is_available():
+ from accelerate.utils import is_pynvml_available
+
+ if not is_pynvml_available():
+ raise ImportError(
+ "To set CPU affinity on CUDA GPUs the `pynvml` package must be available. (`pip install pynvml`)"
+ )
+ import pynvml as nvml
+
+ # The below code is based on https://github.com/NVIDIA/DeepLearningExamples/blob/master/TensorFlow2/LanguageModeling/BERT/gpu_affinity.py
+ nvml.nvmlInit()
+ num_elements = math.ceil(os.cpu_count() / 64)
+ handle = nvml.nvmlDeviceGetHandleByIndex(local_process_index)
+ affinity_string = ""
+ for j in nvml.nvmlDeviceGetCpuAffinity(handle, num_elements):
+ # assume nvml returns list of 64 bit ints
+ affinity_string = f"{j:064b}{affinity_string}"
+ affinity_list = [int(x) for x in affinity_string]
+ affinity_list.reverse() # so core 0 is the 0th element
+ affinity_to_set = [i for i, e in enumerate(affinity_list) if e != 0]
+ os.sched_setaffinity(0, affinity_to_set)
+ if verbose:
+ cpu_cores = os.sched_getaffinity(0)
+ logger.info(f"Assigning {len(cpu_cores)} cpu cores to process {local_process_index}: {cpu_cores}")
+
+
+@lru_cache
+def set_numa_affinity(local_process_index: int, verbose: Optional[bool] = None) -> None:
+ """
+ Assigns the current process to a specific NUMA node. Ideally most efficient when having at least 2 cpus per node.
+
+ This result is cached between calls. If you want to override it, please use
+ `accelerate.utils.environment.override_numa_afifnity`.
+
+ Args:
+ local_process_index (int):
+ The index of the current process on the current server.
+ verbose (bool, *optional*):
+ Whether to print the new cpu cores assignment for each process. If `ACCELERATE_DEBUG_MODE` is enabled, will
+ default to True.
+ """
+ override_numa_affinity(local_process_index=local_process_index, verbose=verbose)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/fsdp_utils.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/fsdp_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..89e1fa4806499f048b977c8321ddaef7211d26b0
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/fsdp_utils.py
@@ -0,0 +1,326 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import os
+import shutil
+from pathlib import Path
+
+import torch
+
+from ..logging import get_logger
+from .constants import FSDP_MODEL_NAME, OPTIMIZER_NAME, SAFE_WEIGHTS_NAME, WEIGHTS_NAME
+from .modeling import is_peft_model
+from .other import save
+from .versions import is_torch_version
+
+
+logger = get_logger(__name__)
+
+
+def enable_fsdp_ram_efficient_loading():
+ """
+ Enables RAM efficient loading of Hugging Face models for FSDP in the environment.
+ """
+ # Sets values for `transformers.modeling_utils.is_fsdp_enabled`
+ if "ACCELERATE_USE_FSDP" not in os.environ:
+ os.environ["ACCELERATE_USE_FSDP"] = "True"
+ os.environ["FSDP_CPU_RAM_EFFICIENT_LOADING"] = "True"
+
+
+def disable_fsdp_ram_efficient_loading():
+ """
+ Disables RAM efficient loading of Hugging Face models for FSDP in the environment.
+ """
+ os.environ["FSDP_CPU_RAM_EFFICIENT_LOADING"] = "False"
+
+
+def _get_model_state_dict(model, adapter_only=False):
+ if adapter_only and is_peft_model(model):
+ from peft import get_peft_model_state_dict
+
+ return get_peft_model_state_dict(model, adapter_name=model.active_adapter)
+ else:
+ return model.state_dict()
+
+
+def _set_model_state_dict(model, state_dict, adapter_only=False):
+ if adapter_only and is_peft_model(model):
+ from peft import set_peft_model_state_dict
+
+ return set_peft_model_state_dict(model, state_dict, adapter_name=model.active_adapter)
+ else:
+ return model.load_state_dict(state_dict)
+
+
+def save_fsdp_model(fsdp_plugin, accelerator, model, output_dir, model_index=0, adapter_only=False):
+ # Note: We import here to reduce import time from general modules, and isolate outside dependencies
+ import torch.distributed.checkpoint as dist_cp
+ from torch.distributed.checkpoint.default_planner import DefaultSavePlanner
+ from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
+ from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType
+
+ os.makedirs(output_dir, exist_ok=True)
+ if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
+ # FSDP raises error when single GPU is used with `offload_to_cpu=True` for FULL_STATE_DICT
+ # so, only enable it when num_processes>1
+ is_multi_process = accelerator.num_processes > 1
+ fsdp_plugin.state_dict_config.offload_to_cpu = is_multi_process
+ fsdp_plugin.state_dict_config.rank0_only = is_multi_process
+
+ with FSDP.state_dict_type(
+ model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config
+ ):
+ state_dict = _get_model_state_dict(model, adapter_only=adapter_only)
+ if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
+ weights_name = f"{FSDP_MODEL_NAME}.bin" if model_index == 0 else f"{FSDP_MODEL_NAME}_{model_index}.bin"
+ output_model_file = os.path.join(output_dir, weights_name)
+ if accelerator.process_index == 0:
+ logger.info(f"Saving model to {output_model_file}")
+ torch.save(state_dict, output_model_file)
+ logger.info(f"Model saved to {output_model_file}")
+ elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
+ weights_name = (
+ f"{FSDP_MODEL_NAME}_rank{accelerator.process_index}.bin"
+ if model_index == 0
+ else f"{FSDP_MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"
+ )
+ output_model_file = os.path.join(output_dir, weights_name)
+ logger.info(f"Saving model to {output_model_file}")
+ torch.save(state_dict, output_model_file)
+ logger.info(f"Model saved to {output_model_file}")
+ elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
+ ckpt_dir = os.path.join(output_dir, f"{FSDP_MODEL_NAME}_{model_index}")
+ os.makedirs(ckpt_dir, exist_ok=True)
+ logger.info(f"Saving model to {ckpt_dir}")
+ state_dict = {"model": state_dict}
+
+ dist_cp.save_state_dict(
+ state_dict=state_dict,
+ storage_writer=dist_cp.FileSystemWriter(ckpt_dir),
+ planner=DefaultSavePlanner(),
+ )
+ logger.info(f"Model saved to {ckpt_dir}")
+
+
+def load_fsdp_model(fsdp_plugin, accelerator, model, input_dir, model_index=0, adapter_only=False):
+ # Note: We import here to reduce import time from general modules, and isolate outside dependencies
+ import torch.distributed.checkpoint as dist_cp
+ from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner
+ from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
+ from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType
+
+ accelerator.wait_for_everyone()
+ if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
+ # FSDP raises error when single GPU is used with `offload_to_cpu=True` for FULL_STATE_DICT
+ # so, only enable it when num_processes>1
+ is_multi_process = accelerator.num_processes > 1
+ fsdp_plugin.state_dict_config.offload_to_cpu = is_multi_process
+ fsdp_plugin.state_dict_config.rank0_only = is_multi_process
+ with FSDP.state_dict_type(
+ model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config
+ ):
+ if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
+ if type(model) is not FSDP and accelerator.process_index != 0:
+ if not fsdp_plugin.sync_module_states:
+ raise ValueError(
+ "Set the `sync_module_states` flag to `True` so that model states are synced across processes when "
+ "initializing FSDP object"
+ )
+ return
+ weights_name = f"{FSDP_MODEL_NAME}.bin" if model_index == 0 else f"{FSDP_MODEL_NAME}_{model_index}.bin"
+ input_model_file = os.path.join(input_dir, weights_name)
+ logger.info(f"Loading model from {input_model_file}")
+ state_dict = torch.load(input_model_file)
+ logger.info(f"Model loaded from {input_model_file}")
+ elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
+ weights_name = (
+ f"{FSDP_MODEL_NAME}_rank{accelerator.process_index}.bin"
+ if model_index == 0
+ else f"{FSDP_MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"
+ )
+ input_model_file = os.path.join(input_dir, weights_name)
+ logger.info(f"Loading model from {input_model_file}")
+ state_dict = torch.load(input_model_file)
+ logger.info(f"Model loaded from {input_model_file}")
+ elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
+ ckpt_dir = (
+ os.path.join(input_dir, f"{FSDP_MODEL_NAME}_{model_index}")
+ if f"{FSDP_MODEL_NAME}" not in input_dir
+ else input_dir
+ )
+ logger.info(f"Loading model from {ckpt_dir}")
+ state_dict = {"model": _get_model_state_dict(model, adapter_only=adapter_only)}
+ dist_cp.load_state_dict(
+ state_dict=state_dict,
+ storage_reader=dist_cp.FileSystemReader(ckpt_dir),
+ planner=DefaultLoadPlanner(),
+ )
+ state_dict = state_dict["model"]
+ logger.info(f"Model loaded from {ckpt_dir}")
+ load_result = _set_model_state_dict(model, state_dict, adapter_only=adapter_only)
+ return load_result
+
+
+def save_fsdp_optimizer(fsdp_plugin, accelerator, optimizer, model, output_dir, optimizer_index=0):
+ # Note: We import here to reduce import time from general modules, and isolate outside dependencies
+ import torch.distributed.checkpoint as dist_cp
+ from torch.distributed.checkpoint.default_planner import DefaultSavePlanner
+ from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
+ from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType
+
+ os.makedirs(output_dir, exist_ok=True)
+ with FSDP.state_dict_type(
+ model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config
+ ):
+ optim_state = FSDP.optim_state_dict(model, optimizer)
+ if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
+ if accelerator.process_index == 0:
+ optim_state_name = (
+ f"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else f"{OPTIMIZER_NAME}_{optimizer_index}.bin"
+ )
+ output_optimizer_file = os.path.join(output_dir, optim_state_name)
+ logger.info(f"Saving Optimizer state to {output_optimizer_file}")
+ torch.save(optim_state, output_optimizer_file)
+ logger.info(f"Optimizer state saved in {output_optimizer_file}")
+ else:
+ ckpt_dir = os.path.join(output_dir, f"{OPTIMIZER_NAME}_{optimizer_index}")
+ os.makedirs(ckpt_dir, exist_ok=True)
+ logger.info(f"Saving Optimizer state to {ckpt_dir}")
+ dist_cp.save_state_dict(
+ state_dict={"optimizer": optim_state},
+ storage_writer=dist_cp.FileSystemWriter(ckpt_dir),
+ planner=DefaultSavePlanner(),
+ )
+ logger.info(f"Optimizer state saved in {ckpt_dir}")
+
+
+def load_fsdp_optimizer(fsdp_plugin, accelerator, optimizer, model, input_dir, optimizer_index=0, adapter_only=False):
+ # Note: We import here to reduce import time from general modules, and isolate outside dependencies
+ import torch.distributed.checkpoint as dist_cp
+ from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict
+ from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
+ from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType
+
+ accelerator.wait_for_everyone()
+ with FSDP.state_dict_type(
+ model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config
+ ):
+ if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
+ optim_state = None
+ if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only:
+ optimizer_name = (
+ f"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else f"{OPTIMIZER_NAME}_{optimizer_index}.bin"
+ )
+ input_optimizer_file = os.path.join(input_dir, optimizer_name)
+ logger.info(f"Loading Optimizer state from {input_optimizer_file}")
+ optim_state = torch.load(input_optimizer_file)
+ logger.info(f"Optimizer state loaded from {input_optimizer_file}")
+ else:
+ ckpt_dir = (
+ os.path.join(input_dir, f"{OPTIMIZER_NAME}_{optimizer_index}")
+ if f"{OPTIMIZER_NAME}" not in input_dir
+ else input_dir
+ )
+ logger.info(f"Loading Optimizer from {ckpt_dir}")
+ optim_state = load_sharded_optimizer_state_dict(
+ model_state_dict=_get_model_state_dict(model, adapter_only=adapter_only),
+ optimizer_key="optimizer",
+ storage_reader=dist_cp.FileSystemReader(ckpt_dir),
+ )
+ optim_state = optim_state["optimizer"]
+ logger.info(f"Optimizer loaded from {ckpt_dir}")
+ flattened_osd = FSDP.optim_state_dict_to_load(model=model, optim=optimizer, optim_state_dict=optim_state)
+ optimizer.load_state_dict(flattened_osd)
+
+
+def _distributed_checkpoint_to_merged_weights(checkpoint_dir: str, save_path: str, safe_serialization: bool = True):
+ """
+ Passthrough to `torch.distributed.checkpoint.format_utils.dcp_to_torch_save`
+
+ Will save under `save_path` as either `model.safetensors` or `pytorch_model.bin`.
+ """
+ # Note: We import here to reduce import time from general modules, and isolate outside dependencies
+ import torch.distributed.checkpoint as dist_cp
+ import torch.distributed.checkpoint.format_utils as dist_cp_format_utils
+
+ state_dict = {}
+ save_path = Path(save_path)
+ save_path.mkdir(exist_ok=True)
+ dist_cp_format_utils._load_state_dict(
+ state_dict,
+ storage_reader=dist_cp.FileSystemReader(checkpoint_dir),
+ planner=dist_cp_format_utils._EmptyStateDictLoadPlanner(),
+ no_dist=True,
+ )
+ save_path = save_path / SAFE_WEIGHTS_NAME if safe_serialization else save_path / WEIGHTS_NAME
+
+ # To handle if state is a dict like {model: {...}}
+ if len(state_dict.keys()) == 1:
+ state_dict = state_dict[list(state_dict)[0]]
+ save(state_dict, save_path, safe_serialization=safe_serialization)
+ return save_path
+
+
+def merge_fsdp_weights(
+ checkpoint_dir: str, output_path: str, safe_serialization: bool = True, remove_checkpoint_dir: bool = False
+):
+ """
+ Merge the weights from sharded FSDP model checkpoints into a single combined checkpoint. Should be used if
+ `SHARDED_STATE_DICT` was used for the model. Weights will be saved to `{output_path}/model.safetensors` if
+ `safe_serialization` else `pytorch_model.bin`.
+
+ Note: this is a CPU-bound process.
+
+ Args:
+ checkpoint_dir (`str`):
+ The directory containing the FSDP checkpoints (can be either the model or optimizer).
+ output_path (`str`):
+ The path to save the merged checkpoint.
+ safe_serialization (`bool`, *optional*, defaults to `True`):
+ Whether to save the merged weights with safetensors (recommended).
+ remove_checkpoint_dir (`bool`, *optional*, defaults to `False`):
+ Whether to remove the checkpoint directory after merging.
+ """
+ checkpoint_dir = Path(checkpoint_dir)
+ from accelerate.state import PartialState
+
+ if not is_torch_version(">=", "2.3.0"):
+ raise ValueError("`merge_fsdp_weights` requires PyTorch >= 2.3.0`")
+
+ # Verify that the checkpoint directory exists
+ if not checkpoint_dir.exists():
+ model_path_exists = (checkpoint_dir / "pytorch_model_fsdp_0").exists()
+ optimizer_path_exists = (checkpoint_dir / "optimizer_0").exists()
+ err = f"Tried to load from {checkpoint_dir} but couldn't find a valid metadata file."
+ if model_path_exists and optimizer_path_exists:
+ err += " However, potential model and optimizer checkpoint directories exist."
+ err += f"Please pass in either {checkpoint_dir}/pytorch_model_fsdp_0 or {checkpoint_dir}/optimizer_0"
+ err += "instead."
+ elif model_path_exists:
+ err += " However, a potential model checkpoint directory exists."
+ err += f"Please try passing in {checkpoint_dir}/pytorch_model_fsdp_0 instead."
+ elif optimizer_path_exists:
+ err += " However, a potential optimizer checkpoint directory exists."
+ err += f"Please try passing in {checkpoint_dir}/optimizer_0 instead."
+ raise ValueError(err)
+
+ # To setup `save` to work
+ state = PartialState()
+ if state.is_main_process:
+ logger.info(f"Merging FSDP weights from {checkpoint_dir}")
+ save_path = _distributed_checkpoint_to_merged_weights(checkpoint_dir, output_path, safe_serialization)
+ logger.info(f"Successfully merged FSDP weights and saved to {save_path}")
+ if remove_checkpoint_dir:
+ logger.info(f"Removing old checkpoint directory {checkpoint_dir}")
+ shutil.rmtree(checkpoint_dir)
+ state.wait_for_everyone()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/imports.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/imports.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b86f96c67e93ac5a97cab11ea5434c01480556c
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/imports.py
@@ -0,0 +1,447 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import importlib
+import importlib.metadata
+import os
+import warnings
+from functools import lru_cache, wraps
+
+import torch
+from packaging import version
+from packaging.version import parse
+
+from .environment import parse_flag_from_env, str_to_bool
+from .versions import compare_versions, is_torch_version
+
+
+# Try to run Torch native job in an environment with TorchXLA installed by setting this value to 0.
+USE_TORCH_XLA = parse_flag_from_env("USE_TORCH_XLA", default=True)
+
+_torch_xla_available = False
+if USE_TORCH_XLA:
+ try:
+ import torch_xla.core.xla_model as xm # noqa: F401
+ import torch_xla.runtime
+
+ _torch_xla_available = True
+ except ImportError:
+ pass
+
+# Keep it for is_tpu_available. It will be removed along with is_tpu_available.
+_tpu_available = _torch_xla_available
+
+# Cache this result has it's a C FFI call which can be pretty time-consuming
+_torch_distributed_available = torch.distributed.is_available()
+
+
+def _is_package_available(pkg_name, metadata_name=None):
+ # Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version
+ package_exists = importlib.util.find_spec(pkg_name) is not None
+ if package_exists:
+ try:
+ # Some libraries have different names in the metadata
+ _ = importlib.metadata.metadata(pkg_name if metadata_name is None else metadata_name)
+ return True
+ except importlib.metadata.PackageNotFoundError:
+ return False
+
+
+def is_torch_distributed_available() -> bool:
+ return _torch_distributed_available
+
+
+def is_ccl_available():
+ try:
+ pass
+ except ImportError:
+ print(
+ "Intel(R) oneCCL Bindings for PyTorch* is required to run DDP on Intel(R) GPUs, but it is not"
+ " detected. If you see \"ValueError: Invalid backend: 'ccl'\" error, please install Intel(R) oneCCL"
+ " Bindings for PyTorch*."
+ )
+ return (
+ importlib.util.find_spec("torch_ccl") is not None
+ or importlib.util.find_spec("oneccl_bindings_for_pytorch") is not None
+ )
+
+
+def get_ccl_version():
+ return importlib.metadata.version("oneccl_bind_pt")
+
+
+def is_import_timer_available():
+ return _is_package_available("import_timer")
+
+
+def is_pynvml_available():
+ return _is_package_available("pynvml") or _is_package_available("pynvml", "nvidia-ml-py")
+
+
+def is_pytest_available():
+ return _is_package_available("pytest")
+
+
+def is_msamp_available():
+ return _is_package_available("msamp", "ms-amp")
+
+
+def is_schedulefree_available():
+ return _is_package_available("schedulefree")
+
+
+def is_transformer_engine_available():
+ return _is_package_available("transformer_engine", "transformer-engine")
+
+
+def is_lomo_available():
+ return _is_package_available("lomo_optim")
+
+
+def is_fp8_available():
+ return is_msamp_available() or is_transformer_engine_available()
+
+
+def is_cuda_available():
+ """
+ Checks if `cuda` is available via an `nvml-based` check which won't trigger the drivers and leave cuda
+ uninitialized.
+ """
+ pytorch_nvml_based_cuda_check_previous_value = os.environ.get("PYTORCH_NVML_BASED_CUDA_CHECK")
+ try:
+ os.environ["PYTORCH_NVML_BASED_CUDA_CHECK"] = str(1)
+ available = torch.cuda.is_available()
+ finally:
+ if pytorch_nvml_based_cuda_check_previous_value:
+ os.environ["PYTORCH_NVML_BASED_CUDA_CHECK"] = pytorch_nvml_based_cuda_check_previous_value
+ else:
+ os.environ.pop("PYTORCH_NVML_BASED_CUDA_CHECK", None)
+
+ return available
+
+
+@lru_cache
+def is_torch_xla_available(check_is_tpu=False, check_is_gpu=False):
+ """
+ Check if `torch_xla` is available. To train a native pytorch job in an environment with torch xla installed, set
+ the USE_TORCH_XLA to false.
+ """
+ assert not (check_is_tpu and check_is_gpu), "The check_is_tpu and check_is_gpu cannot both be true."
+
+ if not _torch_xla_available:
+ return False
+ elif check_is_gpu:
+ return torch_xla.runtime.device_type() in ["GPU", "CUDA"]
+ elif check_is_tpu:
+ return torch_xla.runtime.device_type() == "TPU"
+
+ return True
+
+
+def is_deepspeed_available():
+ if is_mlu_available():
+ return _is_package_available("deepspeed", metadata_name="deepspeed-mlu")
+ return _is_package_available("deepspeed")
+
+
+def is_pippy_available():
+ return is_torch_version(">=", "2.4.0")
+
+
+def is_bf16_available(ignore_tpu=False):
+ "Checks if bf16 is supported, optionally ignoring the TPU"
+ if is_torch_xla_available(check_is_tpu=True):
+ return not ignore_tpu
+ if is_cuda_available():
+ return torch.cuda.is_bf16_supported()
+ if is_mps_available():
+ return False
+ return True
+
+
+def is_4bit_bnb_available():
+ package_exists = _is_package_available("bitsandbytes")
+ if package_exists:
+ bnb_version = version.parse(importlib.metadata.version("bitsandbytes"))
+ return compare_versions(bnb_version, ">=", "0.39.0")
+ return False
+
+
+def is_8bit_bnb_available():
+ package_exists = _is_package_available("bitsandbytes")
+ if package_exists:
+ bnb_version = version.parse(importlib.metadata.version("bitsandbytes"))
+ return compare_versions(bnb_version, ">=", "0.37.2")
+ return False
+
+
+def is_bnb_available():
+ return _is_package_available("bitsandbytes")
+
+
+def is_bitsandbytes_multi_backend_available():
+ if not is_bnb_available():
+ return False
+ import bitsandbytes as bnb
+
+ return "multi_backend" in getattr(bnb, "features", set())
+
+
+def is_torchvision_available():
+ return _is_package_available("torchvision")
+
+
+def is_megatron_lm_available():
+ if str_to_bool(os.environ.get("ACCELERATE_USE_MEGATRON_LM", "False")) == 1:
+ if importlib.util.find_spec("megatron") is not None:
+ try:
+ megatron_version = parse(importlib.metadata.version("megatron-core"))
+ if compare_versions(megatron_version, "==", "0.5.0"):
+ return importlib.util.find_spec(".data", "megatron")
+ except Exception as e:
+ warnings.warn(f"Parse Megatron version failed. Exception:{e}")
+ return False
+
+
+def is_transformers_available():
+ return _is_package_available("transformers")
+
+
+def is_datasets_available():
+ return _is_package_available("datasets")
+
+
+def is_peft_available():
+ return _is_package_available("peft")
+
+
+def is_timm_available():
+ return _is_package_available("timm")
+
+
+def is_triton_available():
+ return _is_package_available("triton")
+
+
+def is_aim_available():
+ package_exists = _is_package_available("aim")
+ if package_exists:
+ aim_version = version.parse(importlib.metadata.version("aim"))
+ return compare_versions(aim_version, "<", "4.0.0")
+ return False
+
+
+def is_tensorboard_available():
+ return _is_package_available("tensorboard") or _is_package_available("tensorboardX")
+
+
+def is_wandb_available():
+ return _is_package_available("wandb")
+
+
+def is_comet_ml_available():
+ return _is_package_available("comet_ml")
+
+
+def is_boto3_available():
+ return _is_package_available("boto3")
+
+
+def is_rich_available():
+ if _is_package_available("rich"):
+ return parse_flag_from_env("ACCELERATE_ENABLE_RICH", False)
+ return False
+
+
+def is_sagemaker_available():
+ return _is_package_available("sagemaker")
+
+
+def is_tqdm_available():
+ return _is_package_available("tqdm")
+
+
+def is_clearml_available():
+ return _is_package_available("clearml")
+
+
+def is_pandas_available():
+ return _is_package_available("pandas")
+
+
+def is_mlflow_available():
+ if _is_package_available("mlflow"):
+ return True
+
+ if importlib.util.find_spec("mlflow") is not None:
+ try:
+ _ = importlib.metadata.metadata("mlflow-skinny")
+ return True
+ except importlib.metadata.PackageNotFoundError:
+ return False
+ return False
+
+
+def is_mps_available(min_version="1.12"):
+ "Checks if MPS device is available. The minimum version required is 1.12."
+ # With torch 1.12, you can use torch.backends.mps
+ # With torch 2.0.0, you can use torch.mps
+ return is_torch_version(">=", min_version) and torch.backends.mps.is_available() and torch.backends.mps.is_built()
+
+
+def is_ipex_available():
+ "Checks if ipex is installed."
+
+ def get_major_and_minor_from_version(full_version):
+ return str(version.parse(full_version).major) + "." + str(version.parse(full_version).minor)
+
+ _torch_version = importlib.metadata.version("torch")
+ if importlib.util.find_spec("intel_extension_for_pytorch") is None:
+ return False
+ _ipex_version = "N/A"
+ try:
+ _ipex_version = importlib.metadata.version("intel_extension_for_pytorch")
+ except importlib.metadata.PackageNotFoundError:
+ return False
+ torch_major_and_minor = get_major_and_minor_from_version(_torch_version)
+ ipex_major_and_minor = get_major_and_minor_from_version(_ipex_version)
+ if torch_major_and_minor != ipex_major_and_minor:
+ warnings.warn(
+ f"Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,"
+ f" but PyTorch {_torch_version} is found. Please switch to the matching version and run again."
+ )
+ return False
+ return True
+
+
+@lru_cache
+def is_mlu_available(check_device=False):
+ "Checks if `torch_mlu` is installed and potentially if a MLU is in the environment"
+ if importlib.util.find_spec("torch_mlu") is None:
+ return False
+
+ import torch_mlu # noqa: F401
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no MLU is found
+ _ = torch.mlu.device_count()
+ return torch.mlu.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "mlu") and torch.mlu.is_available()
+
+
+@lru_cache
+def is_musa_available(check_device=False):
+ "Checks if `torch_musa` is installed and potentially if a MUSA is in the environment"
+ if importlib.util.find_spec("torch_musa") is None:
+ return False
+
+ import torch_musa # noqa: F401
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no MUSA is found
+ _ = torch.musa.device_count()
+ return torch.musa.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "musa") and torch.musa.is_available()
+
+
+@lru_cache
+def is_npu_available(check_device=False):
+ "Checks if `torch_npu` is installed and potentially if a NPU is in the environment"
+ if importlib.util.find_spec("torch_npu") is None:
+ return False
+
+ import torch_npu # noqa: F401
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no NPU is found
+ _ = torch.npu.device_count()
+ return torch.npu.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "npu") and torch.npu.is_available()
+
+
+@lru_cache
+def is_xpu_available(check_device=False):
+ """
+ Checks if XPU acceleration is available either via `intel_extension_for_pytorch` or via stock PyTorch (>=2.4) and
+ potentially if a XPU is in the environment
+ """
+
+ "check if user disables it explicitly"
+ if not parse_flag_from_env("ACCELERATE_USE_XPU", default=True):
+ return False
+
+ if is_ipex_available():
+ if is_torch_version("<=", "1.12"):
+ return False
+
+ import intel_extension_for_pytorch # noqa: F401
+ else:
+ if is_torch_version("<=", "2.3"):
+ return False
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no XPU is found
+ _ = torch.xpu.device_count()
+ return torch.xpu.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "xpu") and torch.xpu.is_available()
+
+
+def is_dvclive_available():
+ return _is_package_available("dvclive")
+
+
+def is_torchdata_available():
+ return _is_package_available("torchdata")
+
+
+# TODO: Remove this function once stateful_dataloader is a stable feature in torchdata.
+def is_torchdata_stateful_dataloader_available():
+ package_exists = _is_package_available("torchdata")
+ if package_exists:
+ torchdata_version = version.parse(importlib.metadata.version("torchdata"))
+ return compare_versions(torchdata_version, ">=", "0.8.0")
+ return False
+
+
+# TODO: Rework this into `utils.deepspeed` and migrate the "core" chunks into `accelerate.deepspeed`
+def deepspeed_required(func):
+ """
+ A decorator that ensures the decorated function is only called when deepspeed is enabled.
+ """
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from accelerate.state import AcceleratorState
+ from accelerate.utils.dataclasses import DistributedType
+
+ if AcceleratorState._shared_state != {} and AcceleratorState().distributed_type != DistributedType.DEEPSPEED:
+ raise ValueError(
+ "DeepSpeed is not enabled, please make sure that an `Accelerator` is configured for `deepspeed` "
+ "before calling this function."
+ )
+ return func(*args, **kwargs)
+
+ return wrapper
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/launch.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/launch.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6f3d60031dfc04e2586224beb59b07f030acaed
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/launch.py
@@ -0,0 +1,674 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+import os
+import subprocess
+import sys
+from ast import literal_eval
+from shutil import which
+from typing import Any, Dict, List, Tuple
+
+import torch
+
+from ..commands.config.config_args import SageMakerConfig
+from ..utils import (
+ DynamoBackend,
+ PrecisionType,
+ is_fp8_available,
+ is_ipex_available,
+ is_mlu_available,
+ is_musa_available,
+ is_npu_available,
+ is_torch_xla_available,
+ is_xpu_available,
+)
+from ..utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS
+from ..utils.other import is_port_in_use, merge_dicts
+from .dataclasses import DistributedType, SageMakerDistributedType
+
+
+def _filter_args(args, parser, default_args=[]):
+ """
+ Filters out all `accelerate` specific args
+ """
+ new_args, _ = parser.parse_known_args(default_args)
+ for key, value in vars(args).items():
+ if key in vars(new_args).keys():
+ setattr(new_args, key, value)
+ return new_args
+
+
+def _get_mpirun_args():
+ """
+ Determines the executable and argument names for mpirun, based on the type of install. The supported MPI programs
+ are: OpenMPI, Intel MPI, or MVAPICH.
+
+ Returns: Program name and arg names for hostfile, num processes, and processes per node
+ """
+ # Find the MPI program name
+ mpi_apps = [x for x in ["mpirun", "mpiexec"] if which(x)]
+
+ if len(mpi_apps) == 0:
+ raise OSError("mpirun or mpiexec were not found. Ensure that Intel MPI, Open MPI, or MVAPICH are installed.")
+
+ # Call the app with the --version flag to determine which MPI app is installed
+ mpi_app = mpi_apps[0]
+ mpirun_version = subprocess.check_output([mpi_app, "--version"])
+
+ if b"Open MPI" in mpirun_version:
+ return mpi_app, "--hostfile", "-n", "--npernode", "--bind-to"
+ else:
+ # Intel MPI and MVAPICH both use the same arg names
+ return mpi_app, "-f", "-n", "-ppn", ""
+
+
+def setup_fp8_env(args: argparse.Namespace, current_env: Dict[str, str]):
+ """
+ Setup the FP8 environment variables.
+ """
+ prefix = "ACCELERATE_"
+ for arg in vars(args):
+ if arg.startswith("fp8_"):
+ value = getattr(args, arg)
+ if value is not None:
+ current_env[f"{prefix}{arg.upper()}"] = str(getattr(args, arg))
+ return current_env
+
+
+def prepare_simple_launcher_cmd_env(args: argparse.Namespace) -> Tuple[List[str], Dict[str, str]]:
+ """
+ Prepares and returns the command list and an environment with the correct simple launcher environment variables.
+ """
+ cmd = []
+ if args.no_python and args.module:
+ raise ValueError("--module and --no_python cannot be used together")
+
+ if args.mpirun_hostfile is not None:
+ mpi_app_name, hostfile_arg, num_proc_arg, proc_per_node_arg, bind_to_arg = _get_mpirun_args()
+ mpirun_ccl = getattr(args, "mpirun_ccl", None)
+ bind_to = getattr(args, "bind-to", "socket")
+ num_machines = args.num_machines
+ num_processes = getattr(args, "num_processes", None)
+ nproc_per_node = str(num_processes // num_machines) if num_processes and num_machines else "1"
+ cmd += [
+ mpi_app_name,
+ hostfile_arg,
+ args.mpirun_hostfile,
+ proc_per_node_arg,
+ nproc_per_node,
+ ]
+ if num_processes:
+ cmd += [num_proc_arg, str(num_processes)]
+ if bind_to_arg:
+ cmd += [bind_to_arg, bind_to]
+ if not args.no_python:
+ cmd.append(sys.executable)
+ if args.module:
+ cmd.append("-m")
+ cmd.append(args.training_script)
+ cmd.extend(args.training_script_args)
+
+ current_env = os.environ.copy()
+ current_env["ACCELERATE_USE_CPU"] = str(args.cpu or args.use_cpu)
+ if args.debug:
+ current_env["ACCELERATE_DEBUG_MODE"] = "true"
+ if args.gpu_ids != "all" and args.gpu_ids is not None:
+ if is_xpu_available():
+ current_env["ZE_AFFINITY_MASK"] = args.gpu_ids
+ elif is_mlu_available():
+ current_env["MLU_VISIBLE_DEVICES"] = args.gpu_ids
+ elif is_musa_available():
+ current_env["MUSA_VISIBLE_DEVICES"] = args.gpu_ids
+ elif is_npu_available():
+ current_env["ASCEND_RT_VISIBLE_DEVICES"] = args.gpu_ids
+ else:
+ current_env["CUDA_VISIBLE_DEVICES"] = args.gpu_ids
+ if args.num_machines > 1:
+ current_env["MASTER_ADDR"] = args.main_process_ip
+ current_env["MASTER_PORT"] = str(args.main_process_port)
+
+ if args.mpirun_hostfile is not None:
+ current_env["CCL_WORKER_COUNT"] = str(mpirun_ccl)
+ elif args.num_processes > 1:
+ current_env["MASTER_ADDR"] = args.main_process_ip if args.main_process_ip is not None else "127.0.0.1"
+ current_env["MASTER_PORT"] = str(args.main_process_port) if args.main_process_port is not None else "29500"
+
+ try:
+ mixed_precision = PrecisionType(args.mixed_precision.lower())
+ except ValueError:
+ raise ValueError(
+ f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}."
+ )
+
+ current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision)
+ if args.mixed_precision.lower() == "fp8":
+ if not is_fp8_available():
+ raise RuntimeError(
+ "FP8 is not available on this machine. Please ensure that either Transformer Engine or MSAMP is installed."
+ )
+ current_env = setup_fp8_env(args, current_env)
+
+ try:
+ dynamo_backend = DynamoBackend(args.dynamo_backend.upper())
+ except ValueError:
+ raise ValueError(
+ f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}."
+ )
+ current_env["ACCELERATE_DYNAMO_BACKEND"] = dynamo_backend.value
+ current_env["ACCELERATE_DYNAMO_MODE"] = args.dynamo_mode
+ current_env["ACCELERATE_DYNAMO_USE_FULLGRAPH"] = str(args.dynamo_use_fullgraph)
+ current_env["ACCELERATE_DYNAMO_USE_DYNAMIC"] = str(args.dynamo_use_dynamic)
+
+ current_env["OMP_NUM_THREADS"] = str(args.num_cpu_threads_per_process)
+ if is_ipex_available():
+ current_env["ACCELERATE_USE_IPEX"] = str(args.ipex).lower()
+ current_env["ACCELERATE_USE_XPU"] = str(args.use_xpu).lower()
+ if args.enable_cpu_affinity:
+ current_env["ACCELERATE_CPU_AFFINITY"] = "1"
+ return cmd, current_env
+
+
+def prepare_multi_gpu_env(args: argparse.Namespace) -> Dict[str, str]:
+ """
+ Prepares and returns an environment with the correct multi-GPU environment variables.
+ """
+ num_processes = args.num_processes
+ num_machines = args.num_machines
+ main_process_ip = args.main_process_ip
+ main_process_port = args.main_process_port
+ if num_machines > 1:
+ args.nproc_per_node = str(num_processes // num_machines)
+ args.nnodes = str(num_machines)
+ args.node_rank = int(args.machine_rank)
+ if getattr(args, "same_network", False):
+ args.master_addr = str(main_process_ip)
+ args.master_port = str(main_process_port)
+ else:
+ args.rdzv_endpoint = f"{main_process_ip}:{main_process_port}"
+ else:
+ args.nproc_per_node = str(num_processes)
+ if main_process_port is not None:
+ args.master_port = str(main_process_port)
+
+ if main_process_port is None:
+ main_process_port = 29500
+
+ # only need to check port availability in main process, in case we have to start multiple launchers on the same machine
+ # for some reasons like splitting log files.
+ need_port_check = num_machines <= 1 or int(args.machine_rank) == 0
+ if need_port_check and is_port_in_use(main_process_port):
+ raise ConnectionError(
+ f"Tried to launch distributed communication on port `{main_process_port}`, but another process is utilizing it. "
+ "Please specify a different port (such as using the `--main_process_port` flag or specifying a different `main_process_port` in your config file)"
+ " and rerun your script. To automatically use the next open port (on a single node), you can set this to `0`."
+ )
+
+ if args.module and args.no_python:
+ raise ValueError("--module and --no_python cannot be used together")
+ elif args.module:
+ args.module = True
+ elif args.no_python:
+ args.no_python = True
+
+ current_env = os.environ.copy()
+ if args.debug:
+ current_env["ACCELERATE_DEBUG_MODE"] = "true"
+ gpu_ids = getattr(args, "gpu_ids", "all")
+ if gpu_ids != "all" and args.gpu_ids is not None:
+ if is_xpu_available():
+ current_env["ZE_AFFINITY_MASK"] = gpu_ids
+ elif is_mlu_available():
+ current_env["MLU_VISIBLE_DEVICES"] = gpu_ids
+ elif is_musa_available():
+ current_env["MUSA_VISIBLE_DEVICES"] = gpu_ids
+ elif is_npu_available():
+ current_env["ASCEND_RT_VISIBLE_DEVICES"] = gpu_ids
+ else:
+ current_env["CUDA_VISIBLE_DEVICES"] = gpu_ids
+ mixed_precision = args.mixed_precision.lower()
+ try:
+ mixed_precision = PrecisionType(mixed_precision)
+ except ValueError:
+ raise ValueError(f"Unknown mixed_precision mode: {mixed_precision}. Choose between {PrecisionType.list()}.")
+
+ current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision)
+ if args.mixed_precision.lower() == "fp8":
+ if not is_fp8_available():
+ raise RuntimeError(
+ "FP8 is not available on this machine. Please ensure that either Transformer Engine or MSAMP is installed."
+ )
+ current_env = setup_fp8_env(args, current_env)
+
+ try:
+ dynamo_backend = DynamoBackend(args.dynamo_backend.upper())
+ except ValueError:
+ raise ValueError(
+ f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}."
+ )
+ current_env["ACCELERATE_DYNAMO_BACKEND"] = dynamo_backend.value
+ current_env["ACCELERATE_DYNAMO_MODE"] = args.dynamo_mode
+ current_env["ACCELERATE_DYNAMO_USE_FULLGRAPH"] = str(args.dynamo_use_fullgraph)
+ current_env["ACCELERATE_DYNAMO_USE_DYNAMIC"] = str(args.dynamo_use_dynamic)
+
+ if args.use_fsdp:
+ current_env["ACCELERATE_USE_FSDP"] = "true"
+ if args.fsdp_cpu_ram_efficient_loading and not args.fsdp_sync_module_states:
+ raise ValueError("When using `--fsdp_cpu_ram_efficient_loading` set `--fsdp_sync_module_states` to `True`")
+
+ current_env["FSDP_SHARDING_STRATEGY"] = str(args.fsdp_sharding_strategy)
+ current_env["FSDP_OFFLOAD_PARAMS"] = str(args.fsdp_offload_params).lower()
+ current_env["FSDP_MIN_NUM_PARAMS"] = str(args.fsdp_min_num_params)
+ if args.fsdp_auto_wrap_policy is not None:
+ current_env["FSDP_AUTO_WRAP_POLICY"] = str(args.fsdp_auto_wrap_policy)
+ if args.fsdp_transformer_layer_cls_to_wrap is not None:
+ current_env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = str(args.fsdp_transformer_layer_cls_to_wrap)
+ if args.fsdp_backward_prefetch is not None:
+ current_env["FSDP_BACKWARD_PREFETCH"] = str(args.fsdp_backward_prefetch)
+ if args.fsdp_state_dict_type is not None:
+ current_env["FSDP_STATE_DICT_TYPE"] = str(args.fsdp_state_dict_type)
+ current_env["FSDP_FORWARD_PREFETCH"] = str(args.fsdp_forward_prefetch).lower()
+ current_env["FSDP_USE_ORIG_PARAMS"] = str(args.fsdp_use_orig_params).lower()
+ current_env["FSDP_CPU_RAM_EFFICIENT_LOADING"] = str(args.fsdp_cpu_ram_efficient_loading).lower()
+ current_env["FSDP_SYNC_MODULE_STATES"] = str(args.fsdp_sync_module_states).lower()
+ current_env["FSDP_ACTIVATION_CHECKPOINTING"] = str(args.fsdp_activation_checkpointing).lower()
+
+ if args.use_megatron_lm:
+ prefix = "MEGATRON_LM_"
+ current_env["ACCELERATE_USE_MEGATRON_LM"] = "true"
+ current_env[prefix + "TP_DEGREE"] = str(args.megatron_lm_tp_degree)
+ current_env[prefix + "PP_DEGREE"] = str(args.megatron_lm_pp_degree)
+ current_env[prefix + "GRADIENT_CLIPPING"] = str(args.megatron_lm_gradient_clipping)
+ if args.megatron_lm_num_micro_batches is not None:
+ current_env[prefix + "NUM_MICRO_BATCHES"] = str(args.megatron_lm_num_micro_batches)
+ if args.megatron_lm_sequence_parallelism is not None:
+ current_env[prefix + "SEQUENCE_PARALLELISM"] = str(args.megatron_lm_sequence_parallelism)
+ if args.megatron_lm_recompute_activations is not None:
+ current_env[prefix + "RECOMPUTE_ACTIVATIONS"] = str(args.megatron_lm_recompute_activations)
+ if args.megatron_lm_use_distributed_optimizer is not None:
+ current_env[prefix + "USE_DISTRIBUTED_OPTIMIZER"] = str(args.megatron_lm_use_distributed_optimizer)
+
+ current_env["OMP_NUM_THREADS"] = str(args.num_cpu_threads_per_process)
+ if args.enable_cpu_affinity:
+ current_env["ACCELERATE_CPU_AFFINITY"] = "1"
+ return current_env
+
+
+def prepare_deepspeed_cmd_env(args: argparse.Namespace) -> Tuple[List[str], Dict[str, str]]:
+ """
+ Prepares and returns the command list and an environment with the correct DeepSpeed environment variables.
+ """
+ num_processes = args.num_processes
+ num_machines = args.num_machines
+ main_process_ip = args.main_process_ip
+ main_process_port = args.main_process_port
+ cmd = None
+
+ # make sure launcher is not None
+ if args.deepspeed_multinode_launcher is None:
+ # set to default pdsh
+ args.deepspeed_multinode_launcher = DEEPSPEED_MULTINODE_LAUNCHERS[0]
+
+ if num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]:
+ cmd = ["deepspeed", "--no_local_rank"]
+ cmd.extend(["--hostfile", str(args.deepspeed_hostfile), "--launcher", str(args.deepspeed_multinode_launcher)])
+ if args.deepspeed_exclusion_filter is not None:
+ cmd.extend(
+ [
+ "--exclude",
+ str(args.deepspeed_exclusion_filter),
+ ]
+ )
+ elif args.deepspeed_inclusion_filter is not None:
+ cmd.extend(
+ [
+ "--include",
+ str(args.deepspeed_inclusion_filter),
+ ]
+ )
+ else:
+ cmd.extend(["--num_gpus", str(args.num_processes // args.num_machines)])
+ if main_process_ip:
+ cmd.extend(["--master_addr", str(main_process_ip)])
+ cmd.extend(["--master_port", str(main_process_port)])
+ if args.module and args.no_python:
+ raise ValueError("--module and --no_python cannot be used together")
+ elif args.module:
+ cmd.append("--module")
+ elif args.no_python:
+ cmd.append("--no_python")
+ cmd.append(args.training_script)
+ cmd.extend(args.training_script_args)
+ elif num_machines > 1 and args.deepspeed_multinode_launcher == DEEPSPEED_MULTINODE_LAUNCHERS[1]:
+ args.nproc_per_node = str(num_processes // num_machines)
+ args.nnodes = str(num_machines)
+ args.node_rank = int(args.machine_rank)
+ if getattr(args, "same_network", False):
+ args.master_addr = str(main_process_ip)
+ args.master_port = str(main_process_port)
+ else:
+ args.rdzv_endpoint = f"{main_process_ip}:{main_process_port}"
+ else:
+ args.nproc_per_node = str(num_processes)
+ if main_process_port is not None:
+ args.master_port = str(main_process_port)
+
+ if main_process_port is None:
+ main_process_port = 29500
+
+ # only need to check port availability in main process, in case we have to start multiple launchers on the same machine
+ # for some reasons like splitting log files.
+ need_port_check = num_machines <= 1 or int(args.machine_rank) == 0
+ if need_port_check and is_port_in_use(main_process_port):
+ raise ConnectionError(
+ f"Tried to launch distributed communication on port `{main_process_port}`, but another process is utilizing it. "
+ "Please specify a different port (such as using the `--main_process_port` flag or specifying a different `main_process_port` in your config file)"
+ " and rerun your script. To automatically use the next open port (on a single node), you can set this to `0`."
+ )
+
+ if args.module and args.no_python:
+ raise ValueError("--module and --no_python cannot be used together")
+ elif args.module:
+ args.module = True
+ elif args.no_python:
+ args.no_python = True
+
+ current_env = os.environ.copy()
+ if args.debug:
+ current_env["ACCELERATE_DEBUG_MODE"] = "true"
+ gpu_ids = getattr(args, "gpu_ids", "all")
+ if gpu_ids != "all" and args.gpu_ids is not None:
+ if is_xpu_available():
+ current_env["ZE_AFFINITY_MASK"] = gpu_ids
+ elif is_mlu_available():
+ current_env["MLU_VISIBLE_DEVICES"] = gpu_ids
+ elif is_musa_available():
+ current_env["MUSA_VISIBLE_DEVICES"] = gpu_ids
+ elif is_npu_available():
+ current_env["ASCEND_RT_VISIBLE_DEVICES"] = gpu_ids
+ else:
+ current_env["CUDA_VISIBLE_DEVICES"] = gpu_ids
+ try:
+ mixed_precision = PrecisionType(args.mixed_precision.lower())
+ except ValueError:
+ raise ValueError(
+ f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}."
+ )
+
+ current_env["PYTHONPATH"] = env_var_path_add("PYTHONPATH", os.path.abspath("."))
+ current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision)
+ if args.mixed_precision.lower() == "fp8":
+ if not is_fp8_available():
+ raise RuntimeError(
+ "FP8 is not available on this machine. Please ensure that either Transformer Engine or MSAMP is installed."
+ )
+ current_env = setup_fp8_env(args, current_env)
+ current_env["ACCELERATE_CONFIG_DS_FIELDS"] = str(args.deepspeed_fields_from_accelerate_config).lower()
+ current_env["ACCELERATE_USE_DEEPSPEED"] = "true"
+ if args.zero_stage is not None:
+ current_env["ACCELERATE_DEEPSPEED_ZERO_STAGE"] = str(args.zero_stage)
+ if args.gradient_accumulation_steps is not None:
+ current_env["ACCELERATE_GRADIENT_ACCUMULATION_STEPS"] = str(args.gradient_accumulation_steps)
+ if args.gradient_clipping is not None:
+ current_env["ACCELERATE_GRADIENT_CLIPPING"] = str(args.gradient_clipping).lower()
+ if args.offload_optimizer_device is not None:
+ current_env["ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE"] = str(args.offload_optimizer_device).lower()
+ if args.offload_param_device is not None:
+ current_env["ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE"] = str(args.offload_param_device).lower()
+ if args.zero3_init_flag is not None:
+ current_env["ACCELERATE_DEEPSPEED_ZERO3_INIT"] = str(args.zero3_init_flag).lower()
+ if args.zero3_save_16bit_model is not None:
+ current_env["ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL"] = str(args.zero3_save_16bit_model).lower()
+ if args.deepspeed_config_file is not None:
+ current_env["ACCELERATE_DEEPSPEED_CONFIG_FILE"] = str(args.deepspeed_config_file)
+ if args.enable_cpu_affinity:
+ current_env["ACCELERATE_CPU_AFFINITY"] = "1"
+ if args.deepspeed_moe_layer_cls_names is not None:
+ current_env["ACCELERATE_DEEPSPEED_MOE_LAYER_CLS_NAMES"] = str(args.deepspeed_moe_layer_cls_names)
+ return cmd, current_env
+
+
+def prepare_tpu(
+ args: argparse.Namespace, current_env: Dict[str, str], pod: bool = False
+) -> Tuple[argparse.Namespace, Dict[str, str]]:
+ """
+ Prepares and returns an environment with the correct TPU environment variables.
+ """
+ if args.mixed_precision == "bf16" and is_torch_xla_available(check_is_tpu=True):
+ if args.downcast_bf16:
+ current_env["XLA_DOWNCAST_BF16"] = "1"
+ else:
+ current_env["XLA_USE_BF16"] = "1"
+ if args.debug:
+ current_env["ACCELERATE_DEBUG_MODE"] = "true"
+ if pod:
+ # Take explicit args and set them up for XLA
+ args.vm = args.tpu_vm
+ args.tpu = args.tpu_name
+ return args, current_env
+
+
+def _convert_nargs_to_dict(nargs: List[str]) -> Dict[str, str]:
+ if len(nargs) < 0:
+ return {}
+ # helper function to infer type for argsparser
+
+ def _infer_type(s):
+ try:
+ s = float(s)
+
+ if s // 1 == s:
+ return int(s)
+ return s
+ except ValueError:
+ return s
+
+ parser = argparse.ArgumentParser()
+ _, unknown = parser.parse_known_args(nargs)
+ for index, argument in enumerate(unknown):
+ if argument.startswith(("-", "--")):
+ action = None
+ if index + 1 < len(unknown): # checks if next index would be in list
+ if unknown[index + 1].startswith(("-", "--")): # checks if next element is an key
+ # raise an error if element is store_true or store_false
+ raise ValueError(
+ "SageMaker doesn’t support argparse actions for `store_true` or `store_false`. Please define explicit types"
+ )
+ else: # raise an error if last element is store_true or store_false
+ raise ValueError(
+ "SageMaker doesn’t support argparse actions for `store_true` or `store_false`. Please define explicit types"
+ )
+ # adds argument to parser based on action_store true
+ if action is None:
+ parser.add_argument(argument, type=_infer_type)
+ else:
+ parser.add_argument(argument, action=action)
+
+ return {
+ key: (literal_eval(value) if value in ("True", "False") else value)
+ for key, value in parser.parse_args(nargs).__dict__.items()
+ }
+
+
+def prepare_sagemager_args_inputs(
+ sagemaker_config: SageMakerConfig, args: argparse.Namespace
+) -> Tuple[argparse.Namespace, Dict[str, Any]]:
+ # configure environment
+ print("Configuring Amazon SageMaker environment")
+ os.environ["AWS_DEFAULT_REGION"] = sagemaker_config.region
+
+ # configure credentials
+ if sagemaker_config.profile is not None:
+ os.environ["AWS_PROFILE"] = sagemaker_config.profile
+ elif args.aws_access_key_id is not None and args.aws_secret_access_key is not None:
+ os.environ["AWS_ACCESS_KEY_ID"] = args.aws_access_key_id
+ os.environ["AWS_SECRET_ACCESS_KEY"] = args.aws_secret_access_key
+ else:
+ raise OSError("You need to provide an aws_access_key_id and aws_secret_access_key when not using aws_profile")
+
+ # extract needed arguments
+ source_dir = os.path.dirname(args.training_script)
+ if not source_dir: # checks if string is empty
+ source_dir = "."
+ entry_point = os.path.basename(args.training_script)
+ if not entry_point.endswith(".py"):
+ raise ValueError(f'Your training script should be a python script and not "{entry_point}"')
+
+ print("Converting Arguments to Hyperparameters")
+ hyperparameters = _convert_nargs_to_dict(args.training_script_args)
+
+ try:
+ mixed_precision = PrecisionType(args.mixed_precision.lower())
+ except ValueError:
+ raise ValueError(
+ f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}."
+ )
+
+ try:
+ dynamo_backend = DynamoBackend(args.dynamo_backend.upper())
+ except ValueError:
+ raise ValueError(
+ f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}."
+ )
+
+ # Environment variables to be set for use during training job
+ environment = {
+ "ACCELERATE_USE_SAGEMAKER": "true",
+ "ACCELERATE_MIXED_PRECISION": str(mixed_precision),
+ "ACCELERATE_DYNAMO_BACKEND": dynamo_backend.value,
+ "ACCELERATE_DYNAMO_MODE": args.dynamo_mode,
+ "ACCELERATE_DYNAMO_USE_FULLGRAPH": str(args.dynamo_use_fullgraph),
+ "ACCELERATE_DYNAMO_USE_DYNAMIC": str(args.dynamo_use_dynamic),
+ "ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE": sagemaker_config.distributed_type.value,
+ }
+ if args.mixed_precision.lower() == "fp8":
+ if not is_fp8_available():
+ raise RuntimeError(
+ "FP8 is not available on this machine. Please ensure that either Transformer Engine or MSAMP is installed."
+ )
+ environment = setup_fp8_env(args, environment)
+ # configure distribution set up
+ distribution = None
+ if sagemaker_config.distributed_type == SageMakerDistributedType.DATA_PARALLEL:
+ distribution = {"smdistributed": {"dataparallel": {"enabled": True}}}
+
+ # configure sagemaker inputs
+ sagemaker_inputs = None
+ if sagemaker_config.sagemaker_inputs_file is not None:
+ print(f"Loading SageMaker Inputs from {sagemaker_config.sagemaker_inputs_file} file")
+ sagemaker_inputs = {}
+ with open(sagemaker_config.sagemaker_inputs_file) as file:
+ for i, line in enumerate(file):
+ if i == 0:
+ continue
+ l = line.split("\t")
+ sagemaker_inputs[l[0]] = l[1].strip()
+ print(f"Loaded SageMaker Inputs: {sagemaker_inputs}")
+
+ # configure sagemaker metrics
+ sagemaker_metrics = None
+ if sagemaker_config.sagemaker_metrics_file is not None:
+ print(f"Loading SageMaker Metrics from {sagemaker_config.sagemaker_metrics_file} file")
+ sagemaker_metrics = []
+ with open(sagemaker_config.sagemaker_metrics_file) as file:
+ for i, line in enumerate(file):
+ if i == 0:
+ continue
+ l = line.split("\t")
+ metric_dict = {
+ "Name": l[0],
+ "Regex": l[1].strip(),
+ }
+ sagemaker_metrics.append(metric_dict)
+ print(f"Loaded SageMaker Metrics: {sagemaker_metrics}")
+
+ # configure session
+ print("Creating Estimator")
+ args = {
+ "image_uri": sagemaker_config.image_uri,
+ "entry_point": entry_point,
+ "source_dir": source_dir,
+ "role": sagemaker_config.iam_role_name,
+ "transformers_version": sagemaker_config.transformers_version,
+ "pytorch_version": sagemaker_config.pytorch_version,
+ "py_version": sagemaker_config.py_version,
+ "base_job_name": sagemaker_config.base_job_name,
+ "instance_count": sagemaker_config.num_machines,
+ "instance_type": sagemaker_config.ec2_instance_type,
+ "debugger_hook_config": False,
+ "distribution": distribution,
+ "hyperparameters": hyperparameters,
+ "environment": environment,
+ "metric_definitions": sagemaker_metrics,
+ }
+
+ if sagemaker_config.additional_args is not None:
+ args = merge_dicts(sagemaker_config.additional_args, args)
+ return args, sagemaker_inputs
+
+
+def env_var_path_add(env_var_name, path_to_add):
+ """
+ Extends a path-based environment variable's value with a new path and returns the updated value. It's up to the
+ caller to set it in os.environ.
+ """
+ paths = [p for p in os.environ.get(env_var_name, "").split(":") if len(p) > 0]
+ paths.append(str(path_to_add))
+ return ":".join(paths)
+
+
+class PrepareForLaunch:
+ """
+ Prepare a function that will launched in a distributed setup.
+
+ Args:
+ launcher (`Callable`):
+ The function to launch.
+ distributed_type ([`~state.DistributedType`]):
+ The distributed type to prepare for.
+ debug (`bool`, *optional*, defaults to `False`):
+ Whether or not this is a debug launch.
+ """
+
+ def __init__(self, launcher, distributed_type="NO", debug=False):
+ self.launcher = launcher
+ self.distributed_type = DistributedType(distributed_type)
+ self.debug = debug
+
+ def __call__(self, index, *args):
+ if self.debug:
+ world_size = int(os.environ.get("WORLD_SIZE"))
+ rdv_file = os.environ.get("ACCELERATE_DEBUG_RDV_FILE")
+ torch.distributed.init_process_group(
+ "gloo",
+ rank=index,
+ store=torch.distributed.FileStore(rdv_file, world_size),
+ world_size=world_size,
+ )
+ elif self.distributed_type in (
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_XPU,
+ DistributedType.MULTI_CPU,
+ ):
+ # Prepare the environment for torch.distributed
+ os.environ["LOCAL_RANK"] = str(index)
+ nproc = int(os.environ.get("NPROC", 1))
+ node_rank = int(os.environ.get("NODE_RANK", 0))
+ os.environ["RANK"] = str(nproc * node_rank + index)
+
+ os.environ["FORK_LAUNCHED"] = str(1)
+ self.launcher(*args)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/megatron_lm.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/megatron_lm.py
new file mode 100644
index 0000000000000000000000000000000000000000..552cb6d35f2a525c9ccde81f6c4e775705d4467f
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/megatron_lm.py
@@ -0,0 +1,1425 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+import math
+import os
+from abc import ABC
+from functools import partial
+
+import torch
+import torch.nn.functional as F
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP
+
+from ..optimizer import AcceleratedOptimizer
+from ..scheduler import AcceleratedScheduler
+from .imports import is_megatron_lm_available
+from .operations import recursively_apply, send_to_device
+
+
+if is_megatron_lm_available():
+ from megatron import (
+ get_args,
+ get_num_microbatches,
+ get_tensorboard_writer,
+ get_tokenizer,
+ print_rank_last,
+ )
+ from megatron.arguments import (
+ _add_data_args,
+ _add_validation_args,
+ core_transformer_config_from_args,
+ parse_args,
+ validate_args,
+ )
+ from megatron.checkpointing import load_args_from_checkpoint, load_checkpoint, save_checkpoint
+ from megatron.core import mpu, tensor_parallel
+ from megatron.core.distributed import DistributedDataParallel as LocalDDP
+ from megatron.core.distributed import finalize_model_grads
+ from megatron.core.enums import ModelType
+ from megatron.core.parallel_state import get_tensor_model_parallel_group, get_tensor_model_parallel_src_rank
+ from megatron.core.pipeline_parallel import get_forward_backward_func
+ from megatron.core.utils import get_model_config
+ from megatron.data.dataset_utils import build_train_valid_test_datasets
+ from megatron.global_vars import set_global_variables
+ from megatron.initialize import (
+ _compile_dependencies,
+ _init_autoresume,
+ _initialize_distributed,
+ _set_random_seed,
+ set_jit_fusion_options,
+ write_args_to_tensorboard,
+ )
+ from megatron.model import BertModel, Float16Module, GPTModel, T5Model
+ from megatron.model.classification import Classification
+ from megatron.optimizer import get_megatron_optimizer
+ from megatron.text_generation.communication import broadcast_int_list, broadcast_tensor
+ from megatron.text_generation.generation import (
+ beam_search_and_return_on_first_stage,
+ generate_tokens_probs_and_return_on_first_stage,
+ )
+ from megatron.tokenizer.tokenizer import _vocab_size_with_padding
+ from megatron.training import (
+ build_train_valid_test_data_iterators,
+ get_optimizer_param_scheduler,
+ num_floating_point_operations,
+ setup_model_and_optimizer,
+ train_step,
+ training_log,
+ )
+ from megatron.utils import (
+ average_losses_across_data_parallel_group,
+ calc_params_l2_norm,
+ get_ltor_masks_and_position_ids,
+ unwrap_model,
+ )
+
+
+# model utilities
+def model_provider_func(pre_process=True, post_process=True, add_encoder=True, add_decoder=True):
+ """Build the model."""
+ args = get_args()
+ mode = "pre-training" if args.pretraining_flag else "fine-tuning"
+ if args.rank == 0:
+ print(f"Building {args.model_type_name} model in the {mode} mode.")
+ print(
+ "The Megatron LM model weights are initialized at random in `accelerator.prepare`. "
+ "Please use `accelerator.load_checkpoint` to load a pre-trained checkpoint matching the distributed setup."
+ )
+ config = core_transformer_config_from_args(args)
+ if args.model_type_name == "bert":
+ if args.pretraining_flag:
+ num_tokentypes = 2 if args.bert_binary_head else 0
+ model = BertModel(
+ config=config,
+ num_tokentypes=num_tokentypes,
+ add_binary_head=args.bert_binary_head,
+ parallel_output=True,
+ pre_process=pre_process,
+ post_process=post_process,
+ )
+ else:
+ model = Classification(
+ config=config,
+ num_classes=args.num_labels,
+ num_tokentypes=2,
+ pre_process=pre_process,
+ post_process=post_process,
+ )
+ elif args.model_type_name == "gpt":
+ model = GPTModel(
+ config=config,
+ num_tokentypes=0,
+ parallel_output=True,
+ pre_process=pre_process,
+ post_process=post_process,
+ )
+ elif args.model_type_name == "t5":
+ model = T5Model(
+ config=config,
+ num_tokentypes=0,
+ parallel_output=True,
+ pre_process=pre_process,
+ post_process=post_process,
+ add_encoder=add_encoder,
+ add_decoder=add_decoder,
+ )
+ else:
+ raise ValueError(f"Unsupported model type: {args.model_type_name}")
+ return model
+
+
+def prepare_model_optimizer_scheduler(accelerator):
+ accelerator.print("Preparing model optimizer scheduler")
+ args = get_args()
+ if accelerator.state.megatron_lm_plugin.custom_prepare_model_function is not None:
+ if accelerator.state.megatron_lm_plugin.custom_model_provider_function is None:
+ raise ValueError(
+ "You must provide a `custom_model_provider_function` when using a `custom_prepare_model_function`."
+ )
+ custom_model_provider_func = accelerator.state.megatron_lm_plugin.custom_model_provider_function
+ model = accelerator.state.megatron_lm_plugin.custom_prepare_model_function(custom_model_provider_func)
+ optimizer = prepare_optimizer(accelerator, model)
+ scheduler = prepare_scheduler(accelerator, optimizer, scheduler=None)
+ else:
+ model_type = ModelType.encoder_or_decoder
+ if args.model_type_name == "t5":
+ model_type = ModelType.encoder_and_decoder
+ model_provider_func_ = model_provider_func
+ if accelerator.state.megatron_lm_plugin.custom_model_provider_function is not None:
+ model_provider_func_ = accelerator.state.megatron_lm_plugin.custom_model_provider_function
+ (model, optimizer, scheduler) = setup_model_and_optimizer(
+ model_provider_func_,
+ model_type,
+ no_wd_decay_cond=args.no_wd_decay_cond,
+ scale_lr_cond=args.scale_lr_cond,
+ lr_mult=args.lr_mult,
+ )
+ args.model_len = len(model)
+ return model, optimizer, scheduler
+
+
+# dataloader utilities
+class MegatronLMDummyDataLoader:
+ """
+ Dummy dataloader presents model parameters or param groups, this is primarily used to follow conventional training
+
+ Args:
+ **dataset_kwargs: Megatron data arguments.
+ """
+
+ def __init__(self, **dataset_kwargs):
+ parser = argparse.ArgumentParser()
+ parser = _add_data_args(parser)
+ parser = _add_validation_args(parser)
+ data_args = parser.parse_known_args()
+ self.dataset_args = vars(data_args[0])
+ self.dataset_args.update(dataset_kwargs)
+ self.dataset_args["megatron_dataset_flag"] = True
+
+ def set_megatron_data_args(self):
+ args = get_args()
+ for key, value in self.dataset_args.items():
+ old_value = getattr(args, key, "")
+ if old_value != value:
+ print(
+ f"WARNING: MegatronLMDummyDataLoader overriding arguments for "
+ f"{key}:{old_value} with {key}:{value}"
+ )
+ setattr(args, key, value)
+
+ def get_train_valid_test_datasets_provider(self, accelerator):
+ def train_valid_test_datasets_provider(train_val_test_num_samples):
+ """Build train, valid, and test datasets."""
+ args = get_args()
+ dataset_args = {
+ "data_prefix": args.data_path if isinstance(args.data_path, (list, tuple)) else [args.data_path],
+ "splits_string": args.split,
+ "train_valid_test_num_samples": train_val_test_num_samples,
+ "seed": args.seed,
+ }
+ if args.model_type_name == "bert":
+ dataset_args.update(
+ {
+ "max_seq_length": args.seq_length,
+ "binary_head": args.bert_binary_head,
+ }
+ )
+ elif args.model_type_name == "gpt":
+ dataset_args.update(
+ {
+ "max_seq_length": args.seq_length,
+ }
+ )
+ elif args.model_type_name == "t5":
+ dataset_args.update(
+ {
+ "max_seq_length": args.encoder_seq_length,
+ "max_seq_length_dec": args.decoder_seq_length,
+ "dataset_type": "t5",
+ }
+ )
+ else:
+ raise ValueError(f"Unsupported model type: {args.model_type_name}")
+ train_ds, valid_ds, test_ds = build_train_valid_test_datasets(**dataset_args)
+ return train_ds, valid_ds, test_ds
+
+ if accelerator.state.megatron_lm_plugin.custom_megatron_datasets_provider_function is not None:
+ return accelerator.state.megatron_lm_plugin.custom_megatron_datasets_provider_function
+ try:
+ args = get_args()
+ # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source
+ if args.model_type_name == "bert":
+ from pretrain_bert import train_valid_test_datasets_provider
+
+ train_valid_test_datasets_provider.is_distributed = True
+ return train_valid_test_datasets_provider
+ elif args.model_type_name == "gpt":
+ from pretrain_gpt import train_valid_test_datasets_provider
+
+ train_valid_test_datasets_provider.is_distributed = True
+ return train_valid_test_datasets_provider
+ elif args.model_type_name == "t5":
+ from pretrain_t5 import train_valid_test_datasets_provider
+
+ train_valid_test_datasets_provider.is_distributed = True
+ return train_valid_test_datasets_provider
+ except ImportError:
+ pass
+ return train_valid_test_datasets_provider
+
+ def build_train_valid_test_data_iterators(self, accelerator):
+ args = get_args()
+
+ train_valid_test_dataset_provider = self.get_train_valid_test_datasets_provider(accelerator)
+ if args.virtual_pipeline_model_parallel_size is not None:
+ train_data_iterator = []
+ valid_data_iterator = []
+ test_data_iterator = []
+ for i in range(getattr(args, "model_len", 0)):
+ mpu.set_virtual_pipeline_model_parallel_rank(i)
+ iterators = build_train_valid_test_data_iterators(train_valid_test_dataset_provider)
+ train_data_iterator.append(iterators[0])
+ valid_data_iterator.append(iterators[1])
+ test_data_iterator.append(iterators[2])
+ else:
+ train_data_iterator, valid_data_iterator, test_data_iterator = build_train_valid_test_data_iterators(
+ train_valid_test_dataset_provider
+ )
+
+ return train_data_iterator, valid_data_iterator, test_data_iterator
+
+
+def _handle_megatron_data_iterator(accelerator, data_iterator):
+ class DummyMegatronDataloader:
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ return {}
+
+ is_data_iterator_empty = data_iterator is None
+ is_src_data_iterator_empty = torch.tensor(is_data_iterator_empty, dtype=torch.bool, device=accelerator.device)
+ torch.distributed.broadcast(
+ is_src_data_iterator_empty, get_tensor_model_parallel_src_rank(), group=get_tensor_model_parallel_group()
+ )
+ if not is_src_data_iterator_empty and is_data_iterator_empty:
+ return DummyMegatronDataloader()
+ return data_iterator
+
+
+def prepare_data_loader(accelerator, dataloader):
+ accelerator.print("Preparing dataloader")
+ args = get_args()
+ if not args.megatron_dataset_flag:
+ from ..data_loader import _PYTORCH_DATALOADER_KWARGS, prepare_data_loader
+
+ micro_batch_size = args.micro_batch_size * args.num_micro_batches
+ kwargs = {k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k]) for k in _PYTORCH_DATALOADER_KWARGS}
+ if kwargs["batch_size"] is None:
+ if isinstance(kwargs["sampler"], torch.utils.data.BatchSampler):
+ kwargs["sampler"].batch_size = micro_batch_size
+ else:
+ del kwargs["sampler"]
+ del kwargs["shuffle"]
+ del kwargs["batch_size"]
+ kwargs["batch_sampler"].batch_size = micro_batch_size
+ else:
+ del kwargs["batch_sampler"]
+ kwargs["batch_size"] = micro_batch_size
+
+ dataloader = torch.utils.data.DataLoader(dataloader.dataset, **kwargs)
+ # split_batches:
+ # Megatron only needs to fetch different data between different dp groups,
+ # and does not need to split the data within the dp group.
+ return prepare_data_loader(
+ dataloader,
+ accelerator.device,
+ num_processes=mpu.get_data_parallel_world_size(),
+ process_index=mpu.get_data_parallel_rank(),
+ split_batches=False,
+ put_on_device=True,
+ rng_types=accelerator.rng_types.copy(),
+ dispatch_batches=accelerator.dispatch_batches,
+ )
+ else:
+ if args.consumed_samples is not None:
+ (
+ args.consumed_train_samples,
+ args.consumed_valid_samples,
+ args.consumed_test_samples,
+ ) = args.consumed_samples
+ else:
+ args.consumed_train_samples, args.consumed_valid_samples, args.consumed_test_samples = 0, 0, 0
+ args.micro_batch_size = args.micro_batch_size * args.num_micro_batches
+ # In order to be compatible with data in transform format,
+ # it needs to increase the size of mbs first,
+ # and then split the large batch data into some mbs.
+ (
+ train_data_iterator,
+ valid_data_iterator,
+ test_data_iterator,
+ ) = dataloader.build_train_valid_test_data_iterators(accelerator)
+ args.micro_batch_size = args.micro_batch_size // args.num_micro_batches
+
+ train_data_iterator = _handle_megatron_data_iterator(
+ accelerator=accelerator, data_iterator=train_data_iterator
+ )
+ valid_data_iterator = _handle_megatron_data_iterator(
+ accelerator=accelerator, data_iterator=valid_data_iterator
+ )
+ test_data_iterator = _handle_megatron_data_iterator(accelerator=accelerator, data_iterator=test_data_iterator)
+
+ return train_data_iterator, valid_data_iterator, test_data_iterator
+
+
+# optimizer utilities
+class MegatronLMOptimizerWrapper(AcceleratedOptimizer):
+ def __init__(self, optimizer):
+ super().__init__(optimizer, device_placement=False, scaler=None)
+
+ def zero_grad(self, set_to_none=None):
+ pass # `model(**batch)` is doing that automatically. Therefore, it's implementation is not needed
+
+ def step(self):
+ pass # `model(**batch)` is doing that automatically. Therefore, it's implementation is not needed
+
+ @property
+ def step_was_skipped(self):
+ """Whether or not the optimizer step was done, or skipped because of gradient overflow."""
+ return self.optimizer.skipped_iter
+
+
+def prepare_optimizer(accelerator, model):
+ accelerator.print("Preparing optimizer")
+ args = get_args()
+ return get_megatron_optimizer(model, args.no_wd_decay_cond, args.scale_lr_cond, args.lr_mult)
+
+
+# scheduler utilities
+class MegatronLMDummyScheduler:
+ """
+ Dummy scheduler presents model parameters or param groups, this is primarily used to follow conventional training
+ loop when scheduler config is specified in the deepspeed config file.
+
+ Args:
+ optimizer (`torch.optim.optimizer.Optimizer`):
+ The optimizer to wrap.
+ total_num_steps (int):
+ Total number of steps.
+ warmup_num_steps (int):
+ Number of steps for warmup.
+ **kwargs (additional keyword arguments, *optional*):
+ Other arguments.
+ """
+
+ def __init__(self, optimizer, total_num_steps=None, warmup_num_steps=0, **kwargs):
+ self.optimizer = optimizer
+ self.total_num_steps = total_num_steps
+ self.warmup_num_steps = warmup_num_steps
+ self.kwargs = kwargs
+
+
+class MegatronLMSchedulerWrapper(AcceleratedScheduler):
+ def __init__(self, scheduler, optimizers):
+ super().__init__(scheduler, optimizers)
+
+ def step(self, *args, **kwargs):
+ return # `model(**batch)` is doing that automatically. Therefore, it's implementation is not needed
+
+
+def prepare_scheduler(accelerator, optimizer, scheduler):
+ accelerator.print("Preparing scheduler")
+ scheduler = get_optimizer_param_scheduler(optimizer)
+ return scheduler
+
+
+class AbstractTrainStep(ABC):
+ """Abstract class for batching, forward pass and loss handler."""
+
+ def __init__(self, name):
+ super().__init__()
+ self.name = name
+
+ def get_batch_func(self, accelerator, megatron_dataset_flag):
+ pass
+
+ def get_forward_step_func(self):
+ pass
+
+ def get_loss_func(self, accelerator):
+ pass
+
+
+class BertTrainStep(AbstractTrainStep):
+ """
+ Bert train step class.
+
+ Args:
+ args (`argparse.Namespace`): Megatron-LM arguments.
+ """
+
+ def __init__(self, accelerator, args):
+ super().__init__("BertTrainStep")
+ self.get_batch = self.get_batch_func(accelerator, args.megatron_dataset_flag)
+ self.loss_func = self.get_loss_func(accelerator, args.pretraining_flag, args.num_labels)
+ self.forward_step = self.get_forward_step_func(args.pretraining_flag, args.bert_binary_head)
+ if not args.model_return_dict:
+ self.model_output_class = None
+ else:
+ from transformers.modeling_outputs import SequenceClassifierOutput
+
+ self.model_output_class = SequenceClassifierOutput
+
+ def get_batch_func(self, accelerator, megatron_dataset_flag):
+ def get_batch_megatron(data_iterator):
+ """Build the batch."""
+
+ # Items and their type.
+ keys = ["text", "types", "labels", "is_random", "loss_mask", "padding_mask"]
+ datatype = torch.int64
+
+ # Broadcast data.
+ if data_iterator is not None:
+ data = next(data_iterator)
+ else:
+ data = None
+ data_b = tensor_parallel.broadcast_data(keys, data, datatype)
+
+ # Unpack.
+ tokens = data_b["text"].long()
+ types = data_b["types"].long()
+ sentence_order = data_b["is_random"].long()
+ loss_mask = data_b["loss_mask"].float()
+ lm_labels = data_b["labels"].long()
+ padding_mask = data_b["padding_mask"].long()
+
+ return tokens, types, sentence_order, loss_mask, lm_labels, padding_mask
+
+ def get_batch_transformer(data_iterator):
+ """Build the batch."""
+ data = next(data_iterator)
+ data = send_to_device(data, torch.cuda.current_device())
+
+ # Unpack.
+ tokens = data["input_ids"].long()
+ padding_mask = data["attention_mask"].long()
+ if "token_type_ids" in data:
+ types = data["token_type_ids"].long()
+ else:
+ types = None
+ if "labels" in data:
+ lm_labels = data["labels"].long()
+ loss_mask = (data["labels"] != -100).to(torch.float)
+ else:
+ lm_labels = None
+ loss_mask = None
+ if "next_sentence_label" in data:
+ sentence_order = data["next_sentence_label"].long()
+ else:
+ sentence_order = None
+
+ return tokens, types, sentence_order, loss_mask, lm_labels, padding_mask
+
+ if accelerator.state.megatron_lm_plugin.custom_get_batch_function is not None:
+ return accelerator.state.megatron_lm_plugin.custom_get_batch_function
+ if megatron_dataset_flag:
+ try:
+ # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source
+ from pretrain_bert import get_batch
+
+ return get_batch
+ except ImportError:
+ pass
+ return get_batch_megatron
+ else:
+ return get_batch_transformer
+
+ def get_loss_func(self, accelerator, pretraining_flag, num_labels):
+ def loss_func_pretrain(loss_mask, sentence_order, output_tensor):
+ lm_loss_, sop_logits = output_tensor
+
+ lm_loss_ = lm_loss_.float()
+ loss_mask = loss_mask.float()
+ lm_loss = torch.sum(lm_loss_.view(-1) * loss_mask.reshape(-1)) / loss_mask.sum()
+
+ if sop_logits is not None:
+ sop_loss = F.cross_entropy(sop_logits.view(-1, 2).float(), sentence_order.view(-1), ignore_index=-1)
+ sop_loss = sop_loss.float()
+ loss = lm_loss + sop_loss
+ averaged_losses = average_losses_across_data_parallel_group([lm_loss, sop_loss])
+ return loss, {"lm loss": averaged_losses[0], "sop loss": averaged_losses[1]}
+
+ else:
+ loss = lm_loss
+ averaged_losses = average_losses_across_data_parallel_group([lm_loss])
+ return loss, {"lm loss": averaged_losses[0]}
+
+ def loss_func_finetune(labels, logits):
+ if num_labels == 1:
+ # We are doing regression
+ loss_fct = MSELoss()
+ loss = loss_fct(logits.view(-1), labels.view(-1))
+ elif self.num_labels > 1 and (labels.dtype in (torch.long, torch.int)):
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, num_labels), labels.view(-1))
+ else:
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+ averaged_losses = average_losses_across_data_parallel_group([loss])
+ return loss, {"loss": averaged_losses[0]}
+
+ if accelerator.state.megatron_lm_plugin.custom_loss_function is not None:
+ return accelerator.state.megatron_lm_plugin.custom_loss_function
+ if pretraining_flag:
+ return loss_func_pretrain
+ else:
+ return loss_func_finetune
+
+ def get_forward_step_func(self, pretraining_flag, bert_binary_head):
+ def forward_step(data_iterator, model):
+ """Forward step."""
+ tokens, types, sentence_order, loss_mask, labels, padding_mask = self.get_batch(data_iterator)
+ if not bert_binary_head:
+ types = None
+ # Forward pass through the model.
+ if pretraining_flag:
+ output_tensor = model(tokens, padding_mask, tokentype_ids=types, lm_labels=labels)
+ return output_tensor, partial(self.loss_func, loss_mask, sentence_order)
+ else:
+ logits = model(tokens, padding_mask, tokentype_ids=types)
+ return logits, partial(self.loss_func, labels)
+
+ return forward_step
+
+
+class GPTTrainStep(AbstractTrainStep):
+ """
+ GPT train step class.
+
+ Args:
+ args (`argparse.Namespace`): Megatron-LM arguments.
+ """
+
+ def __init__(self, accelerator, args):
+ super().__init__("GPTTrainStep")
+ self.get_batch = self.get_batch_func(accelerator, args.megatron_dataset_flag)
+ self.loss_func = self.get_loss_func(accelerator)
+ self.forward_step = self.get_forward_step_func()
+ self.eod_token = args.padded_vocab_size - 1
+ if args.vocab_file is not None:
+ tokenizer = get_tokenizer()
+ self.eod_token = tokenizer.eod
+ self.reset_position_ids = args.reset_position_ids
+ self.reset_attention_mask = args.reset_attention_mask
+ self.eod_mask_loss = args.eod_mask_loss
+ if not args.model_return_dict:
+ self.model_output_class = None
+ else:
+ from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions
+
+ self.model_output_class = CausalLMOutputWithCrossAttentions
+
+ def get_batch_func(self, accelerator, megatron_dataset_flag):
+ def get_batch_megatron(data_iterator):
+ """Generate a batch"""
+ # Items and their type.
+ keys = ["text"]
+ datatype = torch.int64
+
+ # Broadcast data.
+ if data_iterator is not None:
+ data = next(data_iterator)
+ else:
+ data = None
+ data_b = tensor_parallel.broadcast_data(keys, data, datatype)
+
+ # Unpack.
+ tokens_ = data_b["text"].long()
+ labels = tokens_[:, 1:].contiguous()
+ tokens = tokens_[:, :-1].contiguous()
+
+ # Get the masks and postition ids.
+ attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids(
+ tokens, self.eod_token, self.reset_position_ids, self.reset_attention_mask, self.eod_mask_loss
+ )
+
+ return tokens, labels, loss_mask, attention_mask, position_ids
+
+ def get_batch_transformer(data_iterator):
+ data = next(data_iterator)
+ data = {"input_ids": data["input_ids"]}
+ data = send_to_device(data, torch.cuda.current_device())
+
+ tokens_ = data["input_ids"].long()
+ padding = torch.zeros((tokens_.shape[0], 1), dtype=tokens_.dtype, device=tokens_.device) + self.eod_token
+ tokens_ = torch.concat([tokens_, padding], dim=1)
+ labels = tokens_[:, 1:].contiguous()
+ tokens = tokens_[:, :-1].contiguous()
+ # Get the masks and postition ids.
+ attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids(
+ tokens, self.eod_token, self.reset_position_ids, self.reset_attention_mask, True
+ )
+ return tokens, labels, loss_mask, attention_mask, position_ids
+
+ if accelerator.state.megatron_lm_plugin.custom_get_batch_function is not None:
+ return accelerator.state.megatron_lm_plugin.custom_get_batch_function
+ if megatron_dataset_flag:
+ try:
+ # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source
+ from pretrain_gpt import get_batch
+
+ return get_batch
+ except ImportError:
+ pass
+ return get_batch_megatron
+ else:
+ return get_batch_transformer
+
+ def get_loss_func(self, accelerator):
+ args = get_args()
+
+ def loss_func(loss_mask, output_tensor):
+ if args.return_logits:
+ losses, logits = output_tensor
+ else:
+ losses = output_tensor
+ losses = losses.float()
+ loss_mask = loss_mask.view(-1).float()
+ if args.context_parallel_size > 1:
+ loss = torch.cat([torch.sum(losses.view(-1) * loss_mask).view(1), loss_mask.sum().view(1)])
+ torch.distributed.all_reduce(loss, group=mpu.get_context_parallel_group())
+ loss = loss[0] / loss[1]
+ else:
+ loss = torch.sum(losses.view(-1) * loss_mask) / loss_mask.sum()
+
+ # Check individual rank losses are not NaN prior to DP all-reduce.
+ if args.check_for_nan_in_loss_and_grad:
+ global_rank = torch.distributed.get_rank()
+ assert not loss.isnan(), (
+ f"Rank {global_rank}: found NaN in local forward loss calculation. "
+ f"Device: {torch.cuda.current_device()}, node: {os.uname()[1]}"
+ )
+
+ # Reduce loss for logging.
+ averaged_loss = average_losses_across_data_parallel_group([loss])
+
+ output_dict = {"lm loss": averaged_loss[0]}
+ if args.return_logits:
+ output_dict.update({"logits": logits})
+ return loss, output_dict
+
+ if accelerator.state.megatron_lm_plugin.custom_loss_function is not None:
+ return accelerator.state.megatron_lm_plugin.custom_loss_function
+ return loss_func
+
+ def get_forward_step_func(self):
+ def forward_step(data_iterator, model):
+ """Forward step."""
+ # Get the batch.
+ tokens, labels, loss_mask, attention_mask, position_ids = self.get_batch(data_iterator)
+ output_tensor = model(tokens, position_ids, attention_mask, labels=labels)
+
+ return output_tensor, partial(self.loss_func, loss_mask)
+
+ return forward_step
+
+
+class T5TrainStep(AbstractTrainStep):
+ """
+ T5 train step class.
+
+ Args:
+ args (`argparse.Namespace`): Megatron-LM arguments.
+ """
+
+ def __init__(self, accelerator, args):
+ super().__init__("T5TrainStep")
+ self.get_batch = self.get_batch_func(accelerator, args.megatron_dataset_flag)
+ self.loss_func = self.get_loss_func(accelerator)
+ self.forward_step = self.get_forward_step_func()
+ if not args.model_return_dict:
+ self.model_output_class = None
+ else:
+ from transformers.modeling_outputs import Seq2SeqLMOutput
+
+ self.model_output_class = Seq2SeqLMOutput
+
+ @staticmethod
+ def attn_mask_postprocess(attention_mask):
+ # We create a 3D attention mask from a 2D tensor mask.
+ # [b, 1, s]
+ attention_mask_b1s = attention_mask.unsqueeze(1)
+ # [b, s, 1]
+ attention_mask_bs1 = attention_mask.unsqueeze(2)
+ # [b, s, s]
+ attention_mask_bss = attention_mask_b1s * attention_mask_bs1
+ # Convert attention mask to binary:
+ extended_attention_mask = attention_mask_bss < 0.5
+ return extended_attention_mask
+
+ @staticmethod
+ def get_decoder_mask(seq_length, device):
+ attention_mask = torch.tril(torch.ones((1, seq_length, seq_length), device=device))
+ attention_mask = attention_mask < 0.5
+ return attention_mask
+
+ @staticmethod
+ def get_enc_dec_mask(attention_mask, dec_seq_length, device):
+ batch_size, _ = attention_mask.shape
+ # We create a 3D attention mask from a 2D tensor mask.
+ # [b, 1, s]
+ attention_mask_b1s = attention_mask.unsqueeze(1)
+ # [b, s, 1]
+ attention_mask_bs1 = torch.ones((batch_size, dec_seq_length, 1), device=device)
+ attention_mask_bss = attention_mask_bs1 * attention_mask_b1s
+ extended_attention_mask = attention_mask_bss < 0.5
+ return extended_attention_mask
+
+ def get_batch_func(self, accelerator, megatron_dataset_flag):
+ def get_batch_megatron(data_iterator):
+ """Build the batch."""
+
+ keys = ["text_enc", "text_dec", "labels", "loss_mask", "enc_mask", "dec_mask", "enc_dec_mask"]
+ datatype = torch.int64
+
+ # Broadcast data.
+ if data_iterator is not None:
+ data = next(data_iterator)
+ else:
+ data = None
+ data_b = tensor_parallel.broadcast_data(keys, data, datatype)
+
+ # Unpack.
+ tokens_enc = data_b["text_enc"].long()
+ tokens_dec = data_b["text_dec"].long()
+ labels = data_b["labels"].long()
+ loss_mask = data_b["loss_mask"].float()
+
+ enc_mask = data_b["enc_mask"] < 0.5
+ dec_mask = data_b["dec_mask"] < 0.5
+ enc_dec_mask = data_b["enc_dec_mask"] < 0.5
+
+ return tokens_enc, tokens_dec, loss_mask, labels, enc_mask, dec_mask, enc_dec_mask
+
+ def get_batch_transformer(data_iterator):
+ """Build the batch."""
+ data = next(data_iterator)
+ data = send_to_device(data, torch.cuda.current_device())
+
+ tokens_enc = data["input_ids"].long()
+ labels = data["labels"].long()
+ loss_mask = (labels != -100).to(torch.float)
+ if "decoder_input_ids" in data:
+ tokens_dec = data["decoder_input_ids"].long()
+ else:
+ tokens_dec = labels.new_zeros(labels.shape, device=labels.device, dtype=torch.long)
+ tokens_dec[..., 1:] = labels[..., :-1].clone()
+ tokens_dec[..., 0] = 0
+ tokens_dec.masked_fill_(tokens_dec == -100, 0)
+ enc_mask = T5TrainStep.attn_mask_postprocess(data["attention_mask"].long())
+ dec_mask = T5TrainStep.get_decoder_mask(tokens_dec.shape[1], tokens_dec.device)
+ enc_dec_mask = T5TrainStep.get_enc_dec_mask(
+ data["attention_mask"].long(), tokens_dec.shape[1], tokens_dec.device
+ )
+
+ return tokens_enc, tokens_dec, loss_mask, labels, enc_mask, dec_mask, enc_dec_mask
+
+ if accelerator.state.megatron_lm_plugin.custom_get_batch_function is not None:
+ return accelerator.state.megatron_lm_plugin.custom_get_batch_function
+ if megatron_dataset_flag:
+ try:
+ # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source
+ from pretrain_t5 import get_batch
+
+ return get_batch
+ except ImportError:
+ pass
+ return get_batch_megatron
+ else:
+ return get_batch_transformer
+
+ def get_loss_func(self, accelerator):
+ def loss_func(loss_mask, output_tensor):
+ lm_loss_ = output_tensor.float()
+ lm_loss = torch.sum(lm_loss_.view(-1) * loss_mask.reshape(-1)) / loss_mask.sum()
+
+ loss = lm_loss
+ averaged_losses = average_losses_across_data_parallel_group([lm_loss])
+
+ return loss, {"lm loss": averaged_losses[0]}
+
+ if accelerator.state.megatron_lm_plugin.custom_loss_function is not None:
+ return accelerator.state.megatron_lm_plugin.custom_loss_function
+ return loss_func
+
+ def get_forward_step_func(self):
+ def forward_step(data_iterator, model):
+ """Forward step."""
+ # Get the batch.
+ tokens_enc, tokens_dec, loss_mask, lm_labels, enc_mask, dec_mask, enc_dec_mask = self.get_batch(
+ data_iterator
+ )
+ # Forward model lm_labels
+ output_tensor = model(
+ tokens_enc, tokens_dec, enc_mask, dec_mask, enc_dec_mask, tokentype_ids=None, lm_labels=lm_labels
+ )
+
+ return output_tensor, partial(self.loss_func, loss_mask)
+
+ return forward_step
+
+
+def finish_mpu_init():
+ # torch.distributed initialization
+ args = get_args()
+ # Pytorch distributed.
+ _initialize_distributed()
+
+ # Random seeds for reproducibility.
+ if args.rank == 0:
+ print(f"> setting random seeds to {args.seed} ...")
+ _set_random_seed(args.seed, args.data_parallel_random_init)
+
+
+# intialize megatron setup
+def initialize(accelerator, extra_args_provider=None, args_defaults={}):
+ accelerator.print("Initializing Megatron-LM")
+ assert torch.cuda.is_available(), "Megatron requires CUDA."
+
+ # Parse arguments
+ args = parse_args(extra_args_provider, ignore_unknown_args=True)
+
+ # Set defaults
+ for key, value in args_defaults.items():
+ if getattr(args, key, None) is not None:
+ if args.rank == 0:
+ print(
+ f"WARNING: overriding default arguments for " f"{key}:{getattr(args, key)} with {key}:{value}",
+ flush=True,
+ )
+ setattr(args, key, value)
+
+ if args.use_checkpoint_args or args_defaults.get("use_checkpoint_args", False):
+ assert args.load is not None, "--use-checkpoints-args requires --load argument"
+ load_args_from_checkpoint(args)
+
+ validate_args(args)
+
+ # set global args, build tokenizer, and set adlr-autoresume,
+ # tensorboard-writer, and timers.
+ set_global_variables(args)
+
+ # Megatron's MPU is the master. Complete initialization right away.
+ finish_mpu_init()
+
+ # Autoresume.
+ _init_autoresume()
+
+ # Compile dependencies.
+ _compile_dependencies()
+
+ # Set pytorch JIT layer fusion options and warmup JIT functions.
+ set_jit_fusion_options()
+ args = get_args()
+ if getattr(args, "padded_vocab_size", None) is None:
+ args.padded_vocab_size = _vocab_size_with_padding(args.orig_vocab_size, args)
+ if args.model_type_name == "bert" and args.pretraining_flag and args.num_labels == 2:
+ args.bert_binary_head = True
+ else:
+ args.bert_binary_head = False
+ args.iteration = 0
+
+
+class MegatronEngine(torch.nn.Module):
+ """
+ Megatron-LM model wrapper
+
+ Args:
+ accelerator (:class:`~accelerate.Accelerator`): The accelerator object to use.
+ model: Megatron-LM model
+ optimizer: Megatron-LM optimizer
+ lr_scheduler: Megatron-LM lr scheduler
+ """
+
+ def __init__(self, accelerator, model, optimizer, scheduler):
+ super().__init__()
+ self.module = model
+ self.base_model = model[0]
+ self.optimizer = optimizer
+ self.scheduler = scheduler
+ args = get_args()
+ if accelerator.state.megatron_lm_plugin.custom_train_step_class is not None:
+ self.train_step_handler = accelerator.state.megatron_lm_plugin.custom_train_step_class(
+ args, **accelerator.state.megatron_lm_plugin.custom_train_step_kwargs
+ )
+ elif args.model_type_name == "bert":
+ self.train_step_handler = BertTrainStep(accelerator, args)
+ elif args.model_type_name == "gpt":
+ self.train_step_handler = GPTTrainStep(accelerator, args)
+ elif args.model_type_name == "t5":
+ self.train_step_handler = T5TrainStep(accelerator, args)
+ else:
+ raise ValueError(f"Unsupported model type: {args.model_type_name}")
+ self.optimizer.skipped_iter = False
+
+ # Tracking loss.
+ self.total_loss_dict = {}
+ self.eval_total_loss_dict = {}
+ self.iteration = 0
+ self.report_memory_flag = True
+ self.num_floating_point_operations_so_far = 0
+ self.module_config = None
+ if args.tensorboard_dir is not None:
+ write_args_to_tensorboard()
+
+ def get_module_config(self):
+ args = get_args()
+ config = get_model_config(self.module[0])
+ # Setup some training config params
+ config.grad_scale_func = self.optimizer.scale_loss
+ if isinstance(self.module[0], LocalDDP) and args.overlap_grad_reduce:
+ assert config.no_sync_func is None, (
+ "When overlap_grad_reduce is True, config.no_sync_func must be None; "
+ "a custom no_sync_func is not supported when overlapping grad-reduce"
+ )
+ config.no_sync_func = [model_chunk.no_sync for model_chunk in self.module]
+ if len(self.module) == 1:
+ config.no_sync_func = config.no_sync_func[0]
+ if args.delay_grad_reduce:
+ config.grad_sync_func = [model_chunk.start_grad_sync for model_chunk in self.module]
+ if len(self.module) == 1:
+ config.grad_sync_func = config.grad_sync_func[0]
+ if args.overlap_param_gather and args.delay_param_gather:
+ config.param_sync_func = [
+ lambda x: self.optimizer.finish_param_sync(model_index, x) for model_index in range(len(self.module))
+ ]
+ if len(self.module) == 1:
+ config.param_sync_func = config.param_sync_func[0]
+ config.finalize_model_grads_func = finalize_model_grads
+ return config
+
+ def train(self):
+ for model_module in self.module:
+ model_module.train()
+
+ if self.module_config is None:
+ self.module_config = self.get_module_config()
+
+ self.log_eval_results()
+
+ def eval(self):
+ for model_module in self.module:
+ model_module.eval()
+
+ if self.module_config is None:
+ self.module_config = self.get_module_config()
+
+ def get_batch_data_iterator(self, batch_data):
+ args = get_args()
+ data_chunks = []
+ if len(batch_data) > 0:
+ if args.num_micro_batches > 1:
+ for i in range(0, args.num_micro_batches):
+ data_chunks.append(
+ {
+ k: v[i * args.micro_batch_size : (i + 1) * args.micro_batch_size]
+ for k, v in batch_data.items()
+ }
+ )
+ else:
+ data_chunks = [batch_data]
+
+ if len(self.module) > 1:
+ batch_data_iterator = (
+ [iter(data_chunks) for _ in range(len(self.module))]
+ if len(batch_data) > 0
+ else [None] * len(self.module)
+ )
+ else:
+ batch_data_iterator = iter(data_chunks) if len(batch_data) > 0 else None
+ return batch_data_iterator
+
+ def train_step(self, **batch_data):
+ """
+ Training step for Megatron-LM
+
+ Args:
+ batch_data (:obj:`dict`): The batch data to train on.
+ """
+
+ batch_data_iterator = self.get_batch_data_iterator(batch_data)
+
+ loss_reduced, skipped_iter, grad_norm, num_zeros_in_grad = train_step(
+ forward_step_func=self.train_step_handler.forward_step,
+ data_iterator=batch_data_iterator,
+ model=self.module,
+ optimizer=self.optimizer,
+ opt_param_scheduler=self.scheduler,
+ config=self.module_config,
+ )
+
+ self.optimizer.skipped_iter = skipped_iter == 1
+
+ return loss_reduced, skipped_iter, grad_norm, num_zeros_in_grad
+
+ def eval_step(self, **batch_data):
+ """
+ Evaluation step for Megatron-LM
+
+ Args:
+ batch_data (:obj:`dict`): The batch data to evaluate on.
+ """
+
+ args = get_args()
+ batch_data_iterator = self.get_batch_data_iterator(batch_data)
+ forward_backward_func = get_forward_backward_func()
+ loss_dicts = forward_backward_func(
+ forward_step_func=self.train_step_handler.forward_step,
+ data_iterator=batch_data_iterator,
+ model=self.module,
+ num_microbatches=get_num_microbatches(),
+ seq_length=args.seq_length,
+ micro_batch_size=args.micro_batch_size,
+ forward_only=True,
+ )
+ # Empty unused memory
+ if args.empty_unused_memory_level >= 1:
+ torch.cuda.empty_cache()
+
+ args.consumed_valid_samples += (
+ mpu.get_data_parallel_world_size() * args.micro_batch_size * get_num_microbatches()
+ )
+
+ if mpu.is_pipeline_last_stage(ignore_virtual=True):
+ # Average loss across microbatches.
+ loss_reduced = {}
+ for key in loss_dicts[0]:
+ losses_reduced_for_key = [x[key] for x in loss_dicts]
+ if len(losses_reduced_for_key[0].shape) == 0:
+ loss_reduced[key] = sum(losses_reduced_for_key) / len(losses_reduced_for_key)
+ else:
+ loss_reduced[key] = torch.concat(losses_reduced_for_key)
+ return loss_reduced
+ return {}
+
+ def forward(self, **batch_data):
+ # During training, we use train_step()
+ # model(**batch_data) performs following operations by delegating it to `self.train_step`:
+ # 1. Prepare **batch_data for Tendor, Pipeline and Model Parallelism
+ # 2. Set grad to zero.
+ # 3. forward pass and backward pass using Pipeline Parallelism
+ # 4. Empty unused memory.
+ # 5. Reduce gradients.
+ # 6. Update parameters.
+ # 7. Gather params when using Distributed Optimizer (Data Parallelism).
+ # 8. Update learning rate if scheduler is specified.
+ # 9. Empty unused memory.
+ # 10. Average loss across microbatches and across DP ranks.
+ #
+ # During evaluation, we use eval_step()
+ args = get_args()
+ if self.module[0].training:
+ loss_dict, skipped_iter, grad_norm, num_zeros_in_grad = self.train_step(**batch_data)
+ self.iteration += 1
+ batch_size = mpu.get_data_parallel_world_size() * args.micro_batch_size * get_num_microbatches()
+ args.consumed_train_samples += batch_size
+ self.num_floating_point_operations_so_far += num_floating_point_operations(args, batch_size)
+ if args.tensorboard_dir is not None:
+ # Logging.
+ loss_scale = self.optimizer.get_loss_scale().item()
+ params_norm = None
+ if args.log_params_norm:
+ params_norm = calc_params_l2_norm(self.model)
+ self.report_memory_flag = training_log(
+ loss_dict,
+ self.total_loss_dict,
+ self.optimizer.param_groups[0]["lr"],
+ self.iteration,
+ loss_scale,
+ self.report_memory_flag,
+ skipped_iter,
+ grad_norm,
+ params_norm,
+ num_zeros_in_grad,
+ )
+ else:
+ loss_dict = self.eval_step(**batch_data)
+ if args.tensorboard_dir is not None:
+ for key in loss_dict:
+ self.eval_total_loss_dict[key] = (
+ self.eval_total_loss_dict.get(key, torch.cuda.FloatTensor([0.0])) + loss_dict[key]
+ )
+ self.eval_total_loss_dict[key + "_num_iters"] = self.eval_total_loss_dict.get(
+ key + "_num_iters", torch.cuda.FloatTensor([0.0])
+ ) + torch.cuda.FloatTensor([1.0])
+
+ loss = torch.tensor(0.0, device=torch.cuda.current_device())
+ for key in loss_dict:
+ if len(loss_dict[key].shape) == 0:
+ loss += loss_dict[key]
+
+ logits = None
+ if "logits" in loss_dict:
+ logits = loss_dict["logits"]
+ if self.train_step_handler.model_output_class is not None:
+ return self.train_step_handler.model_output_class(loss=loss, logits=logits)
+ return loss
+
+ def log_eval_results(self):
+ args = get_args()
+ if args.tensorboard_dir is None or self.iteration == 0:
+ return
+ args = get_args()
+ writer = get_tensorboard_writer()
+ string = f"validation loss at iteration {self.iteration} | "
+ for key in self.eval_total_loss_dict:
+ if key.endswith("_num_iters"):
+ continue
+ value = self.eval_total_loss_dict[key] / self.eval_total_loss_dict[key + "_num_iters"]
+ string += f"{key} value: {value} | "
+ ppl = math.exp(min(20, value.item()))
+ if args.pretraining_flag:
+ string += f"{key} PPL: {ppl} | "
+ if writer:
+ writer.add_scalar(f"{key} validation", value.item(), self.iteration)
+ if args.pretraining_flag:
+ writer.add_scalar(f"{key} validation ppl", ppl, self.iteration)
+
+ length = len(string) + 1
+ print_rank_last("-" * length)
+ print_rank_last(string)
+ print_rank_last("-" * length)
+ self.eval_total_loss_dict = {}
+
+ def save_checkpoint(self, output_dir):
+ self.log_eval_results()
+ args = get_args()
+ args.save = output_dir
+ torch.distributed.barrier()
+ save_checkpoint(
+ self.iteration,
+ self.module,
+ self.optimizer,
+ self.scheduler,
+ num_floating_point_operations_so_far=self.num_floating_point_operations_so_far,
+ )
+ torch.distributed.barrier()
+
+ def load_checkpoint(self, input_dir):
+ args = get_args()
+ args.load = input_dir
+ args.consumed_train_samples = 0
+ args.consumed_valid_samples = 0
+ torch.distributed.barrier()
+ iteration, num_floating_point_operations_so_far = load_checkpoint(self.module, self.optimizer, self.scheduler)
+ torch.distributed.barrier()
+ self.iteration = iteration
+ self.num_floating_point_operations_so_far = num_floating_point_operations_so_far
+ if args.fp16 and self.iteration == 0:
+ self.optimizer.reload_model_params()
+
+ def megatron_generate(
+ self,
+ inputs,
+ attention_mask=None,
+ max_length=None,
+ max_new_tokens=None,
+ num_beams=None,
+ temperature=None,
+ top_k=None,
+ top_p=None,
+ length_penalty=None,
+ **kwargs,
+ ):
+ """
+ Generate method for GPT2 model. This method is used for inference. Supports both greedy and beam search along
+ with sampling. Refer the Megatron-LM repo for more details
+
+ Args:
+ inputs (torch.Tensor): input ids
+ attention_mask (torch.Tensor, optional): attention mask. Defaults to None.
+ max_length (int, optional): max length of the generated sequence. Defaults to None.
+ Either this or max_new_tokens should be provided.
+ max_new_tokens (int, optional): max number of tokens to be generated. Defaults to None.
+ Either this or max_length should be provided.
+ num_beams (int, optional): number of beams to use for beam search. Defaults to None.
+ temperature (float, optional): temperature for sampling. Defaults to 1.0.
+ top_k (int, optional): top k tokens to consider for sampling. Defaults to 0.0.
+ top_p (float, optional): tokens in top p probability are considered for sampling. Defaults to 0.0.
+ length_penalty (float, optional): length penalty for beam search. Defaults to None.
+ kwargs: additional key-value arguments
+ """
+
+ # checking if required arguments are passed
+ args = get_args()
+ if args.model_type_name != "gpt":
+ raise NotImplementedError("Generate method is not implemented for this model")
+
+ if args.data_parallel_size > 1:
+ raise ValueError("Generate method requires data parallelism to be 1")
+
+ if args.sequence_parallel:
+ raise ValueError("Generate method requires sequence parallelism to be False")
+
+ if args.recompute_granularity is not None:
+ raise ValueError("Checkpoint activations cannot be set for inference")
+
+ if args.vocab_file is None:
+ raise ValueError("Vocab file is required for inference")
+
+ # Prepare inputs
+ if max_length is None and max_new_tokens is None:
+ raise ValueError("`max_length` or `max_new_tokens` are required for inference")
+
+ if temperature is None:
+ temperature = 1.0
+ elif not (0.0 < temperature <= 100.0):
+ raise ValueError("temperature must be a positive number less than or equal to 100.0")
+
+ if top_k is None:
+ top_k = 0
+ elif not (0 <= top_k <= 1000):
+ raise ValueError("top_k must be a positive number less than or equal to 1000")
+
+ if top_p is None:
+ top_p = 0.0
+ elif top_p > 0.0 and top_k > 0.0:
+ raise ValueError("top_p and top_k sampling cannot be set together")
+ else:
+ if not (0.0 <= top_p <= 1.0):
+ raise ValueError("top_p must be less than or equal to 1.0")
+
+ top_p_decay = kwargs.get("top_p_decay", 0.0)
+ if not (0.0 <= top_p_decay <= 1.0):
+ raise ValueError("top_p_decay must be less than or equal to 1.0")
+
+ top_p_bound = kwargs.get("top_p_bound", 0.0)
+ if not (0.0 <= top_p_bound <= 1.0):
+ raise ValueError("top_p_bound must be less than or equal to 1.0")
+
+ add_BOS = kwargs.get("add_BOS", False)
+ if not (isinstance(add_BOS, bool)):
+ raise ValueError("add_BOS must be a boolean")
+
+ beam_width = num_beams
+ if beam_width is not None:
+ if not isinstance(beam_width, int):
+ raise ValueError("beam_width must be an integer")
+ if beam_width < 1:
+ raise ValueError("beam_width must be greater than 0")
+ if inputs.shape[0] > 1:
+ return "When doing beam_search, batch size must be 1"
+
+ tokenizer = get_tokenizer()
+
+ stop_token = kwargs.get("stop_token", tokenizer.eod)
+ if stop_token is not None:
+ if not isinstance(stop_token, int):
+ raise ValueError("stop_token must be an integer")
+
+ if length_penalty is None:
+ length_penalty = 1.0
+
+ sizes_list = None
+ prompts_tokens_tensor = None
+ prompts_length_tensor = None
+ if torch.distributed.get_rank() == 0:
+ # Get the prompts length.
+ if attention_mask is None:
+ prompts_length_tensor = torch.cuda.LongTensor([inputs.shape[1]] * inputs.shape[0])
+ else:
+ prompts_length_tensor = attention_mask.sum(axis=-1).cuda()
+
+ if max_new_tokens is None:
+ max_new_tokens = max_length - inputs.shape[1]
+ if max_new_tokens <= 0:
+ raise ValueError("max_new_tokens must be greater than 0")
+
+ if add_BOS:
+ max_length = max_new_tokens + inputs.shape[1] + 1
+ # making sure that `max_length` is a multiple of 4 to leverage fused kernels
+ max_length = 4 * math.ceil(max_length / 4)
+ max_new_tokens = max_length - (inputs.shape[1] + 1)
+ padding = torch.cuda.LongTensor([[tokenizer.eod] * max_new_tokens] * inputs.shape[0])
+ prompts_tokens_tensor = torch.concat(
+ [torch.unsqueeze(padding[:, 0], axis=-1), inputs.cuda(), padding], axis=-1
+ )
+ else:
+ # making sure that `max_length` is a multiple of 4 to leverage fused kernels
+ max_length = max_new_tokens + inputs.shape[1]
+ max_length = 4 * math.ceil(max_length / 4)
+ max_new_tokens = max_length - inputs.shape[1]
+ padding = torch.cuda.LongTensor([[tokenizer.eod] * max_new_tokens] * inputs.shape[0])
+ prompts_tokens_tensor = torch.concat([inputs.cuda(), padding], axis=-1)
+
+ # We need the sizes of these tensors for the boradcast
+ sizes_list = [
+ prompts_tokens_tensor.size(0), # Batch size
+ prompts_tokens_tensor.size(1),
+ ] # Sequence lenght
+
+ # First, broadcast the sizes.
+ sizes_tensor = broadcast_int_list(2, int_list=sizes_list, rank=0)
+
+ # Now that we have the sizes, we can boradcast the tokens
+ # and length tensors.
+ sizes = sizes_tensor.tolist()
+ context_tokens_tensor = broadcast_tensor(sizes, torch.int64, tensor=prompts_tokens_tensor, rank=0)
+ context_length_tensor = broadcast_tensor(sizes[0], torch.int64, tensor=prompts_length_tensor, rank=0)
+
+ # Run the inference
+ random_seed = kwargs.get("random_seed", 0)
+ torch.random.manual_seed(random_seed)
+ unwrapped_model = unwrap_model(self.base_model, (torchDDP, LocalDDP, Float16Module))
+ if beam_width is not None:
+ tokens, _ = beam_search_and_return_on_first_stage(
+ unwrapped_model,
+ context_tokens_tensor,
+ context_length_tensor,
+ beam_width,
+ stop_token=stop_token,
+ num_return_gen=1,
+ length_penalty=length_penalty,
+ )
+ else:
+ tokens, _, _ = generate_tokens_probs_and_return_on_first_stage(
+ unwrapped_model,
+ context_tokens_tensor,
+ context_length_tensor,
+ return_output_log_probs=False,
+ top_k=top_k,
+ top_p=top_p,
+ top_p_decay=top_p_decay,
+ top_p_bound=top_p_bound,
+ temperature=temperature,
+ use_eod_token_for_early_termination=True,
+ )
+ return tokens
+
+
+# other utilities
+def avg_losses_across_data_parallel_group(losses):
+ """
+ Average losses across data parallel group.
+
+ Args:
+ losses (List[Tensor]): List of losses to average across data parallel group.
+ """
+
+ return average_losses_across_data_parallel_group(losses)
+
+
+def gather_across_data_parallel_groups(tensor):
+ """
+ Recursively gather tensor in a nested list/tuple/dictionary of tensors from data parallel ranks.
+
+ Args:
+ tensor (nested list/tuple/dictionary of `torch.Tensor`):
+ The data to gather across data parallel ranks.
+
+ """
+
+ def _gpu_gather_one(tensor):
+ if tensor.ndim == 0:
+ tensor = tensor.clone()[None]
+ output_tensors = [
+ torch.empty_like(tensor)
+ for _ in range(torch.distributed.get_world_size(group=mpu.get_data_parallel_group()))
+ ]
+ torch.distributed.all_gather(output_tensors, tensor, group=mpu.get_data_parallel_group())
+ return torch.cat(output_tensors, dim=0)
+
+ return recursively_apply(_gpu_gather_one, tensor, error_on_other_type=True)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/memory.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fdde754417ae5339cb379e7e98de96fea8608fb
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/memory.py
@@ -0,0 +1,178 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+A collection of utilities for ensuring that training can always occur. Heavily influenced by the
+[toma](https://github.com/BlackHC/toma) library.
+"""
+
+import functools
+import gc
+import importlib
+import inspect
+import warnings
+
+import torch
+
+from .imports import (
+ is_cuda_available,
+ is_ipex_available,
+ is_mlu_available,
+ is_mps_available,
+ is_musa_available,
+ is_npu_available,
+ is_xpu_available,
+)
+from .versions import compare_versions
+
+
+def clear_device_cache(garbage_collection=False):
+ """
+ Clears the device cache by calling `torch.{backend}.empty_cache`. Can also run `gc.collect()`, but do note that
+ this is a *considerable* slowdown and should be used sparingly.
+ """
+ if garbage_collection:
+ gc.collect()
+
+ if is_xpu_available():
+ torch.xpu.empty_cache()
+ elif is_mlu_available():
+ torch.mlu.empty_cache()
+ elif is_musa_available():
+ torch.musa.empty_cache()
+ elif is_npu_available():
+ torch.npu.empty_cache()
+ elif is_mps_available(min_version="2.0"):
+ torch.mps.empty_cache()
+ elif is_cuda_available():
+ torch.cuda.empty_cache()
+
+
+def release_memory(*objects):
+ """
+ Releases memory from `objects` by setting them to `None` and calls `gc.collect()` and `torch.cuda.empty_cache()`.
+ Returned objects should be reassigned to the same variables.
+
+ Args:
+ objects (`Iterable`):
+ An iterable of objects
+ Returns:
+ A list of `None` objects to replace `objects`
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from accelerate.utils import release_memory
+
+ >>> a = torch.ones(1000, 1000).cuda()
+ >>> b = torch.ones(1000, 1000).cuda()
+ >>> a, b = release_memory(a, b)
+ ```
+ """
+ if not isinstance(objects, list):
+ objects = list(objects)
+ for i in range(len(objects)):
+ objects[i] = None
+ clear_device_cache(garbage_collection=True)
+ return objects
+
+
+def should_reduce_batch_size(exception: Exception) -> bool:
+ """
+ Checks if `exception` relates to CUDA out-of-memory, CUDNN not supported, or CPU out-of-memory
+
+ Args:
+ exception (`Exception`):
+ An exception
+ """
+ _statements = [
+ "CUDA out of memory.", # CUDA OOM
+ "cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.", # CUDNN SNAFU
+ "DefaultCPUAllocator: can't allocate memory", # CPU OOM
+ ]
+ if isinstance(exception, RuntimeError) and len(exception.args) == 1:
+ return any(err in exception.args[0] for err in _statements)
+ return False
+
+
+def find_executable_batch_size(function: callable = None, starting_batch_size: int = 128):
+ """
+ A basic decorator that will try to execute `function`. If it fails from exceptions related to out-of-memory or
+ CUDNN, the batch size is cut in half and passed to `function`
+
+ `function` must take in a `batch_size` parameter as its first argument.
+
+ Args:
+ function (`callable`, *optional*):
+ A function to wrap
+ starting_batch_size (`int`, *optional*):
+ The batch size to try and fit into memory
+
+ Example:
+
+ ```python
+ >>> from accelerate.utils import find_executable_batch_size
+
+
+ >>> @find_executable_batch_size(starting_batch_size=128)
+ ... def train(batch_size, model, optimizer):
+ ... ...
+
+
+ >>> train(model, optimizer)
+ ```
+ """
+ if function is None:
+ return functools.partial(find_executable_batch_size, starting_batch_size=starting_batch_size)
+
+ batch_size = starting_batch_size
+
+ def decorator(*args, **kwargs):
+ nonlocal batch_size
+ clear_device_cache(garbage_collection=True)
+ params = list(inspect.signature(function).parameters.keys())
+ # Guard against user error
+ if len(params) < (len(args) + 1):
+ arg_str = ", ".join([f"{arg}={value}" for arg, value in zip(params[1:], args[1:])])
+ raise TypeError(
+ f"Batch size was passed into `{function.__name__}` as the first argument when called."
+ f"Remove this as the decorator already does so: `{function.__name__}({arg_str})`"
+ )
+ while True:
+ if batch_size == 0:
+ raise RuntimeError("No executable batch size found, reached zero.")
+ try:
+ return function(batch_size, *args, **kwargs)
+ except Exception as e:
+ if should_reduce_batch_size(e):
+ clear_device_cache(garbage_collection=True)
+ batch_size //= 2
+ else:
+ raise
+
+ return decorator
+
+
+def get_xpu_available_memory(device_index: int):
+ if is_ipex_available():
+ ipex_version = importlib.metadata.version("intel_extension_for_pytorch")
+ if compare_versions(ipex_version, ">=", "2.5"):
+ from intel_extension_for_pytorch.xpu import mem_get_info
+
+ return mem_get_info(device_index)[0]
+ warnings.warn(
+ "The XPU `mem_get_info` API is available in IPEX version >=2.5. The current returned available memory is incorrect. Please consider upgrading your IPEX version."
+ )
+ return torch.xpu.max_memory_allocated(device_index)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/modeling.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/modeling.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4230c55994e1a8acd6f00a9083254d84ce059b2
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/modeling.py
@@ -0,0 +1,1873 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import contextlib
+import gc
+import inspect
+import json
+import logging
+import os
+import re
+import shutil
+import tempfile
+import warnings
+from collections import OrderedDict, defaultdict
+from typing import Dict, List, Optional, Set, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from ..state import AcceleratorState
+from .constants import SAFE_WEIGHTS_NAME, WEIGHTS_NAME
+from .dataclasses import AutocastKwargs, CustomDtype, DistributedType
+from .imports import (
+ is_mlu_available,
+ is_mps_available,
+ is_musa_available,
+ is_npu_available,
+ is_peft_available,
+ is_torch_xla_available,
+ is_xpu_available,
+)
+from .memory import clear_device_cache, get_xpu_available_memory
+from .offload import load_offloaded_weight, offload_weight, save_offload_index
+from .tqdm import is_tqdm_available, tqdm
+from .versions import compare_versions, is_torch_version
+
+
+if is_npu_available(check_device=False):
+ import torch_npu # noqa: F401
+
+if is_mlu_available(check_device=False):
+ import torch_mlu # noqa: F401
+
+if is_musa_available(check_device=False):
+ import torch_musa # noqa: F401
+
+from safetensors import safe_open
+from safetensors.torch import load_file as safe_load_file
+
+
+WEIGHTS_INDEX_NAME = "pytorch_model.bin.index.json"
+
+logger = logging.getLogger(__name__)
+
+
+def is_peft_model(model):
+ from .other import extract_model_from_parallel
+
+ if is_peft_available():
+ from peft import PeftModel
+
+ return is_peft_available() and isinstance(extract_model_from_parallel(model), PeftModel)
+
+
+def check_device_same(first_device, second_device):
+ """
+ Utility method to check if two `torch` devices are similar. When dealing with CUDA devices, torch throws `False`
+ for `torch.device("cuda") == torch.device("cuda:0")` whereas they should be the same
+
+ Args:
+ first_device (`torch.device`):
+ First device to check
+ second_device (`torch.device`):
+ Second device to check
+ """
+ if first_device.type != second_device.type:
+ return False
+
+ if first_device.type == "cuda" and first_device.index is None:
+ # In case the first_device is a cuda device and have
+ # the index attribute set to `None`, default it to `0`
+ first_device = torch.device("cuda", index=0)
+
+ if second_device.type == "cuda" and second_device.index is None:
+ # In case the second_device is a cuda device and have
+ # the index attribute set to `None`, default it to `0`
+ second_device = torch.device("cuda", index=0)
+
+ return first_device == second_device
+
+
+def convert_file_size_to_int(size: Union[int, str]):
+ """
+ Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes).
+
+ Args:
+ size (`int` or `str`): The size to convert. Will be directly returned if an `int`.
+
+ Example:
+
+ ```py
+ >>> convert_file_size_to_int("1MiB")
+ 1048576
+ ```
+ """
+ mem_size = -1
+ err_msg = (
+ f"`size` {size} is not in a valid format. Use an integer for bytes, or a string with an unit (like '5.0GB')."
+ )
+ try:
+ if isinstance(size, int):
+ mem_size = size
+ elif size.upper().endswith("GIB"):
+ mem_size = int(float(size[:-3]) * (2**30))
+ elif size.upper().endswith("MIB"):
+ mem_size = int(float(size[:-3]) * (2**20))
+ elif size.upper().endswith("KIB"):
+ mem_size = int(float(size[:-3]) * (2**10))
+ elif size.upper().endswith("GB"):
+ int_size = int(float(size[:-2]) * (10**9))
+ mem_size = int_size // 8 if size.endswith("b") else int_size
+ elif size.upper().endswith("MB"):
+ int_size = int(float(size[:-2]) * (10**6))
+ mem_size = int_size // 8 if size.endswith("b") else int_size
+ elif size.upper().endswith("KB"):
+ int_size = int(float(size[:-2]) * (10**3))
+ mem_size = int_size // 8 if size.endswith("b") else int_size
+ except ValueError:
+ raise ValueError(err_msg)
+
+ if mem_size < 0:
+ raise ValueError(err_msg)
+ return mem_size
+
+
+def dtype_byte_size(dtype: torch.dtype):
+ """
+ Returns the size (in bytes) occupied by one parameter of type `dtype`.
+
+ Example:
+
+ ```py
+ >>> dtype_byte_size(torch.float32)
+ 4
+ ```
+ """
+ if dtype == torch.bool:
+ return 1 / 8
+ elif dtype == CustomDtype.INT2:
+ return 1 / 4
+ elif dtype == CustomDtype.INT4:
+ return 1 / 2
+ elif dtype == CustomDtype.FP8:
+ return 1
+ elif is_torch_version(">=", "2.1.0") and dtype == torch.float8_e4m3fn:
+ return 1
+ bit_search = re.search(r"[^\d](\d+)$", str(dtype))
+ if bit_search is None:
+ raise ValueError(f"`dtype` is not a valid dtype: {dtype}.")
+ bit_size = int(bit_search.groups()[0])
+ return bit_size // 8
+
+
+def id_tensor_storage(tensor: torch.Tensor) -> Tuple[torch.device, int, int]:
+ """
+ Unique identifier to a tensor storage. Multiple different tensors can share the same underlying storage. For
+ example, "meta" tensors all share the same storage, and thus their identifier will all be equal. This identifier is
+ guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with
+ non-overlapping lifetimes may have the same id.
+ """
+ _SIZE = {
+ torch.int64: 8,
+ torch.float32: 4,
+ torch.int32: 4,
+ torch.bfloat16: 2,
+ torch.float16: 2,
+ torch.int16: 2,
+ torch.uint8: 1,
+ torch.int8: 1,
+ torch.bool: 1,
+ torch.float64: 8,
+ }
+ try:
+ storage_ptr = tensor.untyped_storage().data_ptr()
+ storage_size = tensor.untyped_storage().nbytes()
+ except Exception:
+ # Fallback for torch==1.10
+ try:
+ storage_ptr = tensor.storage().data_ptr()
+ storage_size = tensor.storage().size() * _SIZE[tensor.dtype]
+ except NotImplementedError:
+ # Fallback for meta storage
+ storage_ptr = 0
+ # On torch >=2.0 this is the tensor size
+ storage_size = tensor.nelement() * _SIZE[tensor.dtype]
+
+ return tensor.device, storage_ptr, storage_size
+
+
+def set_module_tensor_to_device(
+ module: nn.Module,
+ tensor_name: str,
+ device: Union[int, str, torch.device],
+ value: Optional[torch.Tensor] = None,
+ dtype: Optional[Union[str, torch.dtype]] = None,
+ fp16_statistics: Optional[torch.HalfTensor] = None,
+ tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None,
+):
+ """
+ A helper function to set a given tensor (parameter of buffer) of a module on a specific device (note that doing
+ `param.to(device)` creates a new tensor not linked to the parameter, which is why we need this function).
+
+ Args:
+ module (`torch.nn.Module`):
+ The module in which the tensor we want to move lives.
+ tensor_name (`str`):
+ The full name of the parameter/buffer.
+ device (`int`, `str` or `torch.device`):
+ The device on which to set the tensor.
+ value (`torch.Tensor`, *optional*):
+ The value of the tensor (useful when going from the meta device to any other device).
+ dtype (`torch.dtype`, *optional*):
+ If passed along the value of the parameter will be cast to this `dtype`. Otherwise, `value` will be cast to
+ the dtype of the existing parameter in the model.
+ fp16_statistics (`torch.HalfTensor`, *optional*):
+ The list of fp16 statistics to set on the module, used for 8 bit model serialization.
+ tied_params_map (Dict[int, Dict[torch.device, torch.Tensor]], *optional*, defaults to `None`):
+ A map of current data pointers to dictionaries of devices to already dispatched tied weights. For a given
+ execution device, this parameter is useful to reuse the first available pointer of a shared weight on the
+ device for all others, instead of duplicating memory.
+ """
+ # Recurse if needed
+ if "." in tensor_name:
+ splits = tensor_name.split(".")
+ for split in splits[:-1]:
+ new_module = getattr(module, split)
+ if new_module is None:
+ raise ValueError(f"{module} has no attribute {split}.")
+ module = new_module
+ tensor_name = splits[-1]
+
+ if tensor_name not in module._parameters and tensor_name not in module._buffers:
+ raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
+ is_buffer = tensor_name in module._buffers
+ old_value = getattr(module, tensor_name)
+
+ # Treat the case where old_value (or a custom `value`, typically offloaded to RAM/disk) belongs to a tied group, and one of the weight
+ # in the tied group has already been dispatched to the device, by avoiding reallocating memory on the device and just copying the pointer.
+ if (
+ value is not None
+ and tied_params_map is not None
+ and value.data_ptr() in tied_params_map
+ and device in tied_params_map[value.data_ptr()]
+ ):
+ module._parameters[tensor_name] = tied_params_map[value.data_ptr()][device]
+ return
+ elif (
+ tied_params_map is not None
+ and old_value.data_ptr() in tied_params_map
+ and device in tied_params_map[old_value.data_ptr()]
+ ):
+ module._parameters[tensor_name] = tied_params_map[old_value.data_ptr()][device]
+ return
+
+ if old_value.device == torch.device("meta") and device not in ["meta", torch.device("meta")] and value is None:
+ raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {device}.")
+
+ param = module._parameters[tensor_name] if tensor_name in module._parameters else None
+ param_cls = type(param)
+
+ if value is not None:
+ # We can expect mismatches when using bnb 4bit since Params4bit will reshape and pack the weights.
+ # In other cases, we want to make sure we're not loading checkpoints that do not match the config.
+ if old_value.shape != value.shape and param_cls.__name__ != "Params4bit":
+ raise ValueError(
+ f'Trying to set a tensor of shape {value.shape} in "{tensor_name}" (which has shape {old_value.shape}), this looks incorrect.'
+ )
+
+ if dtype is None:
+ # For compatibility with PyTorch load_state_dict which converts state dict dtype to existing dtype in model
+ value = value.to(old_value.dtype)
+ elif not str(value.dtype).startswith(("torch.uint", "torch.int", "torch.bool")):
+ value = value.to(dtype)
+
+ device_quantization = None
+ with torch.no_grad():
+ # leave it on cpu first before moving them to cuda
+ # # fix the case where the device is meta, we don't want to put it on cpu because there is no data =0
+ if (
+ param is not None
+ and param.device.type != "cuda"
+ and torch.device(device).type == "cuda"
+ and param_cls.__name__ in ["Int8Params", "FP4Params", "Params4bit"]
+ ):
+ device_quantization = device
+ device = "cpu"
+ # `torch.Tensor.to()` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)).
+ if isinstance(device, int):
+ if is_npu_available():
+ device = f"npu:{device}"
+ elif is_mlu_available():
+ device = f"mlu:{device}"
+ elif is_musa_available():
+ device = f"musa:{device}"
+ elif is_xpu_available():
+ device = f"xpu:{device}"
+ if "xpu" in str(device) and not is_xpu_available():
+ raise ValueError(f'{device} is not available, you should use device="cpu" instead')
+ if value is None:
+ new_value = old_value.to(device)
+ if dtype is not None and device in ["meta", torch.device("meta")]:
+ if not str(old_value.dtype).startswith(("torch.uint", "torch.int", "torch.bool")):
+ new_value = new_value.to(dtype)
+
+ if not is_buffer:
+ module._parameters[tensor_name] = param_cls(new_value, requires_grad=old_value.requires_grad)
+ elif isinstance(value, torch.Tensor):
+ new_value = value.to(device)
+ else:
+ new_value = torch.tensor(value, device=device)
+ if device_quantization is not None:
+ device = device_quantization
+ if is_buffer:
+ module._buffers[tensor_name] = new_value
+ elif value is not None or not check_device_same(torch.device(device), module._parameters[tensor_name].device):
+ param_cls = type(module._parameters[tensor_name])
+ kwargs = module._parameters[tensor_name].__dict__
+ if param_cls.__name__ in ["Int8Params", "FP4Params", "Params4bit"]:
+ if param_cls.__name__ == "Int8Params" and new_value.dtype == torch.float32:
+ # downcast to fp16 if any - needed for 8bit serialization
+ new_value = new_value.to(torch.float16)
+ # quantize module that are going to stay on the cpu so that we offload quantized weights
+ if device == "cpu" and param_cls.__name__ == "Int8Params":
+ new_value = param_cls(new_value, requires_grad=old_value.requires_grad, **kwargs).to(0).to("cpu")
+ new_value.CB = new_value.CB.to("cpu")
+ new_value.SCB = new_value.SCB.to("cpu")
+ else:
+ new_value = param_cls(new_value, requires_grad=old_value.requires_grad, **kwargs).to(device)
+ elif param_cls.__name__ in ["QTensor", "QBitsTensor"]:
+ new_value = torch.nn.Parameter(new_value, requires_grad=old_value.requires_grad).to(device)
+ elif param_cls.__name__ in ["AffineQuantizedTensor"]:
+ new_value = torch.nn.Parameter(
+ param_cls(
+ new_value.layout_tensor,
+ new_value.block_size,
+ new_value.shape,
+ new_value.quant_min,
+ new_value.quant_max,
+ new_value.zero_point_domain,
+ ),
+ requires_grad=old_value.requires_grad,
+ ).to(device)
+ else:
+ new_value = param_cls(new_value, requires_grad=old_value.requires_grad).to(device)
+
+ module._parameters[tensor_name] = new_value
+ if fp16_statistics is not None:
+ module._parameters[tensor_name].SCB = fp16_statistics.to(device)
+ del fp16_statistics
+ # as we put the weight to meta, it doesn't have SCB attr anymore. make sure that it is not a meta weight
+ if (
+ module.__class__.__name__ == "Linear8bitLt"
+ and getattr(module.weight, "SCB", None) is None
+ and str(module.weight.device) != "meta"
+ ):
+ # quantize only if necessary
+ device_index = torch.device(device).index if torch.device(device).type == "cuda" else None
+ if not getattr(module.weight, "SCB", None) and device_index is not None:
+ if module.bias is not None and module.bias.device.type != "meta":
+ # if a bias exists, we need to wait until the bias is set on the correct device
+ module = module.cuda(device_index)
+ elif module.bias is None:
+ # if no bias exists, we can quantize right away
+ module = module.cuda(device_index)
+ elif (
+ module.__class__.__name__ == "Linear4bit"
+ and getattr(module.weight, "quant_state", None) is None
+ and str(module.weight.device) != "meta"
+ ):
+ # quantize only if necessary
+ device_index = torch.device(device).index if torch.device(device).type == "cuda" else None
+ if not getattr(module.weight, "quant_state", None) and device_index is not None:
+ module.weight = module.weight.cuda(device_index)
+ # clean pre and post foward hook
+ if device != "cpu":
+ clear_device_cache()
+
+ # When handling tied weights, we update tied_params_map to keep track of the tied weights that have already been allocated on the device in
+ # order to avoid duplicating memory, see above.
+ if (
+ tied_params_map is not None
+ and old_value.data_ptr() in tied_params_map
+ and device not in tied_params_map[old_value.data_ptr()]
+ ):
+ tied_params_map[old_value.data_ptr()][device] = new_value
+ elif (
+ value is not None
+ and tied_params_map is not None
+ and value.data_ptr() in tied_params_map
+ and device not in tied_params_map[value.data_ptr()]
+ ):
+ tied_params_map[value.data_ptr()][device] = new_value
+
+
+def named_module_tensors(
+ module: nn.Module, include_buffers: bool = True, recurse: bool = False, remove_non_persistent: bool = False
+):
+ """
+ A helper function that gathers all the tensors (parameters + buffers) of a given module. If `include_buffers=True`
+ it's the same as doing `module.named_parameters(recurse=recurse) + module.named_buffers(recurse=recurse)`.
+
+ Args:
+ module (`torch.nn.Module`):
+ The module we want the tensors on.
+ include_buffer (`bool`, *optional*, defaults to `True`):
+ Whether or not to include the buffers in the result.
+ recurse (`bool`, *optional`, defaults to `False`):
+ Whether or not to go look in every submodule or just return the direct parameters and buffers.
+ remove_non_persistent (`bool`, *optional*, defaults to `False`):
+ Whether or not to remove the non persistent buffer from the buffers. Useful only when include_buffers =
+ True
+ """
+ yield from module.named_parameters(recurse=recurse)
+
+ if include_buffers:
+ non_persistent_buffers = set()
+ if remove_non_persistent:
+ non_persistent_buffers = get_non_persistent_buffers(module, recurse=recurse)
+ for named_buffer in module.named_buffers(recurse=recurse):
+ name, _ = named_buffer
+ if name not in non_persistent_buffers:
+ yield named_buffer
+
+
+def get_non_persistent_buffers(module: nn.Module, recurse: bool = False):
+ """
+ Gather all non persistent buffers of a given modules into a set
+
+ Args:
+ module (`nn.Module`):
+ The module we want the non persistent buffers on.
+ recurse (`bool`, *optional*, defaults to `False`):
+ Whether or not to go look in every submodule or just return the direct non persistent buffers.
+ """
+
+ non_persistent_buffers_set = module._non_persistent_buffers_set
+ if recurse:
+ for _, m in module.named_modules():
+ non_persistent_buffers_set |= m._non_persistent_buffers_set
+
+ return non_persistent_buffers_set
+
+
+class FindTiedParametersResult(list):
+ """
+ This is a subclass of a list to handle backward compatibility for Transformers. Do not rely on the fact this is not
+ a list or on the `values` method as in the future this will be removed.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ def values(self):
+ warnings.warn(
+ "The 'values' method of FindTiedParametersResult is deprecated and will be removed in Accelerate v1.3.0. ",
+ FutureWarning,
+ )
+ return sum([x[1:] for x in self], [])
+
+
+def check_tied_parameters_in_config(model: nn.Module):
+ """
+ Check if there is any indication in the given model that some weights should be tied.
+
+ Args:
+ model (`torch.nn.Module`): The model to inspect
+
+ Returns:
+ bool: True if the model needs to have tied weights
+ """
+
+ # based on model.tie_weights() method
+ has_tied_word_embedding = False
+ has_tied_encoder_decoder = False
+ has_tied_module = False
+
+ if "PreTrainedModel" in [c.__name__ for c in inspect.getmro(model.__class__)]:
+ has_tied_word_embedding = (
+ hasattr(model, "config")
+ and getattr(model.config, "tie_word_embeddings", False)
+ and model.get_output_embeddings()
+ )
+ has_tied_encoder_decoder = (
+ hasattr(model, "config")
+ and getattr(model.config, "is_encoder_decoder", False)
+ and getattr(model.config, "tie_encoder_decoder", False)
+ )
+ has_tied_module = any(hasattr(module, "_tie_weights") for module in model.modules())
+
+ return any([has_tied_word_embedding, has_tied_encoder_decoder, has_tied_module])
+
+
+def _get_param_device(param, device_map):
+ if param in device_map:
+ return device_map[param]
+ parent_param = ".".join(param.split(".")[:-1])
+ if parent_param == param:
+ raise ValueError(f"The `device_map` does not contain the module {param}.")
+ else:
+ return _get_param_device(parent_param, device_map)
+
+
+def check_tied_parameters_on_same_device(tied_params, device_map):
+ """
+ Check if tied parameters are on the same device
+
+ Args:
+ tied_params (`List[List[str]]`):
+ A list of lists of parameter names being all tied together.
+
+ device_map (`Dict[str, Union[int, str, torch.device]]`):
+ A map that specifies where each submodule should go.
+
+ """
+ for tie_param in tied_params:
+ tie_param_devices = {}
+ for param in tie_param:
+ tie_param_devices[param] = _get_param_device(param, device_map)
+ if len(set(tie_param_devices.values())) > 1:
+ logger.warn(
+ f"Tied parameters are on different devices: {tie_param_devices}. "
+ "Please modify your custom device map or set `device_map='auto'`. "
+ )
+
+
+def _get_named_modules(
+ module: torch.nn.Module,
+ memo: Optional[Set[torch.nn.Module]] = None,
+ prefix: str = "",
+ remove_duplicate: bool = True,
+):
+ """
+ Return an iterator over all modules in the network, yielding both the name of the module as well as the module
+ itself. Copied from PyTorch `torch.nn.Module.named_modules` for compatability with torch < 2.0 versions with
+ `remove_duplicate` option added.
+
+ Args:
+ memo (set of `torch.nn.Module`, *optional*):
+ A memo to store the set of modules already added to the result
+ prefix (`str`, *optional*):
+ A prefix that will be added to the name of the module
+ remove_duplicate (`bool`, *optional*):
+ Whether to remove the duplicated module instances in the result or not
+
+ Yields:
+ (str, Module): Tuple of name and module
+
+ Note:
+ Duplicate modules are returned only once. In the following example, ``l`` will be returned only once.
+ """
+ if memo is None:
+ memo = set()
+ if module not in memo:
+ if remove_duplicate:
+ memo.add(module)
+ yield prefix, module
+ for name, sub_module in module._modules.items():
+ if sub_module is None:
+ continue
+ submodule_prefix = prefix + ("." if prefix else "") + name
+ yield from _get_named_modules(sub_module, memo, submodule_prefix, remove_duplicate)
+
+
+def _get_named_parameters(module: torch.nn.Module, prefix="", recurse=True, remove_duplicate: bool = True):
+ """
+ Help yield various names + members of modules. Copied from PyTorch `torch.nn.Module.named_modules` for
+ compatability with torch < 2.0 versions with `remove_duplicate` option added.
+ """
+ memo = set()
+ modules = (
+ _get_named_modules(module, prefix=prefix, remove_duplicate=remove_duplicate) if recurse else [(prefix, module)]
+ )
+ for module_prefix, module in modules:
+ members = module._parameters.items()
+ for k, v in members:
+ if v is None or v in memo:
+ continue
+ if remove_duplicate:
+ memo.add(v)
+ name = module_prefix + ("." if module_prefix else "") + k
+ yield name, v
+
+
+def find_tied_parameters(model: torch.nn.Module, **kwargs):
+ """
+ Find the tied parameters in a given model.
+
+
+
+ The signature accepts keyword arguments, but they are for the recursive part of this function and you should ignore
+ them.
+
+
+
+ Args:
+ model (`torch.nn.Module`): The model to inspect.
+
+ Returns:
+ List[List[str]]: A list of lists of parameter names being all tied together.
+
+ Example:
+
+ ```py
+ >>> from collections import OrderedDict
+ >>> import torch.nn as nn
+
+ >>> model = nn.Sequential(OrderedDict([("linear1", nn.Linear(4, 4)), ("linear2", nn.Linear(4, 4))]))
+ >>> model.linear2.weight = model.linear1.weight
+ >>> find_tied_parameters(model)
+ [['linear1.weight', 'linear2.weight']]
+ ```
+ """
+
+ # get ALL model parameters and thier names
+ all_named_parameters = {name: param for name, param in _get_named_parameters(model, remove_duplicate=False)}
+
+ # get ONLY unique named parameters,
+ # if parameter is tied and have multiple names, it will be included only once
+ no_duplicate_named_parameters = {
+ name: param for name, param in _get_named_parameters(model, remove_duplicate=True)
+ }
+
+ # the difference of the two sets will give us the tied parameters
+ tied_param_names = set(all_named_parameters.keys()) - set(no_duplicate_named_parameters.keys())
+
+ # 'tied_param_names' contains the names of parameters that are tied in the model, but we do not know
+ # which names refer to the same parameter. To identify this, we need to group them together.
+ tied_param_groups = {}
+ for tied_param_name in tied_param_names:
+ tied_param = all_named_parameters[tied_param_name]
+ for param_name, param in no_duplicate_named_parameters.items():
+ # compare if parameters are the same, if so, group thier names together
+ if param is tied_param:
+ if param_name not in tied_param_groups:
+ tied_param_groups[param_name] = []
+ tied_param_groups[param_name].append(tied_param_name)
+
+ return FindTiedParametersResult([sorted([weight] + list(set(tied))) for weight, tied in tied_param_groups.items()])
+
+
+def retie_parameters(model, tied_params):
+ """
+ Reties tied parameters in a given model if the link was broken (for instance when adding hooks).
+
+ Args:
+ model (`torch.nn.Module`):
+ The model in which to retie parameters.
+ tied_params (`List[List[str]]`):
+ A mapping parameter name to tied parameter name as obtained by `find_tied_parameters`.
+ """
+ for tied_group in tied_params:
+ param_to_tie = None
+ # two loops : the first one to set param_to_tie , the second one to change the values of tied_group
+ for param_name in tied_group:
+ module = model
+ splits = param_name.split(".")
+ for split in splits[:-1]:
+ module = getattr(module, split)
+ param = getattr(module, splits[-1])
+ if param_to_tie is None and param.device != torch.device("meta"):
+ param_to_tie = param
+ break
+ if param_to_tie is not None:
+ for param_name in tied_group:
+ module = model
+ splits = param_name.split(".")
+ for split in splits[:-1]:
+ module = getattr(module, split)
+ setattr(module, splits[-1], param_to_tie)
+
+
+def _get_proper_dtype(dtype: Union[str, torch.device]) -> torch.dtype:
+ """
+ Just does torch.dtype(dtype) if necessary.
+ """
+ if isinstance(dtype, str):
+ # We accept "torch.float16" or just "float16"
+ dtype = dtype.replace("torch.", "")
+ dtype = getattr(torch, dtype)
+ return dtype
+
+
+def compute_module_sizes(
+ model: nn.Module,
+ dtype: Optional[Union[str, torch.device]] = None,
+ special_dtypes: Optional[Dict[str, Union[str, torch.device]]] = None,
+ buffers_only: bool = False,
+):
+ """
+ Compute the size of each submodule of a given model.
+ """
+ if dtype is not None:
+ dtype = _get_proper_dtype(dtype)
+ dtype_size = dtype_byte_size(dtype)
+ if special_dtypes is not None:
+ special_dtypes = {key: _get_proper_dtype(dtyp) for key, dtyp in special_dtypes.items()}
+ special_dtypes_size = {key: dtype_byte_size(dtyp) for key, dtyp in special_dtypes.items()}
+ module_sizes = defaultdict(int)
+
+ module_list = []
+
+ if not buffers_only:
+ module_list = named_module_tensors(model, recurse=True)
+ else:
+ module_list = model.named_buffers(recurse=True)
+
+ for name, tensor in module_list:
+ if special_dtypes is not None and name in special_dtypes:
+ size = tensor.numel() * special_dtypes_size[name]
+ elif dtype is None:
+ size = tensor.numel() * dtype_byte_size(tensor.dtype)
+ elif str(tensor.dtype).startswith(("torch.uint", "torch.int", "torch.bool")):
+ # According to the code in set_module_tensor_to_device, these types won't be converted
+ # so use their original size here
+ size = tensor.numel() * dtype_byte_size(tensor.dtype)
+ else:
+ size = tensor.numel() * min(dtype_size, dtype_byte_size(tensor.dtype))
+ name_parts = name.split(".")
+ for idx in range(len(name_parts) + 1):
+ module_sizes[".".join(name_parts[:idx])] += size
+
+ return module_sizes
+
+
+def compute_module_total_buffer_size(
+ model: nn.Module,
+ dtype: Optional[Union[str, torch.device]] = None,
+ special_dtypes: Optional[Dict[str, Union[str, torch.device]]] = None,
+):
+ """
+ Compute the total size of buffers in each submodule of a given model.
+ """
+ module_sizes = compute_module_sizes(model, dtype=dtype, special_dtypes=special_dtypes, buffers_only=True)
+ return module_sizes.get("", 0)
+
+
+def get_max_layer_size(
+ modules: List[Tuple[str, torch.nn.Module]], module_sizes: Dict[str, int], no_split_module_classes: List[str]
+):
+ """
+ Utility function that will scan a list of named modules and return the maximum size used by one full layer. The
+ definition of a layer being:
+ - a module with no direct children (just parameters and buffers)
+ - a module whose class name is in the list `no_split_module_classes`
+
+ Args:
+ modules (`List[Tuple[str, torch.nn.Module]]`):
+ The list of named modules where we want to determine the maximum layer size.
+ module_sizes (`Dict[str, int]`):
+ A dictionary mapping each layer name to its size (as generated by `compute_module_sizes`).
+ no_split_module_classes (`List[str]`):
+ A list of class names for layers we don't want to be split.
+
+ Returns:
+ `Tuple[int, List[str]]`: The maximum size of a layer with the list of layer names realizing that maximum size.
+ """
+ max_size = 0
+ layer_names = []
+ modules_to_treat = modules.copy()
+ while len(modules_to_treat) > 0:
+ module_name, module = modules_to_treat.pop(0)
+ modules_children = list(module.named_children()) if isinstance(module, torch.nn.Module) else []
+ if len(modules_children) == 0 or module.__class__.__name__ in no_split_module_classes:
+ # No splitting this one so we compare to the max_size
+ size = module_sizes[module_name]
+ if size > max_size:
+ max_size = size
+ layer_names = [module_name]
+ elif size == max_size:
+ layer_names.append(module_name)
+ else:
+ modules_to_treat = [(f"{module_name}.{n}", v) for n, v in modules_children] + modules_to_treat
+ return max_size, layer_names
+
+
+def get_max_memory(max_memory: Optional[Dict[Union[int, str], Union[int, str]]] = None):
+ """
+ Get the maximum memory available if nothing is passed, converts string to int otherwise.
+ """
+ import psutil
+
+ if max_memory is None:
+ max_memory = {}
+ # Make sure CUDA is initialized on each GPU to have the right memory info.
+ if is_npu_available():
+ for i in range(torch.npu.device_count()):
+ try:
+ _ = torch.tensor(0, device=torch.device("npu", i))
+ max_memory[i] = torch.npu.mem_get_info(i)[0]
+ except Exception:
+ logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.")
+ continue
+ elif is_mlu_available():
+ for i in range(torch.mlu.device_count()):
+ try:
+ _ = torch.tensor(0, device=torch.device("mlu", i))
+ max_memory[i] = torch.mlu.mem_get_info(i)[0]
+ except Exception:
+ logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.")
+ continue
+ elif is_musa_available():
+ for i in range(torch.musa.device_count()):
+ try:
+ _ = torch.tensor(0, device=torch.device("musa", i))
+ max_memory[i] = torch.musa.mem_get_info(i)[0]
+ except Exception:
+ logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.")
+ continue
+ elif is_xpu_available():
+ for i in range(torch.xpu.device_count()):
+ try:
+ _ = torch.tensor(0, device=torch.device("xpu", i))
+ max_memory[i] = get_xpu_available_memory(i)
+ except Exception:
+ logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.")
+ continue
+ else:
+ for i in range(torch.cuda.device_count()):
+ try:
+ _ = torch.tensor([0], device=i)
+ max_memory[i] = torch.cuda.mem_get_info(i)[0]
+ except Exception:
+ logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.")
+ continue
+ # allocate everything in the mps device as the RAM is shared
+ if is_mps_available():
+ max_memory["mps"] = psutil.virtual_memory().available
+ else:
+ max_memory["cpu"] = psutil.virtual_memory().available
+ return max_memory
+
+ for key in max_memory:
+ if isinstance(max_memory[key], str):
+ max_memory[key] = convert_file_size_to_int(max_memory[key])
+
+ # Need to sort the device by type to make sure that we allocate the gpu first.
+ # As gpu/npu/xpu are represented by int, we need to sort them first.
+ gpu_devices = [k for k in max_memory.keys() if isinstance(k, int)]
+ gpu_devices.sort()
+ # check if gpu/npu/xpu devices are available and if not, throw a warning
+ if is_npu_available():
+ num_devices = torch.npu.device_count()
+ elif is_mlu_available():
+ num_devices = torch.mlu.device_count()
+ elif is_musa_available():
+ num_devices = torch.musa.device_count()
+ elif is_xpu_available():
+ num_devices = torch.xpu.device_count()
+ else:
+ num_devices = torch.cuda.device_count()
+ for device in gpu_devices:
+ if device >= num_devices or device < 0:
+ logger.warning(f"Device {device} is not available, available devices are {list(range(num_devices))}")
+ # Add the other devices in the preset order if they are available
+ all_devices = gpu_devices + [k for k in ["mps", "cpu", "disk"] if k in max_memory.keys()]
+ # Raise an error if a device is not recognized
+ for k in max_memory.keys():
+ if k not in all_devices:
+ raise ValueError(
+ f"Device {k} is not recognized, available devices are integers(for GPU/XPU), 'mps', 'cpu' and 'disk'"
+ )
+ max_memory = {k: max_memory[k] for k in all_devices}
+
+ return max_memory
+
+
+def clean_device_map(device_map: Dict[str, Union[int, str, torch.device]], module_name: str = ""):
+ """
+ Cleans a device_map by grouping all submodules that go on the same device together.
+ """
+ # Get the value of the current module and if there is only one split across several keys, regroup it.
+ prefix = "" if module_name == "" else f"{module_name}."
+ values = [v for k, v in device_map.items() if k.startswith(prefix)]
+ if len(set(values)) == 1 and len(values) > 1:
+ for k in [k for k in device_map if k.startswith(prefix)]:
+ del device_map[k]
+ device_map[module_name] = values[0]
+
+ # Recurse over the children
+ children_modules = [k for k in device_map.keys() if k.startswith(prefix) and len(k) > len(module_name)]
+ idx = len(module_name.split(".")) + 1 if len(module_name) > 0 else 1
+ children_modules = set(".".join(k.split(".")[:idx]) for k in children_modules)
+ for child in children_modules:
+ clean_device_map(device_map, module_name=child)
+
+ return device_map
+
+
+def load_offloaded_weights(model, index, offload_folder):
+ """
+ Loads the weights from the offload folder into the model.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to load the weights into.
+ index (`dict`):
+ A dictionary containing the parameter name and its metadata for each parameter that was offloaded from the
+ model.
+ offload_folder (`str`):
+ The folder where the offloaded weights are stored.
+ """
+ if index is None or len(index) == 0:
+ # Nothing to do
+ return
+ for param_name, metadata in index.items():
+ if "SCB" in param_name:
+ continue
+ fp16_statistics = None
+ if "weight" in param_name and param_name.replace("weight", "SCB") in index.keys():
+ weight_name = param_name.replace("weight", "SCB")
+ fp16_statistics = load_offloaded_weight(
+ os.path.join(offload_folder, f"{weight_name}.dat"), index[weight_name]
+ )
+ tensor_file = os.path.join(offload_folder, f"{param_name}.dat")
+ weight = load_offloaded_weight(tensor_file, metadata)
+ set_module_tensor_to_device(model, param_name, "cpu", value=weight, fp16_statistics=fp16_statistics)
+
+
+def get_module_leaves(module_sizes):
+ module_children = {}
+ for module in module_sizes:
+ if module == "" or "." not in module:
+ continue
+ parent = module.rsplit(".", 1)[0]
+ module_children[parent] = module_children.get(parent, 0) + 1
+ leaves = [module for module in module_sizes if module_children.get(module, 0) == 0 and module != ""]
+ return leaves
+
+
+def get_balanced_memory(
+ model: nn.Module,
+ max_memory: Optional[Dict[Union[int, str], Union[int, str]]] = None,
+ no_split_module_classes: Optional[List[str]] = None,
+ dtype: Optional[Union[str, torch.dtype]] = None,
+ special_dtypes: Optional[Dict[str, Union[str, torch.device]]] = None,
+ low_zero: bool = False,
+):
+ """
+ Compute a `max_memory` dictionary for [`infer_auto_device_map`] that will balance the use of each available GPU.
+
+
+
+ All computation is done analyzing sizes and dtypes of the model parameters. As a result, the model can be on the
+ meta device (as it would if initialized within the `init_empty_weights` context manager).
+
+
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to analyze.
+ max_memory (`Dict`, *optional*):
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available if unset.
+ Example: `max_memory={0: "1GB"}`.
+ no_split_module_classes (`List[str]`, *optional*):
+ A list of layer class names that should never be split across device (for instance any layer that has a
+ residual connection).
+ dtype (`str` or `torch.dtype`, *optional*):
+ If provided, the weights will be converted to that type when loaded.
+ special_dtypes (`Dict[str, Union[str, torch.device]]`, *optional*):
+ If provided, special dtypes to consider for some specific weights (will override dtype used as default for
+ all weights).
+ low_zero (`bool`, *optional*):
+ Minimizes the number of weights on GPU 0, which is convenient when it's used for other operations (like the
+ Transformers generate function).
+ """
+ # Get default / clean up max_memory
+ user_not_set_max_memory = max_memory is None
+ max_memory = get_max_memory(max_memory)
+
+ if is_npu_available():
+ expected_device_type = "npu"
+ elif is_mlu_available():
+ expected_device_type = "mlu"
+ elif is_musa_available():
+ expected_device_type = "musa"
+ elif is_xpu_available():
+ expected_device_type = "xpu"
+ else:
+ expected_device_type = "cuda"
+ num_devices = len([d for d in max_memory if torch.device(d).type == expected_device_type and max_memory[d] > 0])
+
+ if num_devices == 0:
+ return max_memory
+
+ if num_devices == 1:
+ # We cannot do low_zero on just one GPU, but we will still reserve some memory for the buffer
+ low_zero = False
+ # If user just asked us to handle memory usage, we should avoid OOM
+ if user_not_set_max_memory:
+ for key in max_memory.keys():
+ if isinstance(key, int):
+ max_memory[key] *= 0.9 # 90% is a good compromise
+ logger.info(
+ f"We will use 90% of the memory on device {key} for storing the model, and 10% for the buffer to avoid OOM. "
+ "You can set `max_memory` in to a higher value to use more memory (at your own risk)."
+ )
+ break # only one device
+
+ module_sizes = compute_module_sizes(model, dtype=dtype, special_dtypes=special_dtypes)
+ per_gpu = module_sizes[""] // (num_devices - 1 if low_zero else num_devices)
+
+ # We can't just set the memory to model_size // num_devices as it will end being too small: each GPU will get
+ # slightly less layers and some layers will end up offload at the end. So this function computes a buffer size to
+ # add which is the biggest of:
+ # - the size of no split block (if applicable)
+ # - the mean of the layer sizes
+ if no_split_module_classes is None:
+ no_split_module_classes = []
+ elif not isinstance(no_split_module_classes, (list, tuple)):
+ no_split_module_classes = [no_split_module_classes]
+
+ # Identify the size of the no_split_block modules
+ if len(no_split_module_classes) > 0:
+ no_split_children = {}
+ for name, size in module_sizes.items():
+ if name == "":
+ continue
+ submodule = model
+ for submodule_name in name.split("."):
+ submodule = getattr(submodule, submodule_name)
+ class_name = submodule.__class__.__name__
+ if class_name in no_split_module_classes and class_name not in no_split_children:
+ no_split_children[class_name] = size
+
+ if set(no_split_children.keys()) == set(no_split_module_classes):
+ break
+ buffer = max(no_split_children.values()) if len(no_split_children) > 0 else 0
+ else:
+ buffer = 0
+
+ # Compute mean of final modules. In the first dict of module sizes, leaves are the parameters
+ leaves = get_module_leaves(module_sizes)
+ module_sizes = {n: v for n, v in module_sizes.items() if n not in leaves}
+ # Once removed, leaves are the final modules.
+ leaves = get_module_leaves(module_sizes)
+ mean_leaves = int(sum([module_sizes[n] for n in leaves]) / max(len(leaves), 1))
+ buffer = int(1.25 * max(buffer, mean_leaves))
+ per_gpu += buffer
+
+ # Sorted list of GPUs id (we may have some gpu ids not included in the our max_memory list - let's ignore them)
+ gpus_idx_list = list(
+ sorted(
+ device_id for device_id, device_mem in max_memory.items() if isinstance(device_id, int) and device_mem > 0
+ )
+ )
+ # The last device is left with max_memory just in case the buffer is not enough.
+ for idx in gpus_idx_list[:-1]:
+ max_memory[idx] = min(max_memory[0] if low_zero and idx == 0 else per_gpu, max_memory[idx])
+
+ if low_zero:
+ min_zero = max(0, module_sizes[""] - sum([max_memory[i] for i in range(1, num_devices)]))
+ max_memory[0] = min(min_zero, max_memory[0])
+
+ return max_memory
+
+
+def calculate_maximum_sizes(model: torch.nn.Module):
+ "Computes the total size of the model and its largest layer"
+ sizes = compute_module_sizes(model)
+ # `transformers` models store this information for us
+ no_split_modules = getattr(model, "_no_split_modules", None)
+ if no_split_modules is None:
+ no_split_modules = []
+
+ modules_to_treat = (
+ list(model.named_parameters(recurse=False))
+ + list(model.named_children())
+ + list(model.named_buffers(recurse=False))
+ )
+ largest_layer = get_max_layer_size(modules_to_treat, sizes, no_split_modules)
+ total_size = sizes[""]
+ return total_size, largest_layer
+
+
+def infer_auto_device_map(
+ model: nn.Module,
+ max_memory: Optional[Dict[Union[int, str], Union[int, str]]] = None,
+ no_split_module_classes: Optional[List[str]] = None,
+ dtype: Optional[Union[str, torch.dtype]] = None,
+ special_dtypes: Optional[Dict[str, Union[str, torch.dtype]]] = None,
+ verbose: bool = False,
+ clean_result: bool = True,
+ offload_buffers: bool = False,
+):
+ """
+ Compute a device map for a given model giving priority to GPUs, then offload on CPU and finally offload to disk,
+ such that:
+ - we don't exceed the memory available of any of the GPU.
+ - if offload to the CPU is needed, there is always room left on GPU 0 to put back the layer offloaded on CPU that
+ has the largest size.
+ - if offload to the CPU is needed,we don't exceed the RAM available on the CPU.
+ - if offload to the disk is needed, there is always room left on the CPU to put back the layer offloaded on disk
+ that has the largest size.
+
+
+
+ All computation is done analyzing sizes and dtypes of the model parameters. As a result, the model can be on the
+ meta device (as it would if initialized within the `init_empty_weights` context manager).
+
+
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to analyze.
+ max_memory (`Dict`, *optional*):
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available if unset.
+ Example: `max_memory={0: "1GB"}`.
+ no_split_module_classes (`List[str]`, *optional*):
+ A list of layer class names that should never be split across device (for instance any layer that has a
+ residual connection).
+ dtype (`str` or `torch.dtype`, *optional*):
+ If provided, the weights will be converted to that type when loaded.
+ special_dtypes (`Dict[str, Union[str, torch.device]]`, *optional*):
+ If provided, special dtypes to consider for some specific weights (will override dtype used as default for
+ all weights).
+ verbose (`bool`, *optional*, defaults to `False`):
+ Whether or not to provide debugging statements as the function builds the device_map.
+ clean_result (`bool`, *optional*, defaults to `True`):
+ Clean the resulting device_map by grouping all submodules that go on the same device together.
+ offload_buffers (`bool`, *optional*, defaults to `False`):
+ In the layers that are offloaded on the CPU or the hard drive, whether or not to offload the buffers as
+ well as the parameters.
+ """
+ # Get default / clean up max_memory
+ max_memory = get_max_memory(max_memory)
+ if no_split_module_classes is None:
+ no_split_module_classes = []
+ elif not isinstance(no_split_module_classes, (list, tuple)):
+ no_split_module_classes = [no_split_module_classes]
+
+ devices = list(max_memory.keys())
+ if "disk" not in devices:
+ devices.append("disk")
+ gpus = [device for device in devices if device not in ["cpu", "disk"]]
+
+ # Devices that need to keep space for a potential offloaded layer.
+ if "mps" in gpus:
+ main_devices = ["mps"]
+ elif len(gpus) > 0:
+ main_devices = [gpus[0], "cpu"]
+ else:
+ main_devices = ["cpu"]
+
+ module_sizes = compute_module_sizes(model, dtype=dtype, special_dtypes=special_dtypes)
+ tied_parameters = find_tied_parameters(model)
+
+ if check_tied_parameters_in_config(model) and len(tied_parameters) == 0:
+ logger.warn(
+ "The model weights are not tied. Please use the `tie_weights` method before using the `infer_auto_device` function."
+ )
+
+ device_map = OrderedDict()
+ current_device = 0
+ current_memory_used = 0
+ device_memory_used = {}
+ device_buffer_sizes = {}
+
+ # Direct submodules and parameters
+ modules_to_treat = (
+ list(model.named_parameters(recurse=False))
+ + list(model.named_children())
+ + list(model.named_buffers(recurse=False))
+ )
+ # Initialize maximum largest layer, to know which space to keep in memory
+ max_layer_size, max_layer_names = get_max_layer_size(modules_to_treat, module_sizes, no_split_module_classes)
+
+ # Ready ? This is going to be a bit messy.
+ while len(modules_to_treat) > 0:
+ name, module = modules_to_treat.pop(0)
+ if verbose:
+ print(f"\nTreating module {name}.")
+ # Max size in the remaining layers may have changed since we took one, so we maybe update it.
+ max_layer_names = [n for n in max_layer_names if n != name and not n.startswith(name + ".")]
+ if len(max_layer_names) == 0:
+ max_layer_size, max_layer_names = get_max_layer_size(
+ [(n, m) for n, m in modules_to_treat if isinstance(m, torch.nn.Module)],
+ module_sizes,
+ no_split_module_classes,
+ )
+ # Assess size needed
+ module_size = module_sizes[name]
+
+ # We keep relevant tied parameters only: one of the tied parameters in the group is inside the current module
+ # and the other is not.
+ # Note: If we are currently processing the name `compute.weight`, an other parameter named e.g. `compute.weight_submodule.parameter`
+ # needs to be considered outside the current module, hence the check with additional dots.
+ tied_param_goups = [
+ tied_group
+ for tied_group in tied_parameters
+ if any(name + "." in k + "." for k in tied_group) and not all(name + "." in k + "." for k in tied_group)
+ ]
+
+ if verbose and len(tied_param_goups) > 0:
+ print(f" Found the relevant tied param groups {tied_param_goups}")
+
+ # Then we keep track of all the parameters that are tied to the current module, but not in the current module
+ tied_params = sum(
+ [[p for p in tied_group if name + "." not in p + "."] for tied_group in tied_param_goups], []
+ )
+
+ if verbose and len(tied_params) > 0:
+ print(f" So those parameters need to be taken into account {tied_params}")
+
+ device = devices[current_device]
+ current_max_size = max_memory[device] if device != "disk" else None
+ current_memory_reserved = 0
+ # Reduce max size available by the largest layer.
+ if devices[current_device] in main_devices:
+ current_max_size = current_max_size - max_layer_size
+ current_memory_reserved = max_layer_size
+ # Case 1 -> We're too big!
+ if current_max_size is not None and current_memory_used + module_size > current_max_size:
+ # Split or not split?
+ modules_children = (
+ []
+ if isinstance(module, nn.Parameter) or isinstance(module, torch.Tensor)
+ else list(module.named_children())
+ )
+ if verbose:
+ print(
+ f"Not enough space on {devices[current_device]} to put {name} (space available "
+ f"{current_max_size - current_memory_used}, module size {module_size})."
+ )
+ if len(modules_children) == 0 or module.__class__.__name__ in no_split_module_classes:
+ # -> no split, we go to the next device
+ if verbose:
+ print("This module cannot be split, going to the next device.")
+
+ device_memory_used[device] = current_memory_used + current_memory_reserved
+ current_device += 1
+ modules_to_treat = [(name, module)] + modules_to_treat
+ current_memory_used = 0
+ else:
+ # -> split, we replace the module studied by its children + parameters
+ if verbose:
+ print(f"Splitting {name}.")
+ modules_children = list(module.named_parameters(recurse=False)) + modules_children
+ modules_to_treat = [(f"{name}.{n}", v) for n, v in modules_children] + modules_to_treat
+ # Update the max layer size.
+ max_layer_size, max_layer_names = get_max_layer_size(
+ [(n, m) for n, m in modules_to_treat if isinstance(m, torch.nn.Module)],
+ module_sizes,
+ no_split_module_classes,
+ )
+
+ # Case 2, it fits! We're not entirely out of the wood though, because we may have some tied parameters.
+ elif len(tied_params) > 0:
+ # First locate all tied modules
+ tied_module_names = []
+ tied_modules = []
+ for tied_param in tied_params:
+ tied_module_index = [i for i, (n, _) in enumerate(modules_to_treat) if n in tied_param][0]
+ tied_module_names.append(modules_to_treat[tied_module_index][0])
+ tied_modules.append(modules_to_treat[tied_module_index][1])
+ if verbose:
+ print(
+ f" It looks like {name} is going to fit on {devices[current_device]} but we have tied "
+ f"parameters to account for.\n - Names {tied_params}\n - Module names {tied_module_names}"
+ )
+
+ # Let's see if it all fits first
+ module_size_with_ties = module_size
+ for tied_param, tied_module_name in zip(tied_params, tied_module_names):
+ module_size_with_ties += module_sizes[tied_module_name] - module_sizes[tied_param]
+
+ if current_max_size is None or current_memory_used + module_size_with_ties <= current_max_size:
+ # We really really fit!
+ if verbose:
+ print(f"Putting {name} and {tied_module_names} on {devices[current_device]}.")
+ current_memory_used += module_size_with_ties
+ device_map[name] = devices[current_device]
+ for tied_module_name in tied_module_names:
+ if tied_module_name in [m[0] for m in modules_to_treat]:
+ # The module may have been removed by a previous iteration of this loop.
+ tied_module_index = [i for i, (n, _) in enumerate(modules_to_treat) if n == tied_module_name][
+ 0
+ ]
+ modules_to_treat.pop(tied_module_index)
+ device_map[tied_module_name] = devices[current_device]
+
+ if not offload_buffers and isinstance(module, nn.Module):
+ current_buffer_size = compute_module_total_buffer_size(
+ module, dtype=dtype, special_dtypes=special_dtypes
+ )
+ device_buffer_sizes[device] = device_buffer_sizes.get(device, 0) + current_buffer_size
+
+ else:
+ # We don't fit with the tied modules. Next question is: can we split one of the tied modules to make it
+ # smaller or do we need to go on the next device?
+ if verbose:
+ print(
+ f"Not enough space on {devices[current_device]} to put {name} and {tied_module_names} (space "
+ f"available {current_max_size - current_memory_used}, needed size {module_size_with_ties})."
+ )
+ split_happened = False
+ for tied_module_name, tied_module in zip(tied_module_names, tied_modules):
+ tied_module_children = list(tied_module.named_children())
+ if len(tied_module_children) == 0 or tied_module.__class__.__name__ in no_split_module_classes:
+ # can't break this one.
+ continue
+
+ if verbose:
+ print(f"Splitting {tied_module_name}.")
+ tied_module_children = list(tied_module.named_parameters(recurse=False)) + tied_module_children
+ tied_module_children = [(f"{tied_module_name}.{n}", v) for n, v in tied_module_children]
+ tied_module_index = [i for i, (n, _) in enumerate(modules_to_treat) if n == tied_module_name][0]
+
+ modules_to_treat = (
+ [(name, module)]
+ + modules_to_treat[:tied_module_index]
+ + tied_module_children
+ + modules_to_treat[tied_module_index + 1 :]
+ )
+ # Update the max layer size.
+ max_layer_size, max_layer_names = get_max_layer_size(
+ [(n, m) for n, m in modules_to_treat if isinstance(m, torch.nn.Module)],
+ module_sizes,
+ no_split_module_classes,
+ )
+ split_happened = True
+ break
+
+ if not split_happened:
+ # If the tied module is not split, we go to the next device
+ if verbose:
+ print("None of the tied module can be split, going to the next device.")
+
+ device_memory_used[device] = current_memory_used + current_memory_reserved
+ current_device += 1
+ modules_to_treat = [(name, module)] + modules_to_treat
+ current_memory_used = 0
+
+ else:
+ if verbose:
+ if current_max_size is None:
+ print(f"Putting {name} (size={module_size}) on {devices[current_device]}.")
+ else:
+ print(
+ f"Putting {name} (size={module_size}) on {devices[current_device]} "
+ f"(available={current_max_size - current_memory_used})."
+ )
+ current_memory_used += module_size
+ device_memory_used[device] = current_memory_used + current_memory_reserved
+ device_map[name] = devices[current_device]
+
+ if not offload_buffers and isinstance(module, nn.Module):
+ current_buffer_size = compute_module_total_buffer_size(
+ module, dtype=dtype, special_dtypes=special_dtypes
+ )
+ device_buffer_sizes[device] = device_buffer_sizes.get(device, 0) + current_buffer_size
+
+ if clean_result:
+ device_map = clean_device_map(device_map)
+
+ non_gpu_buffer_size = device_buffer_sizes.get("cpu", 0) + device_buffer_sizes.get("disk", 0)
+ if non_gpu_buffer_size > 0 and not offload_buffers:
+ is_buffer_fit_any_gpu = False
+ for gpu_device, gpu_max_memory in max_memory.items():
+ if gpu_device == "cpu" or gpu_device == "disk":
+ continue
+
+ if not is_buffer_fit_any_gpu:
+ gpu_memory_used = device_memory_used.get(gpu_device, 0)
+
+ if gpu_max_memory >= non_gpu_buffer_size + gpu_memory_used:
+ is_buffer_fit_any_gpu = True
+
+ if len(gpus) > 0 and not is_buffer_fit_any_gpu:
+ warnings.warn(
+ f"Current model requires {non_gpu_buffer_size} bytes of buffer for offloaded layers, which seems does "
+ f"not fit any GPU's remaining memory. If you are experiencing a OOM later, please consider using "
+ f"offload_buffers=True."
+ )
+
+ return device_map
+
+
+def check_device_map(model: nn.Module, device_map: Dict[str, Union[int, str, torch.device]]):
+ """
+ Checks a device map covers everything in a given model.
+
+ Args:
+ model (`torch.nn.Module`): The model to check the device map against.
+ device_map (`Dict[str, Union[int, str, torch.device]]`): The device map to check.
+ """
+ all_model_tensors = [name for name, _ in model.state_dict().items()]
+ for module_name in device_map.keys():
+ if module_name == "":
+ all_model_tensors.clear()
+ break
+ else:
+ all_model_tensors = [
+ name
+ for name in all_model_tensors
+ if not name == module_name and not name.startswith(module_name + ".")
+ ]
+ if len(all_model_tensors) > 0:
+ non_covered_params = ", ".join(all_model_tensors)
+ raise ValueError(
+ f"The device_map provided does not give any device for the following parameters: {non_covered_params}"
+ )
+
+
+def load_state_dict(checkpoint_file, device_map=None):
+ """
+ Load a checkpoint from a given file. If the checkpoint is in the safetensors format and a device map is passed, the
+ weights can be fast-loaded directly on the GPU.
+
+ Args:
+ checkpoint_file (`str`): The path to the checkpoint to load.
+ device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*):
+ A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer
+ name, once a given module name is inside, every submodule of it will be sent to the same device.
+ """
+ if checkpoint_file.endswith(".safetensors"):
+ with safe_open(checkpoint_file, framework="pt") as f:
+ metadata = f.metadata()
+ weight_names = f.keys()
+
+ if metadata is None:
+ logger.warn(
+ f"The safetensors archive passed at {checkpoint_file} does not contain metadata. "
+ "Make sure to save your model with the `save_pretrained` method. Defaulting to 'pt' metadata."
+ )
+ metadata = {"format": "pt"}
+
+ if metadata.get("format") not in ["pt", "tf", "flax"]:
+ raise OSError(
+ f"The safetensors archive passed at {checkpoint_file} does not contain the valid metadata. Make sure "
+ "you save your model with the `save_pretrained` method."
+ )
+ elif metadata["format"] != "pt":
+ raise ValueError(f"The checkpoint passed was saved with {metadata['format']}, we need a the pt format.")
+ if device_map is None:
+ return safe_load_file(checkpoint_file)
+ else:
+ # if we only have one device we can load everything directly
+ if len(set(device_map.values())) == 1:
+ device = list(device_map.values())[0]
+ target_device = device
+ if is_xpu_available():
+ if compare_versions("safetensors", "<", "0.4.2"):
+ raise ImportError("Safetensors version must be >= 0.4.2 for XPU. Please upgrade safetensors.")
+ if isinstance(device, int):
+ target_device = f"xpu:{device}"
+
+ return safe_load_file(checkpoint_file, device=target_device)
+
+ devices = list(set(device_map.values()) - {"disk"})
+ # cpu device should always exist as fallback option
+ if "cpu" not in devices:
+ devices.append("cpu")
+
+ # For each device, get the weights that go there
+ device_weights = {device: [] for device in devices}
+ for module_name, device in device_map.items():
+ if device in devices:
+ device_weights[device].extend(
+ [k for k in weight_names if k == module_name or k.startswith(module_name + ".")]
+ )
+
+ # all weights that haven't defined a device should be loaded on CPU
+ device_weights["cpu"].extend([k for k in weight_names if k not in sum(device_weights.values(), [])])
+ tensors = {}
+ if is_tqdm_available():
+ progress_bar = tqdm(
+ main_process_only=False,
+ total=sum([len(device_weights[device]) for device in devices]),
+ unit="w",
+ smoothing=0,
+ leave=False,
+ )
+ else:
+ progress_bar = None
+ for device in devices:
+ target_device = device
+ if is_xpu_available():
+ if compare_versions("safetensors", "<", "0.4.2"):
+ raise ImportError("Safetensors version must be >= 0.4.2 for XPU. Please upgrade safetensors.")
+ if isinstance(device, int):
+ target_device = f"xpu:{device}"
+
+ with safe_open(checkpoint_file, framework="pt", device=target_device) as f:
+ for key in device_weights[device]:
+ if progress_bar is not None:
+ progress_bar.set_postfix(dev=device, refresh=False)
+ progress_bar.set_description(key)
+ tensors[key] = f.get_tensor(key)
+ if progress_bar is not None:
+ progress_bar.update()
+ if progress_bar is not None:
+ progress_bar.close()
+
+ return tensors
+ else:
+ return torch.load(checkpoint_file, map_location=torch.device("cpu"))
+
+
+def get_state_dict_offloaded_model(model: nn.Module):
+ """
+ Returns the state dictionary for an offloaded model via iterative onloading
+
+ Args:
+ model (`torch.nn.Module`):
+ The offloaded model we want to save
+ """
+ from ..hooks import AlignDevicesHook
+
+ state_dict = {}
+ placeholders = set()
+ for name, module in model.named_modules():
+ if name == "":
+ continue
+ if hasattr(module, "_hf_hook") and isinstance(module._hf_hook, AlignDevicesHook) and module._hf_hook.offload:
+ original_device = module._hf_hook.execution_device
+ # assign hook execution device to cpu
+ module._hf_hook.execution_device = "cpu"
+ # onload meta tensors to execution device
+ try:
+ module._hf_hook.pre_forward(module)
+ except MemoryError:
+ raise MemoryError("Offloaded module must fit in CPU memory to call save_model!") from None
+ module_state_dict = module.state_dict()
+ # offload meta tensors from cpu
+ module._hf_hook.post_forward(module, torch.tensor([]))
+ # re-assign hook to original execution device
+ module._hf_hook.execution_device = original_device
+ else:
+ module_state_dict = module.state_dict()
+
+ for key in module_state_dict:
+ # ignore placeholder parameters that are still on the meta device
+ if module_state_dict[key].device == torch.device("meta"):
+ placeholders.add(name + f".{key}")
+ continue
+ params = module_state_dict[key]
+ state_dict[name + f".{key}"] = params
+ for key in placeholders.copy():
+ if key in state_dict:
+ placeholders.remove(key)
+ if placeholders:
+ logger.warning(f"The following tensors were not saved because they were still on meta device: {placeholders}")
+
+ return state_dict
+
+
+def get_state_dict_from_offload(
+ module: nn.Module,
+ module_name: str,
+ state_dict: Dict[str, Union[str, torch.tensor]],
+ device_to_put_offload: Union[int, str, torch.device] = "cpu",
+):
+ """
+ Retrieve the state dictionary (with parameters) from an offloaded module and load into a specified device (defualts
+ to cpu).
+
+ Args:
+ module: (`torch.nn.Module`):
+ The module we want to retrieve a state dictionary from
+ module_name: (`str`):
+ The name of the module of interest
+ state_dict (`Dict[str, Union[int, str, torch.device]]`):
+ Dictionary of {module names: parameters}
+ device_to_put_offload (`Union[int, str, torch.device]`):
+ Device to load offloaded parameters into, defaults to the cpu.
+ """
+ from ..hooks import AlignDevicesHook
+
+ root = module_name[: module_name.rfind(".")] # module name without .weight or .bias
+ preforward = False
+ if hasattr(module, "_hf_hook") and isinstance(module._hf_hook, AlignDevicesHook) and module._hf_hook.offload:
+ # assign the device to which the offloaded parameters will be sent
+ original_device = module._hf_hook.execution_device
+ module._hf_hook.execution_device = device_to_put_offload
+ module._hf_hook.pre_forward(module)
+ preforward = True
+
+ for m_key in module.state_dict():
+ params = module.state_dict()[m_key]
+ if (root + f".{m_key}") in state_dict:
+ state_dict[root + f".{m_key}"] = params
+
+ if preforward:
+ module._hf_hook.post_forward(module, torch.tensor([]))
+ module._hf_hook.execution_device = original_device
+
+ return state_dict
+
+
+def load_checkpoint_in_model(
+ model: nn.Module,
+ checkpoint: Union[str, os.PathLike],
+ device_map: Optional[Dict[str, Union[int, str, torch.device]]] = None,
+ offload_folder: Optional[Union[str, os.PathLike]] = None,
+ dtype: Optional[Union[str, torch.dtype]] = None,
+ offload_state_dict: bool = False,
+ offload_buffers: bool = False,
+ keep_in_fp32_modules: List[str] = None,
+ offload_8bit_bnb: bool = False,
+ strict: bool = False,
+):
+ """
+ Loads a (potentially sharded) checkpoint inside a model, potentially sending weights to a given device as they are
+ loaded.
+
+
+
+ Once loaded across devices, you still need to call [`dispatch_model`] on your model to make it able to run. To
+ group the checkpoint loading and dispatch in one single call, use [`load_checkpoint_and_dispatch`].
+
+
+
+ Args:
+ model (`torch.nn.Module`):
+ The model in which we want to load a checkpoint.
+ checkpoint (`str` or `os.PathLike`):
+ The folder checkpoint to load. It can be:
+ - a path to a file containing a whole model state dict
+ - a path to a `.json` file containing the index to a sharded checkpoint
+ - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint.
+ - a path to a folder containing a unique pytorch_model.bin or a model.safetensors file.
+ device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*):
+ A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer
+ name, once a given module name is inside, every submodule of it will be sent to the same device.
+ offload_folder (`str` or `os.PathLike`, *optional*):
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
+ dtype (`str` or `torch.dtype`, *optional*):
+ If provided, the weights will be converted to that type when loaded.
+ offload_state_dict (`bool`, *optional*, defaults to `False`):
+ If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if
+ the weight of the CPU state dict + the biggest shard does not fit.
+ offload_buffers (`bool`, *optional*, defaults to `False`):
+ Whether or not to include the buffers in the weights offloaded to disk.
+ keep_in_fp32_modules(`List[str]`, *optional*):
+ A list of the modules that we keep in `torch.float32` dtype.
+ offload_8bit_bnb (`bool`, *optional*):
+ Whether or not to enable offload of 8-bit modules on cpu/disk.
+ strict (`bool`, *optional*, defaults to `False`):
+ Whether to strictly enforce that the keys in the checkpoint state_dict match the keys of the model's
+ state_dict.
+
+ """
+ if offload_8bit_bnb:
+ from .bnb import quantize_and_offload_8bit
+
+ tied_params = find_tied_parameters(model)
+
+ if check_tied_parameters_in_config(model) and len(tied_params) == 0:
+ logger.warn(
+ "The model weights are not tied. Please use the `tie_weights` method before using the `infer_auto_device` function."
+ )
+ if device_map is not None:
+ check_tied_parameters_on_same_device(tied_params, device_map)
+
+ if offload_folder is None and device_map is not None and "disk" in device_map.values():
+ raise ValueError(
+ "At least one of the model submodule will be offloaded to disk, please pass along an `offload_folder`."
+ )
+ elif offload_folder is not None and device_map is not None and "disk" in device_map.values():
+ os.makedirs(offload_folder, exist_ok=True)
+
+ if isinstance(dtype, str):
+ # We accept "torch.float16" or just "float16"
+ dtype = dtype.replace("torch.", "")
+ dtype = getattr(torch, dtype)
+
+ checkpoint_files = None
+ index_filename = None
+ if os.path.isfile(checkpoint):
+ if str(checkpoint).endswith(".json"):
+ index_filename = checkpoint
+ else:
+ checkpoint_files = [checkpoint]
+ elif os.path.isdir(checkpoint):
+ # check if the whole state dict is present
+ potential_state_bin = [f for f in os.listdir(checkpoint) if f == WEIGHTS_NAME]
+ potential_state_safetensor = [f for f in os.listdir(checkpoint) if f == SAFE_WEIGHTS_NAME]
+ if len(potential_state_bin) == 1:
+ checkpoint_files = [os.path.join(checkpoint, potential_state_bin[0])]
+ elif len(potential_state_safetensor) == 1:
+ checkpoint_files = [os.path.join(checkpoint, potential_state_safetensor[0])]
+ else:
+ # otherwise check for sharded checkpoints
+ potential_index = [f for f in os.listdir(checkpoint) if f.endswith(".index.json")]
+ if len(potential_index) == 0:
+ raise ValueError(
+ f"{checkpoint} is not a folder containing a `.index.json` file or a {WEIGHTS_NAME} or a {SAFE_WEIGHTS_NAME} file"
+ )
+ elif len(potential_index) == 1:
+ index_filename = os.path.join(checkpoint, potential_index[0])
+ else:
+ raise ValueError(
+ f"{checkpoint} containing more than one `.index.json` file, delete the irrelevant ones."
+ )
+ else:
+ raise ValueError(
+ "`checkpoint` should be the path to a file containing a whole state dict, or the index of a sharded "
+ f"checkpoint, or a folder containing a sharded checkpoint or the whole state dict, but got {checkpoint}."
+ )
+
+ if index_filename is not None:
+ checkpoint_folder = os.path.split(index_filename)[0]
+ with open(index_filename) as f:
+ index = json.loads(f.read())
+
+ if "weight_map" in index:
+ index = index["weight_map"]
+ checkpoint_files = sorted(list(set(index.values())))
+ checkpoint_files = [os.path.join(checkpoint_folder, f) for f in checkpoint_files]
+
+ # Logic for missing/unexepected keys goes here.
+
+ offload_index = {}
+ if offload_state_dict:
+ state_dict_folder = tempfile.mkdtemp()
+ state_dict_index = {}
+
+ unexpected_keys = set()
+ model_keys = set(model.state_dict().keys())
+ buffer_names = [name for name, _ in model.named_buffers()]
+ for checkpoint_file in checkpoint_files:
+ loaded_checkpoint = load_state_dict(checkpoint_file, device_map=device_map)
+ if device_map is None:
+ model.load_state_dict(loaded_checkpoint, strict=strict)
+ unexpected_keys.update(set(loaded_checkpoint.keys()) - model_keys)
+ else:
+ for param_name, param in loaded_checkpoint.items():
+ # skip SCB parameter (for 8-bit serialization)
+ if "SCB" in param_name:
+ continue
+
+ if param_name not in model_keys:
+ unexpected_keys.add(param_name)
+ if not strict:
+ continue # Skip loading this parameter.
+
+ module_name = param_name
+
+ while len(module_name) > 0 and module_name not in device_map:
+ module_name = ".".join(module_name.split(".")[:-1])
+ if module_name == "" and "" not in device_map:
+ # TODO: group all errors and raise at the end.
+ raise ValueError(f"{param_name} doesn't have any device set.")
+ param_device = device_map[module_name]
+ new_dtype = dtype
+ if dtype is not None and torch.is_floating_point(param):
+ if keep_in_fp32_modules is not None and dtype == torch.float16:
+ proceed = False
+ for key in keep_in_fp32_modules:
+ if ((key in param_name) and (key + "." in param_name)) or key == param_name:
+ proceed = True
+ break
+ if proceed:
+ new_dtype = torch.float32
+
+ if "weight" in param_name and param_name.replace("weight", "SCB") in loaded_checkpoint.keys():
+ if param.dtype == torch.int8:
+ fp16_statistics = loaded_checkpoint[param_name.replace("weight", "SCB")]
+ else:
+ fp16_statistics = None
+
+ if param_device == "disk":
+ if offload_buffers or param_name not in buffer_names:
+ if new_dtype is None:
+ new_dtype = param.dtype
+ if offload_8bit_bnb:
+ quantize_and_offload_8bit(
+ model, param, param_name, new_dtype, offload_folder, offload_index, fp16_statistics
+ )
+ continue
+ else:
+ set_module_tensor_to_device(model, param_name, "meta", dtype=new_dtype)
+ offload_weight(param, param_name, offload_folder, index=offload_index)
+ elif param_device == "cpu" and offload_state_dict:
+ if new_dtype is None:
+ new_dtype = param.dtype
+ if offload_8bit_bnb:
+ quantize_and_offload_8bit(
+ model, param, param_name, new_dtype, state_dict_folder, state_dict_index, fp16_statistics
+ )
+ else:
+ set_module_tensor_to_device(model, param_name, "meta", dtype=new_dtype)
+ offload_weight(param, param_name, state_dict_folder, index=state_dict_index)
+ else:
+ set_module_tensor_to_device(
+ model,
+ param_name,
+ param_device,
+ value=param,
+ dtype=new_dtype,
+ fp16_statistics=fp16_statistics,
+ )
+
+ # Force Python to clean up.
+ del loaded_checkpoint
+ gc.collect()
+
+ if not strict and len(unexpected_keys) > 0:
+ logger.warning(
+ f"Some weights of the model checkpoint at {checkpoint} were not used when"
+ f" initializing {model.__class__.__name__}: {unexpected_keys}. This may or may not be an issue - make sure that the checkpoint does not have unnecessary parameters, or that the model definition correctly corresponds to the checkpoint."
+ )
+
+ save_offload_index(offload_index, offload_folder)
+
+ # Load back offloaded state dict on CPU
+ if offload_state_dict:
+ load_offloaded_weights(model, state_dict_index, state_dict_folder)
+ shutil.rmtree(state_dict_folder)
+
+ retie_parameters(model, tied_params)
+
+
+def get_mixed_precision_context_manager(native_amp: bool = False, autocast_kwargs: AutocastKwargs = None):
+ """
+ Return a context manager for autocasting mixed precision
+
+ Args:
+ native_amp (`bool`, *optional*, defaults to False):
+ Whether mixed precision is actually enabled.
+ cache_enabled (`bool`, *optional*, defaults to True):
+ Whether the weight cache inside autocast should be enabled.
+ """
+ state = AcceleratorState()
+ if autocast_kwargs is None:
+ autocast_kwargs = {}
+ else:
+ autocast_kwargs = autocast_kwargs.to_kwargs()
+ if native_amp:
+ device_type = (
+ "cuda"
+ if (state.distributed_type == DistributedType.XLA and is_torch_xla_available(check_is_gpu=True))
+ else state.device.type
+ )
+ if state.mixed_precision == "fp16":
+ return torch.autocast(device_type=device_type, dtype=torch.float16, **autocast_kwargs)
+ elif state.mixed_precision in ["bf16", "fp8"] and state.distributed_type in [
+ DistributedType.NO,
+ DistributedType.MULTI_CPU,
+ DistributedType.MULTI_GPU,
+ DistributedType.MULTI_MLU,
+ DistributedType.MULTI_MUSA,
+ DistributedType.MULTI_NPU,
+ DistributedType.MULTI_XPU,
+ DistributedType.FSDP,
+ DistributedType.XLA,
+ ]:
+ return torch.autocast(device_type=device_type, dtype=torch.bfloat16, **autocast_kwargs)
+ else:
+ return torch.autocast(device_type=device_type, **autocast_kwargs)
+ else:
+ return contextlib.nullcontext()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/offload.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/offload.py
new file mode 100644
index 0000000000000000000000000000000000000000..d064847ca21bde644b443de315b239414aa2fd51
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/offload.py
@@ -0,0 +1,213 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import os
+from collections.abc import Mapping
+from typing import Dict, List, Optional, Union
+
+import numpy as np
+import torch
+from safetensors import safe_open
+
+
+def offload_weight(weight, weight_name, offload_folder, index=None):
+ dtype = None
+ # Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16.
+ if str(weight.dtype) == "torch.bfloat16":
+ # Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s.
+ weight = weight.view(torch.int16)
+ dtype = "bfloat16"
+ array = weight.cpu().numpy()
+ tensor_file = os.path.join(offload_folder, f"{weight_name}.dat")
+ if index is not None:
+ if dtype is None:
+ dtype = str(array.dtype)
+ index[weight_name] = {"dtype": dtype, "shape": list(array.shape)}
+ if array.ndim == 0:
+ array = array[None]
+ file_array = np.memmap(tensor_file, dtype=array.dtype, mode="w+", shape=array.shape)
+ file_array[:] = array[:]
+ file_array.flush()
+ return index
+
+
+def load_offloaded_weight(weight_file, weight_info):
+ shape = tuple(weight_info["shape"])
+ if shape == ():
+ # NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
+ shape = (1,)
+
+ dtype = weight_info["dtype"]
+ if dtype == "bfloat16":
+ # NumPy does not support bfloat16 so this was saved as a int16
+ dtype = "int16"
+
+ weight = np.memmap(weight_file, dtype=dtype, shape=shape, mode="r")
+
+ if len(weight_info["shape"]) == 0:
+ weight = weight[0]
+ weight = torch.tensor(weight)
+ if weight_info["dtype"] == "bfloat16":
+ weight = weight.view(torch.bfloat16)
+
+ return weight
+
+
+def save_offload_index(index, offload_folder):
+ if index is None or len(index) == 0:
+ # Nothing to save
+ return
+
+ offload_index_file = os.path.join(offload_folder, "index.json")
+ if os.path.isfile(offload_index_file):
+ with open(offload_index_file, encoding="utf-8") as f:
+ current_index = json.load(f)
+ else:
+ current_index = {}
+ current_index.update(index)
+
+ with open(offload_index_file, "w", encoding="utf-8") as f:
+ json.dump(current_index, f, indent=2)
+
+
+def offload_state_dict(save_dir: Union[str, os.PathLike], state_dict: Dict[str, torch.Tensor]):
+ """
+ Offload a state dict in a given folder.
+
+ Args:
+ save_dir (`str` or `os.PathLike`):
+ The directory in which to offload the state dict.
+ state_dict (`Dict[str, torch.Tensor]`):
+ The dictionary of tensors to offload.
+ """
+ os.makedirs(save_dir, exist_ok=True)
+ index = {}
+ for name, parameter in state_dict.items():
+ index = offload_weight(parameter, name, save_dir, index=index)
+
+ # Update index
+ save_offload_index(index, save_dir)
+
+
+class PrefixedDataset(Mapping):
+ """
+ Will access keys in a given dataset by adding a prefix.
+
+ Args:
+ dataset (`Mapping`): Any map with string keys.
+ prefix (`str`): A prefix to add when trying to access any element in the underlying dataset.
+ """
+
+ def __init__(self, dataset: Mapping, prefix: str):
+ self.dataset = dataset
+ self.prefix = prefix
+
+ def __getitem__(self, key):
+ return self.dataset[f"{self.prefix}{key}"]
+
+ def __iter__(self):
+ return iter([key for key in self.dataset if key.startswith(self.prefix)])
+
+ def __len__(self):
+ return len(self.dataset)
+
+
+class OffloadedWeightsLoader(Mapping):
+ """
+ A collection that loads weights stored in a given state dict or memory-mapped on disk.
+
+ Args:
+ state_dict (`Dict[str, torch.Tensor]`, *optional*):
+ A dictionary parameter name to tensor.
+ save_folder (`str` or `os.PathLike`, *optional*):
+ The directory in which the weights are stored (by `offload_state_dict` for instance).
+ index (`Dict`, *optional*):
+ A dictionary from weight name to their information (`dtype`/ `shape` or safetensors filename). Will default
+ to the index saved in `save_folder`.
+ """
+
+ def __init__(
+ self,
+ state_dict: Dict[str, torch.Tensor] = None,
+ save_folder: Optional[Union[str, os.PathLike]] = None,
+ index: Mapping = None,
+ device=None,
+ ):
+ if state_dict is None and save_folder is None and index is None:
+ raise ValueError("Need either a `state_dict`, a `save_folder` or an `index` containing offloaded weights.")
+
+ self.state_dict = {} if state_dict is None else state_dict
+ self.save_folder = save_folder
+ if index is None and save_folder is not None:
+ with open(os.path.join(save_folder, "index.json")) as f:
+ index = json.load(f)
+ self.index = {} if index is None else index
+ self.all_keys = list(self.state_dict.keys())
+ self.all_keys.extend([key for key in self.index if key not in self.all_keys])
+ self.device = device
+
+ def __getitem__(self, key: str):
+ # State dict gets priority
+ if key in self.state_dict:
+ return self.state_dict[key]
+ weight_info = self.index[key]
+ if weight_info.get("safetensors_file") is not None:
+ device = "cpu" if self.device is None else self.device
+ tensor = None
+ try:
+ with safe_open(weight_info["safetensors_file"], framework="pt", device=device) as f:
+ tensor = f.get_tensor(weight_info.get("weight_name", key))
+ except TypeError:
+ # if failed to get_tensor on the device, such as bf16 on mps, try to load it on CPU first
+ with safe_open(weight_info["safetensors_file"], framework="pt", device="cpu") as f:
+ tensor = f.get_tensor(weight_info.get("weight_name", key))
+
+ if "dtype" in weight_info:
+ tensor = tensor.to(getattr(torch, weight_info["dtype"]))
+
+ if tensor.device != torch.device(device):
+ tensor = tensor.to(device)
+ return tensor
+
+ weight_file = os.path.join(self.save_folder, f"{key}.dat")
+ return load_offloaded_weight(weight_file, weight_info)
+
+ def __iter__(self):
+ return iter(self.all_keys)
+
+ def __len__(self):
+ return len(self.all_keys)
+
+
+def extract_submodules_state_dict(state_dict: Dict[str, torch.Tensor], submodule_names: List[str]):
+ """
+ Extract the sub state-dict corresponding to a list of given submodules.
+
+ Args:
+ state_dict (`Dict[str, torch.Tensor]`): The state dict to extract from.
+ submodule_names (`List[str]`): The list of submodule names we want to extract.
+ """
+ result = {}
+ for module_name in submodule_names:
+ # We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the
+ # submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance)
+ result.update(
+ {
+ key: param
+ for key, param in state_dict.items()
+ if key == module_name or key.startswith(module_name + ".")
+ }
+ )
+ return result
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/operations.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/operations.py
new file mode 100644
index 0000000000000000000000000000000000000000..162009e76b6c65d6cd9939522cacb13007e6226d
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/operations.py
@@ -0,0 +1,868 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+A set of basic tensor ops compatible with tpu, gpu, and multigpu
+"""
+
+import pickle
+import warnings
+from contextlib import contextmanager, nullcontext
+from functools import update_wrapper, wraps
+from typing import Any, Mapping
+
+import torch
+
+from ..state import AcceleratorState, PartialState
+from .constants import TORCH_DISTRIBUTED_OPERATION_TYPES
+from .dataclasses import DistributedType, TensorInformation
+from .imports import (
+ is_npu_available,
+ is_torch_distributed_available,
+ is_torch_version,
+ is_torch_xla_available,
+ is_xpu_available,
+)
+
+
+if is_torch_xla_available():
+ import torch_xla.core.xla_model as xm
+
+if is_torch_distributed_available():
+ from torch.distributed import ReduceOp
+
+
+def is_torch_tensor(tensor):
+ return isinstance(tensor, torch.Tensor)
+
+
+def is_torch_xpu_tensor(tensor):
+ return isinstance(
+ tensor,
+ torch.xpu.FloatTensor,
+ torch.xpu.ByteTensor,
+ torch.xpu.IntTensor,
+ torch.xpu.LongTensor,
+ torch.xpu.HalfTensor,
+ torch.xpu.DoubleTensor,
+ torch.xpu.BFloat16Tensor,
+ )
+
+
+def is_tensor_information(tensor_info):
+ return isinstance(tensor_info, TensorInformation)
+
+
+def is_namedtuple(data):
+ """
+ Checks if `data` is a `namedtuple` or not. Can have false positives, but only if a user is trying to mimic a
+ `namedtuple` perfectly.
+ """
+ return isinstance(data, tuple) and hasattr(data, "_asdict") and hasattr(data, "_fields")
+
+
+def honor_type(obj, generator):
+ """
+ Cast a generator to the same type as obj (list, tuple, or namedtuple)
+ """
+ # Some objects may not be able to instantiate from a generator directly
+ if is_namedtuple(obj):
+ return type(obj)(*list(generator))
+ else:
+ return type(obj)(generator)
+
+
+def recursively_apply(func, data, *args, test_type=is_torch_tensor, error_on_other_type=False, **kwargs):
+ """
+ Recursively apply a function on a data structure that is a nested list/tuple/dictionary of a given base type.
+
+ Args:
+ func (`callable`):
+ The function to recursively apply.
+ data (nested list/tuple/dictionary of `main_type`):
+ The data on which to apply `func`
+ *args:
+ Positional arguments that will be passed to `func` when applied on the unpacked data.
+ main_type (`type`, *optional*, defaults to `torch.Tensor`):
+ The base type of the objects to which apply `func`.
+ error_on_other_type (`bool`, *optional*, defaults to `False`):
+ Whether to return an error or not if after unpacking `data`, we get on an object that is not of type
+ `main_type`. If `False`, the function will leave objects of types different than `main_type` unchanged.
+ **kwargs (additional keyword arguments, *optional*):
+ Keyword arguments that will be passed to `func` when applied on the unpacked data.
+
+ Returns:
+ The same data structure as `data` with `func` applied to every object of type `main_type`.
+ """
+ if isinstance(data, (tuple, list)):
+ return honor_type(
+ data,
+ (
+ recursively_apply(
+ func, o, *args, test_type=test_type, error_on_other_type=error_on_other_type, **kwargs
+ )
+ for o in data
+ ),
+ )
+ elif isinstance(data, Mapping):
+ return type(data)(
+ {
+ k: recursively_apply(
+ func, v, *args, test_type=test_type, error_on_other_type=error_on_other_type, **kwargs
+ )
+ for k, v in data.items()
+ }
+ )
+ elif test_type(data):
+ return func(data, *args, **kwargs)
+ elif error_on_other_type:
+ raise TypeError(
+ f"Unsupported types ({type(data)}) passed to `{func.__name__}`. Only nested list/tuple/dicts of "
+ f"objects that are valid for `{test_type.__name__}` should be passed."
+ )
+ return data
+
+
+def send_to_device(tensor, device, non_blocking=False, skip_keys=None):
+ """
+ Recursively sends the elements in a nested list/tuple/dictionary of tensors to a given device.
+
+ Args:
+ tensor (nested list/tuple/dictionary of `torch.Tensor`):
+ The data to send to a given device.
+ device (`torch.device`):
+ The device to send the data to.
+
+ Returns:
+ The same data structure as `tensor` with all tensors sent to the proper device.
+ """
+ if is_torch_tensor(tensor) or hasattr(tensor, "to"):
+ # `torch.Tensor.to("npu")` could not find context when called for the first time (see this [issue](https://gitee.com/ascend/pytorch/issues/I8KECW?from=project-issue)).
+ if device == "npu":
+ device = "npu:0"
+ if device == "xpu":
+ device = "xpu:0"
+ try:
+ return tensor.to(device, non_blocking=non_blocking)
+ except TypeError: # .to() doesn't accept non_blocking as kwarg
+ return tensor.to(device)
+ except AssertionError as error:
+ # `torch.Tensor.to()` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)).
+ # This call is inside the try-block since is_npu_available is not supported by torch.compile.
+ if is_npu_available():
+ if isinstance(device, int):
+ device = f"npu:{device}"
+ elif is_xpu_available():
+ if isinstance(device, int):
+ device = f"xpu:{device}"
+ else:
+ raise error
+ try:
+ return tensor.to(device, non_blocking=non_blocking)
+ except TypeError: # .to() doesn't accept non_blocking as kwarg
+ return tensor.to(device)
+ elif isinstance(tensor, (tuple, list)):
+ return honor_type(
+ tensor, (send_to_device(t, device, non_blocking=non_blocking, skip_keys=skip_keys) for t in tensor)
+ )
+ elif isinstance(tensor, Mapping):
+ if isinstance(skip_keys, str):
+ skip_keys = [skip_keys]
+ elif skip_keys is None:
+ skip_keys = []
+ return type(tensor)(
+ {
+ k: t if k in skip_keys else send_to_device(t, device, non_blocking=non_blocking, skip_keys=skip_keys)
+ for k, t in tensor.items()
+ }
+ )
+ else:
+ return tensor
+
+
+def get_data_structure(data):
+ """
+ Recursively gathers the information needed to rebuild a nested list/tuple/dictionary of tensors.
+
+ Args:
+ data (nested list/tuple/dictionary of `torch.Tensor`):
+ The data to send to analyze.
+
+ Returns:
+ The same data structure as `data` with [`~utils.TensorInformation`] instead of tensors.
+ """
+
+ def _get_data_structure(tensor):
+ return TensorInformation(shape=tensor.shape, dtype=tensor.dtype)
+
+ return recursively_apply(_get_data_structure, data)
+
+
+def get_shape(data):
+ """
+ Recursively gathers the shape of a nested list/tuple/dictionary of tensors as a list.
+
+ Args:
+ data (nested list/tuple/dictionary of `torch.Tensor`):
+ The data to send to analyze.
+
+ Returns:
+ The same data structure as `data` with lists of tensor shapes instead of tensors.
+ """
+
+ def _get_shape(tensor):
+ return list(tensor.shape)
+
+ return recursively_apply(_get_shape, data)
+
+
+def initialize_tensors(data_structure):
+ """
+ Recursively initializes tensors from a nested list/tuple/dictionary of [`~utils.TensorInformation`].
+
+ Returns:
+ The same data structure as `data` with tensors instead of [`~utils.TensorInformation`].
+ """
+
+ def _initialize_tensor(tensor_info):
+ return torch.empty(*tensor_info.shape, dtype=tensor_info.dtype)
+
+ return recursively_apply(_initialize_tensor, data_structure, test_type=is_tensor_information)
+
+
+def find_batch_size(data):
+ """
+ Recursively finds the batch size in a nested list/tuple/dictionary of lists of tensors.
+
+ Args:
+ data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to find the batch size.
+
+ Returns:
+ `int`: The batch size.
+ """
+ if isinstance(data, (tuple, list, Mapping)) and (len(data) == 0):
+ raise ValueError(f"Cannot find the batch size from empty {type(data)}.")
+
+ if isinstance(data, (tuple, list)):
+ return find_batch_size(data[0])
+ elif isinstance(data, Mapping):
+ for k in data.keys():
+ return find_batch_size(data[k])
+ elif not isinstance(data, torch.Tensor):
+ raise TypeError(f"Can only find the batch size of tensors but got {type(data)}.")
+ return data.shape[0]
+
+
+def ignorant_find_batch_size(data):
+ """
+ Same as [`utils.operations.find_batch_size`] except will ignore if `ValueError` and `TypeErrors` are raised
+
+ Args:
+ data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to find the batch size.
+
+ Returns:
+ `int`: The batch size.
+ """
+ try:
+ return find_batch_size(data)
+ except (ValueError, TypeError):
+ pass
+ return None
+
+
+def listify(data):
+ """
+ Recursively finds tensors in a nested list/tuple/dictionary and converts them to a list of numbers.
+
+ Args:
+ data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to convert to regular numbers.
+
+ Returns:
+ The same data structure as `data` with lists of numbers instead of `torch.Tensor`.
+ """
+
+ def _convert_to_list(tensor):
+ tensor = tensor.detach().cpu()
+ if tensor.dtype == torch.bfloat16:
+ # As of Numpy 1.21.4, NumPy does not support bfloat16 (see
+ # https://github.com/numpy/numpy/blob/a47ecdea856986cd60eabbd53265c2ca5916ad5d/doc/source/user/basics.types.rst ).
+ # Until Numpy adds bfloat16, we must convert float32.
+ tensor = tensor.to(torch.float32)
+ return tensor.tolist()
+
+ return recursively_apply(_convert_to_list, data)
+
+
+def _tpu_gather(tensor):
+ def _tpu_gather_one(tensor):
+ if tensor.ndim == 0:
+ tensor = tensor.clone()[None]
+
+ # Can only gather contiguous tensors
+ if not tensor.is_contiguous():
+ tensor = tensor.contiguous()
+ return xm.all_gather(tensor)
+
+ res = recursively_apply(_tpu_gather_one, tensor, error_on_other_type=True)
+ xm.mark_step()
+ return res
+
+
+def _gpu_gather(tensor):
+ state = PartialState()
+ if is_torch_version(">=", "1.13"):
+ gather_op = torch.distributed.all_gather_into_tensor
+ else:
+ gather_op = torch.distributed._all_gather_base
+
+ def _gpu_gather_one(tensor):
+ if tensor.ndim == 0:
+ tensor = tensor.clone()[None]
+
+ # Can only gather contiguous tensors
+ if not tensor.is_contiguous():
+ tensor = tensor.contiguous()
+
+ if state.backend is not None and state.backend != "gloo":
+ # We use `empty` as `all_gather_into_tensor` slightly
+ # differs from `all_gather` for better efficiency,
+ # and we rely on the number of items in the tensor
+ # rather than its direct shape
+ output_tensors = torch.empty(
+ state.num_processes * tensor.numel(),
+ dtype=tensor.dtype,
+ device=state.device,
+ )
+ gather_op(output_tensors, tensor)
+ return output_tensors.view(-1, *tensor.size()[1:])
+ else:
+ # a backend of `None` is always CPU
+ # also gloo does not support `all_gather_into_tensor`,
+ # which will result in a larger memory overhead for the op
+ output_tensors = [torch.empty_like(tensor) for _ in range(state.num_processes)]
+ torch.distributed.all_gather(output_tensors, tensor)
+ return torch.cat(output_tensors, dim=0)
+
+ return recursively_apply(_gpu_gather_one, tensor, error_on_other_type=True)
+
+
+class DistributedOperationException(Exception):
+ """
+ An exception class for distributed operations. Raised if the operation cannot be performed due to the shape of the
+ tensors.
+ """
+
+ pass
+
+
+def verify_operation(function):
+ """
+ Verifies that `tensor` is the same shape across all processes. Only ran if `PartialState().debug` is `True`.
+ """
+
+ @wraps(function)
+ def wrapper(*args, **kwargs):
+ if PartialState().distributed_type == DistributedType.NO or not PartialState().debug:
+ return function(*args, **kwargs)
+ operation = f"{function.__module__}.{function.__name__}"
+ if "tensor" in kwargs:
+ tensor = kwargs["tensor"]
+ else:
+ tensor = args[0]
+ if PartialState().device.type != find_device(tensor).type:
+ raise DistributedOperationException(
+ f"One or more of the tensors passed to {operation} were not on the {tensor.device.type} while the `Accelerator` is configured for {PartialState().device.type}. "
+ f"Please move it to the {PartialState().device.type} before calling {operation}."
+ )
+ shapes = get_shape(tensor)
+ output = gather_object([shapes])
+ if output[0] is not None:
+ are_same = output.count(output[0]) == len(output)
+ if not are_same:
+ process_shape_str = "\n - ".join([f"Process {i}: {shape}" for i, shape in enumerate(output)])
+ raise DistributedOperationException(
+ f"Cannot apply desired operation due to shape mismatches. "
+ "All shapes across devices must be valid."
+ f"\n\nOperation: `{operation}`\nInput shapes:\n - {process_shape_str}"
+ )
+ return function(*args, **kwargs)
+
+ return wrapper
+
+
+def chained_operation(function):
+ """
+ Checks that `verify_operation` failed and if so reports a more helpful error chaining the existing
+ `DistributedOperationException`.
+ """
+
+ @wraps(function)
+ def wrapper(*args, **kwargs):
+ try:
+ return function(*args, **kwargs)
+ except DistributedOperationException as e:
+ operation = f"{function.__module__}.{function.__name__}"
+ raise DistributedOperationException(
+ f"Error found while calling `{operation}`. Please see the earlier error for more details."
+ ) from e
+
+ return wrapper
+
+
+@verify_operation
+def gather(tensor):
+ """
+ Recursively gather tensor in a nested list/tuple/dictionary of tensors from all devices.
+
+ Args:
+ tensor (nested list/tuple/dictionary of `torch.Tensor`):
+ The data to gather.
+
+ Returns:
+ The same data structure as `tensor` with all tensors sent to the proper device.
+ """
+ if PartialState().distributed_type == DistributedType.XLA:
+ return _tpu_gather(tensor)
+ elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES:
+ return _gpu_gather(tensor)
+ else:
+ return tensor
+
+
+def _gpu_gather_object(object: Any):
+ output_objects = [None for _ in range(PartialState().num_processes)]
+ torch.distributed.all_gather_object(output_objects, object)
+ # all_gather_object returns a list of lists, so we need to flatten it
+ return [x for y in output_objects for x in y]
+
+
+def gather_object(object: Any):
+ """
+ Recursively gather object in a nested list/tuple/dictionary of objects from all devices.
+
+ Args:
+ object (nested list/tuple/dictionary of picklable object):
+ The data to gather.
+
+ Returns:
+ The same data structure as `object` with all the objects sent to every device.
+ """
+ if PartialState().distributed_type == DistributedType.XLA:
+ raise NotImplementedError("gather objects in TPU is not supported")
+ elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES:
+ return _gpu_gather_object(object)
+ else:
+ return object
+
+
+def _gpu_broadcast(data, src=0):
+ def _gpu_broadcast_one(tensor, src=0):
+ torch.distributed.broadcast(tensor, src=src)
+ return tensor
+
+ return recursively_apply(_gpu_broadcast_one, data, error_on_other_type=True, src=src)
+
+
+def _tpu_broadcast(tensor, src=0, name="broadcast tensor"):
+ if isinstance(tensor, (list, tuple)):
+ return honor_type(tensor, (_tpu_broadcast(t, name=f"{name}_{i}") for i, t in enumerate(tensor)))
+ elif isinstance(tensor, Mapping):
+ return type(tensor)({k: _tpu_broadcast(v, name=f"{name}_{k}") for k, v in tensor.items()})
+ return xm.mesh_reduce(name, tensor, lambda x: x[src])
+
+
+TENSOR_TYPE_TO_INT = {
+ torch.float: 1,
+ torch.double: 2,
+ torch.half: 3,
+ torch.bfloat16: 4,
+ torch.uint8: 5,
+ torch.int8: 6,
+ torch.int16: 7,
+ torch.int32: 8,
+ torch.int64: 9,
+ torch.bool: 10,
+}
+
+TENSOR_INT_TO_DTYPE = {v: k for k, v in TENSOR_TYPE_TO_INT.items()}
+
+
+def gather_tensor_shape(tensor):
+ """
+ Grabs the shape of `tensor` only available on one process and returns a tensor of its shape
+ """
+ # Allocate 80 bytes to store the shape
+ max_tensor_dimension = 2**20
+ state = PartialState()
+ base_tensor = torch.empty(max_tensor_dimension, dtype=torch.int, device=state.device)
+
+ # Since PyTorch can't just send a tensor to another GPU without
+ # knowing its size, we store the size of the tensor with data
+ # in an allocation
+ if tensor is not None:
+ shape = tensor.shape
+ tensor_dtype = TENSOR_TYPE_TO_INT[tensor.dtype]
+ base_tensor[: len(shape) + 1] = torch.tensor(list(shape) + [tensor_dtype], dtype=int)
+ # Perform a reduction to copy the size data onto all GPUs
+ base_tensor = reduce(base_tensor, reduction="sum")
+ base_tensor = base_tensor[base_tensor.nonzero()]
+ # The last non-zero data contains the coded dtype the source tensor is
+ dtype = int(base_tensor[-1:][0])
+ base_tensor = base_tensor[:-1]
+ return base_tensor, dtype
+
+
+def copy_tensor_to_devices(tensor=None) -> torch.Tensor:
+ """
+ Copys a tensor that only exists on a single device and broadcasts it to other devices. Differs from `broadcast` as
+ each worker doesn't need to know its shape when used (and tensor can be `None`)
+
+ Args:
+ tensor (`torch.tensor`):
+ The tensor that should be sent to all devices. Must only have it be defined on a single device, the rest
+ should be `None`.
+ """
+ state = PartialState()
+ shape, dtype = gather_tensor_shape(tensor)
+ if tensor is None:
+ tensor = torch.zeros(shape, dtype=TENSOR_INT_TO_DTYPE[dtype]).to(state.device)
+ return reduce(tensor, reduction="sum")
+
+
+@verify_operation
+def broadcast(tensor, from_process: int = 0):
+ """
+ Recursively broadcast tensor in a nested list/tuple/dictionary of tensors to all devices.
+
+ Args:
+ tensor (nested list/tuple/dictionary of `torch.Tensor`):
+ The data to gather.
+ from_process (`int`, *optional*, defaults to 0):
+ The process from which to send the data
+
+ Returns:
+ The same data structure as `tensor` with all tensors broadcasted to the proper device.
+ """
+ if PartialState().distributed_type == DistributedType.XLA:
+ return _tpu_broadcast(tensor, src=from_process, name="accelerate.utils.broadcast")
+ elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES:
+ return _gpu_broadcast(tensor, src=from_process)
+ else:
+ return tensor
+
+
+def broadcast_object_list(object_list, from_process: int = 0):
+ """
+ Broadcast a list of picklable objects form one process to the others.
+
+ Args:
+ object_list (list of picklable objects):
+ The list of objects to broadcast. This list will be modified inplace.
+ from_process (`int`, *optional*, defaults to 0):
+ The process from which to send the data.
+
+ Returns:
+ The same list containing the objects from process 0.
+ """
+ if PartialState().distributed_type == DistributedType.XLA:
+ for i, obj in enumerate(object_list):
+ object_list[i] = xm.mesh_reduce("accelerate.utils.broadcast_object_list", obj, lambda x: x[from_process])
+ elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES:
+ torch.distributed.broadcast_object_list(object_list, src=from_process)
+ return object_list
+
+
+def slice_tensors(data, tensor_slice, process_index=None, num_processes=None):
+ """
+ Recursively takes a slice in a nested list/tuple/dictionary of tensors.
+
+ Args:
+ data (nested list/tuple/dictionary of `torch.Tensor`):
+ The data to slice.
+ tensor_slice (`slice`):
+ The slice to take.
+
+ Returns:
+ The same data structure as `data` with all the tensors slices.
+ """
+
+ def _slice_tensor(tensor, tensor_slice):
+ return tensor[tensor_slice]
+
+ return recursively_apply(_slice_tensor, data, tensor_slice)
+
+
+def concatenate(data, dim=0):
+ """
+ Recursively concatenate the tensors in a nested list/tuple/dictionary of lists of tensors with the same shape.
+
+ Args:
+ data (nested list/tuple/dictionary of lists of tensors `torch.Tensor`):
+ The data to concatenate.
+ dim (`int`, *optional*, defaults to 0):
+ The dimension on which to concatenate.
+
+ Returns:
+ The same data structure as `data` with all the tensors concatenated.
+ """
+ if isinstance(data[0], (tuple, list)):
+ return honor_type(data[0], (concatenate([d[i] for d in data], dim=dim) for i in range(len(data[0]))))
+ elif isinstance(data[0], Mapping):
+ return type(data[0])({k: concatenate([d[k] for d in data], dim=dim) for k in data[0].keys()})
+ elif not isinstance(data[0], torch.Tensor):
+ raise TypeError(f"Can only concatenate tensors but got {type(data[0])}")
+ return torch.cat(data, dim=dim)
+
+
+class CannotPadNestedTensorWarning(UserWarning):
+ pass
+
+
+@chained_operation
+def pad_across_processes(tensor, dim=0, pad_index=0, pad_first=False):
+ """
+ Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so they
+ can safely be gathered.
+
+ Args:
+ tensor (nested list/tuple/dictionary of `torch.Tensor`):
+ The data to gather.
+ dim (`int`, *optional*, defaults to 0):
+ The dimension on which to pad.
+ pad_index (`int`, *optional*, defaults to 0):
+ The value with which to pad.
+ pad_first (`bool`, *optional*, defaults to `False`):
+ Whether to pad at the beginning or the end.
+ """
+
+ def _pad_across_processes(tensor, dim=0, pad_index=0, pad_first=False):
+ if getattr(tensor, "is_nested", False):
+ warnings.warn(
+ "Cannot pad nested tensors without more information. Leaving unprocessed.",
+ CannotPadNestedTensorWarning,
+ )
+ return tensor
+ if dim >= len(tensor.shape):
+ return tensor
+
+ # Gather all sizes
+ size = torch.tensor(tensor.shape, device=tensor.device)[None]
+ sizes = gather(size).cpu()
+ # Then pad to the maximum size
+ max_size = max(s[dim] for s in sizes)
+ if max_size == tensor.shape[dim]:
+ return tensor
+
+ old_size = tensor.shape
+ new_size = list(old_size)
+ new_size[dim] = max_size
+ new_tensor = tensor.new_zeros(tuple(new_size)) + pad_index
+ if pad_first:
+ indices = tuple(
+ slice(max_size - old_size[dim], max_size) if i == dim else slice(None) for i in range(len(new_size))
+ )
+ else:
+ indices = tuple(slice(0, old_size[dim]) if i == dim else slice(None) for i in range(len(new_size)))
+ new_tensor[indices] = tensor
+ return new_tensor
+
+ return recursively_apply(
+ _pad_across_processes, tensor, error_on_other_type=True, dim=dim, pad_index=pad_index, pad_first=pad_first
+ )
+
+
+def pad_input_tensors(tensor, batch_size, num_processes, dim=0):
+ """
+ Takes a `tensor` of arbitrary size and pads it so that it can work given `num_processes` needed dimensions.
+
+ New tensors are just the last input repeated.
+
+ E.g.:
+ Tensor: ([3,4,4]) Num processes: 4 Expected result shape: ([4,4,4])
+
+ """
+
+ def _pad_input_tensors(tensor, batch_size, num_processes, dim=0):
+ remainder = batch_size // num_processes
+ last_inputs = batch_size - (remainder * num_processes)
+ if batch_size // num_processes == 0:
+ to_pad = num_processes - batch_size
+ else:
+ to_pad = num_processes - (batch_size // num_processes)
+ # In the rare case that `to_pad` is negative,
+ # we need to pad the last inputs - the found `to_pad`
+ if last_inputs > to_pad & to_pad < 1:
+ to_pad = last_inputs - to_pad
+ old_size = tensor.shape
+ new_size = list(old_size)
+ new_size[0] = batch_size + to_pad
+ new_tensor = tensor.new_zeros(tuple(new_size))
+ indices = tuple(slice(0, old_size[dim]) if i == dim else slice(None) for i in range(len(new_size)))
+ new_tensor[indices] = tensor
+ return new_tensor
+
+ return recursively_apply(
+ _pad_input_tensors,
+ tensor,
+ error_on_other_type=True,
+ batch_size=batch_size,
+ num_processes=num_processes,
+ dim=dim,
+ )
+
+
+@verify_operation
+def reduce(tensor, reduction="mean", scale=1.0):
+ """
+ Recursively reduce the tensors in a nested list/tuple/dictionary of lists of tensors across all processes by the
+ mean of a given operation.
+
+ Args:
+ tensor (nested list/tuple/dictionary of `torch.Tensor`):
+ The data to reduce.
+ reduction (`str`, *optional*, defaults to `"mean"`):
+ A reduction method. Can be of "mean", "sum", or "none"
+ scale (`float`, *optional*):
+ A default scaling value to be applied after the reduce, only valied on XLA.
+
+ Returns:
+ The same data structure as `data` with all the tensors reduced.
+ """
+
+ def _reduce_across_processes(tensor, reduction="mean", scale=1.0):
+ state = PartialState()
+ cloned_tensor = tensor.clone()
+ if state.distributed_type == DistributedType.NO:
+ return cloned_tensor
+ if state.distributed_type == DistributedType.XLA:
+ # Some processes may have different HLO graphs than other
+ # processes, for example in the breakpoint API
+ # accelerator.set_trigger(). Use mark_step to make HLOs
+ # the same on all processes.
+ xm.mark_step()
+ xm.all_reduce(xm.REDUCE_SUM, [cloned_tensor], scale)
+ xm.mark_step()
+ elif state.distributed_type.value in TORCH_DISTRIBUTED_OPERATION_TYPES:
+ torch.distributed.all_reduce(cloned_tensor, ReduceOp.SUM)
+ if reduction == "mean":
+ cloned_tensor /= state.num_processes
+ return cloned_tensor
+
+ return recursively_apply(
+ _reduce_across_processes, tensor, error_on_other_type=True, reduction=reduction, scale=scale
+ )
+
+
+def convert_to_fp32(tensor):
+ """
+ Recursively converts the elements nested list/tuple/dictionary of tensors in FP16/BF16 precision to FP32.
+
+ Args:
+ tensor (nested list/tuple/dictionary of `torch.Tensor`):
+ The data to convert from FP16/BF16 to FP32.
+
+ Returns:
+ The same data structure as `tensor` with all tensors that were in FP16/BF16 precision converted to FP32.
+ """
+
+ def _convert_to_fp32(tensor):
+ return tensor.float()
+
+ def _is_fp16_bf16_tensor(tensor):
+ return (is_torch_tensor(tensor) or hasattr(tensor, "dtype")) and tensor.dtype in (
+ torch.float16,
+ torch.bfloat16,
+ )
+
+ return recursively_apply(_convert_to_fp32, tensor, test_type=_is_fp16_bf16_tensor)
+
+
+class ConvertOutputsToFp32:
+ """
+ Decorator to apply to a function outputing tensors (like a model forward pass) that ensures the outputs in FP16
+ precision will be convert back to FP32.
+
+ Args:
+ model_forward (`Callable`):
+ The function which outputs we want to treat.
+
+ Returns:
+ The same function as `model_forward` but with converted outputs.
+ """
+
+ def __init__(self, model_forward):
+ self.model_forward = model_forward
+ update_wrapper(self, model_forward)
+
+ def __call__(self, *args, **kwargs):
+ return convert_to_fp32(self.model_forward(*args, **kwargs))
+
+ def __getstate__(self):
+ raise pickle.PicklingError(
+ "Cannot pickle a prepared model with automatic mixed precision, please unwrap the model with `Accelerator.unwrap_model(model)` before pickling it."
+ )
+
+
+def convert_outputs_to_fp32(model_forward):
+ model_forward = ConvertOutputsToFp32(model_forward)
+
+ def forward(*args, **kwargs):
+ return model_forward(*args, **kwargs)
+
+ # To act like a decorator so that it can be popped when doing `extract_model_from_parallel`
+ forward.__wrapped__ = model_forward
+
+ return forward
+
+
+def find_device(data):
+ """
+ Finds the device on which a nested dict/list/tuple of tensors lies (assuming they are all on the same device).
+
+ Args:
+ (nested list/tuple/dictionary of `torch.Tensor`): The data we want to know the device of.
+ """
+ if isinstance(data, Mapping):
+ for obj in data.values():
+ device = find_device(obj)
+ if device is not None:
+ return device
+ elif isinstance(data, (tuple, list)):
+ for obj in data:
+ device = find_device(obj)
+ if device is not None:
+ return device
+ elif isinstance(data, torch.Tensor):
+ return data.device
+
+
+@contextmanager
+def GatheredParameters(params, modifier_rank=None, fwd_module=None, enabled=True):
+ """
+ Wrapper around `deepspeed.runtime.zero.GatheredParameters`, but if Zero-3 is not enabled, will be a no-op context
+ manager.
+ """
+ # We need to use the `AcceleratorState` here since it has access to the deepspeed plugin
+ if AcceleratorState().distributed_type != DistributedType.DEEPSPEED or (
+ AcceleratorState().deepspeed_plugin is not None
+ and not AcceleratorState().deepspeed_plugin.is_zero3_init_enabled()
+ ):
+ gather_param_context = nullcontext()
+ else:
+ import deepspeed
+
+ gather_param_context = deepspeed.zero.GatheredParameters(
+ params, modifier_rank=modifier_rank, fwd_module=fwd_module, enabled=enabled
+ )
+ with gather_param_context:
+ yield
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/other.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/other.py
new file mode 100644
index 0000000000000000000000000000000000000000..a313d08685be25707109c4973b346cdb0a4af90b
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/other.py
@@ -0,0 +1,366 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import collections
+import os
+import platform
+import re
+import socket
+from contextlib import contextmanager
+from functools import partial, reduce
+from types import MethodType
+from typing import OrderedDict
+
+import torch
+from packaging.version import Version
+from safetensors.torch import save_file as safe_save_file
+
+from ..commands.config.default import write_basic_config # noqa: F401
+from ..logging import get_logger
+from ..state import PartialState
+from .constants import FSDP_PYTORCH_VERSION
+from .dataclasses import DistributedType
+from .imports import is_deepspeed_available, is_torch_distributed_available, is_torch_xla_available
+from .modeling import id_tensor_storage
+from .transformer_engine import convert_model
+from .versions import is_torch_version
+
+
+logger = get_logger(__name__)
+
+
+if is_torch_xla_available():
+ import torch_xla.core.xla_model as xm
+
+
+def is_compiled_module(module):
+ """
+ Check whether the module was compiled with torch.compile()
+ """
+ if is_torch_version("<", "2.0.0") or not hasattr(torch, "_dynamo"):
+ return False
+ return isinstance(module, torch._dynamo.eval_frame.OptimizedModule)
+
+
+def extract_model_from_parallel(model, keep_fp32_wrapper: bool = True, recursive: bool = False):
+ """
+ Extract a model from its distributed containers.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to extract.
+ keep_fp32_wrapper (`bool`, *optional*):
+ Whether to remove mixed precision hooks from the model.
+ recursive (`bool`, *optional*, defaults to `False`):
+ Whether to recursively extract all cases of `module.module` from `model` as well as unwrap child sublayers
+ recursively, not just the top-level distributed containers.
+
+ Returns:
+ `torch.nn.Module`: The extracted model.
+ """
+ options = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)
+
+ is_compiled = is_compiled_module(model)
+ if is_compiled:
+ compiled_model = model
+ model = model._orig_mod
+
+ if is_deepspeed_available():
+ from deepspeed import DeepSpeedEngine
+
+ options += (DeepSpeedEngine,)
+
+ if is_torch_version(">=", FSDP_PYTORCH_VERSION) and is_torch_distributed_available():
+ from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
+
+ options += (FSDP,)
+
+ while isinstance(model, options):
+ model = model.module
+
+ if recursive:
+ # This is needed in cases such as using FSDPv2 on XLA
+ def _recursive_unwrap(module):
+ # Wrapped modules are standardly wrapped as `module`, similar to the cases earlier
+ # with DDP, DataParallel, DeepSpeed, and FSDP
+ if hasattr(module, "module"):
+ unwrapped_module = _recursive_unwrap(module.module)
+ else:
+ unwrapped_module = module
+ # Next unwrap child sublayers recursively
+ for name, child in unwrapped_module.named_children():
+ setattr(unwrapped_module, name, _recursive_unwrap(child))
+ return unwrapped_module
+
+ # Start with top-level
+ model = _recursive_unwrap(model)
+
+ if not keep_fp32_wrapper:
+ forward = model.forward
+ original_forward = model.__dict__.pop("_original_forward", None)
+ if original_forward is not None:
+ while hasattr(forward, "__wrapped__"):
+ forward = forward.__wrapped__
+ if forward == original_forward:
+ break
+ model.forward = MethodType(forward, model)
+ if getattr(model, "_converted_to_transformer_engine", False):
+ convert_model(model, to_transformer_engine=False)
+
+ if is_compiled:
+ compiled_model._orig_mod = model
+ model = compiled_model
+
+ return model
+
+
+def wait_for_everyone():
+ """
+ Introduces a blocking point in the script, making sure all processes have reached this point before continuing.
+
+
+
+ Make sure all processes will reach this instruction otherwise one of your processes will hang forever.
+
+
+ """
+ PartialState().wait_for_everyone()
+
+
+def clean_state_dict_for_safetensors(state_dict: dict):
+ """
+ Cleans the state dictionary from a model and removes tensor aliasing if present.
+
+ Args:
+ state_dict (`dict`):
+ The state dictionary from a model
+ """
+ ptrs = collections.defaultdict(list)
+ # When bnb serialization is used, weights in state dict can be strings
+ for name, tensor in state_dict.items():
+ if not isinstance(tensor, str):
+ ptrs[id_tensor_storage(tensor)].append(name)
+
+ # These are all pointers of tensors with shared memory
+ shared_ptrs = {ptr: names for ptr, names in ptrs.items() if len(names) > 1}
+ warn_names = set()
+ for names in shared_ptrs.values():
+ # When not all duplicates have been cleaned, we still remove those keys but put a clear warning.
+ # If the link between tensors was done at runtime then `from_pretrained` will not get
+ # the key back leading to random tensor. A proper warning will be shown
+ # during reload (if applicable), but since the file is not necessarily compatible with
+ # the config, better show a proper warning.
+ found_names = [name for name in names if name in state_dict]
+ warn_names.update(found_names[1:])
+ for name in found_names[1:]:
+ del state_dict[name]
+ if len(warn_names) > 0:
+ logger.warning(
+ f"Removed shared tensor {warn_names} while saving. This should be OK, but check by verifying that you don't receive any warning while reloading",
+ )
+ state_dict = {k: v.contiguous() if isinstance(v, torch.Tensor) else v for k, v in state_dict.items()}
+ return state_dict
+
+
+def save(obj, f, save_on_each_node: bool = False, safe_serialization: bool = False):
+ """
+ Save the data to disk. Use in place of `torch.save()`.
+
+ Args:
+ obj:
+ The data to save
+ f:
+ The file (or file-like object) to use to save the data
+ save_on_each_node (`bool`, *optional*, defaults to `False`):
+ Whether to only save on the global main process
+ safe_serialization (`bool`, *optional*, defaults to `False`):
+ Whether to save `obj` using `safetensors` or the traditional PyTorch way (that uses `pickle`).
+ """
+ # When TorchXLA is enabled, it's necessary to transfer all data to the CPU before saving.
+ # Another issue arises with `id_tensor_storage`, which treats all XLA tensors as identical.
+ # If tensors remain on XLA, calling `clean_state_dict_for_safetensors` will result in only
+ # one XLA tensor remaining.
+ if PartialState().distributed_type == DistributedType.XLA:
+ obj = xm._maybe_convert_to_cpu(obj)
+ # Check if it's a model and remove duplicates
+ if safe_serialization:
+ save_func = partial(safe_save_file, metadata={"format": "pt"})
+ if isinstance(obj, OrderedDict):
+ obj = clean_state_dict_for_safetensors(obj)
+ else:
+ save_func = torch.save
+
+ if PartialState().is_main_process and not save_on_each_node:
+ save_func(obj, f)
+ elif PartialState().is_local_main_process and save_on_each_node:
+ save_func(obj, f)
+
+
+@contextmanager
+def clear_environment():
+ """
+ A context manager that will temporarily clear environment variables.
+
+ When this context exits, the previous environment variables will be back.
+
+ Example:
+
+ ```python
+ >>> import os
+ >>> from accelerate.utils import clear_environment
+
+ >>> os.environ["FOO"] = "bar"
+ >>> with clear_environment():
+ ... print(os.environ)
+ ... os.environ["FOO"] = "new_bar"
+ ... print(os.environ["FOO"])
+ {}
+ new_bar
+
+ >>> print(os.environ["FOO"])
+ bar
+ ```
+ """
+ _old_os_environ = os.environ.copy()
+ os.environ.clear()
+
+ try:
+ yield
+ finally:
+ os.environ.clear() # clear any added keys,
+ os.environ.update(_old_os_environ) # then restore previous environment
+
+
+@contextmanager
+def patch_environment(**kwargs):
+ """
+ A context manager that will add each keyword argument passed to `os.environ` and remove them when exiting.
+
+ Will convert the values in `kwargs` to strings and upper-case all the keys.
+
+ Example:
+
+ ```python
+ >>> import os
+ >>> from accelerate.utils import patch_environment
+
+ >>> with patch_environment(FOO="bar"):
+ ... print(os.environ["FOO"]) # prints "bar"
+ >>> print(os.environ["FOO"]) # raises KeyError
+ ```
+ """
+ existing_vars = {}
+ for key, value in kwargs.items():
+ key = key.upper()
+ if key in os.environ:
+ existing_vars[key] = os.environ[key]
+ os.environ[key] = str(value)
+
+ try:
+ yield
+ finally:
+ for key in kwargs:
+ key = key.upper()
+ if key in existing_vars:
+ # restore previous value
+ os.environ[key] = existing_vars[key]
+ else:
+ os.environ.pop(key, None)
+
+
+def get_pretty_name(obj):
+ """
+ Gets a pretty name from `obj`.
+ """
+ if not hasattr(obj, "__qualname__") and not hasattr(obj, "__name__"):
+ obj = getattr(obj, "__class__", obj)
+ if hasattr(obj, "__qualname__"):
+ return obj.__qualname__
+ if hasattr(obj, "__name__"):
+ return obj.__name__
+ return str(obj)
+
+
+def merge_dicts(source, destination):
+ """
+ Recursively merges two dictionaries.
+
+ Args:
+ source (`dict`): The dictionary to merge into `destination`.
+ destination (`dict`): The dictionary to merge `source` into.
+ """
+ for key, value in source.items():
+ if isinstance(value, dict):
+ node = destination.setdefault(key, {})
+ merge_dicts(value, node)
+ else:
+ destination[key] = value
+
+ return destination
+
+
+def is_port_in_use(port: int = None) -> bool:
+ """
+ Checks if a port is in use on `localhost`. Useful for checking if multiple `accelerate launch` commands have been
+ run and need to see if the port is already in use.
+ """
+ if port is None:
+ port = 29500
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ return s.connect_ex(("localhost", port)) == 0
+
+
+def convert_bytes(size):
+ "Converts `size` from bytes to the largest possible unit"
+ for x in ["bytes", "KB", "MB", "GB", "TB"]:
+ if size < 1024.0:
+ return f"{round(size, 2)} {x}"
+ size /= 1024.0
+
+ return f"{round(size, 2)} PB"
+
+
+def check_os_kernel():
+ """Warns if the kernel version is below the recommended minimum on Linux."""
+ # see issue #1929
+ info = platform.uname()
+ system = info.system
+ if system != "Linux":
+ return
+
+ _, version, *_ = re.split(r"(\d+\.\d+\.\d+)", info.release)
+ min_version = "5.5.0"
+ if Version(version) < Version(min_version):
+ msg = (
+ f"Detected kernel version {version}, which is below the recommended minimum of {min_version}; this can "
+ "cause the process to hang. It is recommended to upgrade the kernel to the minimum version or higher."
+ )
+ logger.warning(msg, main_process_only=True)
+
+
+def recursive_getattr(obj, attr: str):
+ """
+ Recursive `getattr`.
+
+ Args:
+ obj:
+ A class instance holding the attribute.
+ attr (`str`):
+ The attribute that is to be retrieved, e.g. 'attribute1.attribute2'.
+ """
+
+ def _getattr(obj, attr):
+ return getattr(obj, attr)
+
+ return reduce(_getattr, [obj] + attr.split("."))
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/random.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/random.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf6e8f4444f7a17510aa55e74cdf997aceb5a3ce
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/random.py
@@ -0,0 +1,132 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import random
+from typing import List, Optional, Union
+
+import numpy as np
+import torch
+
+from ..state import AcceleratorState
+from .constants import CUDA_DISTRIBUTED_TYPES
+from .dataclasses import DistributedType, RNGType
+from .imports import is_mlu_available, is_musa_available, is_npu_available, is_torch_xla_available, is_xpu_available
+
+
+if is_torch_xla_available():
+ import torch_xla.core.xla_model as xm
+
+
+def set_seed(seed: int, device_specific: bool = False, deterministic: bool = False):
+ """
+ Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch`.
+
+ Args:
+ seed (`int`):
+ The seed to set.
+ device_specific (`bool`, *optional*, defaults to `False`):
+ Whether to differ the seed on each device slightly with `self.process_index`.
+ deterministic (`bool`, *optional*, defaults to `False`):
+ Whether to use deterministic algorithms where available. Can slow down training.
+ """
+ if device_specific:
+ seed += AcceleratorState().process_index
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ if is_xpu_available():
+ torch.xpu.manual_seed_all(seed)
+ elif is_npu_available():
+ torch.npu.manual_seed_all(seed)
+ elif is_mlu_available():
+ torch.mlu.manual_seed_all(seed)
+ elif is_musa_available():
+ torch.musa.manual_seed_all(seed)
+ else:
+ torch.cuda.manual_seed_all(seed)
+ # ^^ safe to call this function even if cuda is not available
+ if is_torch_xla_available():
+ xm.set_rng_state(seed)
+
+ if deterministic:
+ torch.use_deterministic_algorithms(True)
+
+
+def synchronize_rng_state(rng_type: Optional[RNGType] = None, generator: Optional[torch.Generator] = None):
+ # Get the proper rng state
+ if rng_type == RNGType.TORCH:
+ rng_state = torch.get_rng_state()
+ elif rng_type == RNGType.CUDA:
+ rng_state = torch.cuda.get_rng_state()
+ elif rng_type == RNGType.XLA:
+ assert is_torch_xla_available(), "Can't synchronize XLA seeds as torch_xla is unavailable."
+ rng_state = torch.tensor(xm.get_rng_state())
+ elif rng_type == RNGType.NPU:
+ assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
+ rng_state = torch.npu.get_rng_state()
+ elif rng_type == RNGType.MLU:
+ assert is_mlu_available(), "Can't synchronize MLU seeds on an environment without MLUs."
+ rng_state = torch.mlu.get_rng_state()
+ elif rng_type == RNGType.MUSA:
+ assert is_musa_available(), "Can't synchronize MUSA seeds on an environment without MUSAs."
+ rng_state = torch.musa.get_rng_state()
+ elif rng_type == RNGType.XPU:
+ assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
+ rng_state = torch.xpu.get_rng_state()
+ elif rng_type == RNGType.GENERATOR:
+ assert generator is not None, "Need a generator to synchronize its seed."
+ rng_state = generator.get_state()
+
+ # Broadcast the rng state from device 0 to other devices
+ state = AcceleratorState()
+ if state.distributed_type == DistributedType.XLA:
+ rng_state = rng_state.to(xm.xla_device())
+ xm.collective_broadcast([rng_state])
+ xm.mark_step()
+ rng_state = rng_state.cpu()
+ elif (
+ state.distributed_type in CUDA_DISTRIBUTED_TYPES
+ or state.distributed_type == DistributedType.MULTI_MLU
+ or state.distributed_type == DistributedType.MULTI_MUSA
+ or state.distributed_type == DistributedType.MULTI_NPU
+ or state.distributed_type == DistributedType.MULTI_XPU
+ ):
+ rng_state = rng_state.to(state.device)
+ torch.distributed.broadcast(rng_state, 0)
+ rng_state = rng_state.cpu()
+ elif state.distributed_type == DistributedType.MULTI_CPU:
+ torch.distributed.broadcast(rng_state, 0)
+
+ # Set the broadcast rng state
+ if rng_type == RNGType.TORCH:
+ torch.set_rng_state(rng_state)
+ elif rng_type == RNGType.CUDA:
+ torch.cuda.set_rng_state(rng_state)
+ elif rng_type == RNGType.NPU:
+ torch.npu.set_rng_state(rng_state)
+ elif rng_type == RNGType.MLU:
+ torch.mlu.set_rng_state(rng_state)
+ elif rng_type == RNGType.MUSA:
+ torch.musa.set_rng_state(rng_state)
+ elif rng_type == RNGType.XPU:
+ torch.xpu.set_rng_state(rng_state)
+ elif rng_type == RNGType.XLA:
+ xm.set_rng_state(rng_state.item())
+ elif rng_type == RNGType.GENERATOR:
+ generator.set_state(rng_state)
+
+
+def synchronize_rng_states(rng_types: List[Union[str, RNGType]], generator: Optional[torch.Generator] = None):
+ for rng_type in rng_types:
+ synchronize_rng_state(RNGType(rng_type), generator=generator)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/rich.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/rich.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d48661b7fcef92ef1168b74cc275c6d3ccc67a1
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/rich.py
@@ -0,0 +1,24 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from .imports import is_rich_available
+
+
+if is_rich_available():
+ from rich.traceback import install
+
+ install(show_locals=False)
+
+else:
+ raise ModuleNotFoundError("To use the rich extension, install rich with `pip install rich`")
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/torch_xla.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/torch_xla.py
new file mode 100644
index 0000000000000000000000000000000000000000..140133926c2f88d39c70f5a9f46a08f88bed36da
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/torch_xla.py
@@ -0,0 +1,51 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import importlib.metadata
+import subprocess
+import sys
+
+
+def install_xla(upgrade: bool = False):
+ """
+ Helper function to install appropriate xla wheels based on the `torch` version in Google Colaboratory.
+
+ Args:
+ upgrade (`bool`, *optional*, defaults to `False`):
+ Whether to upgrade `torch` and install the latest `torch_xla` wheels.
+
+ Example:
+
+ ```python
+ >>> from accelerate.utils import install_xla
+
+ >>> install_xla(upgrade=True)
+ ```
+ """
+ in_colab = False
+ if "IPython" in sys.modules:
+ in_colab = "google.colab" in str(sys.modules["IPython"].get_ipython())
+
+ if in_colab:
+ if upgrade:
+ torch_install_cmd = ["pip", "install", "-U", "torch"]
+ subprocess.run(torch_install_cmd, check=True)
+ # get the current version of torch
+ torch_version = importlib.metadata.version("torch")
+ torch_version_trunc = torch_version[: torch_version.rindex(".")]
+ xla_wheel = f"https://storage.googleapis.com/tpu-pytorch/wheels/colab/torch_xla-{torch_version_trunc}-cp37-cp37m-linux_x86_64.whl"
+ xla_install_cmd = ["pip", "install", xla_wheel]
+ subprocess.run(xla_install_cmd, check=True)
+ else:
+ raise RuntimeError("`install_xla` utility works only on google colab.")
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/tqdm.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/tqdm.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d4873c1573eb2ee7392162f440a76d4f07cd8ce
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/tqdm.py
@@ -0,0 +1,43 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from .imports import is_tqdm_available
+
+
+if is_tqdm_available():
+ from tqdm.auto import tqdm as _tqdm
+
+from ..state import PartialState
+
+
+def tqdm(*args, main_process_only: bool = True, **kwargs):
+ """
+ Wrapper around `tqdm.tqdm` that optionally displays only on the main process.
+
+ Args:
+ main_process_only (`bool`, *optional*):
+ Whether to display the progress bar only on the main process
+ """
+ if not is_tqdm_available():
+ raise ImportError("Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.")
+ if len(args) > 0 and isinstance(args[0], bool):
+ raise ValueError(
+ "Passing `True` or `False` as the first argument to Accelerate's `tqdm` wrapper is unsupported. "
+ "Please use the `main_process_only` keyword argument instead."
+ )
+ disable = kwargs.pop("disable", False)
+ if main_process_only and not disable:
+ disable = PartialState().local_process_index != 0
+ return _tqdm(*args, **kwargs, disable=disable)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/transformer_engine.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/transformer_engine.py
new file mode 100644
index 0000000000000000000000000000000000000000..0899c463de42cc9e8adf3c842b2cc6fa49b5050f
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/transformer_engine.py
@@ -0,0 +1,139 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from types import MethodType
+
+import torch.nn as nn
+
+from .imports import is_fp8_available
+from .operations import GatheredParameters
+
+
+# Do not import `transformer_engine` at package level to avoid potential issues
+
+
+def convert_model(model, to_transformer_engine=True, _convert_linear=True, _convert_ln=True):
+ """
+ Recursively converts the linear and layernorm layers of a model to their `transformers_engine` counterpart.
+ """
+ if not is_fp8_available():
+ raise ImportError("Using `convert_model` requires transformer_engine to be installed.")
+ import transformer_engine.pytorch as te
+
+ for name, module in model.named_children():
+ if isinstance(module, nn.Linear) and to_transformer_engine and _convert_linear:
+ has_bias = module.bias is not None
+ params_to_gather = [module.weight]
+ if has_bias:
+ params_to_gather.append(module.bias)
+
+ with GatheredParameters(params_to_gather, modifier_rank=0):
+ if any(p % 16 != 0 for p in module.weight.shape):
+ return
+ te_module = te.Linear(
+ module.in_features, module.out_features, bias=has_bias, params_dtype=module.weight.dtype
+ )
+ te_module.weight.copy_(module.weight)
+ if has_bias:
+ te_module.bias.copy_(module.bias)
+
+ setattr(model, name, te_module)
+ # Note: @xrsrke (Phuc) found that te.LayerNorm doesn't have any real memory savings or speedups over nn.LayerNorm
+ elif isinstance(module, nn.LayerNorm) and to_transformer_engine and _convert_ln:
+ with GatheredParameters([module.weight, module.bias], modifier_rank=0):
+ te_module = te.LayerNorm(module.normalized_shape[0], eps=module.eps, params_dtype=module.weight.dtype)
+ te_module.weight.copy_(module.weight)
+ te_module.bias.copy_(module.bias)
+
+ setattr(model, name, te_module)
+ elif isinstance(module, te.Linear) and not to_transformer_engine and _convert_linear:
+ has_bias = module.bias is not None
+ new_module = nn.Linear(
+ module.in_features, module.out_features, bias=has_bias, params_dtype=module.weight.dtype
+ )
+ new_module.weight.copy_(module.weight)
+ if has_bias:
+ new_module.bias.copy_(module.bias)
+
+ setattr(model, name, new_module)
+ elif isinstance(module, te.LayerNorm) and not to_transformer_engine and _convert_ln:
+ new_module = nn.LayerNorm(module.normalized_shape[0], eps=module.eps, params_dtype=module.weight.dtype)
+ new_module.weight.copy_(module.weight)
+ new_module.bias.copy_(module.bias)
+
+ setattr(model, name, new_module)
+ else:
+ convert_model(
+ module,
+ to_transformer_engine=to_transformer_engine,
+ _convert_linear=_convert_linear,
+ _convert_ln=_convert_ln,
+ )
+
+
+def has_transformer_engine_layers(model):
+ """
+ Returns whether a given model has some `transformer_engine` layer or not.
+ """
+ if not is_fp8_available():
+ raise ImportError("Using `has_transformer_engine_layers` requires transformer_engine to be installed.")
+ import transformer_engine.pytorch as te
+
+ for m in model.modules():
+ if isinstance(m, (te.LayerNorm, te.Linear, te.TransformerLayer)):
+ return True
+ return False
+
+
+def contextual_fp8_autocast(model_forward, fp8_recipe, use_during_eval=False):
+ """
+ Wrapper for a model's forward method to apply FP8 autocast. Is context aware, meaning that by default it will
+ disable FP8 autocast during eval mode, which is generally better for more accurate metrics.
+ """
+ if not is_fp8_available():
+ raise ImportError("Using `contextual_fp8_autocast` requires transformer_engine to be installed.")
+ from transformer_engine.pytorch import fp8_autocast
+
+ def forward(self, *args, **kwargs):
+ enabled = use_during_eval or self.training
+ with fp8_autocast(enabled=enabled, fp8_recipe=fp8_recipe):
+ return model_forward(*args, **kwargs)
+
+ # To act like a decorator so that it can be popped when doing `extract_model_from_parallel`
+ forward.__wrapped__ = model_forward
+
+ return forward
+
+
+def apply_fp8_autowrap(model, fp8_recipe_handler):
+ """
+ Applies FP8 context manager to the model's forward method
+ """
+ if not is_fp8_available():
+ raise ImportError("Using `apply_fp8_autowrap` requires transformer_engine to be installed.")
+ import transformer_engine.common.recipe as te_recipe
+
+ kwargs = fp8_recipe_handler.to_kwargs() if fp8_recipe_handler is not None else {}
+ if "fp8_format" in kwargs:
+ kwargs["fp8_format"] = getattr(te_recipe.Format, kwargs["fp8_format"])
+ use_during_eval = kwargs.pop("use_autocast_during_eval", False)
+ fp8_recipe = te_recipe.DelayedScaling(**kwargs)
+ new_forward = contextual_fp8_autocast(model.forward, fp8_recipe, use_during_eval)
+
+ if hasattr(model.forward, "__func__"):
+ model.forward = MethodType(new_forward, model)
+ else:
+ model.forward = new_forward
+
+ return model
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/versions.py b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/versions.py
new file mode 100644
index 0000000000000000000000000000000000000000..985c918f0e057bacc70c372f6906071bb73db577
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/src/accelerate/utils/versions.py
@@ -0,0 +1,56 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import importlib.metadata
+from typing import Union
+
+from packaging.version import Version, parse
+
+from .constants import STR_OPERATION_TO_FUNC
+
+
+torch_version = parse(importlib.metadata.version("torch"))
+
+
+def compare_versions(library_or_version: Union[str, Version], operation: str, requirement_version: str):
+ """
+ Compares a library version to some requirement using a given operation.
+
+ Args:
+ library_or_version (`str` or `packaging.version.Version`):
+ A library name or a version to check.
+ operation (`str`):
+ A string representation of an operator, such as `">"` or `"<="`.
+ requirement_version (`str`):
+ The version to compare the library version against
+ """
+ if operation not in STR_OPERATION_TO_FUNC.keys():
+ raise ValueError(f"`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys())}, received {operation}")
+ operation = STR_OPERATION_TO_FUNC[operation]
+ if isinstance(library_or_version, str):
+ library_or_version = parse(importlib.metadata.version(library_or_version))
+ return operation(library_or_version, parse(requirement_version))
+
+
+def is_torch_version(operation: str, version: str):
+ """
+ Compares the current PyTorch version to a given reference with an operation.
+
+ Args:
+ operation (`str`):
+ A string representation of an operator, such as `">"` or `"<="`
+ version (`str`):
+ A string version of PyTorch
+ """
+ return compare_versions(torch_version, operation, version)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero2.json b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero2.json
new file mode 100644
index 0000000000000000000000000000000000000000..f031969eeb8cc01c910493a73ea3bffdff518c8c
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero2.json
@@ -0,0 +1,49 @@
+{
+ "fp16": {
+ "enabled": "auto",
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "bf16": {
+ "enabled": "auto"
+ },
+ "optimizer": {
+ "type": "AdamW",
+ "params": {
+ "lr": "auto",
+ "weight_decay": "auto",
+ "torch_adam": true,
+ "adam_w_mode": true
+ }
+ },
+ "scheduler": {
+ "type": "WarmupLR",
+ "params": {
+ "warmup_min_lr": "auto",
+ "warmup_max_lr": "auto",
+ "warmup_num_steps": "auto"
+ }
+ },
+ "zero_optimization": {
+ "stage": 2,
+ "offload_optimizer": {
+ "device": "cpu",
+ "pin_memory": true
+ },
+ "allgather_partitions": true,
+ "allgather_bucket_size": 2e8,
+ "overlap_comm": true,
+ "reduce_scatter": true,
+ "reduce_bucket_size": "auto",
+ "contiguous_gradients": true
+ },
+ "gradient_accumulation_steps": 1,
+ "gradient_clipping": "auto",
+ "steps_per_print": 2000,
+ "train_batch_size": "auto",
+ "train_micro_batch_size_per_gpu": "auto",
+ "wall_clock_breakdown": false
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero2_model_only.json b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero2_model_only.json
new file mode 100644
index 0000000000000000000000000000000000000000..83f31b24960299e311579a923e6cddeb4de96575
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero2_model_only.json
@@ -0,0 +1,32 @@
+{
+ "fp16": {
+ "enabled": "auto",
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "bf16": {
+ "enabled": "auto"
+ },
+ "zero_optimization": {
+ "stage": 2,
+ "offload_optimizer": {
+ "device": "cpu",
+ "pin_memory": true
+ },
+ "allgather_partitions": true,
+ "allgather_bucket_size": 2e8,
+ "overlap_comm": true,
+ "reduce_scatter": true,
+ "reduce_bucket_size": "auto",
+ "contiguous_gradients": true
+ },
+ "gradient_accumulation_steps": 1,
+ "gradient_clipping": "auto",
+ "steps_per_print": 2000,
+ "train_batch_size": "auto",
+ "train_micro_batch_size_per_gpu": "auto",
+ "wall_clock_breakdown": false
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero3.json b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero3.json
new file mode 100644
index 0000000000000000000000000000000000000000..846cd73614802f6e6f51bce59bae93f771b3b8cd
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero3.json
@@ -0,0 +1,56 @@
+{
+ "fp16": {
+ "enabled": "auto",
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "bf16": {
+ "enabled": "auto"
+ },
+ "optimizer": {
+ "type": "AdamW",
+ "params": {
+ "lr": "auto",
+ "weight_decay": "auto",
+ "torch_adam": true,
+ "adam_w_mode": true
+ }
+ },
+ "scheduler": {
+ "type": "WarmupLR",
+ "params": {
+ "warmup_min_lr": "auto",
+ "warmup_max_lr": "auto",
+ "warmup_num_steps": "auto"
+ }
+ },
+ "zero_optimization": {
+ "stage": 3,
+ "offload_optimizer": {
+ "device": "cpu",
+ "pin_memory": true
+ },
+ "offload_param": {
+ "device": "cpu",
+ "pin_memory": true
+ },
+ "overlap_comm": true,
+ "contiguous_gradients": true,
+ "sub_group_size": 1e9,
+ "reduce_bucket_size": "auto",
+ "stage3_prefetch_bucket_size": "auto",
+ "stage3_param_persistence_threshold": "auto",
+ "stage3_max_live_parameters": 1e9,
+ "stage3_max_reuse_distance": 1e9,
+ "stage3_gather_16bit_weights_on_model_save": "auto"
+ },
+ "gradient_accumulation_steps": 1,
+ "gradient_clipping": "auto",
+ "steps_per_print": 2000,
+ "train_batch_size": "auto",
+ "train_micro_batch_size_per_gpu": "auto",
+ "wall_clock_breakdown": false
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero3_model_only.json b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero3_model_only.json
new file mode 100644
index 0000000000000000000000000000000000000000..18e21c8086b51b0df8d213a3afa4878dcc503a5b
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/ds_config_zero3_model_only.json
@@ -0,0 +1,29 @@
+{
+ "fp16": {
+ "enabled": "auto",
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "bf16": {
+ "enabled": "auto"
+ },
+ "zero_optimization": {
+ "stage": 3,
+ "offload_param": {
+ "device": "cpu",
+ "pin_memory": true
+ },
+ "overlap_comm": true,
+ "sub_group_size": 1e9,
+ "reduce_bucket_size": 1e9,
+ "stage3_prefetch_bucket_size": 1e9,
+ "stage3_param_persistence_threshold": 1e9,
+ "stage3_max_live_parameters": 1e9,
+ "stage3_max_reuse_distance": 1e9,
+ "stage3_gather_16bit_weights_on_model_save": true
+ },
+ "train_micro_batch_size_per_gpu": 1
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/test_deepspeed.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/test_deepspeed.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c1940b8642b00bdaada927b569535f3baee3298
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/test_deepspeed.py
@@ -0,0 +1,1091 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import inspect
+import itertools
+import json
+import os
+import tempfile
+from copy import deepcopy
+from pathlib import Path
+
+import torch
+from parameterized import parameterized
+from torch.utils.data import BatchSampler, DataLoader, RandomSampler, SequentialSampler
+from transformers import AutoConfig, AutoModel, AutoModelForCausalLM, get_scheduler
+from transformers.testing_utils import mockenv_context
+from transformers.trainer_utils import set_seed
+from transformers.utils import is_torch_bf16_available
+
+from accelerate.accelerator import Accelerator
+from accelerate.scheduler import AcceleratedScheduler
+from accelerate.state import AcceleratorState
+from accelerate.test_utils.testing import (
+ AccelerateTestCase,
+ TempDirTestCase,
+ execute_subprocess_async,
+ path_in_accelerate_package,
+ require_deepspeed,
+ require_huggingface_suite,
+ require_multi_device,
+ require_non_cpu,
+ slow,
+)
+from accelerate.test_utils.training import RegressionDataset, RegressionModel
+from accelerate.utils.dataclasses import DeepSpeedPlugin
+from accelerate.utils.deepspeed import (
+ DeepSpeedEngineWrapper,
+ DeepSpeedOptimizerWrapper,
+ DeepSpeedSchedulerWrapper,
+ DummyOptim,
+ DummyScheduler,
+)
+from accelerate.utils.other import patch_environment
+from accelerate.utils.versions import compare_versions
+
+
+set_seed(42)
+
+GPT2_TINY = "sshleifer/tiny-gpt2"
+MOBILEVIT = "apple/mobilevit-xx-small"
+QWEN_MOE = "peft-internal-testing/tiny-random-qwen-1.5-MoE"
+
+ZERO2 = "zero2"
+ZERO3 = "zero3"
+
+FP16 = "fp16"
+BF16 = "bf16"
+
+CUSTOM_OPTIMIZER = "custom_optimizer"
+CUSTOM_SCHEDULER = "custom_scheduler"
+DS_OPTIMIZER = "deepspeed_optimizer"
+DS_SCHEDULER = "deepspeed_scheduler"
+
+NO_CONFIG = "no_config"
+CONFIG_WITH_NO_HIDDEN_SIZE = "config_with_no_hidden_size"
+CONFIG_WITH_HIDDEN_SIZE = "config_with_hidden_size"
+CONFIG_WITH_HIDDEN_SIZES = "config_with_hidden_sizes"
+
+stages = [ZERO2, ZERO3]
+optims = [CUSTOM_OPTIMIZER, DS_OPTIMIZER]
+schedulers = [CUSTOM_SCHEDULER, DS_SCHEDULER]
+model_types = [NO_CONFIG, CONFIG_WITH_NO_HIDDEN_SIZE, CONFIG_WITH_HIDDEN_SIZE, CONFIG_WITH_HIDDEN_SIZES]
+if is_torch_bf16_available():
+ dtypes = [FP16, BF16]
+else:
+ dtypes = [FP16]
+
+
+def parameterized_custom_name_func(func, param_num, param):
+ # customize the test name generator function as we want both params to appear in the sub-test
+ # name, as by default it shows only the first param
+ param_based_name = parameterized.to_safe_name("_".join(str(x) for x in param.args))
+ return f"{func.__name__}_{param_based_name}"
+
+
+# Cartesian-product of zero stages with models to test
+params = list(itertools.product(stages, dtypes))
+optim_scheduler_params = list(itertools.product(optims, schedulers))
+
+
+class DummyConfig:
+ def __init__(self):
+ self._name_or_path = "dummy"
+
+
+@require_deepspeed
+@require_non_cpu
+class DeepSpeedConfigIntegration(AccelerateTestCase):
+ def setUp(self):
+ super().setUp()
+
+ self._test_file_path = inspect.getfile(self.__class__)
+ path = Path(self._test_file_path).resolve()
+ self.test_file_dir_str = str(path.parents[0])
+
+ self.ds_config_file = dict(
+ zero2=f"{self.test_file_dir_str}/ds_config_zero2.json",
+ zero3=f"{self.test_file_dir_str}/ds_config_zero3.json",
+ )
+
+ # use self.get_config_dict(stage) to use these to ensure the original is not modified
+ with open(self.ds_config_file[ZERO2], encoding="utf-8") as f:
+ config_zero2 = json.load(f)
+ with open(self.ds_config_file[ZERO3], encoding="utf-8") as f:
+ config_zero3 = json.load(f)
+ # The following setting slows things down, so don't enable it by default unless needed by a test.
+ # It's in the file as a demo for users since we want everything to work out of the box even if slower.
+ config_zero3["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] = False
+
+ self.ds_config_dict = dict(zero2=config_zero2, zero3=config_zero3)
+
+ self.dist_env = dict(
+ ACCELERATE_USE_DEEPSPEED="true",
+ MASTER_ADDR="localhost",
+ MASTER_PORT="10999",
+ RANK="0",
+ LOCAL_RANK="0",
+ WORLD_SIZE="1",
+ )
+
+ def get_config_dict(self, stage):
+ # As some tests modify the dict, always make a copy
+ return deepcopy(self.ds_config_dict[stage])
+
+ @parameterized.expand(stages, name_func=parameterized_custom_name_func)
+ def test_deepspeed_plugin(self, stage):
+ # Test zero3_init_flag will be set to False when ZeRO stage != 3
+ deepspeed_plugin = DeepSpeedPlugin(
+ gradient_accumulation_steps=1,
+ gradient_clipping=1.0,
+ zero_stage=2,
+ offload_optimizer_device="cpu",
+ offload_param_device="cpu",
+ zero3_save_16bit_model=True,
+ zero3_init_flag=True,
+ )
+ assert not deepspeed_plugin.zero3_init_flag
+ deepspeed_plugin.deepspeed_config = None
+
+ # Test zero3_init_flag will be set to True only when ZeRO stage == 3
+ deepspeed_plugin = DeepSpeedPlugin(
+ gradient_accumulation_steps=1,
+ gradient_clipping=1.0,
+ zero_stage=3,
+ offload_optimizer_device="cpu",
+ offload_param_device="cpu",
+ zero3_save_16bit_model=True,
+ zero3_init_flag=True,
+ )
+ assert deepspeed_plugin.zero3_init_flag
+ deepspeed_plugin.deepspeed_config = None
+
+ # Test config files are loaded correctly
+ deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.ds_config_file[stage], zero3_init_flag=True)
+ if stage == ZERO2:
+ assert not deepspeed_plugin.zero3_init_flag
+ elif stage == ZERO3:
+ assert deepspeed_plugin.zero3_init_flag
+
+ # Test `gradient_accumulation_steps` is set to 1 if unavailable in config file
+ with tempfile.TemporaryDirectory() as dirpath:
+ ds_config = self.get_config_dict(stage)
+ del ds_config["gradient_accumulation_steps"]
+ with open(os.path.join(dirpath, "ds_config.json"), "w") as out_file:
+ json.dump(ds_config, out_file)
+ deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=os.path.join(dirpath, "ds_config.json"))
+ assert deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"] == 1
+ deepspeed_plugin.deepspeed_config = None
+
+ # Test `ValueError` is raised if `zero_optimization` is unavailable in config file
+ with tempfile.TemporaryDirectory() as dirpath:
+ ds_config = self.get_config_dict(stage)
+ del ds_config["zero_optimization"]
+ with open(os.path.join(dirpath, "ds_config.json"), "w") as out_file:
+ json.dump(ds_config, out_file)
+ with self.assertRaises(ValueError) as cm:
+ deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=os.path.join(dirpath, "ds_config.json"))
+ assert "Please specify the ZeRO optimization config in the DeepSpeed config." in str(cm.exception)
+ deepspeed_plugin.deepspeed_config = None
+
+ # Test `deepspeed_config_process`
+ deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.ds_config_file[stage])
+ kwargs = {
+ "fp16.enabled": True,
+ "bf16.enabled": False,
+ "optimizer.params.lr": 5e-5,
+ "optimizer.params.weight_decay": 0.0,
+ "scheduler.params.warmup_min_lr": 0.0,
+ "scheduler.params.warmup_max_lr": 5e-5,
+ "scheduler.params.warmup_num_steps": 0,
+ "train_micro_batch_size_per_gpu": 16,
+ "gradient_clipping": 1.0,
+ "train_batch_size": 16,
+ "zero_optimization.reduce_bucket_size": 5e5,
+ "zero_optimization.stage3_prefetch_bucket_size": 5e5,
+ "zero_optimization.stage3_param_persistence_threshold": 5e5,
+ "zero_optimization.stage3_gather_16bit_weights_on_model_save": False,
+ }
+ deepspeed_plugin.deepspeed_config_process(**kwargs)
+ for ds_key_long, value in kwargs.items():
+ config, ds_key = deepspeed_plugin.hf_ds_config.find_config_node(ds_key_long)
+ if config.get(ds_key) is not None:
+ assert config.get(ds_key) == value
+
+ # Test mismatches
+ mismatches = {
+ "optimizer.params.lr": 1e-5,
+ "optimizer.params.weight_decay": 1e-5,
+ "gradient_accumulation_steps": 2,
+ }
+ with self.assertRaises(ValueError) as cm:
+ new_kwargs = deepcopy(kwargs)
+ new_kwargs.update(mismatches)
+ deepspeed_plugin.deepspeed_config_process(**new_kwargs)
+ for key in mismatches.keys():
+ assert key in str(cm.exception), f"{key} is not in the exception message: {cm.exception}"
+
+ # Test `ValueError` is raised if some config file fields with `auto` value is missing in `kwargs`
+ deepspeed_plugin.deepspeed_config["optimizer"]["params"]["lr"] = "auto"
+ with self.assertRaises(ValueError) as cm:
+ del kwargs["optimizer.params.lr"]
+ deepspeed_plugin.deepspeed_config_process(**kwargs)
+ assert "`optimizer.params.lr` not found in kwargs." in str(cm.exception)
+
+ @parameterized.expand([FP16, BF16], name_func=parameterized_custom_name_func)
+ def test_accelerate_state_deepspeed(self, dtype):
+ AcceleratorState._reset_state(True)
+ deepspeed_plugin = DeepSpeedPlugin(
+ gradient_accumulation_steps=1,
+ gradient_clipping=1.0,
+ zero_stage=ZERO2,
+ offload_optimizer_device="cpu",
+ offload_param_device="cpu",
+ zero3_save_16bit_model=True,
+ zero3_init_flag=True,
+ )
+ with mockenv_context(**self.dist_env):
+ state = Accelerator(mixed_precision=dtype, deepspeed_plugin=deepspeed_plugin).state
+ assert state.deepspeed_plugin.deepspeed_config[dtype]["enabled"]
+
+ def test_init_zero3(self):
+ deepspeed_plugin = DeepSpeedPlugin(
+ gradient_accumulation_steps=1,
+ gradient_clipping=1.0,
+ zero_stage=3,
+ offload_optimizer_device="cpu",
+ offload_param_device="cpu",
+ zero3_save_16bit_model=True,
+ zero3_init_flag=True,
+ )
+
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin) # noqa: F841
+ from transformers.deepspeed import is_deepspeed_zero3_enabled
+
+ assert is_deepspeed_zero3_enabled()
+
+ @parameterized.expand(optim_scheduler_params, name_func=parameterized_custom_name_func)
+ def test_prepare_deepspeed(self, optim_type, scheduler_type):
+ # 1. Testing with one of the ZeRO Stages is enough to test the `_prepare_deepspeed` function.
+ # Here we test using ZeRO Stage 2 with FP16 enabled.
+ from deepspeed.runtime.engine import DeepSpeedEngine
+
+ kwargs = {
+ "optimizer.params.lr": 5e-5,
+ "optimizer.params.weight_decay": 0.0,
+ "scheduler.params.warmup_min_lr": 0.0,
+ "scheduler.params.warmup_max_lr": 5e-5,
+ "scheduler.params.warmup_num_steps": 0,
+ "train_micro_batch_size_per_gpu": 16,
+ "gradient_clipping": 1.0,
+ "train_batch_size": 16,
+ "zero_optimization.reduce_bucket_size": 5e5,
+ "zero_optimization.stage3_prefetch_bucket_size": 5e5,
+ "zero_optimization.stage3_param_persistence_threshold": 5e5,
+ "zero_optimization.stage3_gather_16bit_weights_on_model_save": False,
+ }
+
+ if optim_type == CUSTOM_OPTIMIZER and scheduler_type == CUSTOM_SCHEDULER:
+ # Test custom optimizer + custom scheduler
+ deepspeed_plugin = DeepSpeedPlugin(
+ gradient_accumulation_steps=1,
+ gradient_clipping=1.0,
+ zero_stage=2,
+ offload_optimizer_device="cpu",
+ offload_param_device="cpu",
+ zero3_save_16bit_model=False,
+ zero3_init_flag=False,
+ )
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin)
+
+ train_set = RegressionDataset(length=80)
+ eval_set = RegressionDataset(length=20)
+ train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True)
+ eval_dataloader = DataLoader(eval_set, batch_size=32, shuffle=False)
+ model = AutoModel.from_pretrained(GPT2_TINY)
+ optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
+ lr_scheduler = get_scheduler(
+ name="linear",
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=1000,
+ )
+ dummy_optimizer = DummyOptim(params=model.parameters())
+ dummy_lr_scheduler = DummyScheduler(dummy_optimizer)
+
+ with self.assertRaises(ValueError) as cm:
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, dummy_optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+ assert "You cannot create a `DummyOptim` without specifying an optimizer in the config file." in str(
+ cm.exception
+ )
+ with self.assertRaises(ValueError) as cm:
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler
+ )
+ assert (
+ "Either specify a scheduler in the config file or "
+ "pass in the `lr_scheduler_callable` parameter when using `accelerate.utils.DummyScheduler`."
+ in str(cm.exception)
+ )
+
+ with self.assertRaises(ValueError) as cm:
+ model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler)
+ assert (
+ "When using DeepSpeed, `accelerate.prepare()` requires you to pass at least one of training or evaluation dataloaders "
+ "with `batch_size` attribute returning an integer value "
+ "or alternatively set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file "
+ "or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`."
+ in str(cm.exception)
+ )
+
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+ assert accelerator.deepspeed_config["zero_allow_untested_optimizer"]
+ assert accelerator.deepspeed_config["train_batch_size"], 16
+ assert type(model) is DeepSpeedEngine
+ assert type(optimizer) is DeepSpeedOptimizerWrapper
+ assert type(lr_scheduler) is AcceleratedScheduler
+ assert type(accelerator.deepspeed_engine_wrapped) is DeepSpeedEngineWrapper
+
+ elif optim_type == DS_OPTIMIZER and scheduler_type == DS_SCHEDULER:
+ # Test DeepSpeed optimizer + DeepSpeed scheduler
+ deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.ds_config_file[ZERO2])
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision="fp16")
+ train_set = RegressionDataset(length=80)
+ eval_set = RegressionDataset(length=20)
+ train_dataloader = DataLoader(train_set, batch_size=10, shuffle=True)
+ eval_dataloader = DataLoader(eval_set, batch_size=5, shuffle=False)
+ model = AutoModel.from_pretrained(GPT2_TINY)
+ optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
+ lr_scheduler = get_scheduler(
+ name="linear",
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=1000,
+ )
+ dummy_optimizer = DummyOptim(params=model.parameters())
+ dummy_lr_scheduler = DummyScheduler(dummy_optimizer)
+ kwargs["train_batch_size"] = (
+ kwargs["train_micro_batch_size_per_gpu"]
+ * deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"]
+ * accelerator.num_processes
+ )
+ accelerator.state.deepspeed_plugin.deepspeed_config_process(**kwargs)
+ with self.assertRaises(ValueError) as cm:
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler
+ )
+ assert "You cannot specify an optimizer in the config file and in the code at the same time" in str(
+ cm.exception
+ )
+
+ with self.assertRaises(ValueError) as cm:
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, dummy_optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+ assert "You cannot specify a scheduler in the config file and in the code at the same time" in str(
+ cm.exception
+ )
+
+ with self.assertRaises(ValueError) as cm:
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, dummy_optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+ assert "You cannot specify a scheduler in the config file and in the code at the same time" in str(
+ cm.exception
+ )
+
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler
+ )
+ assert type(model) is DeepSpeedEngine
+ assert type(optimizer) is DeepSpeedOptimizerWrapper
+ assert type(lr_scheduler) is DeepSpeedSchedulerWrapper
+ assert type(accelerator.deepspeed_engine_wrapped) is DeepSpeedEngineWrapper
+
+ elif optim_type == CUSTOM_OPTIMIZER and scheduler_type == DS_SCHEDULER:
+ # Test custom optimizer + DeepSpeed scheduler
+ deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.ds_config_file[ZERO2])
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision="fp16")
+ train_set = RegressionDataset(length=80)
+ eval_set = RegressionDataset(length=20)
+ train_dataloader = DataLoader(train_set, batch_size=10, shuffle=True)
+ eval_dataloader = DataLoader(eval_set, batch_size=5, shuffle=False)
+ model = AutoModel.from_pretrained(GPT2_TINY)
+ optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
+ lr_scheduler = get_scheduler(
+ name="linear",
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=1000,
+ )
+ dummy_optimizer = DummyOptim(params=model.parameters())
+ dummy_lr_scheduler = DummyScheduler(dummy_optimizer)
+ kwargs["train_batch_size"] = (
+ kwargs["train_micro_batch_size_per_gpu"]
+ * deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"]
+ * accelerator.num_processes
+ )
+ accelerator.state.deepspeed_plugin.deepspeed_config_process(**kwargs)
+ del accelerator.state.deepspeed_plugin.deepspeed_config["optimizer"]
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler
+ )
+ assert type(model) is DeepSpeedEngine
+ assert type(optimizer) is DeepSpeedOptimizerWrapper
+ assert type(lr_scheduler) is DeepSpeedSchedulerWrapper
+ assert type(accelerator.deepspeed_engine_wrapped) is DeepSpeedEngineWrapper
+ elif optim_type == DS_OPTIMIZER and scheduler_type is CUSTOM_SCHEDULER:
+ # Test deepspeed optimizer + custom scheduler
+ deepspeed_plugin = DeepSpeedPlugin(hf_ds_config=self.ds_config_file[ZERO2])
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision="fp16")
+ train_set = RegressionDataset(length=80)
+ eval_set = RegressionDataset(length=20)
+ train_dataloader = DataLoader(train_set, batch_size=10, shuffle=True)
+ eval_dataloader = DataLoader(eval_set, batch_size=5, shuffle=False)
+ model = AutoModel.from_pretrained(GPT2_TINY)
+ optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
+ lr_scheduler = get_scheduler(
+ name="linear",
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=1000,
+ )
+ dummy_optimizer = DummyOptim(params=model.parameters())
+ dummy_lr_scheduler = DummyScheduler(dummy_optimizer)
+ kwargs["train_batch_size"] = (
+ kwargs["train_micro_batch_size_per_gpu"]
+ * deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"]
+ * accelerator.num_processes
+ )
+ accelerator.state.deepspeed_plugin.deepspeed_config_process(**kwargs)
+ del accelerator.state.deepspeed_plugin.deepspeed_config["scheduler"]
+ with self.assertRaises(ValueError) as cm:
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, dummy_optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+ assert (
+ "You can only specify `accelerate.utils.DummyScheduler` in the code when using `accelerate.utils.DummyOptim`."
+ in str(cm.exception)
+ )
+
+ # passing `DummyScheduler` without `lr_scheduler_callable` should fail
+ with self.assertRaises(ValueError) as cm:
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler
+ )
+ assert (
+ "Either specify a scheduler in the config file or "
+ "pass in the `lr_scheduler_callable` parameter when using `accelerate.utils.DummyScheduler`."
+ in str(cm.exception)
+ )
+
+ # passing `lr_scheduler_callable` to DummyScheduler should enable DS Optim + Custom Scheduler
+ def _lr_scheduler_callable(optimizer):
+ return get_scheduler(
+ name="linear",
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=1000,
+ )
+
+ dummy_lr_scheduler = DummyScheduler(dummy_optimizer, lr_scheduler_callable=_lr_scheduler_callable)
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler
+ )
+
+ def test_dataloader_with_batch_sampler(self):
+ deepspeed_plugin = DeepSpeedPlugin(
+ gradient_accumulation_steps=1,
+ gradient_clipping=1.0,
+ zero_stage=2,
+ offload_optimizer_device="cpu",
+ offload_param_device="cpu",
+ zero3_save_16bit_model=False,
+ zero3_init_flag=False,
+ )
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin)
+
+ train_set = RegressionDataset(length=80)
+ eval_set = RegressionDataset(length=20)
+ train_dataloader = DataLoader(
+ train_set, batch_sampler=BatchSampler(RandomSampler(train_set), batch_size=10, drop_last=False)
+ )
+ eval_dataloader = DataLoader(
+ eval_set, batch_sampler=BatchSampler(SequentialSampler(eval_set), batch_size=10, drop_last=False)
+ )
+ model = AutoModel.from_pretrained(GPT2_TINY)
+ optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
+ lr_scheduler = get_scheduler(
+ name="linear",
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=1000,
+ )
+
+ with self.assertRaises(ValueError) as cm:
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+ assert (
+ "At least one of the dataloaders passed to `accelerate.prepare()` has `None` as batch size. "
+ "Please set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file "
+ "or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`."
+ in str(cm.exception)
+ )
+
+ def test_save_checkpoints(self):
+ deepspeed_plugin = DeepSpeedPlugin(
+ hf_ds_config=self.ds_config_file[ZERO3],
+ zero3_init_flag=True,
+ )
+ del deepspeed_plugin.deepspeed_config["bf16"]
+ kwargs = {
+ "optimizer.params.lr": 5e-5,
+ "optimizer.params.weight_decay": 0.0,
+ "scheduler.params.warmup_min_lr": 0.0,
+ "scheduler.params.warmup_max_lr": 5e-5,
+ "scheduler.params.warmup_num_steps": 0,
+ "train_micro_batch_size_per_gpu": 16,
+ "gradient_clipping": 1.0,
+ "train_batch_size": 16,
+ "zero_optimization.reduce_bucket_size": 5e5,
+ "zero_optimization.stage3_prefetch_bucket_size": 5e5,
+ "zero_optimization.stage3_param_persistence_threshold": 5e5,
+ "zero_optimization.stage3_gather_16bit_weights_on_model_save": False,
+ }
+
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision="fp16")
+ kwargs["train_batch_size"] = (
+ kwargs["train_micro_batch_size_per_gpu"]
+ * deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"]
+ * accelerator.num_processes
+ )
+ accelerator.state.deepspeed_plugin.deepspeed_config_process(**kwargs)
+
+ train_set = RegressionDataset(length=80)
+ eval_set = RegressionDataset(length=20)
+ train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True)
+ eval_dataloader = DataLoader(eval_set, batch_size=32, shuffle=False)
+ model = AutoModelForCausalLM.from_pretrained("gpt2")
+ dummy_optimizer = DummyOptim(params=model.parameters())
+ dummy_lr_scheduler = DummyScheduler(dummy_optimizer)
+
+ model, _, train_dataloader, eval_dataloader, _ = accelerator.prepare(
+ model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler
+ )
+ with self.assertRaises(ValueError) as cm:
+ accelerator.get_state_dict(model)
+ msg = (
+ "Cannot get 16bit model weights because `stage3_gather_16bit_weights_on_model_save` in DeepSpeed config is False. "
+ "To save the model weights in 16bit, set `stage3_gather_16bit_weights_on_model_save` to True in DeepSpeed config file or "
+ "set `zero3_save_16bit_model` to True when using `accelerate config`. "
+ "To save the full checkpoint, run `model.save_checkpoint(save_dir)` and use `zero_to_fp32.py` to recover weights."
+ )
+ assert msg in str(cm.exception)
+
+ def test_autofill_dsconfig(self):
+ deepspeed_plugin = DeepSpeedPlugin(
+ hf_ds_config=self.ds_config_file[ZERO3],
+ zero3_init_flag=True,
+ )
+ del deepspeed_plugin.deepspeed_config["bf16"]
+ del deepspeed_plugin.deepspeed_config["fp16"]
+
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin)
+ train_set = RegressionDataset(length=80)
+ eval_set = RegressionDataset(length=20)
+ train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True)
+ eval_dataloader = DataLoader(eval_set, batch_size=32, shuffle=False)
+ model = AutoModelForCausalLM.from_pretrained("gpt2")
+ dummy_optimizer = DummyOptim(params=model.parameters(), lr=5e-5, weight_decay=1e-4)
+ dummy_lr_scheduler = DummyScheduler(dummy_optimizer, warmup_num_steps=10, total_num_steps=1000)
+ hidden_size = model.config.hidden_size
+ model, _, train_dataloader, eval_dataloader, _ = accelerator.prepare(
+ model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler
+ )
+ config = accelerator.deepspeed_config
+ assert config["train_micro_batch_size_per_gpu"] == 16
+ assert config["train_batch_size"] == 16
+
+ assert config["optimizer"]["params"]["lr"] == 5e-05
+ assert config["optimizer"]["params"]["weight_decay"] == 1e-4
+
+ assert config["scheduler"]["params"]["warmup_min_lr"] == 0.0
+ assert config["scheduler"]["params"]["warmup_max_lr"] == 5e-05
+ assert config["scheduler"]["params"]["warmup_num_steps"] == 10
+
+ assert config["gradient_clipping"] == 1.0
+ assert config["zero_optimization"]["reduce_bucket_size"] == (hidden_size * hidden_size)
+ assert config["zero_optimization"]["stage3_prefetch_bucket_size"] == int((0.9 * hidden_size) * hidden_size)
+ assert config["zero_optimization"]["stage3_param_persistence_threshold"] == (10 * hidden_size)
+ assert not config["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"]
+
+ @parameterized.expand(model_types, name_func=parameterized_custom_name_func)
+ def test_autofill_comm_buffers_dsconfig(self, model_type):
+ deepspeed_plugin = DeepSpeedPlugin(
+ hf_ds_config=self.ds_config_file[ZERO3],
+ zero3_init_flag=True,
+ )
+ del deepspeed_plugin.deepspeed_config["bf16"]
+ del deepspeed_plugin.deepspeed_config["fp16"]
+ del deepspeed_plugin.deepspeed_config["optimizer"]
+ del deepspeed_plugin.deepspeed_config["scheduler"]
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin)
+ train_set = RegressionDataset(length=80)
+ eval_set = RegressionDataset(length=20)
+ train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True)
+ eval_dataloader = DataLoader(eval_set, batch_size=32, shuffle=False)
+ model = RegressionModel()
+ if model_type == CONFIG_WITH_NO_HIDDEN_SIZE:
+ model.config = DummyConfig()
+ elif model_type == CONFIG_WITH_HIDDEN_SIZE:
+ model.config = AutoConfig.from_pretrained(GPT2_TINY)
+ hidden_size = model.config.hidden_size
+ elif model_type == CONFIG_WITH_HIDDEN_SIZES:
+ model.config = AutoConfig.from_pretrained(MOBILEVIT)
+ hidden_size = max(model.config.hidden_sizes)
+ optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
+ lr_scheduler = get_scheduler(
+ name="linear",
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=1000,
+ )
+
+ if model_type == NO_CONFIG:
+ with self.assertRaises(ValueError) as cm:
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+ msg = "Can't find `model.config` entry"
+ assert msg in str(cm.exception)
+ elif model_type == CONFIG_WITH_NO_HIDDEN_SIZE:
+ with self.assertRaises(ValueError) as cm:
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+ msg = "Can find neither `model.config.hidden_size` nor `model.config.hidden_sizes`"
+ assert msg in str(cm.exception)
+ else:
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+ zero_opt = accelerator.deepspeed_config["zero_optimization"]
+ assert zero_opt["reduce_bucket_size"] == (hidden_size * hidden_size)
+ assert zero_opt["stage3_prefetch_bucket_size"] == int((0.9 * hidden_size) * hidden_size)
+ assert zero_opt["stage3_param_persistence_threshold"] == (10 * hidden_size)
+
+ @parameterized.expand([FP16, BF16], name_func=parameterized_custom_name_func)
+ def test_autofill_dsconfig_from_ds_plugin(self, dtype):
+ ds_config = self.ds_config_dict["zero3"]
+ if dtype == BF16:
+ del ds_config["fp16"]
+ else:
+ del ds_config["bf16"]
+ ds_config[dtype]["enabled"] = "auto"
+ ds_config["zero_optimization"]["stage"] = "auto"
+ ds_config["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] = "auto"
+ ds_config["zero_optimization"]["offload_optimizer"]["device"] = "auto"
+ ds_config["zero_optimization"]["offload_param"]["device"] = "auto"
+ ds_config["gradient_accumulation_steps"] = "auto"
+ ds_config["gradient_clipping"] = "auto"
+
+ deepspeed_plugin = DeepSpeedPlugin(
+ hf_ds_config=ds_config,
+ zero3_init_flag=True,
+ gradient_accumulation_steps=2,
+ gradient_clipping=1.0,
+ zero_stage=2,
+ offload_optimizer_device="cpu",
+ offload_param_device="cpu",
+ zero3_save_16bit_model=True,
+ )
+
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision=dtype)
+ config = accelerator.state.deepspeed_plugin.deepspeed_config
+ assert config["gradient_clipping"] == 1.0
+ assert config["gradient_accumulation_steps"] == 2
+ assert config["zero_optimization"]["stage"] == 2
+ assert config["zero_optimization"]["offload_optimizer"]["device"] == "cpu"
+ assert config["zero_optimization"]["offload_param"]["device"] == "cpu"
+ assert config["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"]
+ assert config[dtype]["enabled"]
+
+ AcceleratorState._reset_state(True)
+ diff_dtype = "bf16" if dtype == "fp16" else "fp16"
+ with mockenv_context(**self.dist_env):
+ with self.assertRaises(ValueError) as cm:
+ accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision=diff_dtype)
+ assert (
+ f"`--mixed_precision` arg cannot be set to `{diff_dtype}` when `{dtype}` is set in the DeepSpeed config file."
+ in str(cm.exception)
+ )
+
+ # base case of passing in `gradient_accumulation_steps` to `DeepSpeedPlugin`
+ AcceleratorState._reset_state(True)
+ deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=4)
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision=dtype)
+ deepspeed_plugin = accelerator.state.deepspeed_plugin
+ assert deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"] == 4
+
+ # filling the `auto` gradient_accumulation_steps via Accelerator's value
+ AcceleratorState._reset_state(True)
+ deepspeed_plugin = DeepSpeedPlugin(
+ hf_ds_config=ds_config,
+ zero3_init_flag=True,
+ gradient_clipping=1.0,
+ zero_stage=2,
+ offload_optimizer_device="cpu",
+ offload_param_device="cpu",
+ zero3_save_16bit_model=True,
+ )
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(
+ deepspeed_plugin=deepspeed_plugin, mixed_precision=dtype, gradient_accumulation_steps=8
+ )
+ train_set = RegressionDataset(length=80)
+ eval_set = RegressionDataset(length=20)
+ train_dataloader = DataLoader(train_set, batch_size=16, shuffle=True)
+ eval_dataloader = DataLoader(eval_set, batch_size=32, shuffle=False)
+ model = AutoModelForCausalLM.from_pretrained("gpt2")
+ dummy_optimizer = DummyOptim(params=model.parameters(), lr=5e-5, weight_decay=1e-4)
+ dummy_lr_scheduler = DummyScheduler(dummy_optimizer, warmup_num_steps=10, total_num_steps=1000)
+ model, _, train_dataloader, eval_dataloader, _ = accelerator.prepare(
+ model, dummy_optimizer, train_dataloader, eval_dataloader, dummy_lr_scheduler
+ )
+ deepspeed_plugin = accelerator.state.deepspeed_plugin
+ assert deepspeed_plugin.deepspeed_config["gradient_accumulation_steps"] == 8
+
+ def test_ds_config_assertions(self):
+ ambiguous_env = self.dist_env.copy()
+ ambiguous_env["ACCELERATE_CONFIG_DS_FIELDS"] = (
+ "gradient_accumulation_steps,gradient_clipping,zero_stage,offload_optimizer_device,offload_param_device,zero3_save_16bit_model,mixed_precision"
+ )
+
+ with mockenv_context(**ambiguous_env):
+ with self.assertRaises(ValueError) as cm:
+ deepspeed_plugin = DeepSpeedPlugin(
+ hf_ds_config=self.ds_config_file[ZERO3],
+ zero3_init_flag=True,
+ gradient_accumulation_steps=1,
+ gradient_clipping=1.0,
+ zero_stage=ZERO2,
+ offload_optimizer_device="cpu",
+ offload_param_device="cpu",
+ zero3_save_16bit_model=True,
+ )
+ _ = Accelerator(deepspeed_plugin=deepspeed_plugin, mixed_precision=FP16)
+ assert (
+ "If you are using an accelerate config file, remove others config variables mentioned in the above specified list."
+ in str(cm.exception)
+ )
+
+ @parameterized.expand(stages, name_func=parameterized_custom_name_func)
+ def test_ds_config(self, stage):
+ deepspeed_plugin = DeepSpeedPlugin(
+ hf_ds_config=self.ds_config_file[stage],
+ zero3_init_flag=True,
+ )
+ assert deepspeed_plugin.zero_stage == int(stage.replace("zero", ""))
+
+ def test_prepare_deepspeed_prepare_moe(self):
+ if compare_versions("transformers", "<", "4.40") and compare_versions("deepspeed", "<", "0.14"):
+ return
+ deepspeed_plugin = DeepSpeedPlugin(
+ zero3_init_flag=True,
+ gradient_accumulation_steps=1,
+ gradient_clipping=1.0,
+ zero_stage=3,
+ offload_optimizer_device="none",
+ offload_param_device="none",
+ zero3_save_16bit_model=True,
+ transformer_moe_cls_names="Qwen2MoeSparseMoeBlock",
+ )
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(mixed_precision="fp16", deepspeed_plugin=deepspeed_plugin)
+ accelerator.state.deepspeed_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = 1
+ model = AutoModelForCausalLM.from_pretrained(QWEN_MOE)
+ model = accelerator.prepare(model)
+ from transformers.models.qwen2_moe.modeling_qwen2_moe import Qwen2MoeSparseMoeBlock
+
+ for module in model.modules():
+ if isinstance(module, Qwen2MoeSparseMoeBlock):
+ assert hasattr(module, "_z3_leaf") and module._z3_leaf
+
+ def test_basic_run(self):
+ test_file_path = path_in_accelerate_package("test_utils", "scripts", "external_deps", "test_performance.py")
+ with tempfile.TemporaryDirectory() as dirpath:
+ cmd = [
+ "accelerate",
+ "launch",
+ "--num_processes=1",
+ "--num_machines=1",
+ "--machine_rank=0",
+ "--mixed_precision=fp16",
+ "--use_deepspeed",
+ "--gradient_accumulation_steps=1",
+ "--zero_stage=2",
+ "--offload_optimizer_device=none",
+ "--offload_param_device=none",
+ test_file_path,
+ "--model_name_or_path=distilbert-base-uncased",
+ "--num_epochs=1",
+ f"--output_dir={dirpath}",
+ ]
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd)
+
+
+@require_deepspeed
+@require_multi_device
+@slow
+class DeepSpeedIntegrationTest(TempDirTestCase):
+ test_scripts_folder = path_in_accelerate_package("test_utils", "scripts", "external_deps")
+
+ def setUp(self):
+ super().setUp()
+ self._test_file_path = inspect.getfile(self.__class__)
+ path = Path(self._test_file_path).resolve()
+ self.test_file_dir_str = str(path.parents[0])
+
+ self.ds_config_file = dict(
+ zero2=f"{self.test_file_dir_str}/ds_config_zero2.json",
+ zero3=f"{self.test_file_dir_str}/ds_config_zero3.json",
+ )
+
+ self.stages = [1, 2, 3]
+ self.zero3_offload_config = False
+ self.performance_lower_bound = 0.82
+ self.peak_memory_usage_upper_bound = {
+ "multi_gpu_fp16": 3200,
+ "deepspeed_stage_1_fp16": 1600,
+ "deepspeed_stage_2_fp16": 2500,
+ "deepspeed_stage_3_zero_init_fp16": 2800,
+ # Disabling below test as it overwhelms the RAM memory usage
+ # on CI self-hosted runner leading to tests getting killed.
+ # "deepspeed_stage_3_cpu_offload_fp16": 1900,
+ }
+ self.n_train = 160
+ self.n_val = 160
+
+ def test_performance(self):
+ self.test_file_path = self.test_scripts_folder / "test_performance.py"
+ cmd = [
+ "accelerate",
+ "launch",
+ "--num_processes=2",
+ "--num_machines=1",
+ "--machine_rank=0",
+ "--mixed_precision=fp16",
+ "--use_deepspeed",
+ "--gradient_accumulation_steps=1",
+ "--gradient_clipping=1",
+ "--zero3_init_flag=True",
+ "--zero3_save_16bit_model=True",
+ ]
+ for stage in self.stages:
+ if stage == 1:
+ continue
+ cmd_stage = cmd.copy()
+ cmd_stage.extend([f"--zero_stage={stage}"])
+ cmd_stage.extend(["--offload_optimizer_device=none", "--offload_param_device=none"])
+ if self.zero3_offload_config:
+ with open(self.ds_config_file[ZERO3], encoding="utf-8") as f:
+ ds_config = json.load(f)
+ del ds_config["bf16"]
+ del ds_config["optimizer"]["params"]["torch_adam"]
+ del ds_config["optimizer"]["params"]["adam_w_mode"]
+ ds_config["fp16"]["enabled"] = True
+ ds_config_path = os.path.join(self.tmpdir, "ds_config.json")
+ with open(ds_config_path, "w") as out_file:
+ json.dump(ds_config, out_file)
+
+ cmd_stage.extend([f"--deepspeed_config_file={ds_config_path}"])
+
+ cmd_stage.extend(
+ [
+ self.test_file_path,
+ f"--output_dir={self.tmpdir}",
+ f"--performance_lower_bound={self.performance_lower_bound}",
+ ]
+ )
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd_stage)
+
+ def test_checkpointing(self):
+ self.test_file_path = self.test_scripts_folder / "test_checkpointing.py"
+ cmd = [
+ "accelerate",
+ "launch",
+ "--num_processes=2",
+ "--num_machines=1",
+ "--machine_rank=0",
+ "--mixed_precision=fp16",
+ "--use_deepspeed",
+ "--gradient_accumulation_steps=1",
+ "--gradient_clipping=1",
+ "--zero3_init_flag=True",
+ "--zero3_save_16bit_model=True",
+ ]
+ for stage in self.stages:
+ if stage == 1:
+ continue
+ cmd_stage = cmd.copy()
+ cmd_stage.extend([f"--zero_stage={stage}"])
+ cmd_stage.extend(["--offload_optimizer_device=none", "--offload_param_device=none"])
+ if self.zero3_offload_config:
+ with open(self.ds_config_file[ZERO3], encoding="utf-8") as f:
+ ds_config = json.load(f)
+ del ds_config["bf16"]
+ del ds_config["optimizer"]["params"]["torch_adam"]
+ del ds_config["optimizer"]["params"]["adam_w_mode"]
+ ds_config["fp16"]["enabled"] = True
+ ds_config_path = os.path.join(self.tmpdir, "ds_config.json")
+ with open(ds_config_path, "w") as out_file:
+ json.dump(ds_config, out_file)
+
+ cmd_stage.extend([f"--deepspeed_config_file={ds_config_path}"])
+
+ cmd_stage.extend(
+ [
+ self.test_file_path,
+ f"--output_dir={self.tmpdir}",
+ "--partial_train_epoch=1",
+ ]
+ )
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd_stage)
+
+ cmd_stage = cmd_stage[:-1]
+ resume_from_checkpoint = os.path.join(self.tmpdir, "epoch_0")
+ cmd_stage.extend(
+ [
+ f"--resume_from_checkpoint={resume_from_checkpoint}",
+ ]
+ )
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd_stage)
+
+ def test_peak_memory_usage(self):
+ if compare_versions("deepspeed", ">", "0.12.6"):
+ self.skipTest(
+ "The test fails when deepspeed>0.12.6. This is something that needs to be fixed on deepspeed library"
+ )
+
+ self.test_file_path = self.test_scripts_folder / "test_peak_memory_usage.py"
+ cmd = [
+ "accelerate",
+ "launch",
+ "--num_processes=2",
+ "--num_machines=1",
+ "--machine_rank=0",
+ ]
+ for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items():
+ cmd_stage = cmd.copy()
+ if "fp16" in spec:
+ cmd_stage.extend(["--mixed_precision=fp16"])
+
+ if "multi_gpu" in spec:
+ continue
+ else:
+ cmd_stage.extend(
+ [
+ "--use_deepspeed",
+ "--gradient_accumulation_steps=1",
+ "--gradient_clipping=1",
+ "--zero3_init_flag=True",
+ "--zero3_save_16bit_model=True",
+ ]
+ )
+ for i in range(3):
+ if f"stage_{i + 1}" in spec:
+ cmd_stage.extend([f"--zero_stage={i + 1}"])
+ break
+ cmd_stage.extend(
+ [
+ "--offload_optimizer_device=none",
+ "--offload_param_device=none",
+ "--offload_optimizer_nvme_path=none",
+ "--offload_param_nvme_path=none",
+ ]
+ )
+ if "cpu_offload" in spec:
+ with open(self.ds_config_file[ZERO3], encoding="utf-8") as f:
+ ds_config = json.load(f)
+ del ds_config["bf16"]
+ del ds_config["fp16"]
+ del ds_config["optimizer"]["params"]["torch_adam"]
+ del ds_config["optimizer"]["params"]["adam_w_mode"]
+ ds_config_path = os.path.join(self.tmpdir, "ds_config.json")
+ with open(ds_config_path, "w") as out_file:
+ json.dump(ds_config, out_file)
+
+ cmd_stage.extend([f"--deepspeed_config_file={ds_config_path}"])
+
+ cmd_stage.extend(
+ [
+ self.test_file_path,
+ f"--output_dir={self.tmpdir}",
+ f"--peak_memory_upper_bound={peak_mem_upper_bound}",
+ f"--n_train={self.n_train}",
+ f"--n_val={self.n_val}",
+ ]
+ )
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd_stage)
+
+ def test_lr_scheduler(self):
+ self.test_file_path = self.test_scripts_folder / "test_performance.py"
+ cmd = [
+ "accelerate",
+ "launch",
+ "--num_processes=2",
+ "--num_machines=1",
+ "--machine_rank=0",
+ "--mixed_precision=no",
+ "--use_deepspeed",
+ "--gradient_accumulation_steps=1",
+ "--gradient_clipping=1",
+ "--zero3_init_flag=True",
+ "--zero3_save_16bit_model=True",
+ "--zero_stage=3",
+ "--offload_optimizer_device=none",
+ "--offload_param_device=none",
+ self.test_file_path,
+ f"--output_dir={self.tmpdir}",
+ f"--performance_lower_bound={self.performance_lower_bound}",
+ ]
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd)
+
+ @require_huggingface_suite
+ def test_zero3_integration(self):
+ self.test_file_path = self.test_scripts_folder / "test_zero3_integration.py"
+ cmd = ["accelerate", "launch", "--num_processes=2", "--num_machines=1", self.test_file_path]
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/test_deepspeed_multiple_model.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/test_deepspeed_multiple_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..f26f40debb346cff3b5a9326553cd713c756d983
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/deepspeed/test_deepspeed_multiple_model.py
@@ -0,0 +1,178 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import inspect
+import json
+from functools import partial
+from pathlib import Path
+
+import torch
+from transformers import AutoModelForCausalLM
+
+from accelerate import Accelerator, DeepSpeedPlugin
+from accelerate.commands.launch import launch_command, launch_command_parser
+from accelerate.test_utils.testing import (
+ AccelerateTestCase,
+ path_in_accelerate_package,
+ require_deepspeed,
+ require_huggingface_suite,
+ require_multi_device,
+ require_non_cpu,
+ slow,
+)
+from accelerate.test_utils.training import RegressionDataset
+from accelerate.utils import patch_environment
+from accelerate.utils.deepspeed import DummyOptim, DummyScheduler, get_active_deepspeed_plugin
+
+
+GPT2_TINY = "hf-internal-testing/tiny-random-gpt2"
+
+
+@require_deepspeed
+@require_non_cpu
+class DeepSpeedConfigIntegration(AccelerateTestCase):
+ parser = launch_command_parser()
+ test_scripts_folder = path_in_accelerate_package("test_utils", "scripts", "external_deps")
+
+ def setUp(self):
+ super().setUp()
+
+ self.dist_env = dict(
+ ACCELERATE_USE_DEEPSPEED="true",
+ MASTER_ADDR="localhost",
+ MASTER_PORT="10999",
+ RANK="0",
+ LOCAL_RANK="0",
+ WORLD_SIZE="1",
+ )
+
+ self._test_file_path = inspect.getfile(self.__class__)
+ path = Path(self._test_file_path).resolve()
+ self.test_file_dir_str = str(path.parents[0])
+
+ self.ds_config_file = dict(
+ zero2=f"{self.test_file_dir_str}/ds_config_zero2.json",
+ zero3_inference=f"{self.test_file_dir_str}/ds_config_zero3_model_only.json",
+ zero3_training=f"{self.test_file_dir_str}/ds_config_zero3.json",
+ )
+
+ with open(self.ds_config_file["zero2"], encoding="utf-8") as f:
+ self.config_zero2 = json.load(f)
+ with open(self.ds_config_file["zero3_training"], encoding="utf-8") as f:
+ self.config_zero3 = json.load(f)
+ with open(self.ds_config_file["zero3_inference"], encoding="utf-8") as f:
+ self.config_zero3_inference = json.load(f)
+
+ self.model_init = partial(AutoModelForCausalLM.from_pretrained, GPT2_TINY)
+
+ def get_ds_plugins(self, zero3_inference=False):
+ ds_zero2 = DeepSpeedPlugin(
+ hf_ds_config=self.config_zero2,
+ )
+ ds_zero3 = DeepSpeedPlugin(
+ hf_ds_config=self.config_zero3 if not zero3_inference else self.config_zero3_inference,
+ )
+ return {"zero2": ds_zero2, "zero3": ds_zero3}
+
+ def test_select_plugin(self):
+ ds_plugins = self.get_ds_plugins()
+ ds_zero2, ds_zero3 = ds_plugins.values()
+ accelerator = Accelerator(
+ deepspeed_plugin=ds_plugins,
+ )
+ # Accelerator's constructor should automatically enable the first plugin
+ assert ds_zero2.selected
+ assert not ds_zero3.selected
+ assert get_active_deepspeed_plugin(accelerator.state) == ds_zero2
+ assert accelerator.deepspeed_plugin == ds_zero2
+ assert accelerator.state.get_deepspeed_plugin("zero2") == ds_zero2
+ accelerator.state.select_deepspeed_plugin("zero3")
+ assert not ds_zero2.selected
+ assert ds_zero3.selected
+ assert get_active_deepspeed_plugin(accelerator.state) == ds_zero3
+ assert accelerator.deepspeed_plugin == ds_zero3
+ assert accelerator.state.get_deepspeed_plugin("zero3") == ds_zero3
+ accelerator.state.select_deepspeed_plugin("zero2")
+ assert not ds_zero3.selected
+ assert ds_zero2.selected
+ assert get_active_deepspeed_plugin(accelerator.state) == ds_zero2
+ assert accelerator.deepspeed_plugin == ds_zero2
+ assert accelerator.state.get_deepspeed_plugin("zero2") == ds_zero2
+
+ @require_huggingface_suite
+ def test_config_reference_update(self):
+ # Make sure that the transformers weakref is updating when we update the config
+ ds_plugins = self.get_ds_plugins(zero3_inference=True)
+ zero2, zero3 = ds_plugins.values()
+ accelerator = Accelerator(deepspeed_plugin=ds_plugins)
+ from transformers.integrations.deepspeed import deepspeed_config
+
+ assert accelerator.deepspeed_plugin is zero2
+ assert deepspeed_config() == accelerator.deepspeed_plugin.hf_ds_config.config
+
+ accelerator.state.select_deepspeed_plugin("zero3")
+ assert accelerator.deepspeed_plugin is zero3
+ assert deepspeed_config() == accelerator.deepspeed_plugin.hf_ds_config.config
+
+ def test_enable_disable_manually_set(self):
+ ds_plugins = self.get_ds_plugins()
+ ds_zero2, _ = ds_plugins.values()
+ with self.assertRaises(ValueError):
+ ds_zero2.select()
+ accelerator = Accelerator(deepspeed_plugin=ds_plugins)
+ accelerator.state.select_deepspeed_plugin("zero2")
+ with self.assertRaises(NotImplementedError):
+ ds_zero2.selected = False
+ assert ds_zero2.selected
+
+ def test_multiple_accelerators(self):
+ ds_plugins = self.get_ds_plugins()
+ ds_zero2, ds_zero3 = ds_plugins.values()
+ _ = Accelerator(
+ deepspeed_plugin=ds_zero2,
+ )
+ with self.assertRaises(NotImplementedError):
+ _ = Accelerator(deepspeed_plugin=ds_zero3)
+
+ def test_prepare_multiple_models_zero3_inference(self):
+ with patch_environment(**self.dist_env):
+ ds_plugins = self.get_ds_plugins(zero3_inference=True)
+ accelerator = Accelerator(deepspeed_plugin=ds_plugins)
+ # Using Zero-2 first
+ model1 = self.model_init()
+ optimizer = DummyOptim(model1.parameters())
+ scheduler = DummyScheduler(optimizer)
+
+ dataset = RegressionDataset()
+ dataloader = torch.utils.data.DataLoader(dataset, batch_size=1)
+ model1, optimizer, scheduler, dataloader = accelerator.prepare(model1, optimizer, scheduler, dataloader)
+ accelerator.state.select_deepspeed_plugin("zero3")
+ model2 = self.model_init()
+ with self.assertLogs(level="WARNING") as captured:
+ model2 = accelerator.prepare(model2)
+ self.assertIn(
+ "A wrapped DeepSpeed engine reference is currently tied for this `Accelerator()` instance.",
+ captured.output[0],
+ )
+
+ assert accelerator.deepspeed_engine_wrapped.engine is model1
+
+ @require_huggingface_suite
+ @require_multi_device
+ @slow
+ def test_train_multiple_models(self):
+ self.test_file_path = self.test_scripts_folder / "test_ds_multiple_model.py"
+ args = ["--num_processes=2", "--num_machines=1", "--main_process_port=10999", str(self.test_file_path)]
+ args = self.parser.parse_args(args)
+ launch_command(args)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/fsdp/test_fsdp.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/fsdp/test_fsdp.py
new file mode 100644
index 0000000000000000000000000000000000000000..11dc5e3510c7d071d8b096990ffbb8b28d2b700d
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/fsdp/test_fsdp.py
@@ -0,0 +1,442 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import functools
+import os
+
+import torch
+from transformers import AutoModel
+from transformers.testing_utils import mockenv_context
+from transformers.trainer_utils import set_seed
+
+from accelerate.accelerator import Accelerator
+from accelerate.state import AcceleratorState
+from accelerate.test_utils.testing import (
+ AccelerateTestCase,
+ TempDirTestCase,
+ execute_subprocess_async,
+ get_launch_command,
+ path_in_accelerate_package,
+ require_fsdp,
+ require_multi_device,
+ require_non_cpu,
+ require_non_torch_xla,
+ slow,
+)
+from accelerate.utils.constants import (
+ FSDP_AUTO_WRAP_POLICY,
+ FSDP_BACKWARD_PREFETCH,
+ FSDP_SHARDING_STRATEGY,
+ FSDP_STATE_DICT_TYPE,
+)
+from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin
+from accelerate.utils.fsdp_utils import disable_fsdp_ram_efficient_loading, enable_fsdp_ram_efficient_loading
+from accelerate.utils.other import patch_environment
+
+
+set_seed(42)
+
+BERT_BASE_CASED = "bert-base-cased"
+LLAMA_TESTING = "hf-internal-testing/tiny-random-LlamaForCausalLM"
+FP16 = "fp16"
+BF16 = "bf16"
+dtypes = [FP16, BF16]
+
+
+@require_fsdp
+@require_non_cpu
+@require_non_torch_xla
+class FSDPPluginIntegration(AccelerateTestCase):
+ def setUp(self):
+ super().setUp()
+
+ self.dist_env = dict(
+ MASTER_ADDR="localhost",
+ MASTER_PORT="10999",
+ RANK="0",
+ LOCAL_RANK="0",
+ WORLD_SIZE="1",
+ )
+
+ self.fsdp_env = dict(ACCELERATE_USE_FSDP="true", **self.dist_env)
+
+ def test_sharding_strategy(self):
+ from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy
+
+ # check that giving enums works fine
+ for i, strategy in enumerate(FSDP_SHARDING_STRATEGY):
+ env = self.fsdp_env.copy()
+ env["FSDP_SHARDING_STRATEGY"] = f"{i + 1}"
+ with mockenv_context(**env):
+ fsdp_plugin = FullyShardedDataParallelPlugin()
+ assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1)
+ fsdp_plugin = FullyShardedDataParallelPlugin(sharding_strategy=ShardingStrategy(i + 1))
+ assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1)
+
+ # check that giving names works fine
+ for i, strategy in enumerate(FSDP_SHARDING_STRATEGY):
+ env = self.fsdp_env.copy()
+ env["FSDP_SHARDING_STRATEGY"] = strategy
+ with mockenv_context(**env):
+ fsdp_plugin = FullyShardedDataParallelPlugin()
+ assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1)
+ fsdp_plugin = FullyShardedDataParallelPlugin(sharding_strategy=strategy)
+ assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1)
+
+ def test_backward_prefetch(self):
+ from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch
+
+ for i, prefetch_policy in enumerate(FSDP_BACKWARD_PREFETCH):
+ expected_value = None if prefetch_policy == "NO_PREFETCH" else BackwardPrefetch(i + 1)
+ env = self.fsdp_env.copy()
+ env["FSDP_BACKWARD_PREFETCH"] = prefetch_policy
+ with mockenv_context(**env):
+ fsdp_plugin = FullyShardedDataParallelPlugin()
+ assert (
+ fsdp_plugin.backward_prefetch == expected_value
+ ), f"Actual: {fsdp_plugin.backward_prefetch} != Expected: {expected_value}"
+
+ # Check if torch enum works
+ if prefetch_policy != "NO_PREFETCH":
+ fsdp_plugin = FullyShardedDataParallelPlugin(backward_prefetch=BackwardPrefetch(i + 1))
+ assert fsdp_plugin.backward_prefetch == expected_value
+
+ # Check if name works
+ fsdp_plugin = FullyShardedDataParallelPlugin(backward_prefetch=prefetch_policy)
+ assert fsdp_plugin.backward_prefetch == expected_value
+
+ def test_state_dict_type(self):
+ from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType
+
+ for i, state_dict_type in enumerate(FSDP_STATE_DICT_TYPE):
+ env = self.fsdp_env.copy()
+ env["FSDP_STATE_DICT_TYPE"] = state_dict_type
+ with mockenv_context(**env):
+ fsdp_plugin = FullyShardedDataParallelPlugin()
+ assert fsdp_plugin.state_dict_type == StateDictType(i + 1)
+ if state_dict_type == "FULL_STATE_DICT":
+ assert fsdp_plugin.state_dict_config.offload_to_cpu
+ assert fsdp_plugin.state_dict_config.rank0_only
+
+ fsdp_plugin = FullyShardedDataParallelPlugin(state_dict_type=StateDictType(i + 1))
+ assert fsdp_plugin.state_dict_type == StateDictType(i + 1)
+ if state_dict_type == "FULL_STATE_DICT":
+ assert fsdp_plugin.state_dict_config.offload_to_cpu
+ assert fsdp_plugin.state_dict_config.rank0_only
+
+ # We can also override the state_dict_type,
+ # typical case: user trains with sharded, but final save is with full
+ fsdp_plugin = FullyShardedDataParallelPlugin(state_dict_type="FULL_STATE_DICT")
+ fsdp_plugin.set_state_dict_type("SHARDED_STATE_DICT")
+ assert fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT
+
+ def test_auto_wrap_policy(self):
+ for model_name in [LLAMA_TESTING, BERT_BASE_CASED]:
+ model = AutoModel.from_pretrained(model_name)
+ layer_to_wrap = "LlamaDecoderLayer" if model_name == LLAMA_TESTING else "BertLayer"
+ for policy in FSDP_AUTO_WRAP_POLICY:
+ env = self.fsdp_env.copy()
+ env["FSDP_AUTO_WRAP_POLICY"] = policy
+ transformer_cls_to_wrap = None
+ min_num_params = None
+ env.pop("FSDP_TRANSFORMER_CLS_TO_WRAP", None)
+ env.pop("FSDP_MIN_NUM_PARAMS", None)
+ if policy == "TRANSFORMER_BASED_WRAP":
+ env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = layer_to_wrap
+ transformer_cls_to_wrap = layer_to_wrap
+ elif policy == "SIZE_BASED_WRAP":
+ env["FSDP_MIN_NUM_PARAMS"] = "2000"
+ min_num_params = 2000
+ # First test via env
+ with mockenv_context(**env):
+ fsdp_plugin = FullyShardedDataParallelPlugin()
+ fsdp_plugin.set_auto_wrap_policy(model)
+ if policy == "NO_WRAP":
+ assert fsdp_plugin.auto_wrap_policy is None
+ else:
+ assert isinstance(fsdp_plugin.auto_wrap_policy, functools.partial)
+
+ # Then manually set the policy
+ fsdp_plugin = FullyShardedDataParallelPlugin(
+ auto_wrap_policy=policy,
+ transformer_cls_names_to_wrap=transformer_cls_to_wrap,
+ min_num_params=min_num_params,
+ )
+ fsdp_plugin.set_auto_wrap_policy(model)
+ if policy == "NO_WRAP":
+ assert fsdp_plugin.auto_wrap_policy is None
+ else:
+ assert isinstance(fsdp_plugin.auto_wrap_policy, functools.partial)
+
+ env = self.fsdp_env.copy()
+ env["FSDP_AUTO_WRAP_POLICY"] = "TRANSFORMER_BASED_WRAP"
+ env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = "T5Layer"
+ with mockenv_context(**env):
+ fsdp_plugin = FullyShardedDataParallelPlugin()
+ with self.assertRaises(Exception) as cm:
+ fsdp_plugin.set_auto_wrap_policy(model)
+ assert "Could not find the transformer layer class T5Layer in the model." in str(cm.exception)
+
+ fsdp_plugin = FullyShardedDataParallelPlugin(
+ auto_wrap_policy="TRANSFORMER_BASED_WRAP",
+ transformer_cls_names_to_wrap="T5Layer",
+ )
+ with self.assertRaises(Exception) as cm:
+ fsdp_plugin.set_auto_wrap_policy(model)
+ assert "Could not find the transformer layer class T5Layer in the model." in str(cm.exception)
+
+ env = self.fsdp_env.copy()
+ env["FSDP_AUTO_WRAP_POLICY"] = "SIZE_BASED_WRAP"
+ env["FSDP_MIN_NUM_PARAMS"] = "0"
+ with mockenv_context(**env):
+ fsdp_plugin = FullyShardedDataParallelPlugin()
+ fsdp_plugin.set_auto_wrap_policy(model)
+ assert fsdp_plugin.auto_wrap_policy is None
+
+ fsdp_plugin = FullyShardedDataParallelPlugin(
+ auto_wrap_policy="SIZE_BASED_WRAP",
+ min_num_params=0,
+ )
+ fsdp_plugin.set_auto_wrap_policy(model)
+ assert fsdp_plugin.auto_wrap_policy is None
+
+ def test_mixed_precision(self):
+ from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision
+ from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler
+
+ for mp_dtype in dtypes:
+ env = self.fsdp_env.copy()
+ env["ACCELERATE_MIXED_PRECISION"] = mp_dtype
+ with mockenv_context(**env):
+ accelerator = Accelerator()
+ if mp_dtype == "fp16":
+ dtype = torch.float16
+ elif mp_dtype == "bf16":
+ dtype = torch.bfloat16
+ mp_policy = MixedPrecision(param_dtype=dtype, reduce_dtype=dtype, buffer_dtype=dtype)
+ assert accelerator.state.fsdp_plugin.mixed_precision_policy == mp_policy
+ if mp_dtype == FP16:
+ assert isinstance(accelerator.scaler, ShardedGradScaler)
+ elif mp_dtype == BF16:
+ assert accelerator.scaler is None
+ AcceleratorState._reset_state(True)
+ plugin = FullyShardedDataParallelPlugin(
+ mixed_precision_policy={"param_dtype": dtype, "reduce_dtype": dtype, "buffer_dtype": dtype}
+ )
+ assert plugin.mixed_precision_policy == mp_policy
+ with mockenv_context(**self.dist_env):
+ accelerator = Accelerator(fsdp_plugin=plugin)
+ assert accelerator.state.fsdp_plugin.mixed_precision_policy == mp_policy
+ AcceleratorState._reset_state(True)
+
+ def test_mixed_precision_buffer_autocast_override(self):
+ from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision
+ from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler
+
+ for mp_dtype in dtypes:
+ if mp_dtype == "fp16":
+ dtype = torch.float16
+ elif mp_dtype == "bf16":
+ dtype = torch.bfloat16
+ mp_policy = MixedPrecision(param_dtype=dtype, reduce_dtype=dtype, buffer_dtype=torch.float32)
+
+ env = self.fsdp_env.copy()
+ env["ACCELERATE_MIXED_PRECISION"] = mp_dtype
+ with mockenv_context(**env):
+ accelerator = Accelerator()
+ accelerator.state.fsdp_plugin.set_mixed_precision(dtype, buffer_autocast=True, override=True)
+ assert accelerator.state.fsdp_plugin.mixed_precision_policy == mp_policy
+ if mp_dtype == FP16:
+ assert isinstance(accelerator.scaler, ShardedGradScaler)
+ elif mp_dtype == BF16:
+ assert accelerator.scaler is None
+ AcceleratorState._reset_state(True)
+
+ def test_cpu_offload(self):
+ from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload
+
+ for flag in [True, False]:
+ env = self.fsdp_env.copy()
+ env["FSDP_OFFLOAD_PARAMS"] = str(flag).lower()
+ with mockenv_context(**env):
+ fsdp_plugin = FullyShardedDataParallelPlugin()
+ assert fsdp_plugin.cpu_offload == CPUOffload(offload_params=flag)
+
+ fsdp_plugin = FullyShardedDataParallelPlugin(cpu_offload=flag)
+ assert fsdp_plugin.cpu_offload == CPUOffload(offload_params=flag)
+
+ def test_cpu_ram_efficient_loading(self):
+ enable_fsdp_ram_efficient_loading()
+ fsdp_plugin = FullyShardedDataParallelPlugin()
+ assert fsdp_plugin.cpu_ram_efficient_loading is True
+ assert os.environ.get("FSDP_CPU_RAM_EFFICIENT_LOADING") == "True"
+ disable_fsdp_ram_efficient_loading()
+ fsdp_plugin = FullyShardedDataParallelPlugin()
+ assert fsdp_plugin.cpu_ram_efficient_loading is False
+ assert os.environ.get("FSDP_CPU_RAM_EFFICIENT_LOADING") == "False"
+
+
+# Skip this test when TorchXLA is available because accelerate.launch does not support TorchXLA FSDP.
+@require_non_torch_xla
+@require_fsdp
+@require_multi_device
+@slow
+class FSDPIntegrationTest(TempDirTestCase):
+ test_scripts_folder = path_in_accelerate_package("test_utils", "scripts", "external_deps")
+
+ def setUp(self):
+ super().setUp()
+ self.performance_lower_bound = 0.82
+ self.performance_configs = [
+ "fsdp_shard_grad_op_transformer_based_wrap",
+ "fsdp_full_shard_transformer_based_wrap",
+ ]
+ self.peak_memory_usage_upper_bound = {
+ "multi_gpu_fp16": 3200,
+ "fsdp_shard_grad_op_transformer_based_wrap_fp16": 2000,
+ "fsdp_full_shard_transformer_based_wrap_fp16": 1900,
+ # Disabling below test as it overwhelms the RAM memory usage
+ # on CI self-hosted runner leading to tests getting killed.
+ # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang
+ }
+ self.n_train = 160
+ self.n_val = 160
+
+ def test_performance(self):
+ self.test_file_path = self.test_scripts_folder / "test_performance.py"
+ cmd = get_launch_command(num_processes=2, num_machines=1, machine_rank=0, use_fsdp=True)
+ for config in self.performance_configs:
+ cmd_config = cmd.copy()
+ for i, strategy in enumerate(FSDP_SHARDING_STRATEGY):
+ if strategy.lower() in config:
+ cmd_config.append(f"--fsdp_sharding_strategy={strategy}")
+ break
+
+ if "fp32" in config:
+ cmd_config.append("--mixed_precision=no")
+ else:
+ cmd_config.append("--mixed_precision=fp16")
+
+ if "cpu_offload" in config:
+ cmd_config.append("--fsdp_offload_params=True")
+
+ for policy in FSDP_AUTO_WRAP_POLICY:
+ if policy.lower() in config:
+ cmd_config.append(f"--fsdp_auto_wrap_policy={policy}")
+ break
+
+ if policy == "TRANSFORMER_BASED_WRAP":
+ cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer")
+ elif policy == "SIZE_BASED_WRAP":
+ cmd_config.append("--fsdp_min_num_params=2000")
+
+ cmd_config.extend(
+ [
+ self.test_file_path,
+ f"--output_dir={self.tmpdir}",
+ f"--performance_lower_bound={self.performance_lower_bound}",
+ ]
+ )
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd_config)
+
+ def test_checkpointing(self):
+ self.test_file_path = self.test_scripts_folder / "test_checkpointing.py"
+ cmd = get_launch_command(
+ num_processes=2,
+ num_machines=1,
+ machine_rank=0,
+ use_fsdp=True,
+ mixed_precision="fp16",
+ fsdp_transformer_layer_cls_to_wrap="BertLayer",
+ )
+
+ for i, strategy in enumerate(FSDP_SHARDING_STRATEGY):
+ cmd_config = cmd.copy()
+ cmd_config.append(f"--fsdp_sharding_strategy={strategy}")
+ if strategy != "FULL_SHARD":
+ continue
+ state_dict_config_index = len(cmd_config)
+ for state_dict_type in FSDP_STATE_DICT_TYPE:
+ # Todo: Currently failing for `LOCAL_STATE_DICT` with error
+ # Unexpected key(s) in state_dict: "_fsdp_wrapped_module._flat_param".
+ if state_dict_type == "LOCAL_STATE_DICT":
+ continue
+
+ cmd_config = cmd_config[:state_dict_config_index]
+ cmd_config.append(f"--fsdp_state_dict_type={state_dict_type}")
+ cmd_config.extend(
+ [
+ self.test_file_path,
+ f"--output_dir={self.tmpdir}",
+ "--partial_train_epoch=1",
+ ]
+ )
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd_config)
+
+ cmd_config = cmd_config[:-1]
+ resume_from_checkpoint = os.path.join(self.tmpdir, "epoch_0")
+ cmd_config.extend(
+ [
+ f"--resume_from_checkpoint={resume_from_checkpoint}",
+ ]
+ )
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd_config)
+
+ def test_peak_memory_usage(self):
+ self.test_file_path = self.test_scripts_folder / "test_peak_memory_usage.py"
+ cmd = get_launch_command(num_processes=2, num_machines=1, machine_rank=0)
+ for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items():
+ cmd_config = cmd.copy()
+ if "fp16" in spec:
+ cmd_config.extend(["--mixed_precision=fp16"])
+ else:
+ cmd_config.extend(["--mixed_precision=no"])
+
+ if "multi_gpu" in spec:
+ continue
+ else:
+ cmd_config.extend(["--use_fsdp"])
+ for i, strategy in enumerate(FSDP_SHARDING_STRATEGY):
+ if strategy.lower() in spec:
+ cmd_config.append(f"--fsdp_sharding_strategy={strategy}")
+ break
+
+ if "cpu_offload" in spec:
+ cmd_config.append("--fsdp_offload_params=True")
+
+ for policy in FSDP_AUTO_WRAP_POLICY:
+ if policy.lower() in spec:
+ cmd_config.append(f"--fsdp_auto_wrap_policy={policy}")
+ break
+
+ if policy == "TRANSFORMER_BASED_WRAP":
+ cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer")
+ elif policy == "SIZE_BASED_WRAP":
+ cmd_config.append("--fsdp_min_num_params=2000")
+
+ cmd_config.extend(
+ [
+ self.test_file_path,
+ f"--output_dir={self.tmpdir}",
+ f"--peak_memory_upper_bound={peak_mem_upper_bound}",
+ f"--n_train={self.n_train}",
+ f"--n_val={self.n_val}",
+ ]
+ )
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd_config)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/tasksmith_behavior.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/tasksmith_behavior.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a19ad60439e0019a76b605106a0678c1e004b9b
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/tasksmith_behavior.py
@@ -0,0 +1,292 @@
+import pytest
+
+
+_SELECTION_CASES = [
+ ('fsdp', True, {'xla', 'mlu', 'musa', 'npu', 'xpu'}, '2.3.0', 'fsdp', None),
+ ('xla', False, {'xla', 'mlu', 'musa', 'npu', 'xpu'}, '2.3.0', 'xla', None),
+ ('mlu', False, {'mlu', 'musa', 'npu', 'xpu'}, '2.3.0', 'mlu', None),
+ ('musa', False, {'musa', 'npu', 'xpu'}, '2.3.0', 'musa', None),
+ ('npu', False, {'npu', 'xpu'}, '2.3.0', 'npu', None),
+ ('xpu', False, {'xpu'}, '2.3.0', 'amp', 'xpu'),
+ ('cuda-old', False, set(), '2.2.2', 'legacy', None),
+ ('cuda-boundary', False, set(), '2.3.0', 'amp', 'cuda'),
+ ('cuda-current', False, set(), '2.11.0', 'amp', 'cuda'),
+ ('xla-tpu', False, {'tpu'}, '2.3.0', 'amp', 'cuda'),
+]
+
+
+@pytest.mark.parametrize('case', _SELECTION_CASES, ids=[case[0] for case in _SELECTION_CASES])
+def test_get_grad_scaler_selection(case, monkeypatch):
+ import operator
+ import sys
+ from types import ModuleType, SimpleNamespace
+ from unittest.mock import Mock
+
+ import torch
+ from packaging.version import parse
+ from torch.distributed.fsdp import sharded_grad_scaler
+
+ import accelerate.utils as utils
+ import accelerate.utils.imports as availability
+ import accelerate.utils.modeling as modeling
+ import accelerate.utils.versions as versions
+ from accelerate.utils import DistributedType
+
+ _, fsdp, available, torch_version, selected, device = case
+ constructors = {name: Mock(name=name, return_value=object()) for name in
+ ('fsdp', 'xla', 'mlu', 'musa', 'npu', 'amp', 'legacy')}
+ monkeypatch.setattr(sharded_grad_scaler, 'ShardedGradScaler', constructors['fsdp'])
+ monkeypatch.setattr(torch.amp, 'GradScaler', constructors['amp'])
+ monkeypatch.setattr(torch.cuda.amp, 'GradScaler', constructors['legacy'])
+ for backend in ('mlu', 'musa', 'npu'):
+ monkeypatch.setattr(torch, backend,
+ SimpleNamespace(amp=SimpleNamespace(GradScaler=constructors[backend])),
+ raising=False)
+
+ # Only the optional AMP import is doubled; no XLA runtime is needed.
+ xla = ModuleType('torch_xla')
+ xla.__path__ = []
+ xamp = ModuleType('torch_xla.amp')
+ xamp.GradScaler = constructors['xla']
+ xla.amp = xamp
+ monkeypatch.setitem(sys.modules, 'torch_xla', xla)
+ monkeypatch.setitem(sys.modules, 'torch_xla.amp', xamp)
+ if hasattr(modeling, 'xamp'):
+ monkeypatch.setattr(modeling, 'xamp', xamp)
+
+ def xla_available(check_is_tpu=False, check_is_gpu=False):
+ if check_is_gpu:
+ return 'xla' in available
+ if check_is_tpu:
+ return 'tpu' in available
+ return bool({'xla', 'tpu'} & available)
+
+ predicates = {'is_torch_xla_available': xla_available}
+ for backend in ('mlu', 'musa', 'npu', 'xpu'):
+ predicates['is_' + backend + '_available'] = (
+ lambda *args, _backend=backend, **kwargs: _backend in available
+ )
+ # Patch both the source predicates and the normal imported aliases.
+ for module in (availability, utils, modeling):
+ for name, predicate in predicates.items():
+ monkeypatch.setattr(module, name, predicate, raising=False)
+
+ comparisons = {'>=': operator.ge, '>': operator.gt, '<=': operator.le,
+ '<': operator.lt, '==': operator.eq, '!=': operator.ne}
+
+ def is_torch_version(operation, requirement):
+ return comparisons[operation](parse(torch_version), parse(requirement))
+
+ # Simulated versions must agree across public version-query routes.
+ # Other installed-package metadata remains untouched.
+ import importlib.metadata
+
+ installed_version = importlib.metadata.version
+
+ def version_for_distribution(distribution_name):
+ if distribution_name.lower().replace('_', '-').replace('.', '-') == 'torch':
+ return torch_version
+ return installed_version(distribution_name)
+
+ monkeypatch.setattr(importlib.metadata, 'version', version_for_distribution)
+ monkeypatch.setattr(torch, '__version__', torch_version)
+ monkeypatch.setattr(versions, 'torch_version', parse(torch_version), raising=False)
+ for module in (versions, availability, utils, modeling):
+ monkeypatch.setattr(module, 'is_torch_version', is_torch_version, raising=False)
+
+ distributed_type = DistributedType.FSDP if fsdp else None
+ settings = dict(init_scale=1024.0, growth_factor=3.0, backoff_factor=0.25,
+ growth_interval=17, enabled=False)
+ # Exercise the actual exported entrypoint, including defaults and every
+ # documented constructor keyword. Expectations are independent of its code.
+ for kwargs in ({}, settings):
+ for constructor in constructors.values():
+ constructor.reset_mock()
+ result = utils.get_grad_scaler(distributed_type, **kwargs)
+ assert result is constructors[selected].return_value
+ if device is None:
+ constructors[selected].assert_called_once_with(**kwargs)
+ else:
+ constructors[selected].assert_called_once_with(device, **kwargs)
+ for name, constructor in constructors.items():
+ if name != selected:
+ constructor.assert_not_called()
+
+
+@pytest.mark.parametrize('precision', ['fp16', 'fp8'])
+def test_accelerator_shared_scaler_policy(precision, monkeypatch):
+ import sys
+ from unittest.mock import Mock
+
+ import torch
+ import accelerate.accelerator as accelerator_module
+ import accelerate.utils.modeling as modeling
+ from accelerate import Accelerator, GradScalerKwargs
+ from accelerate.state import AcceleratorState, GradientState
+ from accelerate.utils import DistributedType, KwargsHandler, clear_environment
+
+ # Real CUDA initialization and real Accelerator.__init__; only optional
+ # MS-AMP capability validation is bypassed, not scaler creation.
+ assert torch.cuda.is_available()
+ helper = modeling.get_grad_scaler
+ constructor_paths = []
+
+ def capture_constructor_path(*args, **kwargs):
+ # Capture only ancestors of actual scaler construction, not unrelated
+ # availability/version helpers called by both entrypoints. A public
+ # wrapper and Accelerator may delegate to the same private selector.
+ path = set()
+ frame = sys._getframe(1)
+ try:
+ while frame is not None:
+ module_name = frame.f_globals.get('__name__', '')
+ if module_name.startswith('accelerate.'):
+ path.add(frame.f_code)
+ frame = frame.f_back
+ finally:
+ del frame
+ constructor_paths.append(path)
+ return constructor.return_value
+
+ constructor = Mock(name='cuda_grad_scaler', return_value=object(),
+ side_effect=capture_constructor_path)
+ settings = dict(init_scale=1024.0, growth_factor=3.0, backoff_factor=0.25,
+ growth_interval=17, enabled=False)
+ monkeypatch.setattr(torch.amp, 'GradScaler', constructor)
+
+ class MSAMPRecipe(KwargsHandler):
+ backend = 'MSAMP'
+ opt_level = 'O2'
+
+ real_state = AcceleratorState
+
+ def fp8_state(**kwargs):
+ # Initialize the ordinary single-GPU state, then emulate a validated
+ # MS-AMP FP8 environment without installing or executing MS-AMP.
+ kwargs['mixed_precision'] = 'no'
+ state = real_state(**kwargs)
+ state._mixed_precision = 'fp8'
+ return state
+
+ if precision == 'fp8':
+ monkeypatch.setattr(accelerator_module, 'AcceleratorState', fp8_state)
+ monkeypatch.setattr(accelerator_module, 'FP8RecipeKwargs', MSAMPRecipe)
+
+ with clear_environment():
+ AcceleratorState._reset_state(reset_partial_state=True)
+ GradientState._reset_state()
+ try:
+ expected_kwargs = settings if precision == 'fp16' else {}
+ # Execute the public policy independently in the same single-GPU
+ # distribution, and verify its observable constructor contract.
+ public_scaler = helper(DistributedType.NO, **expected_kwargs)
+ assert public_scaler is constructor.return_value
+ constructor.assert_called_once_with('cuda', **expected_kwargs)
+ assert len(constructor_paths) == 1
+ public_path = constructor_paths.pop()
+ constructor.reset_mock()
+
+ accelerator = Accelerator(
+ mixed_precision=precision,
+ kwargs_handlers=[GradScalerKwargs(**settings)] if precision == 'fp16' else None,
+ )
+ assert accelerator.mixed_precision == precision
+ assert accelerator.distributed_type == DistributedType.NO
+ assert accelerator.scaler is constructor.return_value
+ constructor.assert_called_once_with('cuda', **expected_kwargs)
+ assert len(constructor_paths) == 1
+ assert public_path & constructor_paths[0], (
+ 'Accelerator and the public utility must share an implementation '
+ 'on the actual scaler-construction path'
+ )
+ finally:
+ AcceleratorState._reset_state(reset_partial_state=True)
+ GradientState._reset_state()
+
+
+def test_get_grad_scaler_importable():
+ from accelerate.utils import get_grad_scaler
+ assert callable(get_grad_scaler)
+
+
+def test_get_grad_scaler_returns_scaler_on_cuda():
+ import torch
+ if not torch.cuda.is_available():
+ pytest.skip("CUDA not available")
+ from accelerate.utils import get_grad_scaler
+ scaler = get_grad_scaler()
+ assert hasattr(scaler, "scale"), "GradScaler missing .scale method"
+ assert hasattr(scaler, "step"), "GradScaler missing .step method"
+ assert hasattr(scaler, "_init_scale"), "GradScaler missing ._init_scale attribute"
+ assert hasattr(scaler, "_growth_factor"), "GradScaler missing ._growth_factor attribute"
+
+
+def test_get_grad_scaler_kwargs_forwarded():
+ import torch
+ if not torch.cuda.is_available():
+ pytest.skip("CUDA not available")
+ from accelerate.utils import get_grad_scaler
+ scaler = get_grad_scaler(init_scale=512, growth_factor=3.0, backoff_factor=0.25)
+ assert scaler._init_scale == 512.0
+ assert scaler._growth_factor == 3.0
+ assert scaler._backoff_factor == 0.25
+
+
+def test_kwargs_handler_adjacent_unaffected():
+ """KwargsHandler.to_kwargs() behavior is unchanged by this refactor."""
+ from dataclasses import dataclass
+ from accelerate.utils import KwargsHandler
+
+ @dataclass
+ class SampleHandler(KwargsHandler):
+ x: int = 0
+ flag: bool = False
+
+ assert SampleHandler().to_kwargs() == {}
+ assert SampleHandler(x=7).to_kwargs() == {"x": 7}
+ assert SampleHandler(x=7, flag=True).to_kwargs() == {"x": 7, "flag": True}
+
+
+def test_accelerator_actual_fsdp_scaler_dispatch(tmp_path):
+ import os
+ import subprocess
+ import sys
+ code = """
+import sys
+from datetime import timedelta
+import torch
+import torch.distributed as dist
+from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler
+from accelerate import Accelerator, FullyShardedDataParallelPlugin, GradScalerKwargs
+from accelerate.state import AcceleratorState, GradientState
+from accelerate.utils import DistributedType
+assert torch.cuda.is_available()
+torch.cuda.set_device(0)
+dist.init_process_group('nccl', init_method='file://' + sys.argv[1], rank=0, world_size=1,
+ timeout=timedelta(seconds=40))
+try:
+ settings = dict(init_scale=512.0, growth_factor=3.0, backoff_factor=0.25,
+ growth_interval=17, enabled=True)
+ accelerator = Accelerator(mixed_precision='fp16',
+ fsdp_plugin=FullyShardedDataParallelPlugin(sync_module_states=False),
+ kwargs_handlers=[GradScalerKwargs(**settings)])
+ assert accelerator.distributed_type == DistributedType.FSDP
+ assert isinstance(accelerator.scaler, ShardedGradScaler)
+ assert accelerator.scaler.get_scale() == 512.0
+ assert accelerator.scaler.get_growth_factor() == 3.0
+ assert accelerator.scaler.get_backoff_factor() == 0.25
+ assert accelerator.scaler.get_growth_interval() == 17
+ value = torch.tensor(2.0, device='cuda', requires_grad=True)
+ accelerator.scaler.scale(value.square()).backward()
+ torch.testing.assert_close(value.grad, torch.tensor(2048.0, device='cuda'))
+finally:
+ AcceleratorState._reset_state(reset_partial_state=True)
+ GradientState._reset_state()
+ dist.destroy_process_group()
+"""
+ env = dict(os.environ, RANK='0', LOCAL_RANK='0', WORLD_SIZE='1', LOCAL_WORLD_SIZE='1',
+ MASTER_ADDR='127.0.0.1', MASTER_PORT='29521',
+ OMP_NUM_THREADS='1', NCCL_SOCKET_IFNAME='lo', GLOO_SOCKET_IFNAME='lo')
+ result = subprocess.run([sys.executable, '-c', code, str(tmp_path / 'rendezvous')],
+ env=env, capture_output=True, text=True, timeout=80)
+ assert result.returncode == 0, result.stdout + result.stderr
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_accelerator.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_accelerator.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b18fe5c90964425f80277e400e0f0c6690d718a
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_accelerator.py
@@ -0,0 +1,764 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import itertools
+import json
+import os
+import pickle
+import tempfile
+import time
+from unittest.mock import patch
+
+import psutil
+import torch
+from parameterized import parameterized
+from torch.utils.data import DataLoader, TensorDataset
+
+from accelerate import DistributedType, infer_auto_device_map, init_empty_weights, load_checkpoint_and_dispatch
+from accelerate.accelerator import Accelerator
+from accelerate.data_loader import DataLoaderDispatcher, DataLoaderShard, skip_first_batches
+from accelerate.state import GradientState, PartialState
+from accelerate.test_utils import (
+ require_bnb,
+ require_multi_gpu,
+ require_non_cpu,
+ require_transformer_engine,
+ slow,
+ torch_device,
+)
+from accelerate.test_utils.testing import (
+ AccelerateTestCase,
+ require_cuda,
+ require_non_torch_xla,
+ require_torchdata_stateful_dataloader,
+)
+from accelerate.utils import FP8RecipeKwargs, is_torchdata_stateful_dataloader_available, patch_environment
+from accelerate.utils.dataclasses import DataLoaderConfiguration
+from accelerate.utils.modeling import get_state_dict_from_offload, load_checkpoint_in_model
+from accelerate.utils.random import set_seed
+
+
+if is_torchdata_stateful_dataloader_available():
+ from torchdata.stateful_dataloader import StatefulDataLoader
+
+
+class ModelWithTiedWeights(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = torch.nn.Linear(2, 4)
+ self.linear2 = torch.nn.Linear(4, 2)
+ self.linear2.weight = self.linear1.weight
+ self.linear2.bias = self.linear1.bias
+
+ def forward(self, x):
+ return self.linear2(self.linear1(x))
+
+
+def create_components(tied_weights=False):
+ model = ModelWithTiedWeights() if tied_weights else torch.nn.Linear(2, 4)
+ optimizer = torch.optim.AdamW(model.parameters(), lr=1.0)
+ scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.01, steps_per_epoch=2, epochs=1)
+ train_dl = DataLoader(TensorDataset(torch.tensor([1, 2, 3])))
+ valid_dl = DataLoader(TensorDataset(torch.tensor([4, 5, 6])))
+ return model, optimizer, scheduler, train_dl, valid_dl
+
+
+class ModelForTest(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = torch.nn.Linear(3, 4)
+ self.batchnorm = torch.nn.BatchNorm1d(4)
+ self.linear2 = torch.nn.Linear(4, 5)
+
+ def forward(self, x):
+ return self.linear2(self.batchnorm(self.linear1(x)))
+
+
+def create_dataloaders_for_test(batch_size=3, n_train_batches: int = 12, n_valid_batches: int = 2, num_workers=0):
+ "Generates a tuple of dummy DataLoaders to test with"
+
+ def get_dataset(n_batches):
+ x = torch.randn(batch_size * n_batches, 3)
+ y = torch.randn(batch_size * n_batches, 5)
+ return TensorDataset(x, y)
+
+ train_dataset = get_dataset(n_train_batches)
+ valid_dataset = get_dataset(n_valid_batches)
+ train_dataloader = DataLoader(train_dataset, batch_size=batch_size, num_workers=num_workers)
+ valid_dataloader = DataLoader(valid_dataset, batch_size=batch_size, num_workers=num_workers)
+ return (train_dataloader, valid_dataloader)
+
+
+def get_signature(model):
+ return sum(param.abs().sum().item() for param in model.parameters())
+
+
+def load_random_weights(model):
+ if isinstance(model, torch.nn.Linear):
+ state = torch.nn.Linear(*tuple(model.weight.T.shape)).state_dict()
+ elif isinstance(model, ModelWithTiedWeights):
+ state = ModelWithTiedWeights().state_dict()
+ model.load_state_dict(state)
+
+
+def parameterized_custom_name_func(func, param_num, param):
+ # customize the test name generator function as we want both params to appear in the sub-test
+ # name, as by default it shows only the first param
+ param_based_name = "use_safetensors" if param.args[0] is True else "use_pytorch"
+ if len(param.args) > 1:
+ param_based_name += "_tied_weights" if param.args[1] is True else ""
+ if len(param.args) > 2:
+ param_based_name += f"_num_workers_{param.args[2]}"
+ if len(param.args) > 3:
+ param_based_name += "_dispatch_batches" if param.args[3] is True else "_no_dispatch_batches"
+ return f"{func.__name__}_{param_based_name}"
+
+
+class AcceleratorTester(AccelerateTestCase):
+ def test_partial_state_after_reset(self):
+ # Verifies that custom getattr errors will be thrown
+ # if the state is reset, but only if trying to
+ # get expected attributes
+ state = PartialState()
+ assert state.num_processes > 0
+
+ with self.assertRaises(AttributeError) as cm:
+ state.someotherthing
+ assert "'PartialState' object has no attribute" in str(cm.exception)
+ assert "This happens if `PartialState._reset_state()`" not in str(cm.exception)
+
+ with self.assertRaises(AttributeError) as cm:
+ state._reset_state()
+ state.num_processes
+ assert "`PartialState` object has no attribute" in str(cm.exception)
+ assert "This happens if `PartialState._reset_state()`" in str(cm.exception)
+
+ state.someotherthing = "MyValue"
+ assert state.someotherthing == "MyValue"
+
+ def test_accelerator_state_after_reset(self):
+ # Verifies that custom getattr errors will be thrown
+ # if the state is reset, but only if trying to
+ # get expected attributes
+ accelerator = Accelerator()
+ assert accelerator.num_processes > 0
+
+ with self.assertRaises(AttributeError) as cm:
+ accelerator.state.someotherthing
+ assert "'AcceleratorState' object has no attribute" in str(cm.exception)
+ assert "This happens if `AcceleratorState._reset_state()`" not in str(cm.exception)
+
+ with self.assertRaises(AttributeError) as cm:
+ accelerator.state._reset_state()
+ accelerator.num_processes
+ assert "`AcceleratorState` object has no attribute" in str(cm.exception)
+ assert "This happens if `AcceleratorState._reset_state()`" in str(cm.exception)
+
+ accelerator.state.someotherthing = "MyValue"
+ assert accelerator.state.someotherthing == "MyValue"
+
+ @require_non_cpu
+ def test_accelerator_can_be_reinstantiated(self):
+ _ = Accelerator()
+ assert PartialState._shared_state["_cpu"] is False
+ assert PartialState._shared_state["device"].type in ["cuda", "mps", "npu", "xpu", "xla"]
+ with self.assertRaises(ValueError):
+ _ = Accelerator(cpu=True)
+
+ @require_cuda
+ def test_setting_cpu_affinity(self):
+ with patch_environment(accelerate_cpu_affinity=1, accelerate_debug_mode=1):
+ with self.assertLogs("accelerate.utils.environment", level="INFO") as cm:
+ _ = Accelerator()
+ assert any("Assigning" in log for log in cm.output)
+ assert any("cpu cores to process" in log for log in cm.output)
+
+ def test_mutable_states(self):
+ accelerator = Accelerator()
+ state = GradientState()
+ assert state.num_steps == 1
+ accelerator.gradient_accumulation_steps = 4
+ assert state.num_steps == 4
+
+ assert state.sync_gradients is True
+ accelerator.sync_gradients = False
+ assert state.sync_gradients is False
+ GradientState._reset_state()
+
+ def test_prepared_objects_are_referenced(self):
+ accelerator = Accelerator()
+ model, optimizer, scheduler, train_dl, valid_dl = create_components()
+
+ (
+ prepared_model,
+ prepared_optimizer,
+ prepared_scheduler,
+ prepared_train_dl,
+ prepared_valid_dl,
+ ) = accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl)
+
+ assert prepared_model in accelerator._models
+ assert prepared_optimizer in accelerator._optimizers
+ assert prepared_scheduler in accelerator._schedulers
+ assert prepared_train_dl in accelerator._dataloaders
+ assert prepared_valid_dl in accelerator._dataloaders
+
+ def test_free_memory_dereferences_prepared_components(self):
+ accelerator = Accelerator()
+ # Free up refs with empty_cache() and gc.collect()
+ accelerator.free_memory()
+ model, optimizer, scheduler, train_dl, valid_dl = create_components()
+ free_cpu_ram_before = psutil.virtual_memory().available // 1024 // 1024
+ model, optimizer, scheduler, train_dl, valid_dl = accelerator.prepare(
+ model, optimizer, scheduler, train_dl, valid_dl
+ )
+
+ # Short sleep here makes this test more reliable
+ time.sleep(1e-3)
+
+ model, optimizer, scheduler, train_dl, valid_dl = accelerator.free_memory(
+ model, optimizer, scheduler, train_dl, valid_dl
+ )
+
+ free_cpu_ram_after = psutil.virtual_memory().available // 1024 // 1024
+
+ assert len(accelerator._models) == 0
+ assert len(accelerator._optimizers) == 0
+ assert len(accelerator._schedulers) == 0
+ assert len(accelerator._dataloaders) == 0
+ # The less-than comes *specifically* from CUDA CPU things/won't be present on CPU builds
+ assert free_cpu_ram_after <= free_cpu_ram_before
+
+ @require_non_torch_xla
+ def test_env_var_device(self):
+ """Tests that setting the torch device with ACCELERATE_TORCH_DEVICE overrides default device."""
+ PartialState._reset_state()
+
+ # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist
+ def noop(*args, **kwargs):
+ pass
+
+ with patch("torch.cuda.set_device", noop), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64"):
+ accelerator = Accelerator()
+ assert str(accelerator.state.device) == "cuda:64"
+
+ @parameterized.expand([(True, True), (True, False), (False, False)], name_func=parameterized_custom_name_func)
+ def test_save_load_model(self, use_safetensors, tied_weights):
+ accelerator = Accelerator()
+ model, optimizer, scheduler, train_dl, valid_dl = create_components(tied_weights)
+ accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl)
+
+ model_signature = get_signature(model)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ accelerator.save_state(tmpdirname, safe_serialization=use_safetensors)
+
+ # make sure random weights don't match
+ load_random_weights(model)
+ assert abs(model_signature - get_signature(model)) > 1e-3
+
+ # make sure loaded weights match
+ accelerator.load_state(tmpdirname)
+ assert abs(model_signature - get_signature(model)) < 1e-3
+
+ @parameterized.expand([True, False], name_func=parameterized_custom_name_func)
+ def test_save_model(self, use_safetensors):
+ accelerator = Accelerator()
+ model = torch.nn.Linear(10, 10)
+
+ model_signature = get_signature(model)
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ accelerator.save_model(model, tmpdirname, safe_serialization=use_safetensors)
+ # make sure loaded weights match
+ load_checkpoint_in_model(model, tmpdirname)
+ assert abs(model_signature - get_signature(model)) < 1e-3
+
+ @parameterized.expand([True, False], name_func=parameterized_custom_name_func)
+ def test_save_sharded_model(self, use_safetensors):
+ accelerator = Accelerator()
+ inputs = torch.randn(3, 3)
+ model = ModelForTest()
+ expected = model(inputs)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ # By setting it to 100, we will split the model int 3 shards
+ accelerator.save_model(model, tmpdirname, safe_serialization=use_safetensors, max_shard_size=100)
+ # make sure loaded weights match
+ load_checkpoint_in_model(model, tmpdirname)
+ output = model(inputs)
+
+ assert torch.allclose(expected, output, atol=1e-5)
+
+ @parameterized.expand([True, False], name_func=parameterized_custom_name_func)
+ def test_save_model_offload(self, use_safetensors):
+ accelerator = Accelerator()
+
+ device_map = {"linear1": "cpu", "batchnorm": "disk", "linear2": "cpu"}
+
+ inputs = torch.randn(3, 3)
+ model = ModelForTest()
+ expected = model(inputs)
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ accelerator.save_model(model, tmp_dir, safe_serialization=use_safetensors)
+ # load and save offloaded model
+ load_checkpoint_and_dispatch(model, tmp_dir, device_map=device_map, offload_folder=tmp_dir)
+ accelerator.save_model(model, tmp_dir, safe_serialization=use_safetensors)
+
+ # load weights that were saved from the offloaded model
+ load_checkpoint_and_dispatch(model, tmp_dir)
+ output = model(inputs)
+ assert torch.allclose(expected, output, atol=1e-5)
+
+ @parameterized.expand([True, False], name_func=parameterized_custom_name_func)
+ @require_non_cpu
+ def test_get_state_dict_from_offload(self, use_safetensors):
+ accelerator = Accelerator()
+
+ device_map = {"linear1": "cpu", "batchnorm": "disk", "linear2": "disk"}
+ model = ModelForTest()
+ offloaded_layer_weight = model.linear2.weight
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ accelerator.save_model(model, tmp_dir, safe_serialization=use_safetensors)
+ # load model with offloaded layers
+ load_checkpoint_and_dispatch(model, tmp_dir, device_map=device_map, offload_folder=tmp_dir)
+ cpu_onloaded_layer = get_state_dict_from_offload(
+ model.linear2, "linear2.weight", {"linear2.weight": ""}, device_to_put_offload="cpu"
+ )
+ device_onloaded_layer = get_state_dict_from_offload(
+ model.linear2, "linear2.weight", {"linear2.weight": ""}, device_to_put_offload=0
+ )
+ cpu_onloaded_layer_weight = cpu_onloaded_layer["linear2.weight"]
+ device_onloaded_layer_weight = device_onloaded_layer["linear2.weight"]
+
+ assert torch.allclose(offloaded_layer_weight, cpu_onloaded_layer_weight)
+ assert torch.allclose(
+ offloaded_layer_weight, device_onloaded_layer_weight.to("cpu")
+ ) # must be on the same device for torch.allclose()
+ assert cpu_onloaded_layer_weight.device.type == "cpu"
+ assert device_onloaded_layer_weight.device.type == torch_device
+
+ @parameterized.expand([True, False], name_func=parameterized_custom_name_func)
+ def test_save_load_model_with_hooks(self, use_safetensors):
+ accelerator = Accelerator()
+ model, optimizer, scheduler, train_dl, valid_dl = create_components()
+ accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl)
+
+ model_signature = get_signature(model)
+
+ # saving hook
+ def save_config(models, weights, output_dir):
+ config = {"class_name": models[0].__class__.__name__}
+
+ with open(os.path.join(output_dir, "data.json"), "w") as f:
+ json.dump(config, f)
+
+ # loading hook
+ def load_config(models, input_dir):
+ with open(os.path.join(input_dir, "data.json")) as f:
+ config = json.load(f)
+
+ models[0].class_name = config["class_name"]
+
+ save_hook = accelerator.register_save_state_pre_hook(save_config)
+ load_hook = accelerator.register_load_state_pre_hook(load_config)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ accelerator.save_state(tmpdirname, safe_serialization=use_safetensors)
+
+ # make sure random weights don't match with hooks
+ load_random_weights(model)
+ assert abs(model_signature - get_signature(model)) > 1e-3
+
+ # random class name to verify correct one is loaded
+ model.class_name = "random"
+
+ # make sure loaded weights match with hooks
+ accelerator.load_state(tmpdirname)
+ assert abs(model_signature - get_signature(model)) < 1e-3
+
+ # mode.class_name is loaded from config
+ assert model.class_name == model.__class__.__name__
+
+ # remove hooks
+ save_hook.remove()
+ load_hook.remove()
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ accelerator.save_state(tmpdirname, safe_serialization=use_safetensors)
+
+ # make sure random weights don't match with hooks removed
+ load_random_weights(model)
+ assert abs(model_signature - get_signature(model)) > 1e-3
+
+ # random class name to verify correct one is loaded
+ model.class_name = "random"
+
+ # make sure loaded weights match with hooks removed
+ accelerator.load_state(tmpdirname)
+ assert abs(model_signature - get_signature(model)) < 1e-3
+
+ # mode.class_name is NOT loaded from config
+ assert model.class_name != model.__class__.__name__
+
+ def test_accelerator_none(self):
+ """Just test that passing None to accelerator.prepare() works."""
+ accelerator = Accelerator()
+ model, optimizer, scheduler, train_dl, valid_dl = create_components()
+ dummy_obj = None
+
+ # This should work
+ model, optimizer, scheduler, train_dl, valid_dl, dummy_obj = accelerator.prepare(
+ model, optimizer, scheduler, train_dl, valid_dl, dummy_obj
+ )
+ assert dummy_obj is None
+
+ def test_is_accelerator_prepared(self):
+ """Checks that `_is_accelerator_prepared` is set properly"""
+ accelerator = Accelerator()
+ model, optimizer, scheduler, train_dl, valid_dl = create_components()
+ dummy_obj = [1, 2, 3]
+
+ # This should work
+ model, optimizer, scheduler, train_dl, valid_dl, dummy_obj = accelerator.prepare(
+ model, optimizer, scheduler, train_dl, valid_dl, dummy_obj
+ )
+ assert (
+ getattr(dummy_obj, "_is_accelerate_prepared", False) is False
+ ), "Dummy object should have `_is_accelerate_prepared` set to `True`"
+ assert (
+ getattr(model, "_is_accelerate_prepared", False) is True
+ ), "Model is missing `_is_accelerator_prepared` or is set to `False`"
+ assert (
+ getattr(optimizer, "_is_accelerate_prepared", False) is True
+ ), "Optimizer is missing `_is_accelerator_prepared` or is set to `False`"
+ assert (
+ getattr(scheduler, "_is_accelerate_prepared", False) is True
+ ), "Scheduler is missing `_is_accelerator_prepared` or is set to `False`"
+ assert (
+ getattr(train_dl, "_is_accelerate_prepared", False) is True
+ ), "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`"
+ assert (
+ getattr(valid_dl, "_is_accelerate_prepared", False) is True
+ ), "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`"
+
+ @require_cuda
+ @slow
+ @require_bnb
+ def test_accelerator_bnb(self):
+ """Tests that the accelerator can be used with the BNB library."""
+ from transformers import AutoModelForCausalLM
+
+ model = AutoModelForCausalLM.from_pretrained(
+ "EleutherAI/gpt-neo-125m",
+ load_in_8bit=True,
+ device_map={"": 0},
+ )
+ accelerator = Accelerator()
+
+ # This should work
+ model = accelerator.prepare(model)
+
+ @require_cuda
+ @slow
+ @require_bnb
+ def test_accelerator_bnb_cpu_error(self):
+ """Tests that the accelerator can be used with the BNB library. This should fail as we are trying to load a model
+ that is loaded between cpu and gpu"""
+ from transformers import AutoModelForCausalLM
+
+ accelerator = Accelerator()
+
+ with init_empty_weights():
+ model = AutoModelForCausalLM.from_pretrained(
+ "EleutherAI/gpt-neo-125m",
+ )
+ model.tie_weights()
+ device_map = infer_auto_device_map(model)
+ device_map["lm_head"] = "cpu"
+
+ model = AutoModelForCausalLM.from_pretrained(
+ "EleutherAI/gpt-neo-125m", device_map=device_map, load_in_8bit=True, llm_int8_enable_fp32_cpu_offload=True
+ )
+
+ # This should not work and get value error
+ with self.assertRaises(ValueError):
+ model = accelerator.prepare(model)
+
+ @require_non_torch_xla
+ @slow
+ @require_bnb
+ @require_multi_gpu
+ def test_accelerator_bnb_multi_device(self):
+ """Tests that the accelerator can be used with the BNB library."""
+ from transformers import AutoModelForCausalLM
+
+ if torch_device == "cuda":
+ PartialState._shared_state = {"distributed_type": DistributedType.MULTI_GPU}
+ elif torch_device == "npu":
+ PartialState._shared_state = {"distributed_type": DistributedType.MULTI_NPU}
+ else:
+ raise ValueError(f"{torch_device} is not supported in test_accelerator_bnb_multi_device.")
+
+ with init_empty_weights():
+ model = AutoModelForCausalLM.from_pretrained(
+ "EleutherAI/gpt-neo-125m",
+ )
+ model.tie_weights()
+ device_map = infer_auto_device_map(model)
+ device_map["lm_head"] = 1
+
+ model = AutoModelForCausalLM.from_pretrained(
+ "EleutherAI/gpt-neo-125m",
+ load_in_8bit=True,
+ device_map=device_map,
+ )
+ accelerator = Accelerator()
+
+ # This should not work and get value error
+ with self.assertRaises(ValueError):
+ _ = accelerator.prepare(model)
+
+ PartialState._reset_state()
+
+ @require_non_torch_xla
+ @slow
+ @require_bnb
+ @require_multi_gpu
+ def test_accelerator_bnb_multi_device_no_distributed(self):
+ """Tests that the accelerator can be used with the BNB library."""
+ from transformers import AutoModelForCausalLM
+
+ with init_empty_weights():
+ model = AutoModelForCausalLM.from_pretrained(
+ "EleutherAI/gpt-neo-125m",
+ )
+ device_map = infer_auto_device_map(model)
+ device_map["lm_head"] = 1
+
+ model = AutoModelForCausalLM.from_pretrained(
+ "EleutherAI/gpt-neo-125m",
+ load_in_8bit=True,
+ device_map=device_map,
+ )
+ accelerator = Accelerator()
+
+ # This should work
+ _ = accelerator.prepare(model)
+
+ @require_non_cpu
+ def test_accelerator_cpu_flag_prepare(self):
+ model = torch.nn.Linear(10, 10)
+ sgd = torch.optim.SGD(model.parameters(), lr=0.01)
+ accelerator = Accelerator(cpu=True)
+ _ = accelerator.prepare(sgd)
+
+ @require_transformer_engine
+ def test_can_unwrap_model_te(self):
+ model, optimizer, *_ = create_components()
+ fp8_recipe = FP8RecipeKwargs(backend="TE")
+ accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[fp8_recipe])
+ inputs = torch.randn(10, 2).to(torch_device)
+ model, optimizer = accelerator.prepare(model, optimizer)
+ model(inputs) # sanity check that this works
+
+ model = accelerator.unwrap_model(model, keep_fp32_wrapper=False)
+ model(inputs) # check that this still works
+
+ # check that pickle roundtrip works
+ model_loaded = pickle.loads(pickle.dumps(model))
+ model_loaded(inputs)
+
+ @require_non_cpu
+ def test_can_unwrap_model_fp16(self):
+ # test for a regression introduced in #872
+ # before the fix, after unwrapping with keep_fp32_wrapper=False, there would be the following error:
+ # Linear.forward() missing 1 required positional argument: 'input'
+ model = create_components()[0]
+ accelerator = Accelerator(mixed_precision="fp16")
+ inputs = torch.randn(10, 2).to(torch_device)
+ model = accelerator.prepare(model)
+ model(inputs) # sanity check that this works
+
+ model = accelerator.unwrap_model(model, keep_fp32_wrapper=False)
+ model(inputs) # check that this still works
+
+ # check that pickle roundtrip works
+ model_loaded = pickle.loads(pickle.dumps(model))
+ model_loaded(inputs)
+
+ def test_can_unwrap_model(self):
+ model = create_components()[0]
+ accelerator = Accelerator(mixed_precision="no", cpu=True)
+ inputs = torch.randn(10, 2)
+ model = accelerator.prepare(model)
+ model(inputs) # sanity check that this works
+
+ model = accelerator.unwrap_model(model, keep_fp32_wrapper=False)
+ model(inputs) # check that this still works
+
+ # check that pickle roundtrip works
+ model_loaded = pickle.loads(pickle.dumps(model))
+ model_loaded(inputs)
+
+ @parameterized.expand([True, False])
+ def test_can_pickle_dataloader(self, dispatch_batches):
+ """
+ Test that pickling a prepared dataloader works.
+ """
+ data = torch.arange(10).to(torch_device)
+ ds = torch.utils.data.TensorDataset(data)
+ dl = torch.utils.data.DataLoader(ds)
+ skip_dl = skip_first_batches(dl, 2)
+
+ # Currently, StatefulDataLoader doesn't seem to support pickling, so we aren't testing that functionality
+ # TODO: Add support for pickling StatefulDataLoader
+ dataloader_config = DataLoaderConfiguration(dispatch_batches=dispatch_batches, use_stateful_dataloader=False)
+ accelerator = Accelerator(dataloader_config=dataloader_config)
+
+ original_dl, _ = accelerator.prepare(dl, skip_dl)
+ if dispatch_batches:
+ assert isinstance(original_dl, DataLoaderDispatcher)
+ else:
+ assert isinstance(original_dl, DataLoaderShard)
+
+ prepared_model_dumps = pickle.dumps(accelerator)
+
+ model_loaded = pickle.loads(prepared_model_dumps)
+ assert len(model_loaded._dataloaders) == 2
+
+ # Assert equality of recovered and original dataloader
+ loaded_dl = model_loaded._dataloaders[0]
+ assert isinstance(loaded_dl, DataLoader)
+ if dispatch_batches:
+ assert isinstance(loaded_dl, DataLoaderDispatcher)
+ else:
+ assert isinstance(loaded_dl, DataLoaderShard)
+ assert len(loaded_dl) == len(original_dl)
+ assert [i for i in loaded_dl] == [i for i in original_dl]
+
+ # Test skip dataloader works as expected as well
+ loaded_skip_dl = model_loaded._dataloaders[1]
+ assert isinstance(loaded_skip_dl, DataLoader)
+ if dispatch_batches:
+ assert isinstance(loaded_dl, DataLoaderDispatcher)
+ else:
+ assert isinstance(loaded_dl, DataLoaderShard)
+ assert len(loaded_skip_dl) == len(original_dl) - 2
+ assert [i for i in loaded_skip_dl] == [i for i in original_dl][2:]
+
+ # Ideally would be a parameterized test which works with either stateful or non-stateful dataloaders, but dependencies are a bit awkward.
+ @require_torchdata_stateful_dataloader
+ def test_prepared_objects_are_referenced_with_stateful_dataloader(self):
+ """Test that setting `use_stateful_dataloader=True` in `DataLoaderConfiguration` prepares a `StatefulDataLoader` object instead of a `DataLoader` object."""
+ dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=True)
+ accelerator = Accelerator(dataloader_config=dataloader_config)
+ model, optimizer, scheduler, train_dl, valid_dl = create_components()
+
+ (
+ prepared_model,
+ prepared_optimizer,
+ prepared_scheduler,
+ prepared_train_dl,
+ prepared_valid_dl,
+ ) = accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl)
+
+ assert prepared_model in accelerator._models
+ assert prepared_optimizer in accelerator._optimizers
+ assert prepared_scheduler in accelerator._schedulers
+ assert prepared_train_dl in accelerator._dataloaders
+ assert prepared_valid_dl in accelerator._dataloaders
+ assert isinstance(prepared_train_dl, StatefulDataLoader)
+ assert isinstance(prepared_valid_dl, StatefulDataLoader)
+
+ @parameterized.expand(
+ itertools.product([True, False], [True, False], [0, 2], [True, False]),
+ name_func=parameterized_custom_name_func,
+ )
+ @require_torchdata_stateful_dataloader
+ def test_save_model_with_stateful_dataloader(self, use_safetensors, tied_weights, num_workers, dispatch_batches):
+ """
+ Test that saving and loading a model with a stateful dataloader returns the same model,
+ and that the dataloader's iterator is restored properly."""
+ set_seed(42)
+ n_train_batches = 64 # Use enough batches to ensure we can get partial iterations on large compute
+ dataloader_config = DataLoaderConfiguration(dispatch_batches=dispatch_batches, use_stateful_dataloader=True)
+ accelerator = Accelerator(dataloader_config=dataloader_config)
+
+ model, optimizer, scheduler, train_dl, valid_dl = create_components(tied_weights)
+ train_dl, valid_dl = create_dataloaders_for_test(n_train_batches=n_train_batches, num_workers=num_workers)
+ model = ModelForTest()
+
+ (
+ prepared_model,
+ prepared_optimizer,
+ prepared_scheduler,
+ prepared_train_dl,
+ prepared_valid_dl,
+ ) = accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl)
+
+ assert isinstance(prepared_train_dl, StatefulDataLoader)
+ assert isinstance(prepared_valid_dl, StatefulDataLoader)
+
+ # Perform 3 training iterations to ensure the dataloader's iterator is advanced
+ num_batches_to_skip = 3
+ model.train()
+ untrained_batches = []
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ for step, batch in enumerate(prepared_train_dl):
+ x, y = batch
+ outputs = prepared_model(x)
+ loss = torch.nn.functional.mse_loss(outputs, y)
+ accelerator.backward(loss)
+ prepared_optimizer.step()
+ prepared_scheduler.step()
+ prepared_optimizer.zero_grad()
+ if step == num_batches_to_skip - 1:
+ # Save the state once we've gone through a few batches
+ accelerator.save_state(f"{tmpdirname}/state", safe_serialization=use_safetensors)
+ if step >= num_batches_to_skip:
+ untrained_batches.append(batch)
+
+ not_skipped_batches = accelerator.gather(untrained_batches)
+ # We then unwrap the trained model
+ unwrapped_model = accelerator.unwrap_model(prepared_model)
+
+ original_linear1 = unwrapped_model.linear1.weight.clone()
+ original_batchnorm = unwrapped_model.batchnorm.weight.clone()
+ original_linear2 = unwrapped_model.linear2.weight.clone()
+
+ # Resume the state
+ accelerator.load_state(f"{tmpdirname}/state")
+
+ # Train this to the end of the DataLoader
+ batches_seen_with_loaded_dl = 0
+ for batch in prepared_train_dl:
+ x, y = batch
+ outputs = prepared_model(x)
+ loss = torch.nn.functional.mse_loss(outputs, y)
+ accelerator.backward(loss)
+ prepared_optimizer.step()
+ prepared_scheduler.step()
+ prepared_optimizer.zero_grad()
+ batches_seen_with_loaded_dl += 1
+
+ unwrapped_model_2 = accelerator.unwrap_model(prepared_model)
+
+ new_linear1 = unwrapped_model_2.linear1.weight
+ new_batchnorm = unwrapped_model_2.batchnorm.weight
+ new_linear2 = unwrapped_model_2.linear2.weight
+
+ # Assert equalities
+ assert batches_seen_with_loaded_dl == len(not_skipped_batches)
+ assert torch.allclose(original_linear1, new_linear1)
+ assert torch.allclose(original_batchnorm, new_batchnorm)
+ assert torch.allclose(original_linear2, new_linear2)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_big_modeling.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_big_modeling.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a2ef54884fea972e493025019766549f8d86cc1
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_big_modeling.py
@@ -0,0 +1,1050 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import copy
+import gc
+import logging
+import os
+import unittest
+from collections import OrderedDict
+from tempfile import TemporaryDirectory
+
+import torch
+import torch.nn as nn
+from transformers import AutoModelForCausalLM, AutoTokenizer
+
+from accelerate.big_modeling import (
+ cpu_offload,
+ cpu_offload_with_hook,
+ disk_offload,
+ dispatch_model,
+ init_empty_weights,
+ init_on_device,
+ load_checkpoint_and_dispatch,
+)
+from accelerate.hooks import remove_hook_from_submodules
+from accelerate.test_utils import (
+ require_bnb,
+ require_cuda,
+ require_multi_device,
+ require_multi_gpu,
+ require_non_cpu,
+ require_non_torch_xla,
+ slow,
+ torch_device,
+)
+from accelerate.utils import is_torch_version, offload_state_dict
+
+
+logger = logging.getLogger(__name__)
+torch_device = f"{torch_device}:0" if torch_device != "cpu" else "cpu"
+
+
+class ModelForTest(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = nn.Linear(3, 4)
+ self.batchnorm = nn.BatchNorm1d(4)
+ self.linear2 = nn.Linear(4, 5)
+
+ def forward(self, x):
+ return self.linear2(self.batchnorm(self.linear1(x)))
+
+
+class LinearWithNonPersistentBuffers(nn.Module):
+ def __init__(self, in_features: int, out_features: int, bias: bool = True, device=None, dtype=None) -> None:
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+ self.register_buffer("weight", torch.ones((out_features, in_features), **factory_kwargs))
+ if bias:
+ self.register_buffer("bias", torch.ones(out_features, **factory_kwargs), persistent=False)
+ else:
+ self.register_buffer("bias", None)
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ return torch.nn.functional.linear(input, self.weight, self.bias)
+
+
+class ModelForTestNonPersistentBuffers(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = LinearWithNonPersistentBuffers(3, 4)
+ self.batchnorm = nn.BatchNorm1d(4)
+ self.linear2 = LinearWithNonPersistentBuffers(4, 5)
+
+ def forward(self, x):
+ return self.linear2(self.batchnorm(self.linear1(x)))
+
+
+class ModelForTestCopy(nn.Module):
+ def __init__(self, id: int):
+ super().__init__()
+ self.id = id
+ self.linear1 = nn.Linear(3, 4)
+ self.batchnorm = nn.BatchNorm1d(4)
+ self.linear2 = nn.Linear(4, 5)
+
+ def forward(self, x):
+ return self.linear2(self.batchnorm(self.linear1(x))), self.id
+
+
+class ModelForTestTiedWeights(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = nn.Linear(4, 4)
+ self.batchnorm = nn.BatchNorm1d(4)
+ self.linear2 = nn.Linear(4, 4)
+
+ def forward(self, x):
+ return self.linear2(self.batchnorm(self.linear1(x)))
+
+
+class BiggerModelForTest(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = nn.Linear(3, 4)
+ self.linear2 = nn.Linear(4, 5)
+ self.batchnorm = nn.BatchNorm1d(5)
+ self.linear3 = nn.Linear(5, 6)
+ self.linear4 = nn.Linear(6, 5)
+
+ def forward(self, x):
+ return self.linear4(self.linear3(self.batchnorm(self.linear2(self.linear1(x)))))
+
+
+# To test preload_module_classes
+class ModuleWithUnusedSubModules(nn.Module):
+ def __init__(self, input_dim, output_dim):
+ super().__init__()
+ self.linear = nn.Linear(input_dim, output_dim)
+
+ def forward(self, x):
+ return x @ self.linear.weight.t() + self.linear.bias
+
+
+class ModelWithUnusedSubModulesForTest(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = ModuleWithUnusedSubModules(3, 4)
+ self.linear2 = ModuleWithUnusedSubModules(4, 5)
+ self.batchnorm = nn.BatchNorm1d(5)
+ self.linear3 = ModuleWithUnusedSubModules(5, 6)
+ self.linear4 = ModuleWithUnusedSubModules(6, 5)
+
+ def forward(self, x):
+ return self.linear4(self.linear3(self.batchnorm(self.linear2(self.linear1(x)))))
+
+
+class BigModelingTester(unittest.TestCase):
+ def test_init_empty_weights(self):
+ # base use
+ with init_empty_weights():
+ module = nn.Linear(4, 5)
+ assert module.weight.device == torch.device("meta")
+
+ # base use with buffers, they are not touched
+ with init_empty_weights():
+ module = nn.BatchNorm1d(4)
+ assert module.weight.device == torch.device("meta")
+ assert module.running_mean.device == torch.device("cpu")
+
+ # Use with include_buffers=True
+ register_parameter_func = nn.Module.register_parameter
+ register_buffer_func = nn.Module.register_buffer
+ with init_empty_weights(include_buffers=True):
+ module = nn.BatchNorm1d(4)
+ # nn.Module.register_parameter/buffer shouldn't be changed with torch >= 2.0
+ if is_torch_version(">=", "2.0"):
+ assert register_parameter_func == nn.Module.register_parameter
+ assert register_buffer_func == nn.Module.register_buffer
+ assert module.weight.device == torch.device("meta")
+ assert module.running_mean.device == torch.device("meta")
+
+ # Double check we didn't break PyTorch
+ module = nn.BatchNorm1d(4)
+ assert module.weight.device == torch.device("cpu")
+ assert module.running_mean.device == torch.device("cpu")
+
+ def test_init_empty_weights_very_large_model(self):
+ # This is a 100 billion parameters model.
+ with init_empty_weights():
+ _ = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
+
+ @require_non_cpu
+ def test_init_on_device(self):
+ device = torch.device(torch_device)
+ with init_on_device(device):
+ model = nn.Linear(10, 10)
+ assert model.weight.device == device
+ assert model.weight.device == device
+
+ def test_cpu_offload(self):
+ model = ModelForTest()
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ device = torch.device(torch_device)
+
+ cpu_offload(model, execution_device=device)
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), 1e-4, 1e-5), f"Expected: {expected}, Actual: {output.cpu()}"
+
+ # Clean up for next test.
+ remove_hook_from_submodules(model)
+
+ cpu_offload(model, execution_device=device, offload_buffers=True)
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), 1e-4, 1e-5), f"Expected: {expected}, Actual: {output.cpu()}"
+
+ def test_cpu_offload_with_unused_submodules(self):
+ model = ModelWithUnusedSubModulesForTest()
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ device = torch.device(torch_device)
+
+ cpu_offload(model, execution_device=device, preload_module_classes=["ModuleWithUnusedSubModules"])
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), 1e-4, 1e-5), f"Expected: {expected}, Actual: {output.cpu()}"
+
+ # Clean up for next test.
+ remove_hook_from_submodules(model)
+
+ cpu_offload(
+ model,
+ execution_device=device,
+ offload_buffers=True,
+ preload_module_classes=["ModuleWithUnusedSubModules"],
+ )
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), 1e-4, 1e-5), f"Expected: {expected}, Actual: {output.cpu()}"
+
+ @slow
+ @require_non_cpu
+ def test_cpu_offload_gpt2(self):
+ tokenizer = AutoTokenizer.from_pretrained("gpt2")
+ inputs = tokenizer("Hello world! My name is", return_tensors="pt").to(torch_device)
+
+ gpt2 = AutoModelForCausalLM.from_pretrained("gpt2")
+ cpu_offload(gpt2, execution_device=0)
+ outputs = gpt2.generate(inputs["input_ids"])
+ assert (
+ tokenizer.decode(outputs[0].tolist())
+ == "Hello world! My name is Kiyoshi, and I'm a student at the University of Tokyo"
+ )
+
+ def test_disk_offload(self):
+ model = ModelForTest()
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ device = torch.device(torch_device)
+
+ with TemporaryDirectory() as tmp_dir:
+ disk_offload(model, tmp_dir, execution_device=device)
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), 1e-4, 1e-5), f"Expected: {expected}, Actual: {output.cpu()}"
+
+ # Clean up for next test.
+ remove_hook_from_submodules(model)
+
+ with TemporaryDirectory() as tmp_dir:
+ disk_offload(model, tmp_dir, execution_device=device, offload_buffers=True)
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), 1e-4, 1e-5), f"Expected: {expected}, Actual: {output.cpu()}"
+
+ def test_disk_offload_with_unused_submodules(self):
+ model = ModelWithUnusedSubModulesForTest()
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ device = torch.device(torch_device)
+
+ with TemporaryDirectory() as tmp_dir:
+ disk_offload(
+ model, tmp_dir, execution_device=device, preload_module_classes=["ModuleWithUnusedSubModules"]
+ )
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), 1e-4, 1e-5), f"Expected: {expected}, Actual: {output.cpu()}"
+
+ # Clean up for next test.
+ remove_hook_from_submodules(model)
+
+ with TemporaryDirectory() as tmp_dir:
+ disk_offload(
+ model,
+ tmp_dir,
+ execution_device=device,
+ offload_buffers=True,
+ preload_module_classes=["ModuleWithUnusedSubModules"],
+ )
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), 1e-4, 1e-5), f"Expected: {expected}, Actual: {output.cpu()}"
+
+ @slow
+ @require_non_cpu
+ def test_disk_offload_gpt2(self):
+ tokenizer = AutoTokenizer.from_pretrained("gpt2")
+ inputs = tokenizer("Hello world! My name is", return_tensors="pt").to(torch_device)
+
+ gpt2 = AutoModelForCausalLM.from_pretrained("gpt2")
+ with TemporaryDirectory() as tmp_dir:
+ disk_offload(gpt2, tmp_dir, execution_device=0)
+ outputs = gpt2.generate(inputs["input_ids"])
+ assert (
+ tokenizer.decode(outputs[0].tolist())
+ == "Hello world! My name is Kiyoshi, and I'm a student at the University of Tokyo"
+ )
+
+ @require_non_cpu
+ def test_dispatch_model_and_remove_hook(self):
+ model = ModelForTest()
+ device_map = {"linear1": "cpu", "batchnorm": "cpu", "linear2": 0}
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ with TemporaryDirectory() as tmp_dir:
+ dispatch_model(model, device_map, offload_dir=tmp_dir)
+ output = model(x)
+ remove_hook_from_submodules(model)
+ # need to check if we get any warning
+ with self.assertLogs(level="WARNING") as cm:
+ # We want to assert there are no warnings, but the 'assertLogs' method does not support that.
+ # Therefore, we are adding a dummy warning, and then we will assert it is the only warning.
+ model.to(torch_device)
+ logger.warning("Dummy warning")
+ self.assertEqual(len(cm.records), 1)
+ self.assertIn(
+ "Dummy warning",
+ cm.records[0].message,
+ )
+ output_bis = model(x.to(torch_device))
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+ assert torch.allclose(expected, output_bis.cpu(), atol=1e-5)
+
+ @require_non_cpu
+ def test_dispatch_model(self):
+ model = ModelForTest()
+ device_map = {"linear1": "disk", "batchnorm": "cpu", "linear2": 0}
+
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ with TemporaryDirectory() as tmp_dir:
+ dispatch_model(model, device_map, offload_dir=tmp_dir)
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_non_cpu
+ def test_dispatch_model_with_non_persistent_buffers(self):
+ model = ModelForTestNonPersistentBuffers()
+ device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": "disk"}
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ with TemporaryDirectory() as tmp_dir:
+ dispatch_model(model, device_map, offload_dir=tmp_dir, offload_buffers=True)
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_non_cpu
+ def test_dispatch_model_tied_weights(self):
+ model = ModelForTestTiedWeights()
+ model.linear1.weight = model.linear2.weight
+ device_map = {"linear1": 0, "batchnorm": 0, "linear2": 0}
+
+ dispatch_model(model, device_map)
+ assert model.linear2.weight is model.linear1.weight
+
+ @require_multi_gpu
+ def test_dispatch_model_tied_weights_memory(self):
+ # Test that we do not duplicate tied weights at any point during dispatch_model call.
+
+ torch.cuda.empty_cache() # Needed in case we run several tests in a row.
+
+ model = nn.Sequential(
+ OrderedDict(
+ [
+ ("linear0", nn.Linear(5000, 5000, bias=False)),
+ ("linear1", nn.Linear(5000, 5000, bias=False)),
+ ("linear2", nn.Linear(5000, 5000, bias=False)),
+ ("linear3", nn.Linear(5000, 5000, bias=False)),
+ ("linear4", nn.Linear(5000, 5000, bias=False)),
+ ]
+ )
+ )
+ model.linear2.weight = model.linear0.weight
+ model.linear3.weight = model.linear0.weight
+ model.linear4.weight = model.linear0.weight
+
+ x = torch.randn(5, 5000)
+ with torch.no_grad():
+ expected = model(x)
+
+ # We should need only 5000 * 5000 * 32 // 8 * 1e-6 = 100 MB on the device 0 for the four linear weights.
+ device_map = {"linear0": 0, "linear1": 1, "linear2": 0, "linear3": 0, "linear4": 0}
+
+ # Just to intialize CUDA context.
+ a = torch.rand(5).to("cuda:0") # noqa: F841
+
+ free_memory_bytes = torch.cuda.mem_get_info("cuda:0")[0]
+ required_memory_bytes = 5000 * 5000 * (32 // 8)
+
+ # Leaving 50 MB of free memory for possible buffers, etc.
+ n_vals = (free_memory_bytes - required_memory_bytes - int(50e6)) // (32 // 8)
+ foo = torch.rand(n_vals, device="cuda:0") # noqa: F841
+
+ # If this does OOM: there is an issue in somewhere in dispatch_model, memory of tied weights is duplicated.
+ try:
+ dispatch_model(model, device_map)
+ except torch.cuda.OutOfMemoryError as e:
+ raise torch.cuda.OutOfMemoryError(
+ f"OOM error in dispatch_model. This is a bug and should not happen, see test_dispatch_model_tied_weights_memory. {e}"
+ )
+ except Exception as e:
+ raise e
+
+ with torch.no_grad():
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_cuda
+ def test_dispatch_model_tied_weights_memory_with_nested_offload_cpu(self):
+ # Test that we do not duplicate tied weights at any point during dispatch_model call.
+
+ torch.cuda.empty_cache() # Needed in case we run several tests in a row.
+
+ class SubModule(torch.nn.Module):
+ def __init__(self, ref_to_parameter):
+ super().__init__()
+ self.parameter = ref_to_parameter
+
+ def forward(self, x):
+ return x + torch.max(self.parameter)
+
+ class LinearModuleAndSubModule(torch.nn.Linear):
+ def __init__(self, in_features, out_features):
+ super().__init__(in_features, out_features, bias=False)
+ self.weight_submodule = SubModule(self.weight)
+ self.weight_submodule2 = SubModule(self.weight)
+ self.weight_submodule3 = SubModule(self.weight)
+ self.weight_submodule4 = SubModule(self.weight)
+
+ def forward(self, x):
+ a = torch.nn.functional.linear(self.weight_submodule(x), self.weight)
+ b = torch.nn.functional.linear(self.weight_submodule2(x), self.weight)
+ c = torch.nn.functional.linear(self.weight_submodule3(x), self.weight)
+ d = torch.nn.functional.linear(self.weight_submodule4(x), self.weight)
+ return a + b + c + d
+
+ class ModelWithSubmodules(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.compute = LinearModuleAndSubModule(5000, 5000)
+ self.compute1 = LinearModuleAndSubModule(5000, 5000)
+
+ def forward(self, x):
+ a = self.compute(x)
+ b = self.compute1(x)
+ return a + b
+
+ # We should need only 2 * 5000 * 5000 * 32 // 8 * 1e-6 = 200 MB on the device 0 for the whole model forward, and not 600 MB.
+ device_map = {"compute": 0, "compute1": "cpu"}
+
+ model = ModelWithSubmodules()
+
+ x = torch.randn(1, 5000)
+ with torch.no_grad():
+ expected = model(x)
+
+ # Just to intialize CUDA context.
+ a = torch.rand(5).to("cuda:0") # noqa: F841
+
+ free_memory_bytes = torch.cuda.mem_get_info("cuda:0")[0]
+ required_memory_bytes = 2 * 5000 * 5000 * (32 // 8) # 200 MB
+
+ # Leaving 150 MB of free memory for possible buffers, etc.
+ n_vals = (free_memory_bytes - required_memory_bytes - int(150e6)) // (32 // 8)
+ foo = torch.rand(n_vals, device="cuda:0") # noqa: F841
+
+ free_memory_bytes_before_dispatch = torch.cuda.mem_get_info("cuda:0")[0]
+ dispatch_model(model, device_map)
+ free_memory_bytes_after_dispatch = torch.cuda.mem_get_info("cuda:0")[0]
+
+ assert (free_memory_bytes_after_dispatch - free_memory_bytes_before_dispatch) * 1e-6 < 130
+
+ original_pointer = model.compute1._hf_hook.weights_map["weight"].data_ptr()
+
+ with torch.no_grad():
+ try:
+ output = model(x)
+ except torch.cuda.OutOfMemoryError as e:
+ raise torch.cuda.OutOfMemoryError(
+ f"OOM error in dispatch_model. This is a bug and should not happen, see test_dispatch_model_tied_weights_memory_with_nested_offload_cpu. {e}"
+ )
+ except Exception as e:
+ raise e
+
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ torch.cuda.empty_cache()
+
+ free_memory_bytes_after_infer = torch.cuda.mem_get_info("cuda:0")[0]
+
+ # Check that we have no more references on GPU for the offloaded tied weight.
+ assert len(model.compute1.weight_submodule._hf_hook.tied_params_map[original_pointer]) == 0
+ assert len(model.compute1._hf_hook.tied_params_map[original_pointer]) == 0
+ assert (free_memory_bytes_after_infer - free_memory_bytes_after_dispatch) * 1e-6 < 130
+
+ # Test is flacky otherwise.
+ del model
+ gc.collect()
+
+ # This test fails because sometimes data_ptr() of compute2.weight is the same as compute1.weight.
+ # I checked that the values are not the same but it gives the same address. This does not happen on my local machine.
+ @require_cuda
+ @unittest.skip(
+ "Flaky test, we should have enough coverage with test_dispatch_model_tied_weights_memory_with_nested_offload_cpu test"
+ )
+ def test_dispatch_model_tied_weights_memory_with_nested_offload_disk(self):
+ # Test that we do not duplicate tied weights at any point during dispatch_model call.
+
+ torch.cuda.empty_cache() # Needed in case we run several tests in a row.
+
+ class SubModule(torch.nn.Module):
+ def __init__(self, ref_to_parameter):
+ super().__init__()
+ self.parameter = ref_to_parameter
+
+ def forward(self, x):
+ return x + torch.max(self.parameter)
+
+ class LinearModuleAndSubModule(torch.nn.Linear):
+ def __init__(self, in_features, out_features):
+ super().__init__(in_features, out_features, bias=False)
+ self.weight_submodule = SubModule(self.weight)
+ self.weight_submodule2 = SubModule(self.weight)
+ self.weight_submodule3 = SubModule(self.weight)
+ self.weight_submodule4 = SubModule(self.weight)
+
+ def forward(self, x):
+ a = torch.nn.functional.linear(self.weight_submodule(x), self.weight)
+ b = torch.nn.functional.linear(self.weight_submodule2(x), self.weight)
+ c = torch.nn.functional.linear(self.weight_submodule3(x), self.weight)
+ d = torch.nn.functional.linear(self.weight_submodule4(x), self.weight)
+ return a + b + c + d
+
+ class ModelWithSubmodules(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.compute = LinearModuleAndSubModule(5000, 5000)
+ self.compute1 = LinearModuleAndSubModule(5000, 5000)
+
+ def forward(self, x):
+ a = self.compute(x)
+ b = self.compute1(x)
+ return a + b
+
+ # We should need only 2 * 5000 * 5000 * 32 // 8 * 1e-6 = 200 MB on the device 0 for the whole model forward, and not 600 MB.
+ device_map = {"compute": 0, "compute1": "disk"}
+
+ model = ModelWithSubmodules()
+
+ x = torch.randn(1, 5000)
+ with torch.no_grad():
+ expected = model(x)
+
+ # Just to intialize CUDA context.
+ a = torch.rand(5).to("cuda:0") # noqa: F841
+
+ free_memory_bytes = torch.cuda.mem_get_info("cuda:0")[0]
+ required_memory_bytes = 2 * 5000 * 5000 * (32 // 8) # 200 MB
+
+ # Leaving 150 MB of free memory for possible buffers, etc.
+ n_vals = (free_memory_bytes - required_memory_bytes - int(200e6)) // (32 // 8)
+ foo = torch.rand(n_vals, device="cuda:0") # noqa: F841
+
+ free_memory_bytes_before_dispatch = torch.cuda.mem_get_info("cuda:0")[0]
+ with TemporaryDirectory() as tmp_dir:
+ dispatch_model(model, device_map, offload_dir=tmp_dir)
+ free_memory_bytes_after_dispatch = torch.cuda.mem_get_info("cuda:0")[0]
+
+ assert (free_memory_bytes_after_dispatch - free_memory_bytes_before_dispatch) * 1e-6 < 130
+
+ with torch.no_grad():
+ try:
+ output = model(x)
+ except torch.cuda.OutOfMemoryError as e:
+ raise torch.cuda.OutOfMemoryError(
+ f"OOM error in dispatch_model. This is a bug and should not happen, see test_dispatch_model_tied_weights_memory_with_nested_offload_disk. {e}"
+ )
+ except Exception as e:
+ raise e
+
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ torch.cuda.empty_cache()
+
+ free_memory_bytes_after_infer = torch.cuda.mem_get_info("cuda:0")[0]
+
+ # Check that we have no more references on GPU for the offloaded tied weight.
+ n_non_empty = 0
+ for pointer, pointer_dict in model.compute1.weight_submodule._hf_hook.tied_params_map.items():
+ if len(pointer_dict) > 0:
+ n_non_empty += 1
+ assert n_non_empty == 1 # `compute` layer one.
+
+ n_non_empty = 0
+ for pointer, pointer_dict in model.compute1._hf_hook.tied_params_map.items():
+ if len(pointer_dict) > 0:
+ n_non_empty += 1
+ assert n_non_empty == 1 # `compute` layer one.
+
+ assert (free_memory_bytes_after_infer - free_memory_bytes_after_dispatch) * 1e-6 < 130
+
+ @require_multi_device
+ def test_dispatch_model_multi_devices(self):
+ model = BiggerModelForTest()
+ device_map = {"linear1": "cpu", "linear2": "disk", "batchnorm": "cpu", "linear3": 0, "linear4": 1}
+
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ with TemporaryDirectory() as tmp_dir:
+ dispatch_model(model, device_map, offload_dir=tmp_dir)
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_non_cpu
+ def test_dispatch_model_copy(self):
+ original_model = ModelForTestCopy(id=1)
+ device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": 0}
+
+ x = torch.randn(2, 3)
+ expected, original_output_id = original_model(x)
+
+ dispatch_model(original_model, device_map)
+
+ copied_model = copy.deepcopy(original_model)
+ copied_model.id = 2
+ output, copied_output_id = copied_model(x)
+
+ assert original_model.id == original_output_id
+ assert copied_model.id == copied_output_id
+ assert copied_model.linear1.forward is not original_model.linear1.forward
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_non_cpu
+ def test_dispatch_model_move_offloaded_model(self):
+ model = ModelForTest()
+ device_map = {"linear1": "disk", "batchnorm": "cpu", "linear2": 0}
+ with TemporaryDirectory() as tmp_dir:
+ dispatch_model(model, device_map, offload_dir=tmp_dir)
+ with self.assertRaises(RuntimeError):
+ model.to(0)
+
+ @require_multi_device
+ def test_dispatch_model_move_model_warning(self):
+ model = ModelForTest()
+ device_map = {"linear1": 0, "batchnorm": 0, "linear2": 1}
+ with TemporaryDirectory() as tmp_dir:
+ dispatch_model(model, device_map, offload_dir=tmp_dir)
+ with self.assertLogs("accelerate.big_modeling", level="WARNING"):
+ model.to("cpu")
+ with self.assertLogs("accelerate.big_modeling", level="WARNING"):
+ model.to(torch_device)
+ with self.assertRaises(RuntimeError):
+ x = torch.randn(2, 3)
+ model(x)
+
+ @slow
+ @require_multi_device
+ def test_dispatch_model_gpt2_on_two_devices(self):
+ tokenizer = AutoTokenizer.from_pretrained("gpt2")
+ inputs = tokenizer("Hello world! My name is", return_tensors="pt").to(torch_device)
+
+ gpt2 = AutoModelForCausalLM.from_pretrained("gpt2")
+ # Dispatch on GPUs 0 and 1
+ device_map = {
+ "transformer.wte": 0,
+ "transformer.wpe": 0,
+ "transformer.ln_f": 1,
+ "lm_head": 0,
+ }
+ for i in range(12):
+ device_map[f"transformer.h.{i}"] = 0 if i <= 5 else 1
+
+ gpt2 = dispatch_model(gpt2, device_map)
+ outputs = gpt2.generate(inputs["input_ids"])
+ assert (
+ tokenizer.decode(outputs[0].tolist())
+ == "Hello world! My name is Kiyoshi, and I'm a student at the University of Tokyo"
+ )
+
+ # Dispatch with a bit of CPU offload
+ gpt2 = AutoModelForCausalLM.from_pretrained("gpt2")
+ for i in range(4):
+ device_map[f"transformer.h.{i}"] = "cpu"
+ gpt2 = dispatch_model(gpt2, device_map)
+ outputs = gpt2.generate(inputs["input_ids"])
+ assert (
+ tokenizer.decode(outputs[0].tolist())
+ == "Hello world! My name is Kiyoshi, and I'm a student at the University of Tokyo"
+ )
+ # Dispatch with a bit of CPU and disk offload
+ gpt2 = AutoModelForCausalLM.from_pretrained("gpt2")
+ for i in range(2):
+ device_map[f"transformer.h.{i}"] = "disk"
+
+ with TemporaryDirectory() as tmp_dir:
+ state_dict = {
+ k: p for k, p in gpt2.state_dict().items() if "transformer.h.0" in k or "transformer.h.1" in k
+ }
+ offload_state_dict(tmp_dir, state_dict)
+ gpt2 = dispatch_model(gpt2, device_map, offload_dir=tmp_dir)
+ outputs = gpt2.generate(inputs["input_ids"])
+ assert (
+ tokenizer.decode(outputs[0].tolist())
+ == "Hello world! My name is Kiyoshi, and I'm a student at the University of Tokyo"
+ )
+
+ @require_non_cpu
+ def test_dispatch_model_with_unused_submodules(self):
+ model = ModelWithUnusedSubModulesForTest()
+ device_map = {"linear1": "cpu", "linear2": "disk", "batchnorm": "cpu", "linear3": 0, "linear4": 0}
+
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ with TemporaryDirectory() as tmp_dir:
+ dispatch_model(
+ model, device_map, offload_dir=tmp_dir, preload_module_classes=["ModuleWithUnusedSubModules"]
+ )
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_multi_device
+ def test_dispatch_model_with_unused_submodules_multi_device(self):
+ model = ModelWithUnusedSubModulesForTest()
+ device_map = {"linear1": "cpu", "linear2": "disk", "batchnorm": "cpu", "linear3": 0, "linear4": 1}
+
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ with TemporaryDirectory() as tmp_dir:
+ dispatch_model(
+ model, device_map, offload_dir=tmp_dir, preload_module_classes=["ModuleWithUnusedSubModules"]
+ )
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_non_cpu
+ def test_dispatch_model_force_hooks(self):
+ model = ModelForTest()
+ device_map = {"": 0}
+
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ dispatch_model(model, device_map, force_hooks=True)
+ output = model(x)
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_non_cpu
+ def test_load_checkpoint_and_dispatch(self):
+ model = ModelForTest()
+ device_map = {"linear1": "cpu", "batchnorm": "cpu", "linear2": 0}
+
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ with TemporaryDirectory() as tmp_dir:
+ checkpoint = os.path.join(tmp_dir, "pt_model.bin")
+ torch.save(model.state_dict(), checkpoint)
+
+ new_model = ModelForTest()
+ new_model = load_checkpoint_and_dispatch(new_model, checkpoint, device_map=device_map)
+
+ # CPU-offloaded weights are on the meta device while waiting for the forward pass.
+ assert new_model.linear1.weight.device == torch.device("meta")
+ assert new_model.linear2.weight.device == torch.device(torch_device)
+
+ output = new_model(x)
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_multi_device
+ def test_load_checkpoint_and_dispatch_multi_device(self):
+ model = BiggerModelForTest()
+ device_map = {"linear1": "cpu", "linear2": "cpu", "batchnorm": 0, "linear3": 0, "linear4": 1}
+
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ with TemporaryDirectory() as tmp_dir:
+ checkpoint = os.path.join(tmp_dir, "pt_model.bin")
+ torch.save(model.state_dict(), checkpoint)
+
+ new_model = BiggerModelForTest()
+ new_model = load_checkpoint_and_dispatch(new_model, checkpoint, device_map=device_map)
+
+ # CPU-offloaded weights are on the meta device while waiting for the forward pass.
+ assert new_model.linear1.weight.device == torch.device("meta")
+ assert new_model.linear2.weight.device == torch.device("meta")
+ assert new_model.linear3.weight.device == torch.device(torch_device)
+ assert new_model.linear4.weight.device == torch.device(torch_device.replace(":0", ":1"))
+
+ output = new_model(x)
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_non_cpu
+ def test_load_checkpoint_and_dispatch_with_unused_submodules(self):
+ model = ModelWithUnusedSubModulesForTest()
+ device_map = {"linear1": "cpu", "linear2": "cpu", "batchnorm": 0, "linear3": 0, "linear4": 0}
+
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ with TemporaryDirectory() as tmp_dir:
+ checkpoint = os.path.join(tmp_dir, "pt_model.bin")
+ torch.save(model.state_dict(), checkpoint)
+
+ new_model = ModelWithUnusedSubModulesForTest()
+ new_model = load_checkpoint_and_dispatch(
+ new_model, checkpoint, device_map=device_map, preload_module_classes=["ModuleWithUnusedSubModules"]
+ )
+
+ # CPU-offloaded weights are on the meta device while waiting for the forward pass.
+ assert new_model.linear1.linear.weight.device == torch.device("meta")
+ assert new_model.linear2.linear.weight.device == torch.device("meta")
+ assert new_model.linear3.linear.weight.device == torch.device(torch_device)
+ assert new_model.linear4.linear.weight.device == torch.device(torch_device)
+
+ output = new_model(x)
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_multi_device
+ def test_load_checkpoint_and_dispatch_multi_device_with_unused_submodules(self):
+ model = ModelWithUnusedSubModulesForTest()
+ device_map = {"linear1": "cpu", "linear2": "cpu", "batchnorm": 0, "linear3": 0, "linear4": 1}
+
+ x = torch.randn(2, 3)
+ expected = model(x)
+
+ with TemporaryDirectory() as tmp_dir:
+ checkpoint = os.path.join(tmp_dir, "pt_model.bin")
+ torch.save(model.state_dict(), checkpoint)
+
+ new_model = ModelWithUnusedSubModulesForTest()
+ new_model = load_checkpoint_and_dispatch(
+ new_model, checkpoint, device_map=device_map, preload_module_classes=["ModuleWithUnusedSubModules"]
+ )
+
+ # CPU-offloaded weights are on the meta device while waiting for the forward pass.
+ assert new_model.linear1.linear.weight.device == torch.device("meta")
+ assert new_model.linear2.linear.weight.device == torch.device("meta")
+ assert new_model.linear3.linear.weight.device == torch.device(torch_device)
+ assert new_model.linear4.linear.weight.device == torch.device(torch_device.replace(":0", ":1"))
+
+ output = new_model(x)
+ assert torch.allclose(expected, output.cpu(), atol=1e-5)
+
+ @require_non_cpu
+ def test_cpu_offload_with_hook(self):
+ model1 = torch.nn.Linear(4, 5)
+ model1, hook1 = cpu_offload_with_hook(model1)
+ assert model1.weight.device == torch.device("cpu")
+
+ inputs = torch.randn(3, 4)
+ outputs = model1(inputs)
+ assert outputs.device == torch.device(torch_device)
+ assert model1.weight.device == torch.device(torch_device)
+
+ hook1.offload()
+ assert model1.weight.device == torch.device("cpu")
+
+ model2 = torch.nn.Linear(5, 5)
+ model2, hook2 = cpu_offload_with_hook(model2, prev_module_hook=hook1)
+ assert model2.weight.device == torch.device("cpu")
+
+ outputs = model1(inputs)
+ assert outputs.device == torch.device(torch_device)
+ assert model1.weight.device == torch.device(torch_device)
+
+ outputs = model2(outputs)
+ assert outputs.device == torch.device(torch_device)
+ assert model1.weight.device == torch.device("cpu")
+ assert model2.weight.device == torch.device(torch_device)
+
+ hook2.offload()
+ assert model2.weight.device == torch.device("cpu")
+
+ @require_non_torch_xla
+ @slow
+ @require_bnb
+ @require_multi_gpu
+ def test_dispatch_model_bnb(self):
+ """Tests that `dispatch_model` quantizes int8 layers"""
+ from huggingface_hub import hf_hub_download
+ from transformers import AutoConfig, AutoModel, BitsAndBytesConfig
+ from transformers.utils.bitsandbytes import replace_with_bnb_linear
+
+ with init_empty_weights():
+ model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
+
+ quantization_config = BitsAndBytesConfig(load_in_8bit=True)
+ model = replace_with_bnb_linear(
+ model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
+ )
+
+ model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin")
+
+ model = load_checkpoint_and_dispatch(
+ model,
+ checkpoint=model_path,
+ device_map="balanced",
+ )
+
+ assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8
+ assert model.h[0].self_attention.query_key_value.weight.device.index == 0
+
+ assert model.h[(-1)].self_attention.query_key_value.weight.dtype == torch.int8
+ assert model.h[(-1)].self_attention.query_key_value.weight.device.index == 1
+
+ @require_cuda
+ @slow
+ @require_bnb
+ def test_dispatch_model_int8_simple(self):
+ """Tests that `dispatch_model` quantizes int8 layers"""
+ from huggingface_hub import hf_hub_download
+ from transformers import AutoConfig, AutoModel, BitsAndBytesConfig
+ from transformers.utils.bitsandbytes import replace_with_bnb_linear
+
+ with init_empty_weights():
+ model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
+
+ quantization_config = BitsAndBytesConfig(load_in_8bit=True)
+ model = replace_with_bnb_linear(
+ model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
+ )
+
+ model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin")
+
+ # test with auto
+ model = load_checkpoint_and_dispatch(
+ model,
+ checkpoint=model_path,
+ device_map="auto",
+ )
+
+ assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8
+ assert model.h[0].self_attention.query_key_value.weight.device.index == 0
+
+ with init_empty_weights():
+ model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
+
+ model = replace_with_bnb_linear(
+ model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
+ )
+
+ # test with str device map
+ model = load_checkpoint_and_dispatch(
+ model,
+ checkpoint=model_path,
+ device_map={"": torch.device("cuda:0")},
+ )
+
+ assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8
+ assert model.h[0].self_attention.query_key_value.weight.device.index == 0
+
+ with init_empty_weights():
+ model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
+
+ model = replace_with_bnb_linear(
+ model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
+ )
+
+ # test with torch.device device map
+ model = load_checkpoint_and_dispatch(
+ model,
+ checkpoint=model_path,
+ device_map={"": "cuda:0"},
+ )
+
+ assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8
+ assert model.h[0].self_attention.query_key_value.weight.device.index == 0
+
+ @require_cuda
+ @slow
+ @require_bnb
+ def test_dipatch_model_fp4_simple(self):
+ """Tests that `dispatch_model` quantizes fp4 layers"""
+ from huggingface_hub import hf_hub_download
+ from transformers import AutoConfig, AutoModel, BitsAndBytesConfig
+ from transformers.utils.bitsandbytes import replace_with_bnb_linear
+
+ with init_empty_weights():
+ model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
+
+ quantization_config = BitsAndBytesConfig(load_in_4bit=True)
+
+ model = replace_with_bnb_linear(
+ model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
+ )
+
+ model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin")
+
+ # test with auto
+ model = load_checkpoint_and_dispatch(
+ model,
+ checkpoint=model_path,
+ device_map="auto",
+ )
+
+ assert model.h[0].self_attention.query_key_value.weight.dtype == torch.uint8
+ assert model.h[0].self_attention.query_key_value.weight.device.index == 0
+
+ with init_empty_weights():
+ model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
+
+ model = replace_with_bnb_linear(
+ model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
+ )
+
+ # test with str device map
+ model = load_checkpoint_and_dispatch(
+ model,
+ checkpoint=model_path,
+ device_map={"": torch.device("cuda:0")},
+ )
+
+ assert model.h[0].self_attention.query_key_value.weight.dtype == torch.uint8
+ assert model.h[0].self_attention.query_key_value.weight.device.index == 0
+
+ with init_empty_weights():
+ model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
+
+ model = replace_with_bnb_linear(
+ model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
+ )
+
+ # test with torch.device device map
+ model = load_checkpoint_and_dispatch(
+ model,
+ checkpoint=model_path,
+ device_map={"": "cuda:0"},
+ )
+
+ assert model.h[0].self_attention.query_key_value.weight.dtype == torch.uint8
+ assert model.h[0].self_attention.query_key_value.weight.device.index == 0
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_cli.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..308a6ad7c760f20a152dacaa9ea2626e177a6d15
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_cli.py
@@ -0,0 +1,515 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+import torch
+from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
+
+import accelerate.commands.test as accelerate_test_cmd
+from accelerate.commands.config.config_args import BaseConfig, ClusterConfig, SageMakerConfig, load_config_from_file
+from accelerate.commands.estimate import estimate_command, estimate_command_parser, gather_data
+from accelerate.commands.launch import _validate_launch_command, launch_command, launch_command_parser
+from accelerate.commands.tpu import tpu_command_launcher, tpu_command_parser
+from accelerate.test_utils.testing import (
+ capture_call_output,
+ path_in_accelerate_package,
+ require_multi_device,
+ require_timm,
+ require_transformers,
+ run_command,
+)
+from accelerate.utils import patch_environment
+from accelerate.utils.launch import prepare_simple_launcher_cmd_env
+
+
+class AccelerateLauncherTester(unittest.TestCase):
+ """
+ Test case for verifying the `accelerate launch` CLI operates correctly.
+ If a `default_config.yaml` file is located in the cache it will temporarily move it
+ for the duration of the tests.
+ """
+
+ test_file_path = path_in_accelerate_package("test_utils", "scripts", "test_cli.py")
+ notebook_launcher_path = path_in_accelerate_package("test_utils", "scripts", "test_notebook.py")
+
+ config_folder = Path.home() / ".cache/huggingface/accelerate"
+ config_file = "default_config.yaml"
+ config_path = config_folder / config_file
+ changed_path = config_folder / "_default_config.yaml"
+
+ test_config_path = Path("tests/test_configs")
+ parser = launch_command_parser()
+
+ @classmethod
+ def setUpClass(cls):
+ if cls.config_path.is_file():
+ cls.config_path.rename(cls.changed_path)
+
+ @classmethod
+ def tearDownClass(cls):
+ if cls.changed_path.is_file():
+ cls.changed_path.rename(cls.config_path)
+
+ def test_no_config(self):
+ args = ["--monitor_interval", "0.1", str(self.test_file_path)]
+ if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
+ args = ["--multi_gpu"] + args
+ args = self.parser.parse_args(["--monitor_interval", "0.1", str(self.test_file_path)])
+ launch_command(args)
+
+ def test_config_compatibility(self):
+ invalid_configs = ["fp8", "invalid", "mpi", "sagemaker"]
+ for config in sorted(self.test_config_path.glob("**/*.yaml")):
+ if any(invalid_config in str(config) for invalid_config in invalid_configs):
+ continue
+ with self.subTest(config_file=config):
+ args = self.parser.parse_args(["--config_file", str(config), str(self.test_file_path)])
+ launch_command(args)
+
+ def test_invalid_keys(self):
+ config_path = self.test_config_path / "invalid_keys.yaml"
+ with self.assertRaises(
+ ValueError,
+ msg="The config file at 'invalid_keys.yaml' had unknown keys ('another_invalid_key', 'invalid_key')",
+ ):
+ args = self.parser.parse_args(["--config_file", str(config_path), str(self.test_file_path)])
+ launch_command(args)
+
+ def test_accelerate_test(self):
+ args = accelerate_test_cmd.test_command_parser().parse_args([])
+ accelerate_test_cmd.test_command(args)
+
+ @require_multi_device
+ def test_notebook_launcher(self):
+ """
+ This test checks a variety of situations and scenarios
+ with the `notebook_launcher`
+ """
+ cmd = ["python", self.notebook_launcher_path]
+ with patch_environment(omp_num_threads=1, accelerate_num_processes=2):
+ run_command(cmd)
+
+ def test_mpi_multicpu_config_cmd(self):
+ """
+ Parses a launch command with a test file and the 0_28_0_mpi.yaml config. Tests getting the command and
+ environment vars and verifies the mpirun command arg values.
+ """
+ mpi_config_path = str(self.test_config_path / "0_28_0_mpi.yaml")
+ test_file_arg = "--cpu"
+
+ with patch("sys.argv", ["accelerate", str(self.test_file_path), test_file_arg]):
+ parser = launch_command_parser()
+ args = parser.parse_args()
+ args.config_file = mpi_config_path
+ args, _, _ = _validate_launch_command(args)
+
+ # Mock out the check for mpirun version to simulate Intel MPI
+ with patch("accelerate.utils.launch.which", return_value=True):
+ with patch("accelerate.utils.launch.subprocess.check_output", return_value=b"Intel MPI"):
+ cmd, _ = prepare_simple_launcher_cmd_env(args)
+
+ # Verify the mpirun command args
+ expected_mpirun_cmd = ["mpirun", "-f", "/home/user/hostfile", "-ppn", "4", "-n", "16"]
+ self.assertGreater(len(cmd), len(expected_mpirun_cmd))
+ generated_mpirun_cmd = cmd[0 : len(expected_mpirun_cmd)]
+ self.assertEqual(expected_mpirun_cmd, generated_mpirun_cmd)
+
+ # Verify the python script and args in the mpirun command
+ python_script_cmd = cmd[len(expected_mpirun_cmd) :]
+ self.assertEqual(len(python_script_cmd), 3)
+ self.assertEqual(python_script_cmd[1], str(self.test_file_path))
+ self.assertEqual(python_script_cmd[2], test_file_arg)
+
+
+class LaunchArgTester(unittest.TestCase):
+ """
+ Test cases revolving around the CLI wrappers
+ """
+
+ parser = launch_command_parser()
+
+ def test_hyphen(self):
+ # Try a little from each cluster
+ args = ["--config-file", "test.yaml", "test.py"]
+ result = self.parser.parse_args(args)
+ assert result.config_file == "test.yaml"
+ assert result.multi_gpu is False
+
+ args = ["--multi-gpu", "--num-processes", "4", "test.py"]
+ result = self.parser.parse_args(args)
+ assert result.multi_gpu is True
+ assert result.num_processes == 4
+ # And use a mix
+ args = ["--multi-gpu", "--use-deepspeed", "--use-fsdp", "--num_processes", "4", "test.py"]
+ result = self.parser.parse_args(args)
+ assert result.multi_gpu is True
+ assert result.use_deepspeed is True
+ assert result.use_fsdp is True
+ assert result.num_processes == 4
+
+ def test_underscore(self):
+ # Try a little from each cluster
+ args = ["--config_file", "test.yaml", "test.py"]
+ result = self.parser.parse_args(args)
+ assert result.config_file == "test.yaml"
+
+ args = ["--multi_gpu", "--num_processes", "4", "test.py"]
+ result = self.parser.parse_args(args)
+ assert result.multi_gpu is True
+ assert result.num_processes == 4
+ # And use a mix
+ args = ["--multi_gpu", "--use_deepspeed", "--use_fsdp", "--num-processes", "4", "test.py"]
+ result = self.parser.parse_args(args)
+ assert result.multi_gpu is True
+ assert result.use_deepspeed is True
+ assert result.use_fsdp is True
+ assert result.num_processes == 4
+
+ def test_duplicate_entities(self):
+ help_return = self.parser.format_help()
+ args = self.parser.parse_args(["test.py"])
+ for arg in args.__dict__:
+ if "_" in arg:
+ bad_arg = f'--{arg.replace("_", "-")}'
+ # Need an exception for `num-processes` since it's in the docstring
+ if bad_arg == "--num-processes":
+ assert help_return.count(bad_arg) == 1, f"Found {bad_arg} in `accelerate launch -h`"
+ else:
+ assert bad_arg not in help_return, f"Found {bad_arg} in `accelerate launch -h`"
+
+
+class ClusterConfigTester(unittest.TestCase):
+ """
+ Test case for verifying the config dataclasses work
+ """
+
+ test_config_path = Path("tests/test_configs")
+
+ def test_base_config(self):
+ # Tests that all the dataclasses can be initialized
+ config = BaseConfig(
+ compute_environment="LOCAL_MACHINE",
+ distributed_type="NO",
+ mixed_precision="fp16",
+ debug=False,
+ use_cpu=False,
+ )
+
+ assert config.compute_environment == "LOCAL_MACHINE"
+ assert config.distributed_type == "NO"
+ assert config.mixed_precision == "fp16"
+ assert config.debug is False
+
+ def test_cluster_config(self):
+ # First normally
+ config = ClusterConfig(
+ compute_environment="LOCAL_MACHINE",
+ distributed_type="NO",
+ mixed_precision="fp16",
+ num_processes=2,
+ debug=False,
+ use_cpu=False,
+ )
+
+ assert config.compute_environment == "LOCAL_MACHINE"
+ assert config.distributed_type == "NO"
+ assert config.mixed_precision == "fp16"
+ assert config.debug is False
+
+ # Then check with other compute environments
+ config = ClusterConfig(
+ compute_environment="LOCAL_MACHINE",
+ distributed_type="MULTI_GPU",
+ mixed_precision="fp16",
+ debug=False,
+ num_processes=2,
+ enable_cpu_affinity=True,
+ use_cpu=False,
+ )
+
+ assert config.distributed_type == "MULTI_GPU"
+ assert config.num_processes == 2
+ assert config.enable_cpu_affinity is True
+
+ def test_sagemaker_config(self):
+ config = SageMakerConfig(
+ compute_environment="AMAZON_SAGEMAKER",
+ distributed_type="NO",
+ mixed_precision="fp16",
+ debug=False,
+ use_cpu=False,
+ ec2_instance_type="MY_TYPE",
+ iam_role_name="MY_ROLE",
+ )
+
+ assert config.compute_environment == "AMAZON_SAGEMAKER"
+ assert config.ec2_instance_type == "MY_TYPE"
+ assert config.iam_role_name == "MY_ROLE"
+
+ config = load_config_from_file(str(self.test_config_path / "0_30_0_sagemaker.yaml"))
+
+
+class TpuConfigTester(unittest.TestCase):
+ """
+ Test case for verifying the `accelerate tpu-config` CLI passes the right `gcloud` command.
+ """
+
+ tpu_name = "test-tpu"
+ tpu_zone = "us-central1-a"
+ command = "ls"
+ cmd = ["accelerate", "tpu-config"]
+ base_output = "cd /usr/share"
+ command_file = "tests/test_samples/test_command_file.sh"
+ gcloud = "Running gcloud compute tpus tpu-vm ssh"
+
+ def setUp(self):
+ self.parser = tpu_command_parser()
+
+ def test_base(self):
+ args = self.parser.parse_args(
+ ["--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug"]
+ )
+ output = capture_call_output(tpu_command_launcher, args)
+ assert f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" in output
+
+ def test_base_backward_compatibility(self):
+ args = self.parser.parse_args(
+ [
+ "--config_file",
+ "tests/test_configs/0_12_0.yaml",
+ "--command",
+ self.command,
+ "--tpu_zone",
+ self.tpu_zone,
+ "--tpu_name",
+ self.tpu_name,
+ "--debug",
+ ]
+ )
+ output = capture_call_output(tpu_command_launcher, args)
+ assert f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" in output
+
+ def test_with_config_file(self):
+ args = self.parser.parse_args(["--config_file", "tests/test_configs/latest.yaml", "--debug"])
+ output = capture_call_output(tpu_command_launcher, args)
+ assert (
+ f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'
+ in output
+ )
+
+ def test_with_config_file_and_command(self):
+ args = self.parser.parse_args(
+ ["--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--debug"]
+ )
+ output = capture_call_output(tpu_command_launcher, args)
+ assert f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" in output
+
+ def test_with_config_file_and_multiple_command(self):
+ args = self.parser.parse_args(
+ [
+ "--config_file",
+ "tests/test_configs/latest.yaml",
+ "--command",
+ self.command,
+ "--command",
+ 'echo "Hello World"',
+ "--debug",
+ ]
+ )
+ output = capture_call_output(tpu_command_launcher, args)
+ assert (
+ f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all'
+ in output
+ )
+
+ def test_with_config_file_and_command_file(self):
+ args = self.parser.parse_args(
+ ["--config_file", "tests/test_configs/latest.yaml", "--command_file", self.command_file, "--debug"]
+ )
+ output = capture_call_output(tpu_command_launcher, args)
+ assert (
+ f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'
+ in output
+ )
+
+ def test_with_config_file_and_command_file_backward_compatibility(self):
+ args = self.parser.parse_args(
+ [
+ "--config_file",
+ "tests/test_configs/0_12_0.yaml",
+ "--command_file",
+ self.command_file,
+ "--tpu_zone",
+ self.tpu_zone,
+ "--tpu_name",
+ self.tpu_name,
+ "--debug",
+ ]
+ )
+ output = capture_call_output(tpu_command_launcher, args)
+ assert (
+ f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'
+ in output
+ )
+
+ def test_accelerate_install(self):
+ args = self.parser.parse_args(
+ ["--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--debug"]
+ )
+ output = capture_call_output(tpu_command_launcher, args)
+ assert (
+ f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all'
+ in output
+ )
+
+ def test_accelerate_install_version(self):
+ args = self.parser.parse_args(
+ [
+ "--config_file",
+ "tests/test_configs/latest.yaml",
+ "--install_accelerate",
+ "--accelerate_version",
+ "12.0.0",
+ "--debug",
+ ]
+ )
+ output = capture_call_output(tpu_command_launcher, args)
+ assert (
+ f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all'
+ in output
+ )
+
+
+class ModelEstimatorTester(unittest.TestCase):
+ """
+ Test case for checking the output of `accelerate estimate-memory` is correct.
+
+ - Uses `estimate_command` when trying to catch raised errors
+ - Uses `gather_data` when just verifying the calculations are correct
+ """
+
+ parser = estimate_command_parser()
+
+ def test_invalid_model_name(self):
+ with self.assertRaises(
+ RepositoryNotFoundError, msg="Repo for model `somebrokenname` does not exist on the Hub"
+ ):
+ args = self.parser.parse_args(["somebrokenname"])
+ estimate_command(args)
+
+ @require_timm
+ def test_invalid_model_name_timm(self):
+ with self.assertRaises(RuntimeError, msg="Tried to load `muellerzr/dummy` with `timm` but"):
+ args = self.parser.parse_args(["muellerzr/dummy", "--library_name", "timm"])
+ estimate_command(args)
+
+ @require_transformers
+ def test_invalid_model_name_transformers(self):
+ with self.assertRaises(RuntimeError, msg="Tried to load `muellerzr/dummy` with `transformers` but"):
+ args = self.parser.parse_args(["muellerzr/dummy", "--library_name", "transformers"])
+ estimate_command(args)
+
+ def test_no_metadata(self):
+ with self.assertRaises(
+ ValueError, msg="Model `muellerzr/dummy` does not have any library metadata on the Hub"
+ ):
+ args = self.parser.parse_args(["muellerzr/dummy"])
+ estimate_command(args)
+
+ def test_gated(self):
+ with self.assertRaises(
+ (GatedRepoError, EnvironmentError),
+ msg="Repo for model `meta-llama/Llama-2-7b-hf` is gated or environment error occurred",
+ ):
+ args = self.parser.parse_args(["meta-llama/Llama-2-7b-hf"])
+ with patch_environment(hf_hub_disable_implicit_token="1"):
+ estimate_command(args)
+
+ @require_transformers
+ def test_remote_code(self):
+ # Also tests that custom `Auto` classes work
+ args = self.parser.parse_args(["hf-internal-testing/test_dynamic_model"])
+ with self.assertRaises(ValueError, msg="--trust_remote_code"):
+ gather_data(args)
+
+ # Verify it works with the flag
+ args = self.parser.parse_args(["hf-internal-testing/test_dynamic_model", "--trust_remote_code"])
+ gather_data(args)
+
+ @require_transformers
+ def test_explicit_dtypes(self):
+ args = self.parser.parse_args(["bert-base-cased", "--dtypes", "float32", "float16"])
+ output = gather_data(args)
+ # The largest layer and total size of the model in bytes
+ largest_layer, total_size = 90669056, 433249280
+ # Check that full precision -> int4 is calculating correctly
+ assert len(output) == 2, f"Output was missing a precision, expected 2 but received {len(output)}"
+
+ for i, factor in enumerate([1, 2]):
+ precision = 32 // factor
+ precision_str = f"float{precision}"
+ largest_layer_estimate = largest_layer / factor
+ total_size_estimate = total_size / factor
+ total_training_size_estimate = total_size_estimate * 4
+
+ assert precision_str == output[i][0], f"Output is missing precision `{precision_str}`"
+ assert (
+ largest_layer_estimate == output[i][1]
+ ), f"Calculation for largest layer size in `{precision_str}` is incorrect."
+
+ assert (
+ total_size_estimate == output[i][2]
+ ), f"Calculation for total size in `{precision_str}` is incorrect."
+ assert total_training_size_estimate == max(
+ output[i][3].values()
+ ), f"Calculation for total training size in `{precision_str}` is incorrect."
+
+ @require_transformers
+ def test_transformers_model(self):
+ args = self.parser.parse_args(["bert-base-cased", "--dtypes", "float32"])
+ output = gather_data(args)
+ # The largest layer and total size of the model in bytes
+ largest_layer, total_size = 90669056, 433249280
+ assert (
+ largest_layer == output[0][1]
+ ), f"Calculation for largest layer size in `fp32` is incorrect, expected {largest_layer} but received {output[0][1]}"
+ assert (
+ total_size == output[0][2]
+ ), f"Calculation for total size in `fp32` is incorrect, expected {total_size} but received {output[0][2]}"
+
+ @require_transformers
+ def test_no_split_modules(self):
+ # idefics-80b-instruct has ["IdeficsDecoderLayer", "IdeficsGatedCrossAttentionLayer"]
+ args = self.parser.parse_args(["HuggingFaceM4/idefics-80b-instruct", "--dtypes", "float32"])
+ output = gather_data(args)
+ # without factoring in `no_split` modules, the largest layer is 721420288 bytes
+ assert output[0][1] != 721420288, "Largest layer calculation incorrect, did not factor in `no_split` modules."
+ # the real answer is 3240165632 bytes
+ assert output[0][1] == 3240165632
+
+ @require_timm
+ def test_timm_model(self):
+ args = self.parser.parse_args(["timm/resnet50.a1_in1k", "--library_name", "timm"])
+ output = gather_data(args)
+ # The largest layer and total size of the model in bytes
+ largest_layer, total_size = 9437184, 102441032
+ assert (
+ largest_layer == output[0][1]
+ ), f"Calculation for largest layer size in `fp32` is incorrect, expected {largest_layer} but received {output[0][1]}"
+ assert (
+ total_size == output[0][2]
+ ), f"Calculation for total size in `fp32` is incorrect, expected {total_size} but received {output[0][2]}"
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_11_0.yaml b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_11_0.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..9ef829e6b53811462f6ffc457312b48e2055ffad
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_11_0.yaml
@@ -0,0 +1,12 @@
+compute_environment: LOCAL_MACHINE
+deepspeed_config: {}
+distributed_type: 'NO'
+fsdp_config: {}
+machine_rank: 0
+main_process_ip: null
+main_process_port: null
+main_training_function: main
+mixed_precision: 'no'
+num_machines: 1
+num_processes: 1
+use_cpu: false
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_12_0.yaml b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_12_0.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..00d06aab98f2a5489d7a1505dc8e1107fcc20762
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_12_0.yaml
@@ -0,0 +1,13 @@
+compute_environment: LOCAL_MACHINE
+deepspeed_config: {}
+distributed_type: 'NO'
+downcast_bf16: 'no'
+fsdp_config: {}
+machine_rank: 0
+main_process_ip: null
+main_process_port: null
+main_training_function: main
+mixed_precision: 'no'
+num_machines: 1
+num_processes: 1
+use_cpu: false
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_28_0_mpi.yaml b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_28_0_mpi.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..afb05eb25798d4eb8acd2c936197a8e3921fa912
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_28_0_mpi.yaml
@@ -0,0 +1,22 @@
+compute_environment: LOCAL_MACHINE
+debug: false
+distributed_type: MULTI_CPU
+downcast_bf16: 'no'
+ipex_config:
+ ipex: true
+machine_rank: 0
+main_process_ip: 127.0.0.1
+main_process_port: 29500
+main_training_function: main
+mixed_precision: 'no'
+mpirun_config:
+ mpirun_ccl: '1'
+ mpirun_hostfile: /home/user/hostfile
+num_machines: 4
+num_processes: 16
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: true
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_30_0_sagemaker.yaml b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_30_0_sagemaker.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..197055fe6da5af66c365b01d5db0b50593a94db8
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_30_0_sagemaker.yaml
@@ -0,0 +1,8 @@
+compute_environment: AMAZON_SAGEMAKER
+debug: false
+distributed_type: NO
+mixed_precision: fp16
+debug: false
+use_cpu: false
+ec2_instance_type: MY_TYPE
+iam_role_name: MY_ROLE
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_34_0_fp8.yaml b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_34_0_fp8.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..21bce1d93dc25dc3613605dcfdece0e6df324369
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/0_34_0_fp8.yaml
@@ -0,0 +1,26 @@
+compute_environment: LOCAL_MACHINE
+debug: false
+distributed_type: MULTI_GPU
+downcast_bf16: 'no'
+enable_cpu_affinity: false
+fp8_config:
+ amax_compute_algorithm: max
+ amax_history_length: 1024
+ backend: TE
+ fp8_format: E4M3
+ interval: 1
+ margin: 0
+ override_linear_precision: false
+ use_autocast_during_eval: false
+gpu_ids: all
+machine_rank: 0
+main_training_function: main
+mixed_precision: fp8
+num_machines: 1
+num_processes: 2
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: false
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/README.md b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..fd88d066c5dfdb82fe5067a8c5644fffa3054d99
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/README.md
@@ -0,0 +1,2 @@
+This folder contains test configs for `accelerate config`. These should be generated for each major version
+and are written based on `accelerate config` and selecting the "No distributed training" option.
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/invalid_keys.yaml b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/invalid_keys.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..3e58ce77be655709f12a95c4935c391e1cc077c2
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/invalid_keys.yaml
@@ -0,0 +1,15 @@
+compute_environment: LOCAL_MACHINE
+deepspeed_config: {}
+distributed_type: 'NO'
+downcast_bf16: 'no'
+fsdp_config: {}
+machine_rank: 0
+main_process_ip: null
+main_process_port: null
+main_training_function: main
+mixed_precision: 'no'
+num_machines: 1
+num_processes: 1
+use_cpu: false
+invalid_key: "invalid_value"
+another_invalid_key: "another_invalid_value"
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/latest.yaml b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/latest.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..456348ef9e6d01326d727b71c1dddd4177f89861
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_configs/latest.yaml
@@ -0,0 +1,21 @@
+compute_environment: LOCAL_MACHINE
+deepspeed_config: {}
+distributed_type: 'NO'
+downcast_bf16: 'no'
+fsdp_config: {}
+gpu_ids: all
+machine_rank: 0
+main_process_ip: null
+main_process_port: null
+main_training_function: main
+megatron_lm_config: {}
+mixed_precision: 'no'
+num_machines: 1
+num_processes: 1
+rdzv_backend: static
+same_network: true
+use_cpu: false
+tpu_name: 'test-tpu'
+tpu_zone: 'us-central1-a'
+commands: null
+command_file: tests/test_samples/test_command_file.sh
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_cpu.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_cpu.py
new file mode 100644
index 0000000000000000000000000000000000000000..d328575a181e79dc3ae231e10aa16ebe4db4bfc7
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_cpu.py
@@ -0,0 +1,27 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+
+from accelerate import debug_launcher
+from accelerate.test_utils import require_cpu, test_ops, test_script
+
+
+@require_cpu
+class MultiCPUTester(unittest.TestCase):
+ def test_cpu(self):
+ debug_launcher(test_script.main)
+
+ def test_ops(self):
+ debug_launcher(test_ops.main)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_data_loader.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_data_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ffbf29c134a2b4758aa532828cf80aa7eb88e03
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_data_loader.py
@@ -0,0 +1,809 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import random
+import unittest
+
+import pytest
+import torch
+from parameterized import parameterized
+from torch.utils.data import BatchSampler, DataLoader, IterableDataset
+
+from accelerate import Accelerator, PartialState
+from accelerate.data_loader import (
+ BatchSamplerShard,
+ DataLoaderDispatcher,
+ DataLoaderShard,
+ DataLoaderStateMixin,
+ IterableDatasetShard,
+ SkipBatchSampler,
+ SkipDataLoader,
+ prepare_data_loader,
+ skip_first_batches,
+)
+from accelerate.state import GradientState
+from accelerate.test_utils.testing import require_torchdata_stateful_dataloader
+from accelerate.utils import is_torchdata_stateful_dataloader_available
+
+
+if is_torchdata_stateful_dataloader_available():
+ from torchdata.stateful_dataloader import (
+ StatefulDataLoader,
+ )
+
+
+def parameterized_custom_name_func(func, param_num, param):
+ # customize the test name generator function as we want both params to appear in the sub-test
+ # name, as by default it shows only the first param
+ param_based_name = f"num_workers_{param.args[0]}"
+ return f"{func.__name__}_{param_based_name}"
+
+
+class RandomIterableDataset(IterableDataset):
+ # For testing, an iterable dataset of random length
+ def __init__(self, p_stop=0.01, max_length=1000):
+ self.p_stop = p_stop
+ self.max_length = max_length
+
+ def __iter__(self):
+ count = 0
+ stop = False
+ while not stop and count < self.max_length:
+ yield count
+ count += 1
+ stop = random.random() < self.p_stop
+
+
+class SimpleIterableDataset(IterableDataset):
+ def __init__(self, num_samples=1000):
+ self.num_samples = num_samples
+
+ def __iter__(self):
+ for _ in range(self.num_samples):
+ yield torch.rand(1)
+
+ def __len__(self):
+ return self.num_samples
+
+ def set_epoch(self, epoch):
+ self.epoch = epoch
+
+
+class DataLoaderTester(unittest.TestCase):
+ def check_batch_sampler_shards(self, batch_sampler, expected, split_batches=False, even_batches=True):
+ batch_sampler_shards = [
+ BatchSamplerShard(batch_sampler, 2, i, split_batches=split_batches, even_batches=even_batches)
+ for i in range(2)
+ ]
+ batch_sampler_lists = [list(batch_sampler_shard) for batch_sampler_shard in batch_sampler_shards]
+ if not split_batches:
+ assert [len(shard) for shard in batch_sampler_shards] == [len(e) for e in expected]
+ assert batch_sampler_lists == expected
+
+ def test_batch_sampler_shards_with_no_splits(self):
+ # Check the shards when the dataset is a round multiple of total batch size.
+ batch_sampler = BatchSampler(range(24), batch_size=3, drop_last=False)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected)
+
+ batch_sampler = BatchSampler(range(24), batch_size=3, drop_last=True)
+ # Expected shouldn't change
+ self.check_batch_sampler_shards(batch_sampler, expected)
+
+ # Check the shards when the dataset is a round multiple of batch size but not total batch size.
+ batch_sampler = BatchSampler(range(21), batch_size=3, drop_last=False)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected)
+
+ batch_sampler = BatchSampler(range(21), batch_size=3, drop_last=True)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected)
+
+ # Check the shards when the dataset is not a round multiple of batch size but has a multiple of
+ # num_processes batch.
+ batch_sampler = BatchSampler(range(22), batch_size=3, drop_last=False)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected)
+
+ batch_sampler = BatchSampler(range(22), batch_size=3, drop_last=True)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected)
+
+ # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of
+ # num_processes batch.
+ batch_sampler = BatchSampler(range(20), batch_size=3, drop_last=False)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected)
+
+ batch_sampler = BatchSampler(range(20), batch_size=3, drop_last=True)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected)
+
+ # Check the shards when the dataset is very small.
+ batch_sampler = BatchSampler(range(2), batch_size=3, drop_last=False)
+ expected = [[[0, 1, 0]], [[1, 0, 1]]]
+ self.check_batch_sampler_shards(batch_sampler, expected)
+
+ batch_sampler = BatchSampler(range(2), batch_size=3, drop_last=True)
+ expected = [[], []]
+ self.check_batch_sampler_shards(batch_sampler, expected)
+
+ def test_batch_sampler_shards_with_splits(self):
+ # Check the shards when the dataset is a round multiple of batch size.
+ batch_sampler = BatchSampler(range(24), batch_size=4, drop_last=False)
+ expected = [
+ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
+ [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True)
+
+ batch_sampler = BatchSampler(range(24), batch_size=4, drop_last=True)
+ # Expected shouldn't change
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True)
+
+ # Check the shards when the dataset is not a round multiple of batch size.
+ batch_sampler = BatchSampler(range(22), batch_size=4, drop_last=False)
+ expected = [
+ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
+ [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True)
+
+ batch_sampler = BatchSampler(range(22), batch_size=4, drop_last=True)
+ expected = [
+ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
+ [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True)
+
+ # Check the shards when the dataset is not a round multiple of batch size or num_processes.
+ batch_sampler = BatchSampler(range(21), batch_size=4, drop_last=False)
+ expected = [
+ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]],
+ [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True)
+
+ batch_sampler = BatchSampler(range(21), batch_size=4, drop_last=True)
+ expected = [
+ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
+ [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True)
+
+ # Check the shards when the dataset is very small.
+ batch_sampler = BatchSampler(range(2), batch_size=4, drop_last=False)
+ expected = [[[0, 1]], [[0, 1]]]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True)
+
+ batch_sampler = BatchSampler(range(2), batch_size=4, drop_last=True)
+ expected = [[], []]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True)
+
+ def test_batch_sampler_shards_with_no_splits_no_even(self):
+ # Check the shards when the dataset is a round multiple of total batch size.
+ batch_sampler = BatchSampler(range(24), batch_size=3, drop_last=False)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False)
+
+ batch_sampler = BatchSampler(range(24), batch_size=3, drop_last=True)
+ # Expected shouldn't change
+ self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False)
+
+ # Check the shards when the dataset is a round multiple of batch size but not total batch size.
+ batch_sampler = BatchSampler(range(21), batch_size=3, drop_last=False)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False)
+
+ batch_sampler = BatchSampler(range(21), batch_size=3, drop_last=True)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False)
+
+ # Check the shards when the dataset is not a round multiple of batch size but has a multiple of
+ # num_processes batch.
+ batch_sampler = BatchSampler(range(22), batch_size=3, drop_last=False)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False)
+
+ batch_sampler = BatchSampler(range(22), batch_size=3, drop_last=True)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False)
+
+ # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of
+ # num_processes batch.
+ batch_sampler = BatchSampler(range(20), batch_size=3, drop_last=False)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False)
+
+ batch_sampler = BatchSampler(range(20), batch_size=3, drop_last=True)
+ expected = [
+ [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
+ [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False)
+
+ # Check the shards when the dataset is very small.
+ batch_sampler = BatchSampler(range(2), batch_size=3, drop_last=False)
+ expected = [[[0, 1]], []]
+ self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False)
+
+ batch_sampler = BatchSampler(range(2), batch_size=3, drop_last=True)
+ expected = [[], []]
+ self.check_batch_sampler_shards(batch_sampler, expected, even_batches=False)
+
+ def test_batch_sampler_shards_with_splits_no_even(self):
+ # Check the shards when the dataset is a round multiple of batch size.
+ batch_sampler = BatchSampler(range(24), batch_size=4, drop_last=False)
+ expected = [
+ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
+ [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False)
+
+ batch_sampler = BatchSampler(range(24), batch_size=4, drop_last=True)
+ # Expected shouldn't change
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False)
+
+ # Check the shards when the dataset is not a round multiple of batch size.
+ batch_sampler = BatchSampler(range(22), batch_size=4, drop_last=False)
+ expected = [
+ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
+ [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False)
+
+ batch_sampler = BatchSampler(range(22), batch_size=4, drop_last=True)
+ expected = [
+ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
+ [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False)
+
+ # Check the shards when the dataset is not a round multiple of batch size or num_processes.
+ batch_sampler = BatchSampler(range(21), batch_size=4, drop_last=False)
+ expected = [
+ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]],
+ [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False)
+
+ batch_sampler = BatchSampler(range(21), batch_size=4, drop_last=True)
+ expected = [
+ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
+ [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
+ ]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False)
+
+ # Check the shards when the dataset is very small.
+ batch_sampler = BatchSampler(range(2), batch_size=4, drop_last=False)
+ expected = [[[0, 1]], []]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False)
+
+ batch_sampler = BatchSampler(range(2), batch_size=4, drop_last=True)
+ expected = [[], []]
+ self.check_batch_sampler_shards(batch_sampler, expected, split_batches=True, even_batches=False)
+
+ def test_batch_sampler_with_varying_batch_size(self):
+ batch_sampler = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]]
+ batch_sampler_shards = [BatchSamplerShard(batch_sampler, 2, i, even_batches=False) for i in range(2)]
+
+ assert len(batch_sampler_shards[0]) == 3
+ assert len(batch_sampler_shards[1]) == 2
+
+ assert list(batch_sampler_shards[0]) == [[0, 1, 2], [5, 6, 7, 8], [12, 13]]
+ assert list(batch_sampler_shards[1]) == [[3, 4], [9, 10, 11]]
+
+ def check_iterable_dataset_shards(
+ self, dataset, seed, batch_size, drop_last=False, num_processes=2, split_batches=False
+ ):
+ random.seed(seed)
+ reference = list(dataset)
+
+ iterable_dataset_shards = [
+ IterableDatasetShard(
+ dataset,
+ batch_size=batch_size,
+ drop_last=drop_last,
+ num_processes=num_processes,
+ process_index=i,
+ split_batches=split_batches,
+ )
+ for i in range(num_processes)
+ ]
+ iterable_dataset_lists = []
+ for iterable_dataset_shard in iterable_dataset_shards:
+ # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results.
+ random.seed(seed)
+ iterable_dataset_lists.append(list(iterable_dataset_shard))
+
+ shard_batch_size = batch_size // num_processes if split_batches else batch_size
+ # All iterable dataset shard should have the same length, a round multiple of shard_batch_size
+ first_list = iterable_dataset_lists[0]
+ for l in iterable_dataset_lists[1:]:
+ assert len(l) == len(first_list)
+ assert (len(l) % shard_batch_size) == 0
+
+ observed = []
+ for idx in range(0, len(first_list), shard_batch_size):
+ for l in iterable_dataset_lists:
+ observed += l[idx : idx + shard_batch_size]
+
+ if not drop_last:
+ while len(reference) < len(observed):
+ reference += reference
+ assert observed == reference[: len(observed)]
+
+ def test_iterable_dataset_shard(self):
+ seed = 42
+ dataset = RandomIterableDataset()
+
+ self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=False, split_batches=False)
+ self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=True, split_batches=False)
+ self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=False, split_batches=True)
+ self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=True, split_batches=True)
+
+ # Edge case with a very small dataset
+ dataset = RandomIterableDataset(max_length=2)
+
+ self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=False, split_batches=False)
+ self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=True, split_batches=False)
+ self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=False, split_batches=True)
+ self.check_iterable_dataset_shards(dataset, seed, batch_size=4, drop_last=True, split_batches=True)
+
+ def test_iterable_dataset_using_none_batch_size(self):
+ dataset = SimpleIterableDataset(100)
+ dataloader = DataLoader(dataset, batch_size=None)
+ dataloader = prepare_data_loader(dataloader)
+ for d in dataloader:
+ assert isinstance(d, torch.Tensor)
+
+ def test_skip_batch_sampler(self):
+ batch_sampler = BatchSampler(range(16), batch_size=4, drop_last=False)
+ new_batch_sampler = SkipBatchSampler(batch_sampler, 2)
+ assert list(new_batch_sampler) == [[8, 9, 10, 11], [12, 13, 14, 15]]
+
+ def test_dataloader_inheritance(self):
+ """
+ `DataLoaderAdapter`'s parent classes are dynamically constructed, assert that subclasses of DataLoaderAdapter
+ are instances of DataLoader and DataLoaderStateMixin.
+ """
+ skip_dl = SkipDataLoader(range(16), batch_size=4, skip_batches=2)
+ dl_shard = DataLoaderShard(range(16), batch_size=4)
+ dl_dispatcher = DataLoaderDispatcher(range(16), batch_size=4)
+
+ # Test dataloaders are instances of instantiated classes
+ # These asserts look redundant, but it's worth checking since we are doing magic tricks such as dynamically overriding __class__
+ assert isinstance(skip_dl, SkipDataLoader)
+ assert isinstance(dl_shard, DataLoaderShard)
+ assert isinstance(dl_dispatcher, DataLoaderDispatcher)
+
+ # Test dataloaders are instances of base classes
+ assert isinstance(skip_dl, DataLoader)
+ assert isinstance(dl_shard, DataLoader)
+ assert isinstance(dl_dispatcher, DataLoader)
+
+ assert isinstance(dl_shard, DataLoaderStateMixin)
+ assert isinstance(dl_dispatcher, DataLoaderStateMixin)
+
+ assert isinstance(skip_dl.base_dataloader, DataLoader)
+ assert isinstance(dl_shard.base_dataloader, DataLoader)
+ assert isinstance(dl_dispatcher.base_dataloader, DataLoader)
+
+ with pytest.raises(AttributeError):
+ _ = DataLoaderShard.base_dataloader
+
+ def test_skip_data_loader(self):
+ dataloader = SkipDataLoader(list(range(16)), batch_size=4, skip_batches=2)
+ assert [t.tolist() for t in dataloader] == [[8, 9, 10, 11], [12, 13, 14, 15]]
+
+ def test_skip_first_batches(self):
+ dataloader = DataLoader(list(range(16)), batch_size=4)
+ new_dataloader = skip_first_batches(dataloader, num_batches=2)
+ assert [t.tolist() for t in new_dataloader] == [[8, 9, 10, 11], [12, 13, 14, 15]]
+
+ def test_end_of_dataloader(self):
+ dataloader = DataLoaderShard(list(range(16)), batch_size=4)
+ for idx, _ in enumerate(dataloader):
+ assert dataloader.end_of_dataloader == (idx == 3)
+
+ # Test it also works on the second iteration
+ for idx, _ in enumerate(dataloader):
+ assert dataloader.end_of_dataloader == (idx == 3)
+
+ def test_end_of_dataloader_dispatcher(self):
+ dataloader = DataLoaderDispatcher(range(16), batch_size=4)
+ for idx, _ in enumerate(dataloader):
+ assert dataloader.end_of_dataloader == (idx == 3)
+
+ # Test it also works on the second iteration
+ for idx, _ in enumerate(dataloader):
+ assert dataloader.end_of_dataloader == (idx == 3)
+
+
+class StatefulDataLoaderTester(unittest.TestCase):
+ @require_torchdata_stateful_dataloader
+ def test_skip_data_loader(self):
+ dataloader = SkipDataLoader(list(range(16)), batch_size=4, skip_batches=2, use_stateful_dataloader=True)
+ assert isinstance(dataloader, StatefulDataLoader)
+ assert [t.tolist() for t in dataloader] == [[8, 9, 10, 11], [12, 13, 14, 15]]
+
+ @require_torchdata_stateful_dataloader
+ def test_end_of_dataloader(self):
+ dataloader = DataLoaderShard(list(range(16)), batch_size=4, use_stateful_dataloader=True)
+ assert dataloader.use_stateful_dataloader
+ assert isinstance(dataloader, StatefulDataLoader)
+ for idx, _ in enumerate(dataloader):
+ assert dataloader.end_of_dataloader == (idx == 3)
+
+ # Test it also works on the second iteration
+ for idx, _ in enumerate(dataloader):
+ assert dataloader.end_of_dataloader == (idx == 3)
+
+ @require_torchdata_stateful_dataloader
+ def test_end_of_dataloader_dispatcher(self):
+ dataloader = DataLoaderDispatcher(range(16), batch_size=4, use_stateful_dataloader=True)
+ assert isinstance(dataloader, StatefulDataLoader)
+ for idx, _ in enumerate(dataloader):
+ assert dataloader.end_of_dataloader == (idx == 3)
+
+ # Test it also works on the second iteration
+ for idx, _ in enumerate(dataloader):
+ assert dataloader.end_of_dataloader == (idx == 3)
+
+ @parameterized.expand([0, 2], name_func=parameterized_custom_name_func)
+ @require_torchdata_stateful_dataloader
+ def test_dataloader_state_dict(self, num_workers):
+ """
+ Test that saving a stateful dataloader's state, then loading it back, gives the same results.
+ """
+ dataset = list(range(16))
+ dataloader = DataLoaderShard(dataset, batch_size=4, use_stateful_dataloader=True, num_workers=num_workers)
+
+ assert dataloader.use_stateful_dataloader
+ assert isinstance(dataloader, StatefulDataLoader)
+ vals = []
+ for idx, val in enumerate(dataloader):
+ vals.append(val)
+ if idx == 1:
+ sd = dataloader.state_dict()
+ assert len(vals) == 4
+
+ dataloader2 = DataLoaderShard(dataset, batch_size=4, use_stateful_dataloader=True, num_workers=num_workers)
+ dataloader2.load_state_dict(sd)
+
+ data1 = vals[2:]
+ data2 = list(dataloader2)
+ assert len(data1) == len(data2)
+ for d1, d2 in zip(data1, data2):
+ assert torch.allclose(d1, d2)
+
+ @parameterized.expand([0, 2], name_func=parameterized_custom_name_func)
+ @require_torchdata_stateful_dataloader
+ def test_dataloader_dispatcher_state_dict(self, num_workers):
+ """
+ Test that saving a stateful dataloader's state, then loading it back, gives the same results.
+ """
+ dataset = list(range(16))
+ dataloader = DataLoaderDispatcher(dataset, batch_size=4, use_stateful_dataloader=True, num_workers=num_workers)
+
+ assert dataloader.use_stateful_dataloader
+ assert isinstance(dataloader, StatefulDataLoader)
+ vals = []
+ for idx, val in enumerate(dataloader):
+ vals.append(val)
+ if idx == 1:
+ sd = dataloader.state_dict()
+ assert len(vals) == 4
+ dataloader2 = DataLoaderDispatcher(
+ dataset, batch_size=4, use_stateful_dataloader=True, num_workers=num_workers
+ )
+ dataloader2.load_state_dict(sd)
+
+ data1 = vals[2:]
+ data2 = list(dataloader2)
+ assert len(data1) == len(data2)
+ for d1, d2 in zip(data1, data2):
+ assert torch.allclose(d1, d2)
+
+ @require_torchdata_stateful_dataloader
+ def test_dataloader_inheritance(self):
+ """
+ `DataLoaderAdapter`'s parent classes are dynamically constructed, assert that if use_stateful_dataloader=True,
+ subclasses of DataLoaderAdapter are instances of StatefulDataLoader and DataLoaderStateMixin.
+ """
+ skip_dl = SkipDataLoader(range(16), batch_size=4, skip_batches=2, use_stateful_dataloader=True)
+ dl_shard = DataLoaderShard(range(16), batch_size=4, use_stateful_dataloader=True)
+ dl_dispatcher = DataLoaderDispatcher(range(16), batch_size=4, use_stateful_dataloader=True)
+
+ # Test dataloaders are instances of instantiated classes
+ # These asserts look redundant, but it's worth checking since we are doing magic tricks such as dynamically overriding __class__
+ assert isinstance(skip_dl, SkipDataLoader)
+ assert isinstance(dl_shard, DataLoaderShard)
+ assert isinstance(dl_dispatcher, DataLoaderDispatcher)
+
+ assert isinstance(skip_dl, StatefulDataLoader)
+ assert isinstance(dl_shard, StatefulDataLoader)
+ assert isinstance(dl_dispatcher, StatefulDataLoader)
+
+ assert isinstance(dl_shard, DataLoaderStateMixin)
+ assert isinstance(dl_dispatcher, DataLoaderStateMixin)
+
+ assert isinstance(skip_dl.base_dataloader, StatefulDataLoader)
+ assert isinstance(dl_shard.base_dataloader, StatefulDataLoader)
+ assert isinstance(dl_dispatcher.base_dataloader, StatefulDataLoader)
+
+ @parameterized.expand([0, 2], name_func=parameterized_custom_name_func)
+ @require_torchdata_stateful_dataloader
+ def test_stateful_dataloader_adapter_equivalent_to_torchdata_stateful_dataloader(self, num_workers):
+ """
+ Assert that `state_dict()` and `load_state_dict()` for derived subclasses of `DataLoaderAdapter` produce
+ the same behavior as `state_dict()` and `load_state_dict()` for `StatefulDataLoader`.
+ """
+ dataset = list(range(64))
+
+ # Set the seed for reproducibility
+ def g():
+ return torch.Generator().manual_seed(42)
+
+ accelerator = Accelerator()
+ stateful_dl = StatefulDataLoader(dataset, batch_size=4, num_workers=num_workers, generator=g())
+ skip_dl = SkipDataLoader(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+ dl_shard = DataLoaderShard(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+ dl_dispatcher = DataLoaderDispatcher(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+
+ dataloaders_under_test = [skip_dl, dl_shard, dl_dispatcher]
+
+ num_batches_to_skip = 8
+
+ def get_first_n_batches(dl, n, device):
+ """
+ Iterate over the first `n` batches of a dataloader then break, returning the batches in a list.
+ """
+ batches = []
+ for idx, batch in enumerate(dl):
+ if idx == n - 1:
+ if hasattr(dl, "end"):
+ dl.end()
+ break
+ batches.append(batch.to(device))
+ return batches
+
+ # Iterate over all of the dataloaders identically, expect the same values
+ expected_batches = get_first_n_batches(stateful_dl, num_batches_to_skip, accelerator.device)
+ batches_from_dataloaders = [
+ get_first_n_batches(dl, num_batches_to_skip, accelerator.device) for dl in dataloaders_under_test
+ ]
+
+ for dl_batches in batches_from_dataloaders:
+ for expected, actual in zip(expected_batches, dl_batches):
+ assert torch.allclose(expected, actual)
+
+ # The adapters should all produce the same state_dict as the reference stateful dataloader
+ expected_state_dict = stateful_dl.state_dict()
+ skip_dl_state_dict = skip_dl.state_dict()
+ dl_shard_state_dict = dl_shard.state_dict()
+ dl_dispatcher_state_dict = dl_dispatcher.state_dict()
+
+ assert expected_state_dict == skip_dl_state_dict
+ assert expected_state_dict == dl_shard_state_dict
+ assert expected_state_dict == dl_dispatcher_state_dict
+
+ # Load the state dict into new dataloaders
+ manual_skip_dl = SkipDataLoader(
+ dataset,
+ batch_size=4,
+ num_workers=num_workers,
+ generator=g(),
+ skip_batches=num_batches_to_skip,
+ use_stateful_dataloader=True,
+ )
+ loaded_stateful_dl = StatefulDataLoader(dataset, batch_size=4, num_workers=num_workers, generator=g())
+ loaded_stateful_dl.load_state_dict(expected_state_dict)
+ loaded_skip_dl = SkipDataLoader(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+ loaded_skip_dl.load_state_dict(expected_state_dict)
+ loaded_dl_shard = DataLoaderShard(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+ loaded_dl_shard.load_state_dict(expected_state_dict)
+ loaded_dl_dispatcher = DataLoaderDispatcher(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+ loaded_dl_dispatcher.load_state_dict(expected_state_dict)
+
+ # Continue the iteration, expecting identical behavior across the board
+ def get_all_batches(dl, device):
+ """
+ Iterate over all batches of a dataloader, returning (batches, num_batches_yielded)
+ """
+ batches = []
+ num_batches_yielded = 0
+ for batch in dl:
+ batches.append(batch.to(device))
+ num_batches_yielded += 1
+ return (batches, num_batches_yielded)
+
+ expected_batch_results = get_all_batches(loaded_stateful_dl, accelerator.device)
+ dataloader_batch_results = [
+ get_all_batches(dl, accelerator.device)
+ for dl in [manual_skip_dl, loaded_skip_dl, loaded_dl_shard, loaded_dl_dispatcher]
+ ]
+ for dl_results in dataloader_batch_results:
+ for expected, actual in zip(expected_batches, dl_batches):
+ assert torch.allclose(expected[0], actual[0])
+ assert expected_batch_results[1] == dl_results[1]
+
+ assert accelerator.gradient_state.active_dataloader is None
+
+ @parameterized.expand([0, 2], name_func=parameterized_custom_name_func)
+ @require_torchdata_stateful_dataloader
+ def test_decoupled_stateful_dataloader_adapter_equivalent_to_torchdata_stateful_dataloader(self, num_workers):
+ """
+ Assert that `state_dict()` and `load_state_dict()` for derived subclasses of `DataLoaderAdapter` produce
+ the same behavior as `state_dict()` and `load_state_dict()` for `StatefulDataLoader` when *not* using
+ Accelerator (and instead using the decoupled `PartialState` workflow).
+ """
+ dataset = list(range(64))
+
+ # Set the seed for reproducibility
+ def g():
+ return torch.Generator().manual_seed(42)
+
+ state = PartialState()
+ stateful_dl = StatefulDataLoader(dataset, batch_size=4, num_workers=num_workers, generator=g())
+ skip_dl = SkipDataLoader(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+ dl_shard = DataLoaderShard(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+ dl_dispatcher = DataLoaderDispatcher(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+
+ dataloaders_under_test = [skip_dl, dl_shard, dl_dispatcher]
+
+ num_batches_to_skip = 8
+
+ def get_first_n_batches(dl, n, device):
+ """
+ Iterate over the first `n` batches of a dataloader then break, returning the batches in a list.
+ """
+ batches = []
+ for idx, batch in enumerate(dl):
+ if idx == n - 1:
+ if hasattr(dl, "end"):
+ dl.end()
+ break
+ batches.append(batch.to(device))
+ return batches
+
+ # Iterate over all of the dataloaders identically, expect the same values
+ expected_batches = get_first_n_batches(stateful_dl, num_batches_to_skip, state.device)
+ batches_from_dataloaders = [
+ get_first_n_batches(dl, num_batches_to_skip, state.device) for dl in dataloaders_under_test
+ ]
+
+ for dl_batches in batches_from_dataloaders:
+ for expected, actual in zip(expected_batches, dl_batches):
+ assert torch.allclose(expected, actual)
+
+ # The adapters should all produce the same state_dict as the reference stateful dataloader
+ expected_state_dict = stateful_dl.state_dict()
+ skip_dl_state_dict = skip_dl.state_dict()
+ dl_shard_state_dict = dl_shard.state_dict()
+ dl_dispatcher_state_dict = dl_dispatcher.state_dict()
+
+ assert expected_state_dict == skip_dl_state_dict
+ assert expected_state_dict == dl_shard_state_dict
+ assert expected_state_dict == dl_dispatcher_state_dict
+
+ # Load the state dict into new dataloaders
+ manual_skip_dl = SkipDataLoader(
+ dataset,
+ batch_size=4,
+ num_workers=num_workers,
+ generator=g(),
+ skip_batches=num_batches_to_skip,
+ use_stateful_dataloader=True,
+ )
+ loaded_stateful_dl = StatefulDataLoader(dataset, batch_size=4, num_workers=num_workers, generator=g())
+ loaded_stateful_dl.load_state_dict(expected_state_dict)
+ loaded_skip_dl = SkipDataLoader(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+ loaded_skip_dl.load_state_dict(expected_state_dict)
+ loaded_dl_shard = DataLoaderShard(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+ loaded_dl_shard.load_state_dict(expected_state_dict)
+ loaded_dl_dispatcher = DataLoaderDispatcher(
+ dataset, batch_size=4, num_workers=num_workers, generator=g(), use_stateful_dataloader=True
+ )
+ loaded_dl_dispatcher.load_state_dict(expected_state_dict)
+
+ # Continue the iteration, expecting identical behavior across the board
+ def get_all_batches(dl, device):
+ """
+ Iterate over all batches of a dataloader, returning (batches, num_batches_yielded)
+ """
+ batches = []
+ num_batches_yielded = 0
+ for batch in dl:
+ batches.append(batch.to(device))
+ num_batches_yielded += 1
+ return (batches, num_batches_yielded)
+
+ expected_batch_results = get_all_batches(loaded_stateful_dl, state.device)
+ dataloader_batch_results = [
+ get_all_batches(dl, state.device)
+ for dl in [manual_skip_dl, loaded_skip_dl, loaded_dl_shard, loaded_dl_dispatcher]
+ ]
+ for dl_results in dataloader_batch_results:
+ for expected, actual in zip(expected_batches, dl_batches):
+ assert torch.allclose(expected[0], actual[0])
+ assert expected_batch_results[1] == dl_results[1]
+
+ # Using the decoupled (`PartialState`) workflow, GradientState should be automatically initialized (with
+ # default parameters) by `DataLoaderDispatcher`
+ assert GradientState._shared_state != {}, "GradientState should already be initialized!"
+
+ gradient_state = GradientState()
+ assert gradient_state.active_dataloader is None
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_examples.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_examples.py
new file mode 100644
index 0000000000000000000000000000000000000000..a16dce52f92a79efb66fff70d5ff768edea8eb4c
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_examples.py
@@ -0,0 +1,290 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import ast
+import os
+import re
+import shutil
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock, skip
+
+import torch
+
+from accelerate.test_utils.examples import compare_against_test
+from accelerate.test_utils.testing import (
+ TempDirTestCase,
+ get_launch_command,
+ require_huggingface_suite,
+ require_multi_device,
+ require_multi_gpu,
+ require_non_xpu,
+ require_pippy,
+ require_schedulefree,
+ require_trackers,
+ run_command,
+ slow,
+)
+from accelerate.utils import write_basic_config
+
+
+# DataLoaders built from `test_samples/MRPC` for quick testing
+# Should mock `{script_name}.get_dataloaders` via:
+# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)
+
+EXCLUDE_EXAMPLES = [
+ "cross_validation.py",
+ "checkpointing.py",
+ "gradient_accumulation.py",
+ "local_sgd.py",
+ "multi_process_metrics.py",
+ "memory.py",
+ "schedule_free.py",
+ "tracking.py",
+ "automatic_gradient_accumulation.py",
+ "fsdp_with_peak_mem_tracking.py",
+ "deepspeed_with_config_support.py",
+ "megatron_lm_gpt_pretraining.py",
+ "early_stopping.py",
+ "ddp_comm_hook.py",
+ "profiler.py",
+]
+
+
+class ExampleDifferenceTests(unittest.TestCase):
+ """
+ This TestCase checks that all of the `complete_*` scripts contain all of the
+ information found in the `by_feature` scripts, line for line. If one fails,
+ then a complete example does not contain all of the features in the features
+ scripts, and should be updated.
+
+ Each example script should be a single test (such as `test_nlp_example`),
+ and should run `one_complete_example` twice: once with `parser_only=True`,
+ and the other with `parser_only=False`. This is so that when the test
+ failures are returned to the user, they understand if the discrepancy lies in
+ the `main` function, or the `training_loop` function. Otherwise it will be
+ unclear.
+
+ Also, if there are any expected differences between the base script used and
+ `complete_nlp_example.py` (the canonical base script), these should be included in
+ `special_strings`. These would be differences in how something is logged, print statements,
+ etc (such as calls to `Accelerate.log()`)
+ """
+
+ by_feature_path = Path("examples", "by_feature").resolve()
+ examples_path = Path("examples").resolve()
+
+ def one_complete_example(
+ self, complete_file_name: str, parser_only: bool, secondary_filename: str = None, special_strings: list = None
+ ):
+ """
+ Tests a single `complete` example against all of the implemented `by_feature` scripts
+
+ Args:
+ complete_file_name (`str`):
+ The filename of a complete example
+ parser_only (`bool`):
+ Whether to look at the main training function, or the argument parser
+ secondary_filename (`str`, *optional*):
+ A potential secondary base file to strip all script information not relevant for checking,
+ such as "cv_example.py" when testing "complete_cv_example.py"
+ special_strings (`list`, *optional*):
+ A list of strings to potentially remove before checking no differences are left. These should be
+ diffs that are file specific, such as different logging variations between files.
+ """
+ self.maxDiff = None
+ for item in os.listdir(self.by_feature_path):
+ if item not in EXCLUDE_EXAMPLES:
+ item_path = self.by_feature_path / item
+ if item_path.is_file() and item_path.suffix == ".py":
+ with self.subTest(
+ tested_script=complete_file_name,
+ feature_script=item,
+ tested_section="main()" if parser_only else "training_function()",
+ ):
+ diff = compare_against_test(
+ self.examples_path / complete_file_name, item_path, parser_only, secondary_filename
+ )
+ diff = "\n".join(diff)
+ if special_strings is not None:
+ for string in special_strings:
+ diff = diff.replace(string, "")
+ assert diff == ""
+
+ def test_nlp_examples(self):
+ self.one_complete_example("complete_nlp_example.py", True)
+ self.one_complete_example("complete_nlp_example.py", False)
+
+ def test_cv_examples(self):
+ cv_path = (self.examples_path / "cv_example.py").resolve()
+ special_strings = [
+ " " * 16 + "{\n\n",
+ " " * 20 + '"accuracy": eval_metric["accuracy"],\n\n',
+ " " * 20 + '"f1": eval_metric["f1"],\n\n',
+ " " * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n',
+ " " * 20 + '"epoch": epoch,\n\n',
+ " " * 16 + "},\n\n",
+ " " * 16 + "step=epoch,\n",
+ " " * 12,
+ " " * 8 + "for step, batch in enumerate(active_dataloader):\n",
+ ]
+ self.one_complete_example("complete_cv_example.py", True, cv_path, special_strings)
+ self.one_complete_example("complete_cv_example.py", False, cv_path, special_strings)
+
+
+@mock.patch.dict(os.environ, {"TESTING_MOCKED_DATALOADERS": "1"})
+@require_huggingface_suite
+class FeatureExamplesTests(TempDirTestCase):
+ clear_on_setup = False
+
+ @classmethod
+ def setUpClass(cls):
+ super().setUpClass()
+ cls._tmpdir = tempfile.mkdtemp()
+ cls.config_file = Path(cls._tmpdir) / "default_config.yml"
+
+ write_basic_config(save_location=cls.config_file)
+ cls.launch_args = get_launch_command(config_file=cls.config_file)
+
+ @classmethod
+ def tearDownClass(cls):
+ super().tearDownClass()
+ shutil.rmtree(cls._tmpdir)
+
+ def test_checkpointing_by_epoch(self):
+ testargs = f"""
+ examples/by_feature/checkpointing.py
+ --checkpointing_steps epoch
+ --output_dir {self.tmpdir}
+ """.split()
+ run_command(self.launch_args + testargs)
+ assert (self.tmpdir / "epoch_0").exists()
+
+ def test_checkpointing_by_steps(self):
+ testargs = f"""
+ examples/by_feature/checkpointing.py
+ --checkpointing_steps 1
+ --output_dir {self.tmpdir}
+ """.split()
+ _ = run_command(self.launch_args + testargs)
+ assert (self.tmpdir / "step_2").exists()
+
+ def test_load_states_by_epoch(self):
+ testargs = f"""
+ examples/by_feature/checkpointing.py
+ --resume_from_checkpoint {self.tmpdir / "epoch_0"}
+ """.split()
+ output = run_command(self.launch_args + testargs, return_stdout=True)
+ assert "epoch 0:" not in output
+ assert "epoch 1:" in output
+
+ def test_load_states_by_steps(self):
+ testargs = f"""
+ examples/by_feature/checkpointing.py
+ --resume_from_checkpoint {self.tmpdir / "step_2"}
+ """.split()
+ output = run_command(self.launch_args + testargs, return_stdout=True)
+ if torch.cuda.is_available():
+ num_processes = torch.cuda.device_count()
+ else:
+ num_processes = 1
+ if num_processes > 1:
+ assert "epoch 0:" not in output
+ assert "epoch 1:" in output
+ else:
+ assert "epoch 0:" in output
+ assert "epoch 1:" in output
+
+ @slow
+ def test_cross_validation(self):
+ testargs = """
+ examples/by_feature/cross_validation.py
+ --num_folds 2
+ """.split()
+ with mock.patch.dict(os.environ, {"TESTING_MOCKED_DATALOADERS": "0"}):
+ output = run_command(self.launch_args + testargs, return_stdout=True)
+ results = re.findall("({.+})", output)
+ results = [r for r in results if "accuracy" in r][-1]
+ results = ast.literal_eval(results)
+ assert results["accuracy"] >= 0.75
+
+ def test_multi_process_metrics(self):
+ testargs = ["examples/by_feature/multi_process_metrics.py"]
+ run_command(self.launch_args + testargs)
+
+ @require_schedulefree
+ def test_schedulefree(self):
+ testargs = ["examples/by_feature/schedule_free.py"]
+ run_command(self.launch_args + testargs)
+
+ @require_trackers
+ @mock.patch.dict(os.environ, {"WANDB_MODE": "offline", "DVCLIVE_TEST": "true"})
+ def test_tracking(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ testargs = f"""
+ examples/by_feature/tracking.py
+ --with_tracking
+ --project_dir {tmpdir}
+ """.split()
+ run_command(self.launch_args + testargs)
+ assert os.path.exists(os.path.join(tmpdir, "tracking"))
+
+ def test_gradient_accumulation(self):
+ testargs = ["examples/by_feature/gradient_accumulation.py"]
+ run_command(self.launch_args + testargs)
+
+ def test_local_sgd(self):
+ testargs = ["examples/by_feature/local_sgd.py"]
+ run_command(self.launch_args + testargs)
+
+ def test_early_stopping(self):
+ testargs = ["examples/by_feature/early_stopping.py"]
+ run_command(self.launch_args + testargs)
+
+ def test_profiler(self):
+ testargs = ["examples/by_feature/profiler.py"]
+ run_command(self.launch_args + testargs)
+
+ @require_multi_device
+ def test_ddp_comm_hook(self):
+ testargs = ["examples/by_feature/ddp_comm_hook.py", "--ddp_comm_hook", "fp16"]
+ run_command(self.launch_args + testargs)
+
+ @skip(
+ reason="stable-diffusion-v1-5 is no longer available. Potentially `Comfy-Org/stable-diffusion-v1-5-archive` once diffusers support is added."
+ )
+ @require_multi_device
+ def test_distributed_inference_examples_stable_diffusion(self):
+ testargs = ["examples/inference/distributed/stable_diffusion.py"]
+ run_command(self.launch_args + testargs)
+
+ @require_multi_device
+ def test_distributed_inference_examples_phi2(self):
+ testargs = ["examples/inference/distributed/phi2.py"]
+ run_command(self.launch_args + testargs)
+
+ @require_non_xpu
+ @require_pippy
+ @require_multi_gpu
+ def test_pippy_examples_bert(self):
+ testargs = ["examples/inference/pippy/bert.py"]
+ run_command(self.launch_args + testargs)
+
+ @require_non_xpu
+ @require_pippy
+ @require_multi_gpu
+ def test_pippy_examples_gpt2(self):
+ testargs = ["examples/inference/pippy/gpt2.py"]
+ run_command(self.launch_args + testargs)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_grad_sync.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_grad_sync.py
new file mode 100644
index 0000000000000000000000000000000000000000..26b00333c699f2f8271e5832913681b217c2b5ea
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_grad_sync.py
@@ -0,0 +1,51 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+
+from accelerate import debug_launcher
+from accelerate.test_utils import (
+ DEFAULT_LAUNCH_COMMAND,
+ device_count,
+ execute_subprocess_async,
+ path_in_accelerate_package,
+ require_cpu,
+ require_multi_device,
+ require_non_cpu,
+ test_sync,
+)
+from accelerate.utils import patch_environment
+
+
+class SyncScheduler(unittest.TestCase):
+ test_file_path = path_in_accelerate_package("test_utils", "scripts", "test_sync.py")
+
+ @require_cpu
+ def test_gradient_sync_cpu_noop(self):
+ debug_launcher(test_sync.main, num_processes=1)
+
+ @require_cpu
+ def test_gradient_sync_cpu_multi(self):
+ debug_launcher(test_sync.main)
+
+ @require_non_cpu
+ def test_gradient_sync_gpu(self):
+ test_sync.main()
+
+ @require_multi_device
+ def test_gradient_sync_gpu_multi(self):
+ print(f"Found {device_count} devices.")
+ cmd = DEFAULT_LAUNCH_COMMAND + [self.test_file_path]
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_hooks.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..13e83b7d9a7e245d8cc4f5ce0a1aba0e69ad78de
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_hooks.py
@@ -0,0 +1,401 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import inspect
+import unittest
+
+import torch
+import torch.nn as nn
+from torch.fx import symbolic_trace
+
+from accelerate.hooks import (
+ AlignDevicesHook,
+ ModelHook,
+ SequentialHook,
+ add_hook_to_module,
+ attach_align_device_hook,
+ remove_hook_from_module,
+ remove_hook_from_submodules,
+)
+from accelerate.test_utils import require_multi_device, torch_device
+
+
+torch_device = f"{torch_device}:0" if torch_device != "cpu" else "cpu"
+
+
+class ModelForTest(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = nn.Linear(3, 4)
+ self.batchnorm = nn.BatchNorm1d(4)
+ self.linear2 = nn.Linear(4, 5)
+
+ def forward(self, x):
+ return self.linear2(self.batchnorm(self.linear1(x)))
+
+
+class PreForwardHook(ModelHook):
+ def pre_forward(self, module, *args, **kwargs):
+ return (args[0] + 1,) + args[1:], kwargs
+
+
+class PostForwardHook(ModelHook):
+ def post_forward(self, module, output):
+ return output + 1
+
+
+class HooksModelTester(unittest.TestCase):
+ def test_add_and_remove_hooks(self):
+ test_model = ModelForTest()
+ test_hook = ModelHook()
+
+ add_hook_to_module(test_model, test_hook)
+ assert test_model._hf_hook == test_hook
+ assert hasattr(test_model, "_old_forward")
+
+ # Check adding the hook did not change the name or the signature
+ assert test_model.forward.__name__ == "forward"
+ assert list(inspect.signature(test_model.forward).parameters) == ["x"]
+
+ remove_hook_from_module(test_model)
+ assert not hasattr(test_model, "_hf_hook")
+ assert not hasattr(test_model, "_old_forward")
+
+ def test_append_and_remove_hooks(self):
+ test_model = ModelForTest()
+ test_hook = ModelHook()
+
+ add_hook_to_module(test_model, test_hook)
+ add_hook_to_module(test_model, test_hook, append=True)
+
+ assert isinstance(test_model._hf_hook, SequentialHook) is True
+ assert len(test_model._hf_hook.hooks) == 2
+ assert hasattr(test_model, "_old_forward")
+
+ # Check adding the hook did not change the name or the signature
+ assert test_model.forward.__name__ == "forward"
+ assert list(inspect.signature(test_model.forward).parameters) == ["x"]
+
+ remove_hook_from_module(test_model)
+ assert not hasattr(test_model, "_hf_hook")
+ assert not hasattr(test_model, "_old_forward")
+
+ def test_pre_forward_hook_is_executed(self):
+ test_model = ModelForTest()
+ x = torch.randn(2, 3)
+ expected = test_model(x + 1)
+ expected2 = test_model(x + 2)
+
+ test_hook = PreForwardHook()
+ add_hook_to_module(test_model, test_hook)
+ output1 = test_model(x)
+ assert torch.allclose(output1, expected, atol=1e-5)
+
+ # Attaching a hook to a model when it already has one replaces, does not chain
+ test_hook = PreForwardHook()
+ add_hook_to_module(test_model, test_hook)
+ output1 = test_model(x)
+ assert torch.allclose(output1, expected, atol=1e-5)
+
+ # You need to use the sequential hook to chain two or more hooks
+ test_hook = SequentialHook(PreForwardHook(), PreForwardHook())
+ add_hook_to_module(test_model, test_hook)
+
+ output2 = test_model(x)
+ assert torch.allclose(output2, expected2, atol=1e-5)
+
+ def test_post_forward_hook_is_executed(self):
+ test_model = ModelForTest()
+ x = torch.randn(2, 3)
+ output = test_model(x)
+
+ test_hook = PostForwardHook()
+ add_hook_to_module(test_model, test_hook)
+ output1 = test_model(x)
+ assert torch.allclose(output1, (output + 1), atol=1e-5)
+
+ # Attaching a hook to a model when it already has one replaces, does not chain
+ test_hook = PostForwardHook()
+ add_hook_to_module(test_model, test_hook)
+ output1 = test_model(x)
+ assert torch.allclose(output1, (output + 1), atol=1e-5)
+
+ # You need to use the sequential hook to chain two or more hooks
+ test_hook = SequentialHook(PostForwardHook(), PostForwardHook())
+ add_hook_to_module(test_model, test_hook)
+
+ output2 = test_model(x)
+ assert torch.allclose(output2, output + 2, atol=1e-5)
+
+ def test_no_grad_in_hook(self):
+ test_model = ModelForTest()
+ x = torch.randn(2, 3)
+ output = test_model(x)
+
+ test_hook = PostForwardHook()
+ add_hook_to_module(test_model, test_hook)
+ output1 = test_model(x)
+ assert torch.allclose(output1, (output + 1))
+ assert output1.requires_grad
+
+ test_hook.no_grad = True
+ output1 = test_model(x)
+ assert not output1.requires_grad
+
+ @require_multi_device
+ def test_align_devices_as_model_parallelism(self):
+ model = ModelForTest()
+ # Everything is on CPU
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ # This will move each submodule on different devices
+ add_hook_to_module(model.linear1, AlignDevicesHook(execution_device=0))
+ add_hook_to_module(model.batchnorm, AlignDevicesHook(execution_device=0))
+ add_hook_to_module(model.linear2, AlignDevicesHook(execution_device=1))
+
+ assert model.linear1.weight.device == torch.device(torch_device)
+ assert model.batchnorm.weight.device == torch.device(torch_device)
+ assert model.batchnorm.running_mean.device == torch.device(torch_device)
+ assert model.linear2.weight.device == torch.device(torch_device.replace(":0", ":1"))
+
+ # We can still make a forward pass. The input does not need to be on any particular device
+ x = torch.randn(2, 3)
+ output = model(x)
+ assert output.device == torch.device(torch_device.replace(":0", ":1"))
+
+ # We can add a general hook to put back output on same device as input.
+ add_hook_to_module(model, AlignDevicesHook(io_same_device=True))
+ x = torch.randn(2, 3).to(torch_device)
+ output = model(x)
+ assert output.device == torch.device(torch_device)
+
+ def test_align_devices_as_cpu_offload(self):
+ model = ModelForTest()
+
+ # Everything is on CPU
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ # This will move each submodule on different devices
+ hook_kwargs = {"execution_device": torch_device, "offload": True}
+
+ add_hook_to_module(model.linear1, AlignDevicesHook(**hook_kwargs))
+ add_hook_to_module(model.batchnorm, AlignDevicesHook(**hook_kwargs))
+ add_hook_to_module(model.linear2, AlignDevicesHook(**hook_kwargs))
+
+ # Parameters have been offloaded, so on the meta device
+ assert model.linear1.weight.device == torch.device("meta")
+ assert model.batchnorm.weight.device == torch.device("meta")
+ assert model.linear2.weight.device == torch.device("meta")
+ # Buffers are not included in the offload by default, so are on the execution device
+ device = torch.device(hook_kwargs["execution_device"])
+ assert model.batchnorm.running_mean.device == device
+
+ x = torch.randn(2, 3)
+ output = model(x)
+ assert output.device == device
+
+ # Removing hooks loads back the weights in the model.
+ remove_hook_from_module(model.linear1)
+ remove_hook_from_module(model.batchnorm)
+ remove_hook_from_module(model.linear2)
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ # Now test with buffers included in the offload
+ hook_kwargs = {
+ "execution_device": torch_device,
+ "offload": True,
+ "offload_buffers": True,
+ }
+
+ add_hook_to_module(model.linear1, AlignDevicesHook(**hook_kwargs))
+ add_hook_to_module(model.batchnorm, AlignDevicesHook(**hook_kwargs))
+ add_hook_to_module(model.linear2, AlignDevicesHook(**hook_kwargs))
+
+ # Parameters have been offloaded, so on the meta device, buffers included
+ assert model.linear1.weight.device == torch.device("meta")
+ assert model.batchnorm.weight.device == torch.device("meta")
+ assert model.linear2.weight.device == torch.device("meta")
+ assert model.batchnorm.running_mean.device == torch.device("meta")
+
+ x = torch.randn(2, 3)
+ output = model(x)
+ assert output.device == device
+
+ # Removing hooks loads back the weights in the model.
+ remove_hook_from_module(model.linear1)
+ remove_hook_from_module(model.batchnorm)
+ remove_hook_from_module(model.linear2)
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ def test_attach_align_device_hook_as_cpu_offload(self):
+ model = ModelForTest()
+
+ # Everything is on CPU
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ # This will move each submodule on different devices
+ execution_device = torch_device
+ attach_align_device_hook(model, execution_device=execution_device, offload=True)
+
+ # Parameters have been offloaded, so on the meta device
+ assert model.linear1.weight.device == torch.device("meta")
+ assert model.batchnorm.weight.device == torch.device("meta")
+ assert model.linear2.weight.device == torch.device("meta")
+ # Buffers are not included in the offload by default, so are on the execution device
+ device = torch.device(execution_device)
+ assert model.batchnorm.running_mean.device == device
+
+ x = torch.randn(2, 3)
+ output = model(x)
+ assert output.device == device
+
+ # Removing hooks loads back the weights in the model.
+ remove_hook_from_submodules(model)
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ # Now test with buffers included in the offload
+ attach_align_device_hook(model, execution_device=execution_device, offload=True, offload_buffers=True)
+
+ # Parameters have been offloaded, so on the meta device, buffers included
+ assert model.linear1.weight.device == torch.device("meta")
+ assert model.batchnorm.weight.device == torch.device("meta")
+ assert model.linear2.weight.device == torch.device("meta")
+ assert model.batchnorm.running_mean.device == torch.device("meta")
+
+ x = torch.randn(2, 3)
+ output = model(x)
+ assert output.device == device
+
+ # Removing hooks loads back the weights in the model.
+ remove_hook_from_submodules(model)
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ def test_attach_align_device_hook_as_cpu_offload_with_weight_map(self):
+ model = ModelForTest()
+
+ # Everything is on CPU
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ # This will move each submodule on different devices
+ execution_device = torch_device
+ attach_align_device_hook(
+ model, execution_device=execution_device, offload=True, weights_map=model.state_dict()
+ )
+
+ # Parameters have been offloaded, so on the meta device
+ assert model.linear1.weight.device == torch.device("meta")
+ assert model.batchnorm.weight.device == torch.device("meta")
+ assert model.linear2.weight.device == torch.device("meta")
+ # Buffers are not included in the offload by default, so are on the execution device
+ device = torch.device(execution_device)
+ assert model.batchnorm.running_mean.device == device
+
+ x = torch.randn(2, 3)
+ output = model(x)
+ assert output.device == device
+
+ # Removing hooks loads back the weights in the model.
+ remove_hook_from_submodules(model)
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ # Now test with buffers included in the offload
+ attach_align_device_hook(
+ model,
+ execution_device=execution_device,
+ offload=True,
+ weights_map=model.state_dict(),
+ offload_buffers=True,
+ )
+
+ # Parameters have been offloaded, so on the meta device, buffers included
+ assert model.linear1.weight.device == torch.device("meta")
+ assert model.batchnorm.weight.device == torch.device("meta")
+ assert model.linear2.weight.device == torch.device("meta")
+ assert model.batchnorm.running_mean.device == torch.device("meta")
+
+ x = torch.randn(2, 3)
+ output = model(x)
+ assert output.device == device
+
+ # Removing hooks loads back the weights in the model.
+ remove_hook_from_submodules(model)
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ def test_add_remove_hook_fx_graph_module(self):
+ with torch.no_grad():
+ test_model = ModelForTest()
+ test_hook = ModelHook()
+
+ x = torch.randn(2, 3)
+ output1 = test_model(x)
+
+ graph_model = symbolic_trace(test_model)
+
+ output2 = graph_model(x)
+
+ assert torch.allclose(output1, output2)
+
+ add_hook_to_module(graph_model, test_hook)
+ remove_hook_from_module(graph_model, recurse=True)
+
+ # We want to make sure that `add_hook_to_module` and `remove_hook_from_module` yields back an fx.GraphModule
+ # that behaves correctly (for example that is not frozen, see https://github.com/huggingface/accelerate/pull/2369).
+ # For that, we add a sigmoid node to the FX graph and make sure that the new output (output3 below) is different than
+ # the original model's output.
+ linear2_node = None
+ for node in graph_model.graph.nodes:
+ if node.name == "linear2":
+ linear2_node = node
+ assert linear2_node is not None
+
+ graph_model.graph.inserting_after(linear2_node)
+ new_node = graph_model.graph.create_node(
+ op="call_function", target=torch.sigmoid, args=(linear2_node,), name="relu"
+ )
+
+ output_node = None
+ for node in graph_model.graph.nodes:
+ if node.name == "output":
+ output_node = node
+ assert output_node is not None
+
+ output_node.replace_input_with(linear2_node, new_node)
+
+ graph_model.graph.lint()
+ graph_model.recompile()
+
+ output3 = graph_model(x)
+
+ # Now the output is expected to be different since we modified the graph.
+ assert not torch.allclose(output1, output3)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_imports.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_imports.py
new file mode 100644
index 0000000000000000000000000000000000000000..57e49dcd9a275ff7130c62aba4191512d3ead67d
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_imports.py
@@ -0,0 +1,100 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import subprocess
+import sys
+
+from accelerate.test_utils import require_transformer_engine
+from accelerate.test_utils.testing import TempDirTestCase, require_import_timer
+from accelerate.utils import is_import_timer_available
+
+
+if is_import_timer_available():
+ from import_timer import calculate_total_time, read_import_profile
+ from import_timer.core import get_paths_above_threshold, sort_nodes_by_total_time
+
+
+def convert_list_to_string(data):
+ end_result = ""
+ arrow_right = "->"
+ for path in data:
+ end_result += f"{arrow_right.join(path[0])} {path[1]:.3f}s\n"
+ return end_result
+
+
+def run_import_time(command: str):
+ output = subprocess.run([sys.executable, "-X", "importtime", "-c", command], capture_output=True, text=True)
+ return output.stderr
+
+
+@require_import_timer
+class ImportSpeedTester(TempDirTestCase):
+ """
+ Test suite which checks if imports have seen slowdowns
+ based on a particular baseline.
+
+ If the error messages are not clear enough to get a
+ full view of what is slowing things down (or to
+ figure out how deep the initial depth should be),
+ please view the profile with the `tuna` framework:
+ `tuna import.log`.
+ """
+
+ clear_on_setup = False
+
+ @classmethod
+ def setUpClass(cls):
+ super().setUpClass()
+ output = run_import_time("import torch")
+ data = read_import_profile(output)
+ total_time = calculate_total_time(data)
+ cls.pytorch_time = total_time
+
+ def test_base_import(self):
+ output = run_import_time("import accelerate")
+ data = read_import_profile(output)
+ total_time = calculate_total_time(data)
+ pct_more = (total_time - self.pytorch_time) / self.pytorch_time * 100
+ # Base import should never be more than 20% slower than raw torch import
+ err_msg = f"Base import is more than 20% slower than raw torch import ({pct_more:.2f}%), please check the attached `tuna` profile:\n"
+ sorted_data = sort_nodes_by_total_time(data)
+ paths_above_threshold = get_paths_above_threshold(sorted_data, 0.05, max_depth=7)
+ err_msg += f"\n{convert_list_to_string(paths_above_threshold)}"
+ self.assertLess(pct_more, 20, err_msg)
+
+ def test_cli_import(self):
+ output = run_import_time("from accelerate.commands.launch import launch_command_parser")
+ data = read_import_profile(output)
+ total_time = calculate_total_time(data)
+ pct_more = (total_time - self.pytorch_time) / self.pytorch_time * 100
+ # Base import should never be more than 20% slower than raw torch import
+ err_msg = f"Base import is more than 20% slower than raw torch import ({pct_more:.2f}%), please check the attached `tuna` profile:\n"
+ sorted_data = sort_nodes_by_total_time(data)
+ paths_above_threshold = get_paths_above_threshold(sorted_data, 0.05, max_depth=7)
+ err_msg += f"\n{convert_list_to_string(paths_above_threshold)}"
+ self.assertLess(pct_more, 20, err_msg)
+
+
+@require_transformer_engine
+class LazyImportTester(TempDirTestCase):
+ """
+ Test suite which checks if specific packages are lazy-loaded.
+
+ Eager-import will trigger circular import in some case,
+ e.g. in huggingface/accelerate#3056.
+ """
+
+ def test_te_import(self):
+ output = run_import_time("import accelerate, accelerate.utils.transformer_engine")
+
+ self.assertFalse(" transformer_engine" in output, "`transformer_engine` should not be imported on import")
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_kwargs_handlers.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_kwargs_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf8bd1bd9392bfd89b55bb8cc754a998ea8999d8
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_kwargs_handlers.py
@@ -0,0 +1,197 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import inspect
+import os
+import unittest
+from dataclasses import dataclass
+
+import torch
+
+from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs
+from accelerate.state import AcceleratorState
+from accelerate.test_utils import (
+ DEFAULT_LAUNCH_COMMAND,
+ execute_subprocess_async,
+ path_in_accelerate_package,
+ require_multi_device,
+ require_non_cpu,
+ require_non_xpu,
+)
+from accelerate.test_utils.testing import slow
+from accelerate.utils import AutocastKwargs, KwargsHandler, ProfileKwargs, TorchDynamoPlugin, clear_environment
+from accelerate.utils.dataclasses import DistributedType
+
+
+@dataclass
+class MockClass(KwargsHandler):
+ a: int = 0
+ b: bool = False
+ c: float = 3.0
+
+
+class KwargsHandlerTester(unittest.TestCase):
+ def test_kwargs_handler(self):
+ # If no defaults are changed, `to_kwargs` returns an empty dict.
+ assert MockClass().to_kwargs() == {}
+ assert MockClass(a=2).to_kwargs() == {"a": 2}
+ assert MockClass(a=2, b=True).to_kwargs() == {"a": 2, "b": True}
+ assert MockClass(a=2, c=2.25).to_kwargs() == {"a": 2, "c": 2.25}
+
+ @require_non_cpu
+ @require_non_xpu
+ def test_grad_scaler_kwargs(self):
+ # If no defaults are changed, `to_kwargs` returns an empty dict.
+ scaler_handler = GradScalerKwargs(init_scale=1024, growth_factor=2)
+ AcceleratorState._reset_state()
+ accelerator = Accelerator(mixed_precision="fp16", kwargs_handlers=[scaler_handler])
+ assert accelerator.mixed_precision == "fp16"
+ scaler = accelerator.scaler
+
+ # Check the kwargs have been applied
+ assert scaler._init_scale == 1024.0
+ assert scaler._growth_factor == 2.0
+
+ # Check the other values are at the default
+ assert scaler._backoff_factor == 0.5
+ assert scaler._growth_interval == 2000
+ assert scaler._enabled is True
+
+ @require_multi_device
+ def test_ddp_kwargs(self):
+ cmd = DEFAULT_LAUNCH_COMMAND + [inspect.getfile(self.__class__)]
+ execute_subprocess_async(cmd)
+
+ @require_non_cpu
+ def test_autocast_kwargs(self):
+ kwargs = AutocastKwargs(enabled=False)
+ AcceleratorState._reset_state()
+ accelerator = Accelerator(mixed_precision="fp16")
+
+ a_float32 = torch.rand((8, 8), device=accelerator.device)
+ b_float32 = torch.rand((8, 8), device=accelerator.device)
+ c_float32 = torch.rand((8, 8), device=accelerator.device)
+ d_float32 = torch.rand((8, 8), device=accelerator.device)
+
+ with accelerator.autocast():
+ e_float16 = torch.mm(a_float32, b_float32)
+ assert e_float16.dtype == torch.float16
+
+ with accelerator.autocast(autocast_handler=kwargs):
+ # Convert e_float16 to float32
+ f_float32 = torch.mm(c_float32, e_float16.float())
+ assert f_float32.dtype == torch.float32
+
+ g_float16 = torch.mm(d_float32, f_float32)
+ # We should be back in fp16
+ assert g_float16.dtype == torch.float16
+
+ @slow
+ def test_profile_kwargs(self):
+ # Arrange
+ schedule_options = [
+ dict(wait=1, warmup=1, active=2, repeat=1),
+ dict(wait=2, warmup=2, active=2, repeat=2),
+ dict(wait=0, warmup=1, active=3, repeat=3, skip_first=1),
+ dict(wait=3, warmup=2, active=1, repeat=1, skip_first=2),
+ dict(wait=1, warmup=0, active=1, repeat=5),
+ ]
+
+ total_steps = 100
+
+ for option in schedule_options:
+ count = 0
+ table_outputs = []
+ steps_per_cycle = option["wait"] + option["warmup"] + option["active"]
+ effective_steps = max(0, total_steps - option.get("skip_first", 0))
+ cycles = effective_steps // steps_per_cycle
+ if option["repeat"] > 0:
+ expected_count = min(cycles, option["repeat"])
+ else:
+ expected_count = cycles
+
+ def on_trace_ready(prof):
+ nonlocal count
+ nonlocal table_outputs
+
+ count += 1
+ table_outputs.append(prof.key_averages().table(sort_by="cpu_time_total", row_limit=-1))
+
+ kwargs = ProfileKwargs(activities=["cpu"], on_trace_ready=on_trace_ready, schedule_option=option)
+ accelerator = Accelerator(kwargs_handlers=[kwargs])
+
+ # Act
+ with accelerator.profile() as prof:
+ for _ in range(total_steps):
+ prof.step()
+ torch.tensor([1, 2, 3, 4, 5], device=accelerator.device)
+
+ # Assert
+ assert isinstance(prof, torch.profiler.profile)
+ assert count == expected_count, f"Option: {option}, Expected count: {expected_count}, but got {count}"
+ for output in table_outputs:
+ self.assertIn("CPU time total:", output)
+
+ def test_torch_dynamo_plugin(self):
+ with clear_environment():
+ prefix = "ACCELERATE_DYNAMO_"
+ # nvfuser's dynamo backend name is "nvprims_nvfuser"
+ # use "nvfuser" here to cause exception if this test causes os.environ changed permanently
+ os.environ[prefix + "BACKEND"] = "aot_ts_nvfuser"
+ os.environ[prefix + "MODE"] = "reduce-overhead"
+
+ dynamo_plugin_kwargs = TorchDynamoPlugin().to_kwargs()
+ assert dynamo_plugin_kwargs == {"backend": "aot_ts_nvfuser", "mode": "reduce-overhead"}
+ assert os.environ.get(prefix + "BACKEND") != "aot_ts_nvfuser"
+
+ @require_multi_device
+ def test_ddp_comm_hook(self):
+ cmd = DEFAULT_LAUNCH_COMMAND + [path_in_accelerate_package("test_utils", "scripts", "test_ddp_comm_hook.py")]
+ execute_subprocess_async(cmd)
+
+
+def main():
+ ddp_scaler = DistributedDataParallelKwargs(bucket_cap_mb=15, find_unused_parameters=True)
+ accelerator = Accelerator(kwargs_handlers=[ddp_scaler])
+
+ # Skip this test due to TorchXLA not using torch.nn.parallel.DistributedDataParallel for model wrapping.
+ if accelerator.distributed_type == DistributedType.XLA:
+ return
+
+ model = torch.nn.Linear(100, 200)
+ model = accelerator.prepare(model)
+
+ # Check the values changed in kwargs
+ error_msg = ""
+ observed_bucket_cap_map = model.bucket_bytes_cap // (1024 * 1024)
+ if observed_bucket_cap_map != 15:
+ error_msg += f"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n"
+ if model.find_unused_parameters is not True:
+ error_msg += f"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n"
+
+ # Check the values of the defaults
+ if model.dim != 0:
+ error_msg += f"Default value not respected, should have `0` but found {model.dim}.\n"
+ if model.broadcast_buffers is not True:
+ error_msg += f"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n"
+ if model.gradient_as_bucket_view is not False:
+ error_msg += f"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n"
+
+ # Raise error at the end to make sure we don't stop at the first failure.
+ if len(error_msg) > 0:
+ raise ValueError(error_msg)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_logging.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..a91c609ddc058d86ff66be2f8a7d929111590f1d
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_logging.py
@@ -0,0 +1,91 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import inspect
+import logging
+import os
+
+import pytest
+
+from accelerate import Accelerator
+from accelerate.logging import get_logger
+
+
+def current_lineno() -> int:
+ # A simple helper that returns the lineno of its call-site.
+ caller_frame = inspect.currentframe().f_back
+ caller_info = inspect.getframeinfo(caller_frame)
+ return caller_info.lineno
+
+
+class CustomLogger(logging.LoggerAdapter):
+ # Mocks a user-defined custom logger wrapper that sets `stacklevel=3`.
+ def log(self, level, msg, *args, **kwargs):
+ # E.g. the user wants to modify `stacklevel`, `accelerate.logging`
+ # should respect the user's `stacklevel`. For the specific value
+ # of `3`, calling `CustomLogger.log()`, etc., should log that callsite,
+ # rather than the callsite of the following `self.logger.log()`.
+ kwargs["stacklevel"] = 3
+ self.logger.log(level, msg, *args, **kwargs)
+
+
+@pytest.fixture(scope="module")
+def accelerator():
+ return Accelerator()
+
+
+@pytest.mark.usefixtures("accelerator")
+def test_log_stack(caplog):
+ logger = get_logger(__name__)
+ logging.basicConfig(
+ format="%(filename)s:%(name)s:%(lineno)s:%(funcName)s - %(message)s",
+ datefmt="%m/%d %H:%M:%S",
+ )
+
+ message = "Test"
+ lineno = current_lineno() + 1 # the next line is the actual callsite
+ logger.warning(message)
+
+ assert len(caplog.records) == 1
+ rec = caplog.records[0]
+ assert rec.levelname == logging.getLevelName(logging.WARNING)
+ assert rec.filename == os.path.basename(__file__)
+ assert rec.name == __name__
+ assert rec.lineno == lineno
+ assert rec.funcName == test_log_stack.__name__
+ assert rec.message == message
+
+
+@pytest.mark.usefixtures("accelerator")
+def test_custom_stacklevel(caplog):
+ wrapped_logger = get_logger(__name__)
+ logging.basicConfig(
+ format="%(filename)s:%(name)s:%(lineno)s:%(funcName)s - %(message)s",
+ datefmt="%m/%d %H:%M:%S",
+ )
+ logger = CustomLogger(wrapped_logger, {})
+
+ message = "Test"
+ lineno = current_lineno() + 1 # the next line is the actual callsite
+ logger.warning(message)
+
+ # `CustomLogger.log` set custom `stacklevel=3`, so `logger.warning` should
+ # log its callsite (rather than those of the `warpped_logger`).
+ assert len(caplog.records) == 1
+ rec = caplog.records[0]
+ assert rec.levelname == logging.getLevelName(logging.WARNING)
+ assert rec.filename == os.path.basename(__file__)
+ assert rec.name == __name__
+ assert rec.lineno == lineno
+ assert rec.funcName == test_custom_stacklevel.__name__
+ assert rec.message == message
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_memory_utils.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_memory_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b8f74f19c0050cda9eb3616280735dc5114dd2f
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_memory_utils.py
@@ -0,0 +1,115 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+
+from torch import nn
+
+from accelerate.test_utils import memory_allocated_func, require_non_cpu, require_non_torch_xla, torch_device
+from accelerate.utils.memory import find_executable_batch_size, release_memory
+
+
+def raise_fake_out_of_memory():
+ raise RuntimeError("CUDA out of memory.")
+
+
+class ModelForTest(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = nn.Linear(3, 4)
+ self.batchnorm = nn.BatchNorm1d(4)
+ self.linear2 = nn.Linear(4, 5)
+
+ def forward(self, x):
+ return self.linear2(self.batchnorm(self.linear1(x)))
+
+
+class MemoryTest(unittest.TestCase):
+ def test_memory_implicit(self):
+ batch_sizes = []
+
+ @find_executable_batch_size(starting_batch_size=128)
+ def mock_training_loop_function(batch_size):
+ nonlocal batch_sizes
+ batch_sizes.append(batch_size)
+ if batch_size != 8:
+ raise_fake_out_of_memory()
+
+ mock_training_loop_function()
+ assert batch_sizes == [128, 64, 32, 16, 8]
+
+ def test_memory_explicit(self):
+ batch_sizes = []
+
+ @find_executable_batch_size(starting_batch_size=128)
+ def mock_training_loop_function(batch_size, arg1):
+ nonlocal batch_sizes
+ batch_sizes.append(batch_size)
+ if batch_size != 8:
+ raise_fake_out_of_memory()
+ return batch_size, arg1
+
+ bs, arg1 = mock_training_loop_function("hello")
+ assert batch_sizes == [128, 64, 32, 16, 8]
+ assert [bs, arg1] == [8, "hello"]
+
+ def test_start_zero(self):
+ @find_executable_batch_size(starting_batch_size=0)
+ def mock_training_loop_function(batch_size):
+ pass
+
+ with self.assertRaises(RuntimeError) as cm:
+ mock_training_loop_function()
+ assert "No executable batch size found, reached zero." in cm.exception.args[0]
+
+ def test_approach_zero(self):
+ @find_executable_batch_size(starting_batch_size=16)
+ def mock_training_loop_function(batch_size):
+ if batch_size > 0:
+ raise_fake_out_of_memory()
+ pass
+
+ with self.assertRaises(RuntimeError) as cm:
+ mock_training_loop_function()
+ assert "No executable batch size found, reached zero." in cm.exception.args[0]
+
+ def test_verbose_guard(self):
+ @find_executable_batch_size(starting_batch_size=128)
+ def mock_training_loop_function(batch_size, arg1, arg2):
+ if batch_size != 8:
+ raise raise_fake_out_of_memory()
+
+ with self.assertRaises(TypeError) as cm:
+ mock_training_loop_function(128, "hello", "world")
+ assert "Batch size was passed into `f`" in cm.exception.args[0]
+ assert "`f(arg1='hello', arg2='world')" in cm.exception.args[0]
+
+ def test_any_other_error(self):
+ @find_executable_batch_size(starting_batch_size=16)
+ def mock_training_loop_function(batch_size):
+ raise ValueError("Oops, we had an error!")
+
+ with self.assertRaises(ValueError) as cm:
+ mock_training_loop_function()
+ assert "Oops, we had an error!" in cm.exception.args[0]
+
+ @require_non_cpu
+ @require_non_torch_xla
+ def test_release_memory(self):
+ starting_memory = memory_allocated_func()
+ model = ModelForTest()
+ model.to(torch_device)
+ assert memory_allocated_func() > starting_memory
+ model = release_memory(model)
+ assert memory_allocated_func() == starting_memory
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_metrics.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..d953e2edee7de4e33baddc75df214f8ca96a64c2
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_metrics.py
@@ -0,0 +1,61 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+
+import numpy as np
+from packaging import version
+
+from accelerate import debug_launcher
+from accelerate.test_utils import (
+ DEFAULT_LAUNCH_COMMAND,
+ device_count,
+ execute_subprocess_async,
+ path_in_accelerate_package,
+ require_cpu,
+ require_huggingface_suite,
+ require_multi_device,
+ require_single_device,
+)
+from accelerate.utils import patch_environment
+
+
+@require_huggingface_suite
+@unittest.skipIf(version.parse(np.__version__) >= version.parse("2.0"), "Test requires numpy version < 2.0")
+class MetricTester(unittest.TestCase):
+ def setUp(self):
+ self.test_file_path = path_in_accelerate_package("test_utils", "scripts", "external_deps", "test_metrics.py")
+
+ from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401
+
+ self.test_metrics = test_metrics
+
+ @require_cpu
+ def test_metric_cpu_noop(self):
+ debug_launcher(self.test_metrics.main, num_processes=1)
+
+ @require_cpu
+ def test_metric_cpu_multi(self):
+ debug_launcher(self.test_metrics.main)
+
+ @require_single_device
+ def test_metric_accelerator(self):
+ self.test_metrics.main()
+
+ @require_multi_device
+ def test_metric_accelerator_multi(self):
+ print(f"Found {device_count} devices.")
+ cmd = DEFAULT_LAUNCH_COMMAND + [self.test_file_path]
+ with patch_environment(omp_num_threads=1, ACCELERATE_LOG_LEVEL="INFO"):
+ execute_subprocess_async(cmd)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_modeling_utils.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_modeling_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..50dd06cd61a04af54d1d82aedd32b694a2b2e862
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_modeling_utils.py
@@ -0,0 +1,787 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import os
+import tempfile
+import unittest
+import warnings
+from collections import OrderedDict
+from typing import Dict, Optional
+
+import torch
+import torch.nn as nn
+from parameterized import parameterized
+from safetensors.torch import save_file
+
+from accelerate import init_empty_weights
+from accelerate.test_utils import (
+ require_cuda,
+ require_huggingface_suite,
+ require_multi_device,
+ require_non_cpu,
+ torch_device,
+)
+from accelerate.utils.modeling import (
+ check_device_map,
+ clean_device_map,
+ compute_module_sizes,
+ compute_module_total_buffer_size,
+ convert_file_size_to_int,
+ find_tied_parameters,
+ get_balanced_memory,
+ infer_auto_device_map,
+ load_checkpoint_in_model,
+ load_state_dict,
+ named_module_tensors,
+ retie_parameters,
+ set_module_tensor_to_device,
+)
+
+
+torch_device = f"{torch_device}:0" if torch_device != "cpu" else "cpu"
+
+
+class ModelForTest(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = nn.Linear(3, 4)
+ self.batchnorm = nn.BatchNorm1d(4)
+ self.linear2 = nn.Linear(4, 5)
+
+ def forward(self, x):
+ return self.linear2(self.batchnorm(self.linear1(x)))
+
+
+class LinearWithNonPersistentBuffers(nn.Module):
+ def __init__(self, in_features: int, out_features: int, bias: bool = True, device=None, dtype=None) -> None:
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+ self.register_buffer("weight", torch.empty((out_features, in_features), **factory_kwargs))
+ if bias:
+ self.register_buffer("bias", torch.empty(out_features, **factory_kwargs), persistent=False)
+ else:
+ self.register_buffer("bias", None)
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ return torch.nn.functional.linear(input, self.weight, self.bias)
+
+
+class ModelSeveralDtypes(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.register_buffer("int_param", torch.randint(high=10, size=(15, 30)))
+ self.register_parameter("float_param", torch.nn.Parameter(torch.rand(10, 5)))
+
+ def forward(self, x):
+ return x + 2
+
+
+def sequential_model(num_layers):
+ layers = OrderedDict([(f"linear{i}", nn.Linear(1000, 1000)) for i in range(1, num_layers + 1)])
+ return nn.Sequential(layers)
+
+
+class ModelingUtilsTester(unittest.TestCase):
+ def check_set_module_tensor_for_device(self, model, device1, device2):
+ assert model.linear1.weight.device == torch.device(device1)
+
+ with self.subTest("Access by submodule and direct name for a parameter"):
+ set_module_tensor_to_device(model.linear1, "weight", device2)
+ assert model.linear1.weight.device == torch.device(device2)
+
+ if torch.device(device2) == torch.device("meta"):
+ with self.assertRaises(ValueError):
+ # We need a `value` to set the weight back on device1
+ set_module_tensor_to_device(model.linear1, "weight", device1)
+
+ set_module_tensor_to_device(model.linear1, "weight", device1, value=torch.randn(4, 3))
+ else:
+ set_module_tensor_to_device(model.linear1, "weight", device1)
+ assert model.linear1.weight.device == torch.device(device1)
+
+ with self.subTest("Access by module and full name for a parameter"):
+ set_module_tensor_to_device(model, "linear1.weight", device2)
+ assert model.linear1.weight.device == torch.device(device2)
+
+ if torch.device(device2) == torch.device("meta"):
+ with self.assertRaises(ValueError):
+ # We need a `value` to set the weight back on device1
+ set_module_tensor_to_device(model, "linear1.weight", device1)
+ set_module_tensor_to_device(model, "linear1.weight", device1, value=torch.randn(4, 3))
+ else:
+ set_module_tensor_to_device(model, "linear1.weight", device1)
+ assert model.linear1.weight.device == torch.device(device1)
+
+ assert model.batchnorm.running_mean.device == torch.device(device1)
+
+ with self.subTest("Access by submodule and direct name for a buffer"):
+ set_module_tensor_to_device(model.batchnorm, "running_mean", device2)
+ assert model.batchnorm.running_mean.device == torch.device(device2)
+
+ if torch.device(device2) == torch.device("meta"):
+ with self.assertRaises(ValueError):
+ # We need a `value` to set the weight back on device1
+ set_module_tensor_to_device(model.batchnorm, "running_mean", device1)
+ set_module_tensor_to_device(model.batchnorm, "running_mean", device1, value=torch.randn(4))
+ else:
+ set_module_tensor_to_device(model.batchnorm, "running_mean", device1)
+ assert model.batchnorm.running_mean.device == torch.device(device1)
+
+ with self.subTest("Access by module and full name for a parameter"):
+ set_module_tensor_to_device(model, "batchnorm.running_mean", device2)
+ assert model.batchnorm.running_mean.device == torch.device(device2)
+
+ if torch.device(device2) == torch.device("meta"):
+ with self.assertRaises(ValueError):
+ # We need a `value` to set the weight back on CPU
+ set_module_tensor_to_device(model, "batchnorm.running_mean", device1)
+
+ set_module_tensor_to_device(model, "batchnorm.running_mean", device1, value=torch.randn(4))
+ else:
+ set_module_tensor_to_device(model, "batchnorm.running_mean", device1)
+ assert model.batchnorm.running_mean.device == torch.device(device1)
+
+ def test_set_module_tensor_to_meta_and_cpu(self):
+ model = ModelForTest()
+ self.check_set_module_tensor_for_device(model, "cpu", "meta")
+
+ @require_non_cpu
+ def test_set_module_tensor_to_cpu_and_gpu(self):
+ model = ModelForTest()
+ self.check_set_module_tensor_for_device(model, "cpu", torch_device)
+
+ @require_non_cpu
+ def test_set_module_tensor_to_meta_and_gpu(self):
+ model = ModelForTest().to(torch_device)
+ self.check_set_module_tensor_for_device(model, torch_device, "meta")
+
+ @require_multi_device
+ def test_set_module_tensor_between_gpus(self):
+ model = ModelForTest().to(torch_device)
+ self.check_set_module_tensor_for_device(model, torch_device, torch_device.replace("0", "1"))
+
+ def test_set_module_tensor_sets_dtype(self):
+ model = ModelForTest()
+ set_module_tensor_to_device(model, "linear1.weight", "cpu", value=model.linear1.weight, dtype=torch.float16)
+ assert model.linear1.weight.dtype == torch.float16
+
+ def test_set_module_tensor_checks_shape(self):
+ model = ModelForTest()
+ tensor = torch.zeros((2, 2))
+ with self.assertRaises(ValueError) as cm:
+ set_module_tensor_to_device(model, "linear1.weight", "cpu", value=tensor)
+ assert (
+ str(cm.exception)
+ == 'Trying to set a tensor of shape torch.Size([2, 2]) in "weight" (which has shape torch.Size([4, 3])), this looks incorrect.'
+ )
+
+ def test_named_tensors(self):
+ model = nn.BatchNorm1d(4)
+ named_tensors = named_module_tensors(model)
+ assert [name for name, _ in named_tensors] == [
+ "weight",
+ "bias",
+ "running_mean",
+ "running_var",
+ "num_batches_tracked",
+ ]
+
+ named_tensors = named_module_tensors(model, include_buffers=False)
+ assert [name for name, _ in named_tensors] == ["weight", "bias"]
+
+ model = ModelForTest()
+ named_tensors = named_module_tensors(model)
+ assert [name for name, _ in named_tensors] == []
+
+ named_tensors = named_module_tensors(model, recurse=True)
+ assert [name for name, _ in named_tensors] == [
+ "linear1.weight",
+ "linear1.bias",
+ "batchnorm.weight",
+ "batchnorm.bias",
+ "linear2.weight",
+ "linear2.bias",
+ "batchnorm.running_mean",
+ "batchnorm.running_var",
+ "batchnorm.num_batches_tracked",
+ ]
+
+ named_tensors = named_module_tensors(model, include_buffers=False, recurse=True)
+ assert [name for name, _ in named_tensors] == [
+ "linear1.weight",
+ "linear1.bias",
+ "batchnorm.weight",
+ "batchnorm.bias",
+ "linear2.weight",
+ "linear2.bias",
+ ]
+
+ model = LinearWithNonPersistentBuffers(10, 10)
+
+ named_tensors = named_module_tensors(model, include_buffers=True, remove_non_persistent=False)
+ assert [name for name, _ in named_tensors] == ["weight", "bias"]
+
+ named_tensors = named_module_tensors(model, include_buffers=True, remove_non_persistent=True)
+ assert [name for name, _ in named_tensors] == ["weight"]
+
+ def test_find_tied_parameters(self):
+ model = sequential_model(4)
+ assert find_tied_parameters(model) == []
+
+ model.linear2.weight = model.linear1.weight
+ assert find_tied_parameters(model) == [["linear1.weight", "linear2.weight"]]
+
+ model.linear4.weight = model.linear1.weight
+ assert find_tied_parameters(model) == [["linear1.weight", "linear2.weight", "linear4.weight"]]
+
+ model = sequential_model(5)
+ model.linear1.weight = model.linear4.weight
+ model.linear2.weight = model.linear3.weight
+ model.linear5.weight = model.linear2.weight
+ tied_params = sorted(find_tied_parameters(model), key=lambda x: len(x))
+ assert tied_params == [
+ ["linear1.weight", "linear4.weight"],
+ ["linear2.weight", "linear3.weight", "linear5.weight"],
+ ]
+
+ model = nn.Sequential(OrderedDict([("block1", sequential_model(4)), ("block2", sequential_model(4))]))
+ model.block1.linear1.weight = model.block2.linear1.weight
+ assert find_tied_parameters(model) == [["block1.linear1.weight", "block2.linear1.weight"]]
+
+ layer = nn.Linear(10, 10)
+ model = nn.Sequential(layer, layer)
+ tied_params = find_tied_parameters(model)
+ assert sorted(tied_params) == [["0.bias", "1.bias"], ["0.weight", "1.weight"]]
+
+ def test_retie_parameters(self):
+ model = sequential_model(2)
+ retie_parameters(model, [["linear1.weight", "linear2.weight"]])
+ assert model.linear1.weight is model.linear2.weight
+
+ model = sequential_model(3)
+ retie_parameters(model, [["linear1.weight", "linear2.weight", "linear3.weight"]])
+
+ assert model.linear1.weight is model.linear2.weight
+ assert model.linear1.weight is model.linear3.weight
+
+ model = sequential_model(5)
+ retie_parameters(
+ model, [["linear1.weight", "linear4.weight"], ["linear2.weight", "linear3.weight", "linear5.weight"]]
+ )
+
+ assert model.linear1.weight is model.linear4.weight
+ assert model.linear2.weight is model.linear3.weight
+ assert model.linear2.weight is model.linear5.weight
+
+ model = nn.Sequential(OrderedDict([("block1", sequential_model(4)), ("block2", sequential_model(4))]))
+ retie_parameters(model, [["block1.linear1.weight", "block2.linear1.weight"]])
+
+ assert model.block1.linear1.weight is model.block2.linear1.weight
+
+ def test_compute_module_sizes(self):
+ model = ModelForTest()
+ expected_sizes = {"": 236, "linear1": 64, "linear1.weight": 48, "linear1.bias": 16}
+ expected_sizes.update({"linear2": 100, "linear2.weight": 80, "linear2.bias": 20})
+ expected_sizes.update({"batchnorm": 72, "batchnorm.weight": 16, "batchnorm.bias": 16})
+ expected_sizes.update(
+ {"batchnorm.running_mean": 16, "batchnorm.running_var": 16, "batchnorm.num_batches_tracked": 8}
+ )
+
+ module_sizes = compute_module_sizes(model)
+ assert module_sizes == expected_sizes
+
+ model.half()
+ expected_sizes = {k: s // 2 for k, s in expected_sizes.items()}
+ # This one is not converted to half.
+ expected_sizes["batchnorm.num_batches_tracked"] = 8
+ # This impacts batchnorm and total
+ expected_sizes["batchnorm"] += 4
+ expected_sizes[""] += 4
+
+ module_sizes = compute_module_sizes(model)
+ assert module_sizes == expected_sizes
+
+ def test_compute_module_total_buffer_size(self):
+ model = ModelForTest()
+ model.linear1.register_buffer("test_buffer", torch.zeros(10, 10))
+ model.register_buffer("test_buffer2", torch.zeros(20, 10))
+
+ buffer_size = compute_module_total_buffer_size(model)
+ assert buffer_size == 1240
+
+ model.half()
+ buffer_size = compute_module_total_buffer_size(model)
+ assert buffer_size == 624
+
+ def test_check_device_map(self):
+ model = ModelForTest()
+ check_device_map(model, {"": 0})
+ with self.assertRaises(ValueError):
+ check_device_map(model, {"linear1": 0, "linear2": 1})
+
+ check_device_map(model, {"linear1": 0, "linear2": 1, "batchnorm": 1})
+
+ def shard_test_model(self, model, tmp_dir):
+ module_index = {
+ "linear1": "checkpoint_part1.bin",
+ "batchnorm": "checkpoint_part2.bin",
+ "linear2": "checkpoint_part3.bin",
+ }
+ index = {}
+ for name, _ in model.state_dict().items():
+ module = name.split(".")[0]
+ index[name] = module_index[module]
+
+ with open(os.path.join(tmp_dir, "weight_map.index.json"), "w") as f:
+ json.dump(index, f)
+
+ for module, fname in module_index.items():
+ state_dict = {k: v for k, v in model.state_dict().items() if k.startswith(module)}
+ full_fname = os.path.join(tmp_dir, fname)
+ torch.save(state_dict, full_fname)
+
+ def test_load_checkpoint_in_model(self):
+ # Check with whole checkpoint
+ model = ModelForTest()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ fname = os.path.join(tmp_dir, "pt_model.bin")
+ torch.save(model.state_dict(), fname)
+ load_checkpoint_in_model(model, fname)
+
+ # Check with sharded index
+ model = ModelForTest()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ self.shard_test_model(model, tmp_dir)
+ index_file = os.path.join(tmp_dir, "weight_map.index.json")
+ load_checkpoint_in_model(model, index_file)
+
+ # Check with sharded checkpoint
+ model = ModelForTest()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ self.shard_test_model(model, tmp_dir)
+ load_checkpoint_in_model(model, tmp_dir)
+
+ @require_non_cpu
+ def test_load_checkpoint_in_model_one_gpu(self):
+ device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": "cpu"}
+
+ # Check with whole checkpoint
+ model = ModelForTest()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ fname = os.path.join(tmp_dir, "pt_model.bin")
+ torch.save(model.state_dict(), fname)
+ load_checkpoint_in_model(model, fname, device_map=device_map)
+ assert model.linear1.weight.device == torch.device(torch_device)
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ # Check with sharded index
+ model = ModelForTest()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ self.shard_test_model(model, tmp_dir)
+ index_file = os.path.join(tmp_dir, "weight_map.index.json")
+ load_checkpoint_in_model(model, index_file, device_map=device_map)
+
+ assert model.linear1.weight.device == torch.device(torch_device)
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ # Check with sharded checkpoint folder
+ model = ModelForTest()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ self.shard_test_model(model, tmp_dir)
+ load_checkpoint_in_model(model, tmp_dir, device_map=device_map)
+
+ assert model.linear1.weight.device == torch.device(torch_device)
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ @require_non_cpu
+ def test_load_checkpoint_in_model_disk_offload(self):
+ device_map = {"linear1": "cpu", "batchnorm": "disk", "linear2": "cpu"}
+
+ model = ModelForTest()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ fname = os.path.join(tmp_dir, "pt_model.bin")
+ torch.save(model.state_dict(), fname)
+ load_checkpoint_in_model(model, fname, device_map=device_map, offload_folder=tmp_dir)
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("meta")
+ # Buffers are not offloaded by default
+ assert model.batchnorm.running_mean.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ model = ModelForTest()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ fname = os.path.join(tmp_dir, "pt_model.bin")
+ torch.save(model.state_dict(), fname)
+ load_checkpoint_in_model(model, fname, device_map=device_map, offload_folder=tmp_dir, offload_buffers=True)
+ assert model.linear1.weight.device == torch.device("cpu")
+ assert model.batchnorm.weight.device == torch.device("meta")
+ assert model.batchnorm.running_mean.device == torch.device("meta")
+ assert model.linear2.weight.device == torch.device("cpu")
+
+ @require_multi_device
+ def test_load_checkpoint_in_model_two_gpu(self):
+ device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": 1}
+
+ # Check with whole checkpoint
+ model = ModelForTest()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ fname = os.path.join(tmp_dir, "pt_model.bin")
+ torch.save(model.state_dict(), fname)
+ load_checkpoint_in_model(model, fname, device_map=device_map)
+ assert model.linear1.weight.device == torch.device(torch_device)
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device(torch_device.replace("0", "1"))
+
+ # Check with sharded index
+ model = ModelForTest()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ self.shard_test_model(model, tmp_dir)
+ index_file = os.path.join(tmp_dir, "weight_map.index.json")
+ load_checkpoint_in_model(model, index_file, device_map=device_map)
+
+ assert model.linear1.weight.device == torch.device(torch_device)
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device(torch_device.replace("0", "1"))
+
+ # Check with sharded checkpoint
+ model = ModelForTest()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ self.shard_test_model(model, tmp_dir)
+ load_checkpoint_in_model(model, tmp_dir, device_map=device_map)
+
+ assert model.linear1.weight.device == torch.device(torch_device)
+ assert model.batchnorm.weight.device == torch.device("cpu")
+ assert model.linear2.weight.device == torch.device(torch_device.replace("0", "1"))
+
+ def test_load_checkpoint_in_model_dtype(self):
+ with tempfile.NamedTemporaryFile(suffix=".pt") as tmpfile:
+ model = ModelSeveralDtypes()
+ torch.save(model.state_dict(), tmpfile.name)
+
+ new_model = ModelSeveralDtypes()
+ load_checkpoint_in_model(
+ new_model, tmpfile.name, offload_state_dict=True, dtype=torch.float16, device_map={"": "cpu"}
+ )
+
+ assert new_model.int_param.dtype == torch.int64
+ assert new_model.float_param.dtype == torch.float16
+
+ @parameterized.expand([(None,), ({"": "cpu"},)])
+ def test_load_checkpoint_in_model_unexpected_keys(self, device_map: Optional[Dict]):
+ model = ModelForTest()
+
+ state_dict = model.state_dict()
+ state_dict["foo"] = torch.rand(4, 5)
+ with tempfile.NamedTemporaryFile(suffix=".pt") as tmpfile:
+ torch.save(state_dict, tmpfile)
+
+ model = ModelForTest()
+
+ with self.assertLogs() as cm:
+ load_checkpoint_in_model(model, tmpfile.name, device_map=device_map)
+
+ self.assertTrue(any("were not used when" in out for out in cm.output))
+
+ with self.assertRaises((ValueError, RuntimeError)):
+ load_checkpoint_in_model(model, tmpfile.name, device_map=device_map, strict=True)
+
+ def test_clean_device_map(self):
+ # Regroup everything if all is on the same device
+ assert clean_device_map({"a": 0, "b": 0, "c": 0}) == {"": 0}
+ # Regroups children of level 1 on the same device
+ assert clean_device_map({"a.x": 0, "a.y": 0, "b.x": 1, "b.y": 1, "c": 1}) == {"a": 0, "b": 1, "c": 1}
+ # Regroups children of level 2 on the same device
+ assert clean_device_map({"a.x": 0, "a.y": 0, "b.x.0": 1, "b.x.1": 1, "b.y.0": 2, "b.y.1": 2, "c": 2}) == {
+ "a": 0,
+ "b.x": 1,
+ "b.y": 2,
+ "c": 2,
+ }
+
+ def test_infer_auto_device_map(self):
+ model = ModelForTest()
+ # model has size 236: linear1 64, batchnorm 72, linear2 100
+
+ device_map = infer_auto_device_map(model, max_memory={0: 200, 1: 200})
+ # only linear1 fits on device 0 as we keep memory available for the maximum layer in case of offload
+ assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": 1}
+
+ device_map = infer_auto_device_map(model, max_memory={0: 200, 1: 172, 2: 200})
+ # On device 1, we don't care about keeping size available for the max layer, so even if there is just the
+ # size available for batchnorm + linear2, they fit here.
+ assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": 1}
+
+ model.linear1.weight = model.linear2.weight
+ device_map = infer_auto_device_map(model, max_memory={0: 200, 1: 200})
+ # By tying weights, the whole model fits on device 0
+ assert device_map == {"": 0}
+
+ # When splitting a bigger model, the split is done at the layer level
+ model = nn.Sequential(ModelForTest(), ModelForTest(), ModelForTest())
+ device_map = infer_auto_device_map(model, max_memory={0: 500, 1: 500})
+ assert device_map == {"0": 0, "1.linear1": 0, "1.batchnorm": 0, "1.linear2": 1, "2": 1}
+
+ # With no_split_module_classes, it's done at that module level
+ model = nn.Sequential(ModelForTest(), ModelForTest(), ModelForTest())
+ device_map = infer_auto_device_map(
+ model, max_memory={0: 500, 1: 500}, no_split_module_classes=["ModelForTest"]
+ )
+ assert device_map == {"0": 0, "1": 1, "2": 1}
+
+ def test_infer_auto_device_map_with_tied_weights(self):
+ model = nn.Sequential(
+ OrderedDict([("layer1", ModelForTest()), ("layer2", ModelForTest()), ("layer3", ModelForTest())])
+ )
+ model.layer3.linear2.weight = model.layer1.linear2.weight
+ device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 500})
+ expected = {"layer1": 0, "layer3.linear2": 0, "layer2": 1, "layer3.linear1": 1, "layer3.batchnorm": 1}
+ assert device_map == expected
+
+ # With three weights tied together
+ model.layer2.linear2.weight = model.layer1.linear2.weight
+ device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 500})
+ expected = {
+ "layer1": 0,
+ "layer2.linear2": 0,
+ "layer3.linear2": 0,
+ "layer2.linear1": 1,
+ "layer2.batchnorm": 1,
+ "layer3.linear1": 1,
+ "layer3.batchnorm": 1,
+ }
+ assert device_map == expected
+
+ # With two groups of weights tied together
+ model.layer2.linear1.weight = model.layer1.linear1.weight
+ device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 500})
+ expected = {
+ "layer1": 0,
+ "layer2.linear1": 0,
+ "layer2.linear2": 0,
+ "layer3.linear2": 0,
+ "layer2.batchnorm": 1,
+ "layer3.linear1": 1,
+ "layer3.batchnorm": 1,
+ }
+ assert device_map == expected
+
+ # With weights ties in the same module
+ model = nn.Sequential(
+ OrderedDict(
+ [
+ ("linear1", nn.Linear(4, 4)),
+ ("linear2", nn.Linear(6, 6)),
+ ("linear3", nn.Linear(4, 4)),
+ ("linear4", nn.Linear(6, 6)),
+ ]
+ )
+ )
+ model.linear3.weight = model.linear1.weight
+ model.linear3.bias = model.linear1.bias
+ device_map = infer_auto_device_map(model, max_memory={0: 250, 1: 400})
+ expected = {"linear1": 0, "linear2": 1, "linear3": 0, "linear4": 1}
+ assert device_map == expected
+
+ # With tied weights sharing a same prefix name (`compute.weight` vs `compute.weight_submodule.parameter`)
+ class SubModule(torch.nn.Module):
+ def __init__(self, ref_to_parameter):
+ super().__init__()
+ self.parameter = ref_to_parameter
+
+ def forward(self, x):
+ return self.x + torch.max(self.parameter)
+
+ class LinearModuleAndSubModule(torch.nn.Linear):
+ def __init__(self, in_features, out_features):
+ super().__init__(in_features, out_features)
+ self.weight_submodule = SubModule(self.weight)
+
+ def forward(self, x):
+ return torch.nn.functional.linear(self.weight_submodule(x), self.weight)
+
+ class Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.compute = LinearModuleAndSubModule(3, 8)
+
+ def forward(self, x):
+ return self.compute(x)
+
+ model = Model()
+
+ device_memory = {0: 4, "cpu": 96000} # Low memory device, just to force splitting and trigger the error
+ infer_auto_device_map(model, device_memory)
+
+ @require_huggingface_suite
+ def test_infer_auto_device_map_on_t0pp(self):
+ from transformers import AutoConfig, AutoModelForSeq2SeqLM
+
+ config = AutoConfig.from_pretrained("bigscience/T0pp")
+ with init_empty_weights():
+ model = AutoModelForSeq2SeqLM.from_config(config)
+ model.tie_weights()
+
+ special_dtypes = {n: torch.float32 for n, _ in model.named_parameters() if "wo" in n}
+ max_memory = {0: 10**10, 1: 10**10, "cpu": 10**10}
+ device_map = infer_auto_device_map(
+ model,
+ no_split_module_classes=["T5Block"],
+ dtype=torch.float16,
+ max_memory=max_memory,
+ special_dtypes=special_dtypes,
+ )
+
+ # The 3 tied weights should all be on device 0
+ assert device_map["shared"] == 0
+ assert device_map["encoder.embed_tokens"] == 0
+ assert device_map["decoder.embed_tokens"] == 0
+
+ def test_infer_auto_device_map_with_buffer_check(self):
+ model = ModelForTest()
+ model.linear1.register_buffer("test_buffer1", torch.zeros(10, 2))
+ model.batchnorm.register_buffer("test_buffer2", torch.zeros(10, 3))
+ model.linear2.register_buffer("test_buffer3", torch.zeros(10, 3))
+ # model has size 236(parameters) + 360(buffers): linear1 64 + 80, batchnorm 72 + 160, linear2 100 + 120
+
+ # Only linear1 (144) fits on device 0, and remaining buffers (batchnorm's 160 + linear2's 120 = 280) won't fit
+ # device 0, because they will also be loaded to device 0 all at once when inferencing without offload_buffers
+ # Should print a warning as intended in such case
+ with self.assertWarns(Warning):
+ device_map = infer_auto_device_map(model, max_memory={0: 400, "cpu": "1GB"})
+ assert device_map == {"linear1": 0, "batchnorm": "cpu", "linear2": "cpu"}
+
+ # Only linear1 (144) fits on device 0, and remaining buffers (batchnorm's 160 + linear2's 120 = 280) won't fit
+ # device 0, but with offload_buffers they won't be loaded to device 0 all at once, so it's ok now
+ # Should NOT print a warning in such case
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+ device_map = infer_auto_device_map(model, max_memory={0: 400, "cpu": "1GB"}, offload_buffers=True)
+ assert len(w) == 0
+ assert device_map == {"linear1": 0, "batchnorm": "cpu", "linear2": "cpu"}
+
+ def test_infer_auto_device_map_with_buffer_check_and_multi_devices(self):
+ model = ModelForTest()
+ model.linear1.register_buffer("test_buffer1", torch.zeros(10, 2))
+ model.batchnorm.register_buffer("test_buffer2", torch.zeros(10, 3))
+ model.linear2.register_buffer("test_buffer3", torch.zeros(10, 3))
+ model.linear3 = nn.Linear(4, 5)
+ model.linear3.register_buffer("test_buffer4", torch.zeros(10, 2))
+ # model has size 336(parameters) + 440(buffers): linear1 64 + 80, batchnorm 72 + 160, linear2 100 + 120,
+ # linear3 100 + 80
+
+ # Now we have two devices, linear1 will fit on device 0, batchnorm will fit on device 1, and the second device
+ # can hold all remaining buffers
+ # Should NOT print a warning in such case
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+ device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 400, "cpu": "1GB"})
+ assert len(w) == 0
+ assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": "cpu", "linear3": "cpu"}
+
+ # Now we have two devices, but neither the first nor the second device can hold all remaining buffers
+ # Should print a warning as intended in such case
+ with self.assertWarns(Warning):
+ device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 200, "cpu": "1GB"})
+ assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": "cpu", "linear3": "cpu"}
+
+ # Now we have two devices, neither can hold all the buffers, but we are using the offload_buffers=True
+ # Should NOT print a warning in such case
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+ device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 200, "cpu": "1GB"}, offload_buffers=True)
+ assert len(w) == 0
+ assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": "cpu", "linear3": "cpu"}
+
+ @require_cuda
+ def test_get_balanced_memory(self):
+ model = ModelForTest()
+ # model has size 236: linear1 64, batchnorm 72, linear2 100
+ max_memory = get_balanced_memory(model, max_memory={0: 200, 1: 200})
+ assert {0: 200, 1: 200} == max_memory
+
+ # We should be able to set models on a non-contiguous sub-set of
+ max_memory = get_balanced_memory(model, max_memory={0: 200, 2: 200})
+ assert {0: 200, 2: 200} == max_memory
+
+ max_memory = get_balanced_memory(model, max_memory={0: 300, 1: 300})
+ assert {0: 215, 1: 300} == max_memory
+
+ # Last device always get max memory to give more buffer and avoid accidental CPU offload
+ max_memory = get_balanced_memory(model, max_memory={0: 300, 1: 500})
+ assert {0: 215, 1: 500} == max_memory
+
+ # Last device always get max memory to give more buffer, even if CPU is provided
+ max_memory = get_balanced_memory(model, max_memory={0: 300, "cpu": 1000})
+ assert {0: 300, "cpu": 1000} == max_memory
+
+ # If we set a device to 0, it's not counted.
+ max_memory = get_balanced_memory(model, max_memory={0: 0, 1: 300, 2: 300})
+ assert {0: 0, 1: 215, 2: 300} == max_memory
+
+ # If we set a device to 0, it's not counted.
+ max_memory = get_balanced_memory(model, max_memory={0: 0, "cpu": 100})
+ assert {0: 0, "cpu": 100} == max_memory
+
+ @require_non_cpu
+ def test_load_state_dict(self):
+ state_dict = {k: torch.randn(4, 5) for k in ["a", "b", "c"]}
+ device_maps = [{"a": "cpu", "b": 0, "c": "disk"}, {"a": 0, "b": 0, "c": "disk"}, {"a": 0, "b": 0, "c": 0}]
+
+ for device_map in device_maps:
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ checkpoint_file = os.path.join(tmp_dir, "model.safetensors")
+ save_file(state_dict, checkpoint_file, metadata={"format": "pt"})
+
+ loaded_state_dict = load_state_dict(checkpoint_file, device_map=device_map)
+
+ for param, device in device_map.items():
+ device = device if device != "disk" else "cpu"
+ assert loaded_state_dict[param].device == torch.device(device)
+
+ def test_convert_file_size(self):
+ result = convert_file_size_to_int("0MB")
+ assert result == 0
+
+ result = convert_file_size_to_int("100MB")
+ assert result == (100 * (10**6))
+
+ result = convert_file_size_to_int("2GiB")
+ assert result == (2 * (2**30))
+
+ result = convert_file_size_to_int("512KiB")
+ assert result == (512 * (2**10))
+
+ result = convert_file_size_to_int("1.5GB")
+ assert result == (1.5 * (10**9))
+
+ result = convert_file_size_to_int("100KB")
+ assert result == (100 * (10**3))
+
+ result = convert_file_size_to_int(500)
+ assert result == 500
+
+ with self.assertRaises(ValueError):
+ convert_file_size_to_int("5MBB")
+
+ with self.assertRaises(ValueError):
+ convert_file_size_to_int("5k0MB")
+
+ with self.assertRaises(ValueError):
+ convert_file_size_to_int("-1GB")
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_multigpu.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_multigpu.py
new file mode 100644
index 0000000000000000000000000000000000000000..76652e76ff57cd3a86c50af408ce2097b22fa302
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_multigpu.py
@@ -0,0 +1,157 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import inspect
+import unittest
+
+import torch
+
+from accelerate import Accelerator
+from accelerate.big_modeling import dispatch_model
+from accelerate.test_utils import (
+ DEFAULT_LAUNCH_COMMAND,
+ assert_exception,
+ device_count,
+ execute_subprocess_async,
+ get_launch_command,
+ path_in_accelerate_package,
+ require_huggingface_suite,
+ require_multi_device,
+ require_multi_gpu,
+ require_non_torch_xla,
+ require_non_xpu,
+ require_pippy,
+ require_torchvision,
+ torch_device,
+)
+from accelerate.utils import patch_environment
+
+
+class MultiDeviceTester(unittest.TestCase):
+ test_file_path = path_in_accelerate_package("test_utils", "scripts", "test_script.py")
+ data_loop_file_path = path_in_accelerate_package("test_utils", "scripts", "test_distributed_data_loop.py")
+ operation_file_path = path_in_accelerate_package("test_utils", "scripts", "test_ops.py")
+ pippy_file_path = path_in_accelerate_package("test_utils", "scripts", "external_deps", "test_pippy.py")
+ merge_weights_file_path = path_in_accelerate_package("test_utils", "scripts", "test_merge_weights.py")
+
+ @require_multi_device
+ def test_multi_device(self):
+ print(f"Found {device_count} devices.")
+ cmd = DEFAULT_LAUNCH_COMMAND + [self.test_file_path]
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd)
+
+ @require_multi_device
+ def test_multi_device_ops(self):
+ print(f"Found {device_count} devices.")
+ cmd = DEFAULT_LAUNCH_COMMAND + [self.operation_file_path]
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd)
+
+ @require_multi_device
+ def test_pad_across_processes(self):
+ print(f"Found {device_count} devices.")
+ cmd = DEFAULT_LAUNCH_COMMAND + [inspect.getfile(self.__class__)]
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd)
+
+ @require_multi_device
+ def test_multi_device_merge_fsdp_weights(self):
+ print(f"Found {device_count} devices.")
+ cmd = DEFAULT_LAUNCH_COMMAND + [self.merge_weights_file_path]
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd)
+
+ @require_non_torch_xla
+ @require_multi_device
+ def test_distributed_data_loop(self):
+ """
+ This TestCase checks the behaviour that occurs during distributed training or evaluation,
+ when the batch size does not evenly divide the dataset size.
+ """
+ print(f"Found {device_count} devices, using 2 devices only")
+ cmd = get_launch_command(num_processes=2) + [self.data_loop_file_path]
+ env_kwargs = dict(omp_num_threads=1)
+ if torch_device == "xpu":
+ env_kwargs.update(ze_affinity_mask="0,1")
+ elif torch_device == "npu":
+ env_kwargs.update(ascend_rt_visible_devices="0,1")
+ elif torch_device == "mlu":
+ env_kwargs.update(mlu_visible_devices="0,1")
+ else:
+ env_kwargs.update(cuda_visible_devices="0,1")
+ with patch_environment(**env_kwargs):
+ execute_subprocess_async(cmd)
+
+ @require_non_xpu
+ @require_multi_gpu
+ @require_pippy
+ @require_torchvision
+ @require_huggingface_suite
+ def test_pippy(self):
+ """
+ Checks the integration with the pippy framework
+ """
+ print(f"Found {device_count} devices")
+ cmd = get_launch_command(multi_gpu=True, num_processes=device_count) + [self.pippy_file_path]
+ with patch_environment(omp_num_threads=1):
+ execute_subprocess_async(cmd)
+
+
+if __name__ == "__main__":
+ accelerator = Accelerator()
+ shape = (accelerator.state.process_index + 2, 10)
+ tensor = torch.randint(0, 10, shape).to(accelerator.device)
+
+ error_msg = ""
+
+ tensor1 = accelerator.pad_across_processes(tensor)
+ if tensor1.shape[0] != accelerator.state.num_processes + 1:
+ error_msg += f"Found shape {tensor1.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
+ if not torch.equal(tensor1[: accelerator.state.process_index + 2], tensor):
+ error_msg += "Tensors have different values."
+ if not torch.all(tensor1[accelerator.state.process_index + 2 :] == 0):
+ error_msg += "Padding was not done with the right value (0)."
+
+ tensor2 = accelerator.pad_across_processes(tensor, pad_first=True)
+ if tensor2.shape[0] != accelerator.state.num_processes + 1:
+ error_msg += f"Found shape {tensor2.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
+ index = accelerator.state.num_processes - accelerator.state.process_index - 1
+ if not torch.equal(tensor2[index:], tensor):
+ error_msg += "Tensors have different values."
+ if not torch.all(tensor2[:index] == 0):
+ error_msg += "Padding was not done with the right value (0)."
+
+ # Raise error at the end to make sure we don't stop at the first failure.
+ if len(error_msg) > 0:
+ raise ValueError(error_msg)
+
+ # Check device_map
+ accelerator.print("Test `device_map` cannot be prepared.")
+
+ class ModelForTest(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = torch.nn.Linear(3, 4)
+ self.batchnorm = torch.nn.BatchNorm1d(4)
+ self.linear2 = torch.nn.Linear(4, 5)
+
+ def forward(self, x):
+ return self.linear2(self.batchnorm(self.linear1(x)))
+
+ device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": 1}
+ model = ModelForTest()
+ dispatch_model(model, device_map=device_map)
+ with assert_exception(ValueError, "You can't train a model that has been loaded with"):
+ model = accelerator.prepare_model(model)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_offload.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_offload.py
new file mode 100644
index 0000000000000000000000000000000000000000..95566a4bcbfe5340e558b0717d6acbe2f2145c77
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_offload.py
@@ -0,0 +1,114 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import unittest
+from tempfile import TemporaryDirectory
+
+import torch
+import torch.nn as nn
+
+from accelerate.utils import (
+ OffloadedWeightsLoader,
+ extract_submodules_state_dict,
+ load_offloaded_weight,
+ offload_state_dict,
+ offload_weight,
+)
+
+
+class ModelForTest(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.linear1 = nn.Linear(3, 4)
+ self.batchnorm = nn.BatchNorm1d(4)
+ self.linear2 = nn.Linear(4, 5)
+
+ def forward(self, x):
+ return self.linear2(self.batchnorm(self.linear1(x)))
+
+
+class OffloadTester(unittest.TestCase):
+ def test_offload_state_dict(self):
+ model = ModelForTest()
+ with TemporaryDirectory() as tmp_dir:
+ offload_state_dict(tmp_dir, model.state_dict())
+ index_file = os.path.join(tmp_dir, "index.json")
+ assert os.path.isfile(index_file)
+ # TODO: add tests on what is inside the index
+
+ for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]:
+ weight_file = os.path.join(tmp_dir, f"{key}.dat")
+ assert os.path.isfile(weight_file)
+ # TODO: add tests on the fact weights are properly loaded
+
+ def test_offload_weight(self):
+ dtypes = [torch.float16, torch.float32, torch.bfloat16]
+
+ for dtype in dtypes:
+ weight = torch.randn(2, 3, dtype=dtype)
+ with TemporaryDirectory() as tmp_dir:
+ index = offload_weight(weight, "weight", tmp_dir, {})
+ weight_file = os.path.join(tmp_dir, "weight.dat")
+ assert os.path.isfile(weight_file)
+ assert index == {"weight": {"shape": [2, 3], "dtype": str(dtype).split(".")[1]}}
+
+ new_weight = load_offloaded_weight(weight_file, index["weight"])
+ assert torch.equal(weight, new_weight)
+
+ def test_offload_weights_loader(self):
+ model = ModelForTest()
+ state_dict = model.state_dict()
+ cpu_part = {k: v for k, v in state_dict.items() if "linear2" not in k}
+ disk_part = {k: v for k, v in state_dict.items() if "linear2" in k}
+
+ with TemporaryDirectory() as tmp_dir:
+ offload_state_dict(tmp_dir, disk_part)
+ weight_map = OffloadedWeightsLoader(state_dict=cpu_part, save_folder=tmp_dir)
+
+ # Every key is there with the right value
+ assert sorted(weight_map) == sorted(state_dict.keys())
+ for key, param in state_dict.items():
+ assert torch.allclose(param, weight_map[key])
+
+ cpu_part = {k: v for k, v in state_dict.items() if "weight" in k}
+ disk_part = {k: v for k, v in state_dict.items() if "weight" not in k}
+
+ with TemporaryDirectory() as tmp_dir:
+ offload_state_dict(tmp_dir, disk_part)
+ weight_map = OffloadedWeightsLoader(state_dict=cpu_part, save_folder=tmp_dir)
+
+ # Every key is there with the right value
+ assert sorted(weight_map) == sorted(state_dict.keys())
+ for key, param in state_dict.items():
+ assert torch.allclose(param, weight_map[key])
+
+ with TemporaryDirectory() as tmp_dir:
+ offload_state_dict(tmp_dir, state_dict)
+ # Duplicates are removed
+ weight_map = OffloadedWeightsLoader(state_dict=cpu_part, save_folder=tmp_dir)
+
+ # Every key is there with the right value
+ assert sorted(weight_map) == sorted(state_dict.keys())
+ for key, param in state_dict.items():
+ assert torch.allclose(param, weight_map[key])
+
+ def test_extract_submodules_state_dict(self):
+ state_dict = {"a.1": 0, "a.10": 1, "a.2": 2}
+ extracted = extract_submodules_state_dict(state_dict, ["a.1", "a.2"])
+ assert extracted == {"a.1": 0, "a.2": 2}
+
+ state_dict = {"a.1.a": 0, "a.10.a": 1, "a.2.a": 2}
+ extracted = extract_submodules_state_dict(state_dict, ["a.1", "a.2"])
+ assert extracted == {"a.1.a": 0, "a.2.a": 2}
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_optimizer.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..374733ae762464dab80040a7bebb29bdf9c34205
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_optimizer.py
@@ -0,0 +1,86 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import pickle
+import unittest
+
+import torch
+
+from accelerate import Accelerator
+from accelerate.state import AcceleratorState
+from accelerate.test_utils import require_cpu, require_non_cpu, require_non_xpu
+
+
+@require_cpu
+class CPUOptimizerTester(unittest.TestCase):
+ def test_accelerated_optimizer_pickling(self):
+ model = torch.nn.Linear(10, 10)
+ optimizer = torch.optim.SGD(model.parameters(), 0.1)
+ accelerator = Accelerator()
+ optimizer = accelerator.prepare(optimizer)
+ try:
+ pickle.loads(pickle.dumps(optimizer))
+ except Exception as e:
+ self.fail(f"Accelerated optimizer pickling failed with {e}")
+ AcceleratorState._reset_state()
+
+
+@require_non_cpu
+@require_non_xpu
+class OptimizerTester(unittest.TestCase):
+ def test_accelerated_optimizer_step_was_skipped(self):
+ model = torch.nn.Linear(5, 5)
+ optimizer = torch.optim.SGD(model.parameters(), 0.1)
+ accelerator = Accelerator(mixed_precision="fp16")
+ model, optimizer = accelerator.prepare(model, optimizer)
+
+ loss = model(torch.randn(2, 5, device=accelerator.device)).sum()
+ accelerator.backward(loss)
+ for p in model.parameters():
+ # Fake the gradients, as if there's no overflow
+ p.grad.fill_(0.01)
+
+ optimizer.step()
+ assert optimizer.step_was_skipped is False
+
+ loss = model(torch.randn(2, 5, device=accelerator.device)).sum()
+ accelerator.backward(loss)
+ for p in model.parameters():
+ p.grad.fill_(0.01)
+ # Manually set the gradients to be NaN, as if there's an overflow
+ p.grad[0] = torch.tensor(float("nan"))
+
+ optimizer.step()
+ assert optimizer.step_was_skipped is True
+
+ loss = model(torch.randn(2, 5, device=accelerator.device)).sum()
+ accelerator.backward(loss)
+ for p in model.parameters():
+ p.grad.fill_(0.01)
+ # Manually set the gradients to be NaN, as if there's an overflow
+ p.grad[0] = torch.tensor(float("nan"))
+
+ optimizer.step()
+ assert optimizer.step_was_skipped is True
+
+ loss = model(torch.randn(2, 5, device=accelerator.device)).sum()
+ accelerator.backward(loss)
+ for p in model.parameters():
+ # Fake the gradients, as if there's no overflow
+ p.grad.fill_(0.01)
+
+ optimizer.step()
+ assert optimizer.step_was_skipped is False
+
+ AcceleratorState._reset_state()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_quantization.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_quantization.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5e9466d8d9d8df48ee41a3ada0cbd3e2130185e
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_quantization.py
@@ -0,0 +1,966 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import gc
+import tempfile
+import unittest
+
+import torch
+import torch.nn as nn
+
+from accelerate import Accelerator, init_empty_weights
+from accelerate.test_utils import (
+ require_bnb,
+ require_cuda,
+ require_huggingface_suite,
+ require_multi_gpu,
+ require_non_torch_xla,
+ slow,
+)
+from accelerate.utils.bnb import load_and_quantize_model
+from accelerate.utils.dataclasses import BnbQuantizationConfig
+
+
+class BitsAndBytesConfigIntegration(unittest.TestCase):
+ def test_BnbQuantizationConfig(self):
+ with self.assertRaises(ValueError):
+ BnbQuantizationConfig(load_in_8bit=True, load_in_4bit=True)
+
+
+@require_non_torch_xla
+@slow
+@require_cuda
+@require_bnb
+@require_huggingface_suite
+class MixedInt8EmptyModelTest(unittest.TestCase):
+ # We keep the constants inside the init function and model loading inside setUp function
+
+ # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
+ # Therefore here we use only bloom-1b3 to test our module
+ model_name = "marcsun13/bloom-1b7_with_lm_head"
+
+ # Constant values
+ # This was obtained on a Quadro RTX 8000 so the number might slightly change
+ EXPECTED_RELATIVE_DIFFERENCE = 1.540025
+
+ input_text = "Hello my name is"
+ EXPECTED_OUTPUT = "Hello my name is John.\nI am a friend of the family.\n"
+ MAX_NEW_TOKENS = 10
+
+ def setUp(self):
+ """
+ Setup quantized model from empty model
+ """
+ from huggingface_hub import hf_hub_download
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
+
+ # Models and tokenizer
+ self.model_fp16 = AutoModelForCausalLM.from_pretrained(
+ self.model_name, torch_dtype=torch.float16, device_map="auto"
+ )
+
+ # create model on meta device
+ with init_empty_weights():
+ self.model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+ self.model_8bit.tie_weights()
+
+ self.weights_location = hf_hub_download(self.model_name, "pytorch_model.bin")
+ self.bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
+
+ self.model_8bit = load_and_quantize_model(
+ self.model_8bit,
+ self.bnb_quantization_config,
+ weights_location=self.weights_location,
+ device_map={"": 0},
+ no_split_module_classes=["BloomBlock"],
+ )
+
+ self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7")
+ self.accelerate = Accelerator()
+
+ def tearDown(self):
+ r"""
+ TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
+ avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
+ """
+ del self.model_fp16
+ del self.model_8bit
+
+ gc.collect()
+ torch.cuda.empty_cache()
+
+ def test_memory_footprint(self):
+ r"""
+ A simple test to check if the model conversion has been done correctly by checking on the
+ memory footprint of the converted model and the class type of the linear layers of the converted models
+ """
+ from bitsandbytes.nn import Int8Params
+
+ mem_fp16 = self.model_fp16.get_memory_footprint()
+ mem_8bit = self.model_8bit.get_memory_footprint()
+
+ assert round((mem_fp16 / mem_8bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0
+ assert self.model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+
+ def test_linear_are_8bit(self):
+ r"""
+ A simple test to check if the model conversion has been done correctly by checking on the
+ memory footprint of the converted model and the class type of the linear layers of the converted models
+ """
+
+ self.model_fp16.get_memory_footprint()
+ self.model_8bit.get_memory_footprint()
+
+ for name, module in self.model_8bit.named_modules():
+ if isinstance(module, torch.nn.Linear):
+ modules_not_converted = (
+ self.bnb_quantization_config.keep_in_fp32_modules + self.bnb_quantization_config.skip_modules
+ )
+ if name not in modules_not_converted:
+ assert module.weight.dtype == torch.int8
+
+ def test_llm_skip(self):
+ r"""
+ A simple test to check if `llm_int8_skip_modules` works as expected
+ """
+ import bitsandbytes as bnb
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ bnb_quantization_config = BnbQuantizationConfig(
+ load_in_8bit=True, skip_modules=["lm_head", "transformer.word_embeddings"]
+ )
+
+ with init_empty_weights():
+ model = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+
+ model.tie_weights()
+ model = load_and_quantize_model(
+ model,
+ bnb_quantization_config,
+ weights_location=self.weights_location,
+ device_map="auto",
+ no_split_module_classes=["BloomBlock"],
+ )
+
+ assert model.transformer.h[1].mlp.dense_4h_to_h.weight.dtype == torch.int8
+ assert isinstance(model.transformer.h[1].mlp.dense_4h_to_h, bnb.nn.Linear8bitLt)
+ assert isinstance(model.lm_head, nn.Linear)
+ assert model.lm_head.weight.dtype != torch.int8
+
+ def check_inference_correctness(self, model):
+ r"""
+ Test the generation quality of the quantized model and see that we are matching the expected output.
+ Given that we are operating on small numbers + the testing model is relatively small, we might not get
+ the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
+ """
+ # Check that inference pass works on the model
+ encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
+
+ # Check the exactness of the results
+ output_parallel = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10)
+
+ # Get the generation
+ output_text = self.tokenizer.decode(output_parallel[0], skip_special_tokens=True)
+ assert output_text == self.EXPECTED_OUTPUT
+
+ def test_generate_quality(self):
+ self.check_inference_correctness(self.model_8bit)
+
+ def test_fp32_8bit_conversion(self):
+ r"""
+ Test whether it is possible to mix both `8bit` and `fp32` weights when using `keep_in_fp32_modules` correctly.
+ """
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True, keep_in_fp32_modules=["lm_head"])
+
+ with init_empty_weights():
+ model = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+
+ model.tie_weights()
+ model = load_and_quantize_model(
+ model,
+ bnb_quantization_config,
+ weights_location=self.weights_location,
+ device_map="auto",
+ no_split_module_classes=["BloomBlock"],
+ )
+ assert model.lm_head.weight.dtype == torch.float32
+
+ @require_multi_gpu
+ def test_cpu_gpu_loading_custom_device_map(self):
+ from bitsandbytes.nn import Int8Params
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ r"""
+ A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`.
+ """
+ device_map = {
+ "transformer.word_embeddings": "cpu",
+ "transformer.word_embeddings_layernorm": 0,
+ "lm_head": "cpu",
+ "transformer.h.0": "cpu",
+ "transformer.h.1": "cpu",
+ "transformer.h.2": "cpu",
+ "transformer.h.3": 0,
+ "transformer.h.4": 0,
+ "transformer.h.5": 0,
+ "transformer.h.6": 0,
+ "transformer.h.7": 0,
+ "transformer.h.8": 0,
+ "transformer.h.9": 1,
+ "transformer.h.10": 0,
+ "transformer.h.11": 1,
+ "transformer.h.12": 0,
+ "transformer.h.13": 0,
+ "transformer.h.14": 1,
+ "transformer.h.15": 0,
+ "transformer.h.16": 0,
+ "transformer.h.17": 1,
+ "transformer.h.18": 1,
+ "transformer.h.19": 0,
+ "transformer.h.20": 1,
+ "transformer.h.21": 1,
+ "transformer.h.22": 0,
+ "transformer.h.23": 0,
+ "transformer.ln_f": 1,
+ }
+ bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
+
+ with init_empty_weights():
+ model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+
+ model_8bit.tie_weights()
+ model_8bit = load_and_quantize_model(
+ model_8bit,
+ bnb_quantization_config,
+ weights_location=self.weights_location,
+ device_map=device_map,
+ no_split_module_classes=["BloomBlock"],
+ )
+ assert model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+ assert model_8bit.transformer.h[1].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+ self.check_inference_correctness(model_8bit)
+
+ @require_multi_gpu
+ def test_cpu_gpu_loading_custom_device_map_offload_state_dict(self):
+ from bitsandbytes.nn import Int8Params
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ r"""
+ A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map` and offload_state_dict=True.
+ """
+ device_map = {
+ "transformer.word_embeddings": "cpu",
+ "transformer.word_embeddings_layernorm": 0,
+ "lm_head": "cpu",
+ "transformer.h.0": "cpu",
+ "transformer.h.1": "cpu",
+ "transformer.h.2": "cpu",
+ "transformer.h.3": 0,
+ "transformer.h.4": 0,
+ "transformer.h.5": 0,
+ "transformer.h.6": 0,
+ "transformer.h.7": 0,
+ "transformer.h.8": 0,
+ "transformer.h.9": 1,
+ "transformer.h.10": 0,
+ "transformer.h.11": 1,
+ "transformer.h.12": 0,
+ "transformer.h.13": 0,
+ "transformer.h.14": 1,
+ "transformer.h.15": 0,
+ "transformer.h.16": 0,
+ "transformer.h.17": 1,
+ "transformer.h.18": 1,
+ "transformer.h.19": 0,
+ "transformer.h.20": 1,
+ "transformer.h.21": 1,
+ "transformer.h.22": 0,
+ "transformer.h.23": 0,
+ "transformer.ln_f": 1,
+ }
+
+ bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
+
+ with init_empty_weights():
+ model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+
+ model_8bit.tie_weights()
+ model_8bit = load_and_quantize_model(
+ model_8bit,
+ bnb_quantization_config,
+ weights_location=self.weights_location,
+ device_map=device_map,
+ no_split_module_classes=["BloomBlock"],
+ offload_state_dict=True,
+ )
+ assert model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+ assert model_8bit.transformer.h[1].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+ self.check_inference_correctness(model_8bit)
+
+ @require_multi_gpu
+ def test_cpu_gpu_disk_loading_custom_device_map_kwargs(self):
+ from bitsandbytes.nn import Int8Params
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ r"""
+ A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`.
+ This time we also add `disk` on the device_map - using the kwargs directly instead of the quantization config
+ """
+ device_map = {
+ "transformer.word_embeddings": "cpu",
+ "transformer.word_embeddings_layernorm": 0,
+ "lm_head": "cpu",
+ "transformer.h.0": "cpu",
+ "transformer.h.1": "cpu",
+ "transformer.h.2": "cpu",
+ "transformer.h.3": "disk",
+ "transformer.h.4": "disk",
+ "transformer.h.5": "disk",
+ "transformer.h.6": 0,
+ "transformer.h.7": 0,
+ "transformer.h.8": 0,
+ "transformer.h.9": 1,
+ "transformer.h.10": 0,
+ "transformer.h.11": 1,
+ "transformer.h.12": 0,
+ "transformer.h.13": 0,
+ "transformer.h.14": 1,
+ "transformer.h.15": 0,
+ "transformer.h.16": 0,
+ "transformer.h.17": 1,
+ "transformer.h.18": 1,
+ "transformer.h.19": 0,
+ "transformer.h.20": 1,
+ "transformer.h.21": 1,
+ "transformer.h.22": 0,
+ "transformer.h.23": 0,
+ "transformer.ln_f": 1,
+ }
+ bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
+
+ with init_empty_weights():
+ model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+ model_8bit.tie_weights()
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model_8bit = load_and_quantize_model(
+ model_8bit,
+ bnb_quantization_config,
+ weights_location=self.weights_location,
+ device_map=device_map,
+ no_split_module_classes=["BloomBlock"],
+ offload_folder=tmpdirname,
+ offload_state_dict=True,
+ )
+ assert model_8bit.transformer.h[4].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+ assert model_8bit.transformer.h[5].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+ self.check_inference_correctness(model_8bit)
+
+ def test_int8_serialization(self):
+ r"""
+ Test whether it is possible to serialize a model in 8-bit.
+ """
+ from bitsandbytes.nn import Int8Params
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ # saving state dict for now but will save config and other in the future
+ self.accelerate.save_model(self.model_8bit, tmpdirname)
+
+ with init_empty_weights():
+ # let's suppose that we can get the right config
+ model_8bit_from_saved = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+ model_8bit_from_saved.tie_weights()
+
+ bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
+
+ model_8bit_from_saved = load_and_quantize_model(
+ model_8bit_from_saved,
+ bnb_quantization_config,
+ weights_location=tmpdirname,
+ device_map="auto",
+ no_split_module_classes=["BloomBlock"],
+ )
+
+ assert model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+ assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "SCB")
+ assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "CB")
+
+ self.check_inference_correctness(model_8bit_from_saved)
+
+ @require_multi_gpu
+ def test_int8_serialization_offload(self):
+ r"""
+ Test whether it is possible to serialize a model in 8-bit and offload weights to cpu/disk
+ """
+
+ from bitsandbytes.nn import Int8Params
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ # saving state dict for now but will save config and other in the future
+ self.accelerate.save_model(self.model_8bit, tmpdirname)
+
+ with init_empty_weights():
+ # let's suppose that we can get the right config
+ model_8bit_from_saved = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+ model_8bit_from_saved.tie_weights()
+ bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
+ device_map = {
+ "transformer.word_embeddings": "cpu",
+ "transformer.word_embeddings_layernorm": 0,
+ "lm_head": "cpu",
+ "transformer.h.0": "cpu",
+ "transformer.h.1": "cpu",
+ "transformer.h.2": "cpu",
+ "transformer.h.3": "disk",
+ "transformer.h.4": "disk",
+ "transformer.h.5": "disk",
+ "transformer.h.6": 0,
+ "transformer.h.7": 0,
+ "transformer.h.8": 0,
+ "transformer.h.9": 1,
+ "transformer.h.10": 0,
+ "transformer.h.11": 1,
+ "transformer.h.12": 0,
+ "transformer.h.13": 0,
+ "transformer.h.14": 1,
+ "transformer.h.15": 0,
+ "transformer.h.16": 0,
+ "transformer.h.17": 1,
+ "transformer.h.18": 1,
+ "transformer.h.19": 0,
+ "transformer.h.20": 1,
+ "transformer.h.21": 1,
+ "transformer.h.22": 0,
+ "transformer.h.23": 0,
+ "transformer.ln_f": 1,
+ }
+ model_8bit_from_saved = load_and_quantize_model(
+ model_8bit_from_saved,
+ bnb_quantization_config,
+ weights_location=tmpdirname,
+ device_map=device_map,
+ no_split_module_classes=["BloomBlock"],
+ offload_folder=tmpdirname + "/tmp",
+ offload_state_dict=True,
+ )
+
+ assert model_8bit_from_saved.transformer.h[4].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+ assert model_8bit_from_saved.transformer.h[5].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+ self.check_inference_correctness(model_8bit_from_saved)
+
+ def test_int8_serialization_shard(self):
+ r"""
+ Test whether it is possible to serialize a model in 8-bit.
+ """
+ from bitsandbytes.nn import Int8Params
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ # saving state dict for now but will save config and other in the future
+ self.accelerate.save_model(self.model_8bit, tmpdirname, max_shard_size="1GB")
+
+ with init_empty_weights():
+ # let's suppose that we can get the right config
+ model_8bit_from_saved = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+
+ model_8bit_from_saved.tie_weights()
+
+ bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
+
+ model_8bit_from_saved = load_and_quantize_model(
+ model_8bit_from_saved,
+ bnb_quantization_config,
+ weights_location=tmpdirname,
+ device_map="auto",
+ no_split_module_classes=["BloomBlock"],
+ )
+
+ assert model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+ assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "SCB")
+ assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "CB")
+
+ self.check_inference_correctness(model_8bit_from_saved)
+
+
+@require_non_torch_xla
+@slow
+@require_cuda
+@require_bnb
+@require_huggingface_suite
+class MixedInt8LoaddedModelTest(unittest.TestCase):
+ # We keep the constants inside the init function and model loading inside setUp function
+
+ # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
+ # Therefore here we use only bloom-1b3 to test our module
+ model_name = "marcsun13/bloom-1b7_with_lm_head"
+
+ # Constant values
+ # This was obtained on a Quadro RTX 8000 so the number might slightly change
+ EXPECTED_RELATIVE_DIFFERENCE = 1.540025
+
+ input_text = "Hello my name is"
+ EXPECTED_OUTPUT = "Hello my name is John.\nI am a friend of the family.\n"
+ MAX_NEW_TOKENS = 10
+
+ def setUp(self):
+ """
+ Setup quantized model from loaded model
+ """
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ # Models and tokenizer
+ self.model_fp16 = AutoModelForCausalLM.from_pretrained(
+ self.model_name, torch_dtype=torch.float16, device_map="auto"
+ )
+
+ self.bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
+
+ self.model_8bit = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16)
+ self.model_8bit = load_and_quantize_model(self.model_8bit, self.bnb_quantization_config)
+
+ self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7")
+
+ def tearDown(self):
+ r"""
+ TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
+ avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
+ """
+ del self.model_fp16
+ del self.model_8bit
+
+ gc.collect()
+ torch.cuda.empty_cache()
+
+ def test_memory_footprint(self):
+ r"""
+ A simple test to check if the model conversion has been done correctly by checking on the
+ memory footprint of the converted model and the class type of the linear layers of the converted models
+ """
+ from bitsandbytes.nn import Int8Params
+
+ mem_fp16 = self.model_fp16.get_memory_footprint()
+ mem_8bit = self.model_8bit.get_memory_footprint()
+
+ assert round((mem_fp16 / mem_8bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0
+ assert self.model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
+
+ def test_linear_are_8bit(self):
+ r"""
+ A simple test to check if the model conversion has been done correctly by checking on the
+ memory footprint of the converted model and the class type of the linear layers of the converted models
+ """
+
+ self.model_fp16.get_memory_footprint()
+ self.model_8bit.get_memory_footprint()
+
+ for name, module in self.model_8bit.named_modules():
+ if isinstance(module, torch.nn.Linear):
+ modules_not_converted = (
+ self.bnb_quantization_config.keep_in_fp32_modules + self.bnb_quantization_config.skip_modules
+ )
+ if name not in modules_not_converted:
+ assert module.weight.dtype == torch.int8
+
+ def test_generate_quality(self):
+ r"""
+ Test the generation quality of the quantized model and see that we are matching the expected output.
+ Given that we are operating on small numbers + the testing model is relatively small, we might not get
+ the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
+ """
+ encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
+
+ output_sequences = self.model_8bit.generate(
+ input_ids=encoded_input["input_ids"].to(self.model_8bit.device), max_new_tokens=10
+ )
+
+ assert self.tokenizer.decode(output_sequences[0], skip_special_tokens=True) == self.EXPECTED_OUTPUT
+
+ def test_fp32_8bit_conversion(self):
+ r"""
+ Test whether it is possible to mix both `8bit` and `fp32` weights when using `keep_in_fp32_modules` correctly.
+ """
+ from transformers import AutoModelForCausalLM
+
+ bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True, keep_in_fp32_modules=["lm_head"])
+
+ model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16)
+ model = load_and_quantize_model(model, bnb_quantization_config)
+ assert model.lm_head.weight.dtype == torch.float32
+
+
+@require_non_torch_xla
+@slow
+@require_cuda
+@require_bnb
+@require_huggingface_suite
+class Bnb4BitEmptyModelTest(unittest.TestCase):
+ # We keep the constants inside the init function and model loading inside setUp function
+
+ # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
+ # Therefore here we use only bloom-1b3 to test our module
+ model_name = "marcsun13/bloom-1b7_with_lm_head"
+
+ # Constant values
+ # This was obtained on a RTX Titan so the number might slightly change
+ EXPECTED_RELATIVE_DIFFERENCE = 2.109659552692574
+
+ input_text = "Hello my name is"
+ EXPECTED_OUTPUTS = set()
+ EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I")
+ EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n")
+ MAX_NEW_TOKENS = 10
+
+ def setUp(self):
+ from huggingface_hub import hf_hub_download
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
+
+ super().setUp()
+
+ # Models and tokenizer
+ self.model_fp16 = AutoModelForCausalLM.from_pretrained(
+ self.model_name, torch_dtype=torch.float16, device_map="auto"
+ )
+
+ # create model on meta device
+ with init_empty_weights():
+ self.model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+
+ self.model_4bit.tie_weights()
+ self.weights_location = hf_hub_download(self.model_name, "pytorch_model.bin")
+ self.bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True)
+
+ self.model_4bit = load_and_quantize_model(
+ self.model_4bit,
+ self.bnb_quantization_config,
+ weights_location=self.weights_location,
+ device_map={"": 0},
+ no_split_module_classes=["BloomBlock"],
+ )
+
+ self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7")
+
+ def tearDown(self):
+ """
+ TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
+ avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
+ """
+ super().tearDown()
+ del self.model_fp16
+ del self.model_4bit
+
+ gc.collect()
+ torch.cuda.empty_cache()
+
+ def test_memory_footprint(self):
+ r"""
+ A simple test to check if the model conversion has been done correctly by checking on the
+ memory footprint of the converted model and the class type of the linear layers of the converted models
+ """
+ from bitsandbytes.nn import Params4bit
+
+ mem_fp16 = self.model_fp16.get_memory_footprint()
+ mem_4bit = self.model_4bit.get_memory_footprint()
+
+ assert round((mem_fp16 / mem_4bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0
+ assert self.model_4bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Params4bit
+
+ def check_inference_correctness(self, model):
+ r"""
+ Test the generation quality of the quantized model and see that we are matching the expected output.
+ Given that we are operating on small numbers + the testing model is relatively small, we might not get
+ the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
+ """
+ # Check that inference pass works on the model
+ encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
+
+ # Check the exactness of the results
+ output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10)
+
+ assert self.tokenizer.decode(output_sequences[0], skip_special_tokens=True) in self.EXPECTED_OUTPUTS
+
+ def test_generate_quality(self):
+ self.check_inference_correctness(self.model_4bit)
+
+ def test_linear_are_4bit(self):
+ r"""
+ A simple test to check if the model conversion has been done correctly by checking on the
+ memory footprint of the converted model and the class type of the linear layers of the converted models
+ """
+
+ self.model_fp16.get_memory_footprint()
+ self.model_4bit.get_memory_footprint()
+
+ for name, module in self.model_4bit.named_modules():
+ if isinstance(module, torch.nn.Linear):
+ if (
+ name
+ not in self.bnb_quantization_config.keep_in_fp32_modules
+ + self.bnb_quantization_config.skip_modules
+ ):
+ # 4-bit parameters are packed in uint8 variables
+ assert module.weight.dtype == torch.uint8
+
+ def test_fp32_4bit_conversion(self):
+ r"""
+ Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly.
+ """
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True, keep_in_fp32_modules=["lm_head"])
+
+ with init_empty_weights():
+ model = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+
+ model.tie_weights()
+ model = load_and_quantize_model(
+ model,
+ bnb_quantization_config,
+ weights_location=self.weights_location,
+ device_map="auto",
+ no_split_module_classes=["BloomBlock"],
+ )
+ assert model.lm_head.weight.dtype == torch.float32
+
+ @require_multi_gpu
+ def test_cpu_gpu_loading_random_device_map(self):
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ r"""
+ A test to check is dispatching a model on cpu & gpu works correctly using a random `device_map`.
+ """
+ device_map = {
+ "transformer.word_embeddings": "cpu",
+ "transformer.word_embeddings_layernorm": 0,
+ "lm_head": "cpu",
+ "transformer.h.0": 0,
+ "transformer.h.1": 0,
+ "transformer.h.2": 0,
+ "transformer.h.3": 0,
+ "transformer.h.4": 0,
+ "transformer.h.5": 0,
+ "transformer.h.6": 0,
+ "transformer.h.7": 0,
+ "transformer.h.8": 0,
+ "transformer.h.9": 1,
+ "transformer.h.10": 0,
+ "transformer.h.11": 1,
+ "transformer.h.12": 0,
+ "transformer.h.13": 0,
+ "transformer.h.14": 1,
+ "transformer.h.15": 0,
+ "transformer.h.16": 0,
+ "transformer.h.17": 1,
+ "transformer.h.18": 1,
+ "transformer.h.19": 0,
+ "transformer.h.20": 1,
+ "transformer.h.21": 1,
+ "transformer.h.22": 0,
+ "transformer.h.23": 0,
+ "transformer.ln_f": 1,
+ }
+
+ bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True)
+
+ with init_empty_weights():
+ model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+
+ model_4bit.tie_weights()
+ model_4bit = load_and_quantize_model(
+ model_4bit,
+ bnb_quantization_config,
+ weights_location=self.weights_location,
+ device_map=device_map,
+ no_split_module_classes=["BloomBlock"],
+ )
+ self.check_inference_correctness(model_4bit)
+
+ @require_multi_gpu
+ def test_cpu_gpu_loading_custom_device_map(self):
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ r"""
+ A test to check is dispatching a model on cpu & gpu works correctly using a random `device_map`.
+ """
+ device_map = {
+ "transformer.word_embeddings": "cpu",
+ "transformer.word_embeddings_layernorm": "cpu",
+ "lm_head": "cpu",
+ "transformer.h": 0,
+ "transformer.ln_f": 1,
+ }
+
+ bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True)
+
+ with init_empty_weights():
+ model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+
+ model_4bit.tie_weights()
+ model_4bit = load_and_quantize_model(
+ model_4bit,
+ bnb_quantization_config,
+ weights_location=self.weights_location,
+ device_map=device_map,
+ no_split_module_classes=["BloomBlock"],
+ )
+ self.check_inference_correctness(model_4bit)
+
+ @require_multi_gpu
+ def test_cpu_gpu_disk_loading_custom_device_map_kwargs(self):
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ r"""
+ A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`.
+ This time we also add `disk` on the device_map - using the kwargs directly instead of the quantization config
+ """
+ device_map = {
+ "transformer.word_embeddings": 0,
+ "transformer.word_embeddings_layernorm": "disk",
+ "lm_head": 0,
+ "transformer.h": 1,
+ "transformer.ln_f": "cpu",
+ }
+ bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True)
+
+ with init_empty_weights():
+ model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
+
+ model_4bit.tie_weights()
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model_4bit = load_and_quantize_model(
+ model_4bit,
+ bnb_quantization_config,
+ weights_location=self.weights_location,
+ device_map=device_map,
+ no_split_module_classes=["BloomBlock"],
+ offload_folder=tmpdirname,
+ offload_state_dict=True,
+ )
+ self.check_inference_correctness(model_4bit)
+
+
+@require_non_torch_xla
+@slow
+@require_cuda
+@require_bnb
+@require_huggingface_suite
+class Bnb4BitTestLoadedModel(unittest.TestCase):
+ # We keep the constants inside the init function and model loading inside setUp function
+
+ # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
+ # Therefore here we use only bloom-1b3 to test our module
+ model_name = "marcsun13/bloom-1b7_with_lm_head"
+
+ # Constant values
+ # This was obtained on a RTX Titan so the number might slightly change
+ EXPECTED_RELATIVE_DIFFERENCE = 2.109659552692574
+
+ input_text = "Hello my name is"
+ EXPECTED_OUTPUTS = set()
+ EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I")
+ EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n")
+ MAX_NEW_TOKENS = 10
+
+ def setUp(self):
+ """
+ Setup quantized model from loaded model
+ """
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ super().setUp()
+
+ # Models and tokenizer
+ self.model_fp16 = AutoModelForCausalLM.from_pretrained(
+ self.model_name, torch_dtype=torch.float16, device_map="auto"
+ )
+
+ self.bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True)
+
+ self.model_4bit = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16)
+ self.model_4bit = load_and_quantize_model(self.model_4bit, self.bnb_quantization_config)
+
+ self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7")
+
+ def tearDown(self):
+ """
+ TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
+ avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
+ """
+ super().tearDown()
+ del self.model_fp16
+ del self.model_4bit
+
+ gc.collect()
+ torch.cuda.empty_cache()
+
+ def test_memory_footprint(self):
+ r"""
+ A simple test to check if the model conversion has been done correctly by checking on the
+ memory footprint of the converted model and the class type of the linear layers of the converted models
+ """
+ from bitsandbytes.nn import Params4bit
+
+ mem_fp16 = self.model_fp16.get_memory_footprint()
+ mem_4bit = self.model_4bit.get_memory_footprint()
+
+ assert round((mem_fp16 / mem_4bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0
+ assert self.model_4bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Params4bit
+
+ def test_linear_are_4bit(self):
+ r"""
+ A simple test to check if the model conversion has been done correctly by checking on the
+ memory footprint of the converted model and the class type of the linear layers of the converted models
+ """
+
+ self.model_fp16.get_memory_footprint()
+ self.model_4bit.get_memory_footprint()
+
+ for name, module in self.model_4bit.named_modules():
+ if isinstance(module, torch.nn.Linear):
+ if (
+ name
+ not in self.bnb_quantization_config.keep_in_fp32_modules
+ + self.bnb_quantization_config.skip_modules
+ ):
+ # 4-bit parameters are packed in uint8 variables
+ assert module.weight.dtype == torch.uint8
+
+ def test_generate_quality(self):
+ r"""
+ Test the generation quality of the quantized model and see that we are matching the expected output.
+ Given that we are operating on small numbers + the testing model is relatively small, we might not get
+ the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
+ """
+ encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
+
+ output_sequences = self.model_4bit.generate(
+ input_ids=encoded_input["input_ids"].to(self.model_4bit.device), max_new_tokens=10
+ )
+
+ assert self.tokenizer.decode(output_sequences[0], skip_special_tokens=True) in self.EXPECTED_OUTPUTS
+
+ def test_fp32_4bit_conversion(self):
+ r"""
+ Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly.
+ """
+ from transformers import AutoModelForCausalLM
+
+ bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True, keep_in_fp32_modules=["lm_head"])
+
+ model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16)
+ model = load_and_quantize_model(model, bnb_quantization_config)
+ assert model.lm_head.weight.dtype == torch.float32
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_sagemaker.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_sagemaker.py
new file mode 100644
index 0000000000000000000000000000000000000000..5166c0237eef6ad924fd401ca4974dafac224cfe
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_sagemaker.py
@@ -0,0 +1,76 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import unittest
+from dataclasses import dataclass
+
+import pytest
+
+from accelerate.commands.config.config_args import SageMakerConfig
+from accelerate.utils import ComputeEnvironment
+from accelerate.utils.launch import _convert_nargs_to_dict
+
+
+@dataclass
+class MockLaunchConfig(SageMakerConfig):
+ compute_environment = ComputeEnvironment.AMAZON_SAGEMAKER
+ fp16 = True
+ ec2_instance_type = "ml.p3.2xlarge"
+ iam_role_name = "accelerate_sagemaker_execution_role"
+ profile = "hf-sm"
+ region = "us-east-1"
+ num_machines = 1
+ base_job_name = "accelerate-sagemaker-1"
+ pytorch_version = "1.6"
+ transformers_version = "4.4"
+ training_script = "train.py"
+ success_training_script_args = [
+ "--model_name_or_path",
+ "bert",
+ "--do_train",
+ "False",
+ "--epochs",
+ "3",
+ "--learning_rate",
+ "5e-5",
+ "--max_steps",
+ "50.5",
+ ]
+ fail_training_script_args = [
+ "--model_name_or_path",
+ "bert",
+ "--do_train",
+ "--do_test",
+ "False",
+ "--do_predict",
+ "--epochs",
+ "3",
+ "--learning_rate",
+ "5e-5",
+ "--max_steps",
+ "50.5",
+ ]
+
+
+class SageMakerLaunch(unittest.TestCase):
+ def test_args_convert(self):
+ # If no defaults are changed, `to_kwargs` returns an empty dict.
+ converted_args = _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args)
+ assert isinstance(converted_args["model_name_or_path"], str)
+ assert isinstance(converted_args["do_train"], bool)
+ assert isinstance(converted_args["epochs"], int)
+ assert isinstance(converted_args["learning_rate"], float)
+ assert isinstance(converted_args["max_steps"], float)
+
+ with pytest.raises(ValueError):
+ _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_samples/MRPC/dev.csv b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_samples/MRPC/dev.csv
new file mode 100644
index 0000000000000000000000000000000000000000..96beccda96d7e164e4484e037a52fb338cc22180
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_samples/MRPC/dev.csv
@@ -0,0 +1,7 @@
+label,sentence1,sentence2
+equivalent,He said the foodservice pie business doesn 't fit the company 's long-term growth strategy .,""" The foodservice pie business does not fit our long-term growth strategy ."
+not_equivalent,Magnarelli said Racicot hated the Iraqi regime and looked forward to using his long years of training in the war .,"His wife said he was "" 100 percent behind George Bush "" and looked forward to using his years of training in the war ."
+not_equivalent,"The dollar was at 116.92 yen against the yen , flat on the session , and at 1.2891 against the Swiss franc , also flat .","The dollar was at 116.78 yen JPY = , virtually flat on the session , and at 1.2871 against the Swiss franc CHF = , down 0.1 percent ."
+equivalent,The AFL-CIO is waiting until October to decide if it will endorse a candidate .,The AFL-CIO announced Wednesday that it will decide in October whether to endorse a candidate before the primaries .
+not_equivalent,No dates have been set for the civil or the criminal trial .,"No dates have been set for the criminal or civil cases , but Shanley has pleaded not guilty ."
+equivalent,Wal-Mart said it would check all of its million-plus domestic workers to ensure they were legally employed .,It has also said it would review all of its domestic employees more than 1 million to ensure they have legal status .
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_samples/MRPC/train.csv b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_samples/MRPC/train.csv
new file mode 100644
index 0000000000000000000000000000000000000000..96beccda96d7e164e4484e037a52fb338cc22180
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_samples/MRPC/train.csv
@@ -0,0 +1,7 @@
+label,sentence1,sentence2
+equivalent,He said the foodservice pie business doesn 't fit the company 's long-term growth strategy .,""" The foodservice pie business does not fit our long-term growth strategy ."
+not_equivalent,Magnarelli said Racicot hated the Iraqi regime and looked forward to using his long years of training in the war .,"His wife said he was "" 100 percent behind George Bush "" and looked forward to using his years of training in the war ."
+not_equivalent,"The dollar was at 116.92 yen against the yen , flat on the session , and at 1.2891 against the Swiss franc , also flat .","The dollar was at 116.78 yen JPY = , virtually flat on the session , and at 1.2871 against the Swiss franc CHF = , down 0.1 percent ."
+equivalent,The AFL-CIO is waiting until October to decide if it will endorse a candidate .,The AFL-CIO announced Wednesday that it will decide in October whether to endorse a candidate before the primaries .
+not_equivalent,No dates have been set for the civil or the criminal trial .,"No dates have been set for the criminal or civil cases , but Shanley has pleaded not guilty ."
+equivalent,Wal-Mart said it would check all of its million-plus domestic workers to ensure they were legally employed .,It has also said it would review all of its domestic employees more than 1 million to ensure they have legal status .
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_samples/test_command_file.sh b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_samples/test_command_file.sh
new file mode 100644
index 0000000000000000000000000000000000000000..592a7d5324e281f0bfc5490e4ae303cae1fe7df1
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_samples/test_command_file.sh
@@ -0,0 +1,2 @@
+echo "hello world"
+echo "this is a second command"
\ No newline at end of file
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_scheduler.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..edad5a73365dd0655b6456cc3c2dd073f42c38c3
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_scheduler.py
@@ -0,0 +1,142 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import unittest
+from functools import partial
+
+import torch
+
+from accelerate import Accelerator, debug_launcher
+from accelerate.state import AcceleratorState, GradientState
+from accelerate.test_utils import require_cpu, require_huggingface_suite
+from accelerate.utils import GradientAccumulationPlugin
+
+
+def one_cycle_test(num_processes=2, step_scheduler_with_optimizer=True, split_batches=False):
+ accelerator = Accelerator(step_scheduler_with_optimizer=step_scheduler_with_optimizer, split_batches=split_batches)
+ model = torch.nn.Linear(2, 4)
+ optimizer = torch.optim.AdamW(model.parameters(), lr=1.0)
+ scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.01, steps_per_epoch=2, epochs=1)
+ model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler)
+
+ # Optimizer has stepped
+ scheduler.step()
+ if step_scheduler_with_optimizer or (num_processes == 1):
+ assert (
+ scheduler.scheduler.last_epoch == num_processes
+ ), f"Last Epoch ({scheduler.scheduler.last_epoch}) != Num Processes ({num_processes})"
+ else:
+ assert (
+ scheduler.scheduler.last_epoch != num_processes
+ ), f"Last Epoch ({scheduler.scheduler.last_epoch}) == Num Processes ({num_processes})"
+
+
+def lambda_test(num_processes=2, step_scheduler_with_optimizer=True, split_batches=False):
+ accelerator = Accelerator(step_scheduler_with_optimizer=step_scheduler_with_optimizer, split_batches=split_batches)
+ model = torch.nn.Linear(2, 4)
+ optimizer = torch.optim.AdamW(model.parameters(), lr=1.0)
+ scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda n: 1 - n / 10)
+ model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler)
+
+ # Optimizer has stepped
+ optimizer._is_overflow = False
+ scheduler.step()
+ expected_lr = 1 - (num_processes if (step_scheduler_with_optimizer and not split_batches) else 1) / 10
+ assert (
+ scheduler.get_last_lr()[0] == expected_lr
+ ), f"Wrong lr found at first step, expected {expected_lr}, got {scheduler.get_last_lr()[0]}"
+
+ # Optimizer has not stepped
+ optimizer._is_overflow = True
+ scheduler.step()
+ if not step_scheduler_with_optimizer:
+ expected_lr = 1 - 2 / 10
+ assert (
+ scheduler.get_last_lr()[0] == expected_lr
+ ), f"Wrong lr found at second step, expected {expected_lr}, got {scheduler.get_last_lr()[0]}"
+
+
+def accumulation_test(num_processes: int = 2):
+ """
+ With this test, an observed batch size of 64 should result in neglible
+ differences in the scheduler after going through the correct number of steps.
+
+ Uses single, two, and four steps to test.
+ """
+ from transformers import get_linear_schedule_with_warmup
+
+ steps = [1, 2, 4]
+ for num_steps in steps:
+ plugin = GradientAccumulationPlugin(num_steps=num_steps, adjust_scheduler=num_steps > 1)
+ accelerator = Accelerator(gradient_accumulation_plugin=plugin)
+ model = torch.nn.Linear(2, 4)
+ optimizer = torch.optim.AdamW(model.parameters(), lr=10.0)
+ scheduler = get_linear_schedule_with_warmup(optimizer=optimizer, num_warmup_steps=0, num_training_steps=20)
+
+ model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler)
+
+ for i in range(10 * num_steps):
+ with accelerator.accumulate(model):
+ optimizer.step()
+ scheduler.step()
+
+ if i == (10 * num_steps - 2):
+ assert (
+ scheduler.get_last_lr()[0] != 0
+ ), f"Wrong lr found at second-to-last step, expected non-zero, got {scheduler.get_last_lr()[0]}. num_steps: {num_steps}"
+ assert (
+ scheduler.get_last_lr()[0] == 0
+ ), f"Wrong lr found at last step, expected 0, got {scheduler.get_last_lr()[0]}"
+ GradientState._reset_state()
+
+
+@require_cpu
+class SchedulerTester(unittest.TestCase):
+ def test_lambda_scheduler_steps_with_optimizer_single_process(self):
+ debug_launcher(partial(lambda_test, num_processes=1), num_processes=1)
+ debug_launcher(partial(lambda_test, num_processes=1, split_batches=True), num_processes=1)
+
+ def test_one_cycle_scheduler_steps_with_optimizer_single_process(self):
+ debug_launcher(partial(one_cycle_test, num_processes=1), num_processes=1)
+ debug_launcher(partial(one_cycle_test, num_processes=1, split_batches=True), num_processes=1)
+
+ def test_lambda_scheduler_not_step_with_optimizer_single_process(self):
+ debug_launcher(partial(lambda_test, num_processes=1, step_scheduler_with_optimizer=False), num_processes=1)
+
+ def test_one_cycle_scheduler_not_step_with_optimizer_single_process(self):
+ debug_launcher(partial(one_cycle_test, num_processes=1, step_scheduler_with_optimizer=False), num_processes=1)
+
+ def test_lambda_scheduler_steps_with_optimizer_multiprocess(self):
+ AcceleratorState._reset_state(True)
+ debug_launcher(lambda_test)
+ debug_launcher(partial(lambda_test, num_processes=1, split_batches=True), num_processes=1)
+
+ def test_one_cycle_scheduler_steps_with_optimizer_multiprocess(self):
+ AcceleratorState._reset_state(True)
+ debug_launcher(one_cycle_test)
+ debug_launcher(partial(one_cycle_test, num_processes=1, split_batches=True), num_processes=1)
+
+ def test_lambda_scheduler_not_step_with_optimizer_multiprocess(self):
+ AcceleratorState._reset_state(True)
+ debug_launcher(partial(lambda_test, step_scheduler_with_optimizer=False))
+
+ def test_one_cycle_scheduler_not_step_with_optimizer_multiprocess(self):
+ AcceleratorState._reset_state(True)
+ debug_launcher(partial(one_cycle_test, step_scheduler_with_optimizer=False))
+
+ @require_huggingface_suite
+ def test_accumulation(self):
+ AcceleratorState._reset_state(True)
+ debug_launcher(partial(accumulation_test, num_processes=1))
+ debug_launcher(accumulation_test)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_state_checkpointing.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_state_checkpointing.py
new file mode 100644
index 0000000000000000000000000000000000000000..bce4191bd4498c016bc972d5e5af19caff46013e
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_state_checkpointing.py
@@ -0,0 +1,446 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import inspect
+import logging
+import os
+import random
+import shutil
+import tempfile
+import unittest
+import uuid
+from contextlib import contextmanager
+
+import pytest
+import torch
+from parameterized import parameterized_class
+from torch import nn
+from torch.utils.data import DataLoader, TensorDataset
+
+from accelerate import Accelerator
+from accelerate.test_utils import (
+ DEFAULT_LAUNCH_COMMAND,
+ execute_subprocess_async,
+ require_non_cpu,
+ require_non_torch_xla,
+)
+from accelerate.utils import DistributedType, ProjectConfiguration, set_seed
+
+
+logger = logging.getLogger(__name__)
+
+
+def dummy_dataloaders(a=2, b=3, batch_size=16, n_train_batches: int = 10, n_valid_batches: int = 2):
+ "Generates a tuple of dummy DataLoaders to test with"
+
+ def get_dataset(n_batches):
+ x = torch.randn(batch_size * n_batches, 1)
+ return TensorDataset(x, a * x + b + 0.1 * torch.randn(batch_size * n_batches, 1))
+
+ train_dataset = get_dataset(n_train_batches)
+ valid_dataset = get_dataset(n_valid_batches)
+ train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4)
+ valid_dataloader = DataLoader(valid_dataset, shuffle=False, batch_size=batch_size, num_workers=4)
+ return (train_dataloader, valid_dataloader)
+
+
+def train(num_epochs, model, dataloader, optimizer, accelerator, scheduler=None):
+ "Trains for `num_epochs`"
+ rands = []
+ for epoch in range(num_epochs):
+ # Train quickly
+ model.train()
+ for batch in dataloader:
+ x, y = batch
+ outputs = model(x)
+ loss = torch.nn.functional.mse_loss(outputs, y)
+ accelerator.backward(loss)
+ optimizer.step()
+ optimizer.zero_grad()
+ rands.append(random.random()) # Introduce some randomness
+ if scheduler is not None:
+ scheduler.step()
+ return rands
+
+
+class DummyModel(nn.Module):
+ "Simple model to do y=mx+b"
+
+ def __init__(self):
+ super().__init__()
+ self.a = nn.Parameter(torch.randn(1))
+ self.b = nn.Parameter(torch.randn(1))
+
+ def forward(self, x):
+ return x * self.a + self.b
+
+
+def parameterized_custom_name_func(func, param_num, param):
+ # customize the test name generator function as we want both params to appear in the sub-test
+ # name, as by default it shows only the first param
+ param_based_name = "use_safetensors" if param["use_safetensors"] is True else "use_pytorch"
+ return f"{func.__name__}_{param_based_name}"
+
+
+@parameterized_class(("use_safetensors",), [[True], [False]], class_name_func=parameterized_custom_name_func)
+class CheckpointTest(unittest.TestCase):
+ def check_adam_state(self, state1, state2, distributed_type):
+ # For DistributedType.XLA, the `accelerator.save_state` function calls `xm._maybe_convert_to_cpu` before saving.
+ # As a result, all tuple values are converted to lists. Therefore, we need to convert them back here.
+ # Remove this code once Torch XLA fixes this issue.
+ if distributed_type == DistributedType.XLA:
+ state1["param_groups"][0]["betas"] = tuple(state1["param_groups"][0]["betas"])
+ state2["param_groups"][0]["betas"] = tuple(state2["param_groups"][0]["betas"])
+ assert state1 == state2
+
+ def test_with_save_limit(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ set_seed(42)
+ model = DummyModel()
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
+ train_dataloader, valid_dataloader = dummy_dataloaders()
+ project_config = ProjectConfiguration(total_limit=1, project_dir=tmpdir, automatic_checkpoint_naming=True)
+ # Train baseline
+ accelerator = Accelerator(project_config=project_config)
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
+ model, optimizer, train_dataloader, valid_dataloader
+ )
+ # Save initial
+ accelerator.save_state(safe_serialization=self.use_safetensors)
+
+ # Save second state
+ accelerator.save_state(safe_serialization=self.use_safetensors)
+ assert len(os.listdir(accelerator.project_dir)) == 1
+
+ def test_can_resume_training_with_folder(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ set_seed(42)
+ model = DummyModel()
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
+ train_dataloader, valid_dataloader = dummy_dataloaders()
+ # Train baseline
+ accelerator = Accelerator()
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
+ model, optimizer, train_dataloader, valid_dataloader
+ )
+ # Save initial
+ initial = os.path.join(tmpdir, "initial")
+ accelerator.save_state(initial, safe_serialization=self.use_safetensors)
+ (a, b) = model.a.item(), model.b.item()
+ opt_state = optimizer.state_dict()
+ ground_truth_rands = train(3, model, train_dataloader, optimizer, accelerator)
+ (a1, b1) = model.a.item(), model.b.item()
+ opt_state1 = optimizer.state_dict()
+
+ # Train partially
+ set_seed(42)
+ model = DummyModel()
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
+ train_dataloader, valid_dataloader = dummy_dataloaders()
+ accelerator = Accelerator()
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
+ model, optimizer, train_dataloader, valid_dataloader
+ )
+ accelerator.load_state(initial)
+ (a2, b2) = model.a.item(), model.b.item()
+ opt_state2 = optimizer.state_dict()
+ self.assertEqual(a, a2)
+ self.assertEqual(b, b2)
+ assert a == a2
+ assert b == b2
+ self.check_adam_state(opt_state, opt_state2, accelerator.distributed_type)
+
+ test_rands = train(2, model, train_dataloader, optimizer, accelerator)
+ # Save everything
+ checkpoint = os.path.join(tmpdir, "checkpoint")
+ accelerator.save_state(checkpoint, safe_serialization=self.use_safetensors)
+
+ # Load everything back in and make sure all states work
+ accelerator.load_state(checkpoint)
+ test_rands += train(1, model, train_dataloader, optimizer, accelerator)
+ (a3, b3) = model.a.item(), model.b.item()
+ opt_state3 = optimizer.state_dict()
+ assert a1 == a3
+ assert b1 == b3
+ self.check_adam_state(opt_state1, opt_state3, accelerator.distributed_type)
+ assert ground_truth_rands == test_rands
+
+ def test_can_resume_training(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ set_seed(42)
+ model = DummyModel()
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
+ train_dataloader, valid_dataloader = dummy_dataloaders()
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True)
+
+ # Train baseline
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
+ model, optimizer, train_dataloader, valid_dataloader
+ )
+ # Save initial
+ accelerator.save_state(safe_serialization=self.use_safetensors)
+ (a, b) = model.a.item(), model.b.item()
+ opt_state = optimizer.state_dict()
+ ground_truth_rands = train(3, model, train_dataloader, optimizer, accelerator)
+ (a1, b1) = model.a.item(), model.b.item()
+ opt_state1 = optimizer.state_dict()
+
+ # Train partially
+ set_seed(42)
+ model = DummyModel()
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
+ train_dataloader, valid_dataloader = dummy_dataloaders()
+ project_config = ProjectConfiguration(iteration=1, automatic_checkpoint_naming=True)
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
+ model, optimizer, train_dataloader, valid_dataloader
+ )
+ accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_0"))
+ (a2, b2) = model.a.item(), model.b.item()
+ opt_state2 = optimizer.state_dict()
+ assert a == a2
+ assert b == b2
+ self.check_adam_state(opt_state, opt_state2, accelerator.distributed_type)
+
+ test_rands = train(2, model, train_dataloader, optimizer, accelerator)
+ # Save everything
+ accelerator.save_state(safe_serialization=self.use_safetensors)
+
+ # Load everything back in and make sure all states work
+ accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_1"))
+ test_rands += train(1, model, train_dataloader, optimizer, accelerator)
+ (a3, b3) = model.a.item(), model.b.item()
+ opt_state3 = optimizer.state_dict()
+ assert a1 == a3
+ assert b1 == b3
+ self.check_adam_state(opt_state1, opt_state3, accelerator.distributed_type)
+ assert ground_truth_rands == test_rands
+
+ def test_can_resume_training_checkpoints_relative_path(self):
+ # See #1983
+ # This test is like test_can_resume_training but uses a relative path for the checkpoint and automatically
+ # infers the checkpoint path when loading.
+ @contextmanager
+ def temporary_relative_directory():
+ # This is equivalent to tempfile.TemporaryDirectory() except that it returns a relative path
+ rand_dir = f"test_path_{uuid.uuid4()}"
+ os.mkdir(rand_dir)
+ try:
+ yield rand_dir
+ finally:
+ shutil.rmtree(rand_dir)
+
+ with temporary_relative_directory() as tmpdir:
+ set_seed(42)
+ model = DummyModel()
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
+ train_dataloader, valid_dataloader = dummy_dataloaders()
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True)
+
+ # Train baseline
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
+ model, optimizer, train_dataloader, valid_dataloader
+ )
+ # Save initial
+ accelerator.save_state(safe_serialization=self.use_safetensors)
+ (a, b) = model.a.item(), model.b.item()
+ opt_state = optimizer.state_dict()
+ ground_truth_rands = train(3, model, train_dataloader, optimizer, accelerator)
+ (a1, b1) = model.a.item(), model.b.item()
+ opt_state1 = optimizer.state_dict()
+
+ # Train partially
+ set_seed(42)
+ model = DummyModel()
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
+ train_dataloader, valid_dataloader = dummy_dataloaders()
+ project_config = ProjectConfiguration(iteration=1, automatic_checkpoint_naming=True)
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
+ model, optimizer, train_dataloader, valid_dataloader = accelerator.prepare(
+ model, optimizer, train_dataloader, valid_dataloader
+ )
+ accelerator.load_state() # <= infer the directory automatically
+ (a2, b2) = model.a.item(), model.b.item()
+ opt_state2 = optimizer.state_dict()
+ assert a == a2
+ assert b == b2
+ self.check_adam_state(opt_state, opt_state2, accelerator.distributed_type)
+ assert opt_state == opt_state2
+
+ test_rands = train(2, model, train_dataloader, optimizer, accelerator)
+ # Save everything
+ accelerator.save_state(safe_serialization=self.use_safetensors)
+
+ # Load everything back in and make sure all states work
+ accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_1"))
+ test_rands += train(1, model, train_dataloader, optimizer, accelerator)
+ (a3, b3) = model.a.item(), model.b.item()
+ opt_state3 = optimizer.state_dict()
+ assert a1 == a3
+ assert b1 == b3
+ self.check_adam_state(opt_state1, opt_state3, accelerator.distributed_type)
+ assert ground_truth_rands == test_rands
+
+ def test_invalid_registration(self):
+ t = torch.tensor([1, 2, 3])
+ t1 = torch.tensor([2, 3, 4])
+ net = DummyModel()
+ opt = torch.optim.Adam(net.parameters())
+ accelerator = Accelerator()
+ with self.assertRaises(ValueError) as ve:
+ accelerator.register_for_checkpointing(t, t1, net, opt)
+ message = str(ve.exception)
+ assert "Item at index 0" in message
+ assert "Item at index 1" in message
+ assert "Item at index 2" not in message
+ assert "Item at index 3" not in message
+
+ def test_with_scheduler(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ set_seed(42)
+ model = DummyModel()
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
+ scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
+ train_dataloader, valid_dataloader = dummy_dataloaders()
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True)
+ # Train baseline
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
+ model, optimizer, train_dataloader, valid_dataloader, scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, valid_dataloader, scheduler
+ )
+ # Save initial
+ accelerator.save_state(safe_serialization=self.use_safetensors)
+ scheduler_state = scheduler.state_dict()
+ train(3, model, train_dataloader, optimizer, accelerator, scheduler)
+ assert scheduler_state != scheduler.state_dict()
+
+ # Load everything back in and make sure all states work
+ accelerator.load_state(os.path.join(tmpdir, "checkpoints", "checkpoint_0"))
+ assert scheduler_state == scheduler.state_dict()
+
+ def test_automatic_loading(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ set_seed(42)
+ model = DummyModel()
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
+ scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
+ train_dataloader, valid_dataloader = dummy_dataloaders()
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True)
+ # Train baseline
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
+ model, optimizer, train_dataloader, valid_dataloader, scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, valid_dataloader, scheduler
+ )
+ # Save initial
+ accelerator.save_state(safe_serialization=self.use_safetensors)
+ train(2, model, train_dataloader, optimizer, accelerator, scheduler)
+ (a2, b2) = model.a.item(), model.b.item()
+ # Save a first time
+ accelerator.save_state(safe_serialization=self.use_safetensors)
+ train(1, model, train_dataloader, optimizer, accelerator, scheduler)
+ (a3, b3) = model.a.item(), model.b.item()
+
+ # Load back in the last saved checkpoint, should point to a2, b2
+ accelerator.load_state()
+ assert a3 != model.a.item()
+ assert b3 != model.b.item()
+ assert a2 == model.a.item()
+ assert b2 == model.b.item()
+
+ def test_checkpoint_deletion(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ set_seed(42)
+ model = DummyModel()
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True, total_limit=2)
+ # Train baseline
+ accelerator = Accelerator(project_dir=tmpdir, project_config=project_config)
+ model = accelerator.prepare(model)
+ # Save 3 states:
+ for _ in range(11):
+ accelerator.save_state(safe_serialization=self.use_safetensors)
+ assert not os.path.exists(os.path.join(tmpdir, "checkpoints", "checkpoint_0"))
+ assert os.path.exists(os.path.join(tmpdir, "checkpoints", "checkpoint_9"))
+ assert os.path.exists(os.path.join(tmpdir, "checkpoints", "checkpoint_10"))
+
+ @require_non_cpu
+ @require_non_torch_xla
+ def test_map_location(self):
+ cmd = DEFAULT_LAUNCH_COMMAND + [inspect.getfile(self.__class__)]
+ execute_subprocess_async(
+ cmd,
+ env={
+ **os.environ,
+ "USE_SAFETENSORS": str(self.use_safetensors),
+ "OMP_NUM_THREADS": "1",
+ },
+ )
+
+
+if __name__ == "__main__":
+ use_safetensors = os.environ.get("USE_SAFETENSORS", "False") == "True"
+ savedir = "/tmp/accelerate/state_checkpointing"
+ model = DummyModel()
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
+ scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
+ train_dataloader, valid_dataloader = dummy_dataloaders()
+ project_config = ProjectConfiguration(automatic_checkpoint_naming=True)
+ # Train baseline
+ accelerator = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="no")
+ if accelerator.process_index == 0:
+ if os.path.exists(savedir):
+ shutil.rmtree(savedir)
+ os.makedirs(savedir)
+ model, optimizer, train_dataloader, valid_dataloader, scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, valid_dataloader, scheduler
+ )
+ model, optimizer = accelerator.prepare(model, optimizer)
+ train(3, model, train_dataloader, optimizer, accelerator, scheduler)
+ # Check that the intial optimizer is loaded on the GPU
+ for group in optimizer.param_groups:
+ param_device = group["params"][0].device
+ break
+ assert param_device.type == accelerator.device.type
+ model = model.cpu()
+ accelerator.wait_for_everyone()
+ accelerator.save_state(safe_serialization=use_safetensors)
+ accelerator.wait_for_everyone()
+
+ # Check CPU state
+ accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="cpu")
+ for group in optimizer.param_groups:
+ param_device = group["params"][0].device
+ break
+ assert (
+ param_device.type == torch.device("cpu").type
+ ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"
+
+ # Check device state
+ model.to(accelerator.device)
+ accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="on_device")
+ for group in optimizer.param_groups:
+ param_device = group["params"][0].device
+ break
+ assert (
+ param_device.type == accelerator.device.type
+ ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"
+
+ # Check error
+ with pytest.raises(TypeError, match="Unsupported optimizer map location passed"):
+ accelerator.load_state(os.path.join(savedir, "checkpoints", "checkpoint_0"), map_location="invalid")
+ accelerator.wait_for_everyone()
+ if accelerator.process_index == 0:
+ shutil.rmtree(savedir)
+ accelerator.wait_for_everyone()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_tpu.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_tpu.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5a3c406a3aaf9a6065bff25007b2deeddd9214f
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_tpu.py
@@ -0,0 +1,34 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import sys
+import unittest
+
+from accelerate.test_utils import execute_subprocess_async, path_in_accelerate_package, require_tpu
+
+
+class MultiTPUTester(unittest.TestCase):
+ test_file_path = path_in_accelerate_package("test_utils", "scripts", "test_script.py")
+ test_dir = os.path.dirname(__file__)
+
+ @require_tpu
+ def test_tpu(self):
+ distributed_args = f"""
+ {self.test_dir}/xla_spawn.py
+ --num_cores 8
+ {self.test_file_path}
+ """.split()
+ cmd = [sys.executable] + distributed_args
+ execute_subprocess_async(cmd)
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_tracking.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_tracking.py
new file mode 100644
index 0000000000000000000000000000000000000000..99a147f55c1553481183d7fb98e6cbedcf040679
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_tracking.py
@@ -0,0 +1,535 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import csv
+import json
+import logging
+import os
+import re
+import subprocess
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+from typing import Optional
+from unittest import mock
+
+import numpy as np
+import torch
+from packaging import version
+
+# We use TF to parse the logs
+from accelerate import Accelerator
+from accelerate.test_utils.testing import (
+ MockingTestCase,
+ TempDirTestCase,
+ require_clearml,
+ require_comet_ml,
+ require_dvclive,
+ require_pandas,
+ require_tensorboard,
+ require_wandb,
+ skip,
+)
+from accelerate.tracking import CometMLTracker, GeneralTracker
+from accelerate.utils import (
+ ProjectConfiguration,
+ is_comet_ml_available,
+ is_dvclive_available,
+ is_tensorboard_available,
+)
+
+
+if is_comet_ml_available():
+ from comet_ml import OfflineExperiment
+
+if is_tensorboard_available():
+ import struct
+
+ import tensorboard.compat.proto.event_pb2 as event_pb2
+
+if is_dvclive_available():
+ from dvclive.plots.metric import Metric
+ from dvclive.serialize import load_yaml
+ from dvclive.utils import parse_metrics
+
+logger = logging.getLogger(__name__)
+
+
+@require_tensorboard
+class TensorBoardTrackingTest(unittest.TestCase):
+ @unittest.skipIf(version.parse(np.__version__) >= version.parse("2.0"), "TB doesn't support numpy 2.0")
+ def test_init_trackers(self):
+ project_name = "test_project_with_config"
+ with tempfile.TemporaryDirectory() as dirpath:
+ accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath)
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
+ accelerator.init_trackers(project_name, config)
+ accelerator.end_training()
+ for child in Path(f"{dirpath}/{project_name}").glob("*/**"):
+ log = list(filter(lambda x: x.is_file(), child.iterdir()))[0]
+ assert str(log) != ""
+
+ def test_log(self):
+ project_name = "test_project_with_log"
+ with tempfile.TemporaryDirectory() as dirpath:
+ accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath)
+ accelerator.init_trackers(project_name)
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
+ accelerator.log(values, step=0)
+ accelerator.end_training()
+ # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
+ # Names are randomly generated each time
+ log = list(filter(lambda x: x.is_file(), Path(f"{dirpath}/{project_name}").iterdir()))[0]
+ assert str(log) != ""
+
+ def test_log_with_tensor(self):
+ project_name = "test_project_with_log"
+ with tempfile.TemporaryDirectory() as dirpath:
+ accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath)
+ accelerator.init_trackers(project_name)
+ values = {"tensor": torch.tensor(1)}
+ accelerator.log(values, step=0)
+ accelerator.end_training()
+ # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
+ # Names are randomly generated each time
+ log = list(filter(lambda x: x.is_file(), Path(f"{dirpath}/{project_name}").iterdir()))[0]
+ # Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685
+ with open(log, "rb") as f:
+ data = f.read()
+ found_tensor = False
+ while data:
+ header = struct.unpack("Q", data[:8])
+
+ event_str = data[12 : 12 + int(header[0])] # 8+4
+ data = data[12 + int(header[0]) + 4 :]
+ event = event_pb2.Event()
+
+ event.ParseFromString(event_str)
+ if event.HasField("summary"):
+ for value in event.summary.value:
+ if value.simple_value == 1.0 and value.tag == "tensor":
+ found_tensor = True
+ assert found_tensor, "Converted tensor was not found in the log file!"
+
+ def test_project_dir(self):
+ with self.assertRaisesRegex(ValueError, "Logging with `tensorboard` requires a `logging_dir`"):
+ _ = Accelerator(log_with="tensorboard")
+ with tempfile.TemporaryDirectory() as dirpath:
+ _ = Accelerator(log_with="tensorboard", project_dir=dirpath)
+
+ def test_project_dir_with_config(self):
+ config = ProjectConfiguration(total_limit=30)
+ with tempfile.TemporaryDirectory() as dirpath:
+ _ = Accelerator(log_with="tensorboard", project_dir=dirpath, project_config=config)
+
+
+@require_wandb
+@mock.patch.dict(os.environ, {"WANDB_MODE": "offline"})
+class WandBTrackingTest(TempDirTestCase, MockingTestCase):
+ def setUp(self):
+ super().setUp()
+ # wandb let's us override where logs are stored to via the WANDB_DIR env var
+ self.add_mocks(mock.patch.dict(os.environ, {"WANDB_DIR": self.tmpdir}))
+
+ @staticmethod
+ def parse_log(log: str, section: str, record: bool = True):
+ """
+ Parses wandb log for `section` and returns a dictionary of
+ all items in that section. Section names are based on the
+ output of `wandb sync --view --verbose` and items starting
+ with "Record" in that result
+ """
+ # Big thanks to the W&B team for helping us parse their logs
+ pattern = rf"{section} ([\S\s]*?)\n\n"
+ if record:
+ pattern = rf"Record: {pattern}"
+ cleaned_record = re.findall(pattern, log)[0]
+ # A config
+ if section == "config" or section == "history":
+ cleaned_record = re.findall(r'"([a-zA-Z0-9_.,]+)', cleaned_record)
+ return {key: val for key, val in zip(cleaned_record[0::2], cleaned_record[1::2])}
+ # Everything else
+ else:
+ return dict(re.findall(r'(\w+): "([^\s]+)"', cleaned_record))
+
+ @skip
+ def test_wandb(self):
+ project_name = "test_project_with_config"
+ accelerator = Accelerator(log_with="wandb")
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
+ kwargs = {"wandb": {"tags": ["my_tag"]}}
+ accelerator.init_trackers(project_name, config, kwargs)
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
+ accelerator.log(values, step=0)
+ accelerator.end_training()
+ # The latest offline log is stored at wandb/latest-run/*.wandb
+ for child in Path(f"{self.tmpdir}/wandb/latest-run").glob("*"):
+ if child.is_file() and child.suffix == ".wandb":
+ cmd = ["wandb", "sync", "--view", "--verbose", str(child)]
+ content = subprocess.check_output(cmd, encoding="utf8", errors="ignore")
+ break
+
+ # Check HPS through careful parsing and cleaning
+ logged_items = self.parse_log(content, "config")
+ assert logged_items["num_iterations"] == "12"
+ assert logged_items["learning_rate"] == "0.01"
+ assert logged_items["some_boolean"] == "false"
+ assert logged_items["some_string"] == "some_value"
+ assert logged_items["some_string"] == "some_value"
+
+ # Run tags
+ logged_items = self.parse_log(content, "run", False)
+ assert logged_items["tags"] == "my_tag"
+
+ # Actual logging
+ logged_items = self.parse_log(content, "history")
+ assert logged_items["total_loss"] == "0.1"
+ assert logged_items["iteration"] == "1"
+ assert logged_items["my_text"] == "some_value"
+ assert logged_items["_step"] == "0"
+
+
+# Comet has a special `OfflineExperiment` we need to use for testing
+def offline_init(self, run_name: str, tmpdir: str):
+ self.run_name = run_name
+ self.writer = OfflineExperiment(project_name=run_name, offline_directory=tmpdir)
+ logger.info(f"Initialized offline CometML project {self.run_name}")
+ logger.info("Make sure to log any initial configurations with `self.store_init_configuration` before training!")
+
+
+@require_comet_ml
+@mock.patch.object(CometMLTracker, "__init__", offline_init)
+class CometMLTest(unittest.TestCase):
+ @staticmethod
+ def get_value_from_key(log_list, key: str, is_param: bool = False):
+ "Extracts `key` from Comet `log`"
+ for log in log_list:
+ j = json.loads(log)["payload"]
+ if is_param and "param" in j.keys():
+ if j["param"]["paramName"] == key:
+ return j["param"]["paramValue"]
+ if "log_other" in j.keys():
+ if j["log_other"]["key"] == key:
+ return j["log_other"]["val"]
+ if "metric" in j.keys():
+ if j["metric"]["metricName"] == key:
+ return j["metric"]["metricValue"]
+ if j.get("key", None) == key:
+ return j["value"]
+
+ def test_init_trackers(self):
+ with tempfile.TemporaryDirectory() as d:
+ tracker = CometMLTracker("test_project_with_config", d)
+ accelerator = Accelerator(log_with=tracker)
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
+ accelerator.init_trackers(None, config)
+ accelerator.end_training()
+ log = os.listdir(d)[0] # Comet is nice, it's just a zip file here
+ # We parse the raw logs
+ p = os.path.join(d, log)
+ archive = zipfile.ZipFile(p, "r")
+ log = archive.open("messages.json").read().decode("utf-8")
+ list_of_json = log.split("\n")[:-1]
+ assert self.get_value_from_key(list_of_json, "num_iterations", True) == 12
+ assert self.get_value_from_key(list_of_json, "learning_rate", True) == 0.01
+ assert self.get_value_from_key(list_of_json, "some_boolean", True) is False
+ assert self.get_value_from_key(list_of_json, "some_string", True) == "some_value"
+
+ def test_log(self):
+ with tempfile.TemporaryDirectory() as d:
+ tracker = CometMLTracker("test_project_with_config", d)
+ accelerator = Accelerator(log_with=tracker)
+ accelerator.init_trackers(None)
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
+ accelerator.log(values, step=0)
+ accelerator.end_training()
+ log = os.listdir(d)[0] # Comet is nice, it's just a zip file here
+ # We parse the raw logs
+ p = os.path.join(d, log)
+ archive = zipfile.ZipFile(p, "r")
+ log = archive.open("messages.json").read().decode("utf-8")
+ list_of_json = log.split("\n")[:-1]
+ assert self.get_value_from_key(list_of_json, "curr_step", True) == 0
+ assert self.get_value_from_key(list_of_json, "total_loss") == 0.1
+ assert self.get_value_from_key(list_of_json, "iteration") == 1
+ assert self.get_value_from_key(list_of_json, "my_text") == "some_value"
+
+
+@require_clearml
+class ClearMLTest(TempDirTestCase, MockingTestCase):
+ def setUp(self):
+ super().setUp()
+ # ClearML offline session location is stored in CLEARML_CACHE_DIR
+ self.add_mocks(mock.patch.dict(os.environ, {"CLEARML_CACHE_DIR": str(self.tmpdir)}))
+
+ @staticmethod
+ def _get_offline_dir(accelerator):
+ from clearml.config import get_offline_dir
+
+ return get_offline_dir(task_id=accelerator.get_tracker("clearml", unwrap=True).id)
+
+ @staticmethod
+ def _get_metrics(offline_dir):
+ metrics = []
+ with open(os.path.join(offline_dir, "metrics.jsonl")) as f:
+ json_lines = f.readlines()
+ for json_line in json_lines:
+ metrics.extend(json.loads(json_line))
+ return metrics
+
+ def test_init_trackers(self):
+ from clearml import Task
+ from clearml.utilities.config import text_to_config_dict
+
+ Task.set_offline(True)
+ accelerator = Accelerator(log_with="clearml")
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
+ accelerator.init_trackers("test_project_with_config", config)
+
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
+ accelerator.end_training()
+
+ with open(os.path.join(offline_dir, "task.json")) as f:
+ offline_session = json.load(f)
+ clearml_offline_config = text_to_config_dict(offline_session["configuration"]["General"]["value"])
+ assert config == clearml_offline_config
+
+ def test_log(self):
+ from clearml import Task
+
+ Task.set_offline(True)
+ accelerator = Accelerator(log_with="clearml")
+ accelerator.init_trackers("test_project_with_log")
+ values_with_iteration = {"should_be_under_train": 1, "eval_value": 2, "test_value": 3.1, "train_value": 4.1}
+ accelerator.log(values_with_iteration, step=1)
+ single_values = {"single_value_1": 1.1, "single_value_2": 2.2}
+ accelerator.log(single_values)
+
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
+ accelerator.end_training()
+
+ metrics = ClearMLTest._get_metrics(offline_dir)
+ assert (len(values_with_iteration) + len(single_values)) == len(metrics)
+ for metric in metrics:
+ if metric["metric"] == "Summary":
+ assert metric["variant"] in single_values
+ assert metric["value"] == single_values[metric["variant"]]
+ elif metric["metric"] == "should_be_under_train":
+ assert metric["variant"] == "train"
+ assert metric["iter"] == 1
+ assert metric["value"] == values_with_iteration["should_be_under_train"]
+ else:
+ values_with_iteration_key = metric["variant"] + "_" + metric["metric"]
+ assert values_with_iteration_key in values_with_iteration
+ assert metric["iter"] == 1
+ assert metric["value"] == values_with_iteration[values_with_iteration_key]
+
+ def test_log_images(self):
+ from clearml import Task
+
+ Task.set_offline(True)
+ accelerator = Accelerator(log_with="clearml")
+ accelerator.init_trackers("test_project_with_log_images")
+
+ base_image = np.eye(256, 256, dtype=np.uint8) * 255
+ base_image_3d = np.concatenate((np.atleast_3d(base_image), np.zeros((256, 256, 2), dtype=np.uint8)), axis=2)
+ images = {
+ "base_image": base_image,
+ "base_image_3d": base_image_3d,
+ }
+ accelerator.get_tracker("clearml").log_images(images, step=1)
+
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
+ accelerator.end_training()
+
+ images_saved = Path(os.path.join(offline_dir, "data")).rglob("*.jpeg")
+ assert len(list(images_saved)) == len(images)
+
+ def test_log_table(self):
+ from clearml import Task
+
+ Task.set_offline(True)
+ accelerator = Accelerator(log_with="clearml")
+ accelerator.init_trackers("test_project_with_log_table")
+
+ accelerator.get_tracker("clearml").log_table(
+ "from lists with columns", columns=["A", "B", "C"], data=[[1, 3, 5], [2, 4, 6]]
+ )
+ accelerator.get_tracker("clearml").log_table("from lists", data=[["A2", "B2", "C2"], [7, 9, 11], [8, 10, 12]])
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
+ accelerator.end_training()
+
+ metrics = ClearMLTest._get_metrics(offline_dir)
+ assert len(metrics) == 2
+ for metric in metrics:
+ assert metric["metric"] in ("from lists", "from lists with columns")
+ plot = json.loads(metric["plot_str"])
+ if metric["metric"] == "from lists with columns":
+ print(plot["data"][0])
+ self.assertCountEqual(plot["data"][0]["header"]["values"], ["A", "B", "C"])
+ self.assertCountEqual(plot["data"][0]["cells"]["values"], [[1, 2], [3, 4], [5, 6]])
+ else:
+ self.assertCountEqual(plot["data"][0]["header"]["values"], ["A2", "B2", "C2"])
+ self.assertCountEqual(plot["data"][0]["cells"]["values"], [[7, 8], [9, 10], [11, 12]])
+
+ @require_pandas
+ def test_log_table_pandas(self):
+ import pandas as pd
+ from clearml import Task
+
+ Task.set_offline(True)
+ accelerator = Accelerator(log_with="clearml")
+ accelerator.init_trackers("test_project_with_log_table_pandas")
+
+ accelerator.get_tracker("clearml").log_table(
+ "from df", dataframe=pd.DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}), step=1
+ )
+
+ offline_dir = ClearMLTest._get_offline_dir(accelerator)
+ accelerator.end_training()
+
+ metrics = ClearMLTest._get_metrics(offline_dir)
+ assert len(metrics) == 1
+ assert metrics[0]["metric"] == "from df"
+ plot = json.loads(metrics[0]["plot_str"])
+ self.assertCountEqual(plot["data"][0]["header"]["values"], [["A"], ["B"], ["C"]])
+ self.assertCountEqual(plot["data"][0]["cells"]["values"], [[1, 2], [3, 4], [5, 6]])
+
+
+class MyCustomTracker(GeneralTracker):
+ "Basic tracker that writes to a csv for testing"
+
+ _col_names = [
+ "total_loss",
+ "iteration",
+ "my_text",
+ "learning_rate",
+ "num_iterations",
+ "some_boolean",
+ "some_string",
+ ]
+
+ name = "my_custom_tracker"
+ requires_logging_directory = False
+
+ def __init__(self, dir: str):
+ self.f = open(f"{dir}/log.csv", "w+")
+ self.writer = csv.DictWriter(self.f, fieldnames=self._col_names)
+ self.writer.writeheader()
+
+ @property
+ def tracker(self):
+ return self.writer
+
+ def store_init_configuration(self, values: dict):
+ logger.info("Call init")
+ self.writer.writerow(values)
+
+ def log(self, values: dict, step: Optional[int]):
+ logger.info("Call log")
+ self.writer.writerow(values)
+
+ def finish(self):
+ self.f.close()
+
+
+class CustomTrackerTestCase(unittest.TestCase):
+ def test_init_trackers(self):
+ with tempfile.TemporaryDirectory() as d:
+ tracker = MyCustomTracker(d)
+ accelerator = Accelerator(log_with=tracker)
+ config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"}
+ accelerator.init_trackers("Some name", config)
+ accelerator.end_training()
+ with open(f"{d}/log.csv") as f:
+ data = csv.DictReader(f)
+ data = next(data)
+ truth = {
+ "total_loss": "",
+ "iteration": "",
+ "my_text": "",
+ "learning_rate": "0.01",
+ "num_iterations": "12",
+ "some_boolean": "False",
+ "some_string": "some_value",
+ }
+ assert data == truth
+
+ def test_log(self):
+ with tempfile.TemporaryDirectory() as d:
+ tracker = MyCustomTracker(d)
+ accelerator = Accelerator(log_with=tracker)
+ accelerator.init_trackers("Some name")
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
+ accelerator.log(values, step=0)
+ accelerator.end_training()
+ with open(f"{d}/log.csv") as f:
+ data = csv.DictReader(f)
+ data = next(data)
+ truth = {
+ "total_loss": "0.1",
+ "iteration": "1",
+ "my_text": "some_value",
+ "learning_rate": "",
+ "num_iterations": "",
+ "some_boolean": "",
+ "some_string": "",
+ }
+ assert data == truth
+
+
+@require_dvclive
+@mock.patch("dvclive.live.get_dvc_repo", return_value=None)
+class DVCLiveTrackingTest(unittest.TestCase):
+ def test_init_trackers(self, mock_repo):
+ project_name = "test_project_with_config"
+ with tempfile.TemporaryDirectory() as dirpath:
+ accelerator = Accelerator(log_with="dvclive")
+ config = {
+ "num_iterations": 12,
+ "learning_rate": 1e-2,
+ "some_boolean": False,
+ "some_string": "some_value",
+ }
+ init_kwargs = {"dvclive": {"dir": dirpath, "save_dvc_exp": False, "dvcyaml": None}}
+ accelerator.init_trackers(project_name, config, init_kwargs)
+ accelerator.end_training()
+ live = accelerator.trackers[0].live
+ params = load_yaml(live.params_file)
+ assert params == config
+
+ def test_log(self, mock_repo):
+ project_name = "test_project_with_log"
+ with tempfile.TemporaryDirectory() as dirpath:
+ accelerator = Accelerator(log_with="dvclive", project_dir=dirpath)
+ init_kwargs = {"dvclive": {"dir": dirpath, "save_dvc_exp": False, "dvcyaml": None}}
+ accelerator.init_trackers(project_name, init_kwargs=init_kwargs)
+ values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
+ # Log step 0
+ accelerator.log(values)
+ # Log step 1
+ accelerator.log(values)
+ # Log step 3 (skip step 2)
+ accelerator.log(values, step=3)
+ accelerator.end_training()
+ live = accelerator.trackers[0].live
+ logs, latest = parse_metrics(live)
+ assert latest.pop("step") == 3
+ assert latest == values
+ scalars = os.path.join(live.plots_dir, Metric.subfolder)
+ for val in values.keys():
+ val_path = os.path.join(scalars, f"{val}.tsv")
+ steps = [int(row["step"]) for row in logs[val_path]]
+ assert steps == [0, 1, 3]
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_utils.py b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed4481ed92c5a3d5adbb19c9ba37b41ecc209006
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/tests/test_utils.py
@@ -0,0 +1,406 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import os
+import pickle
+import tempfile
+import unittest
+import warnings
+from collections import UserDict, namedtuple
+from typing import NamedTuple, Optional
+from unittest.mock import Mock, patch
+
+import numpy as np
+import pytest
+import torch
+from torch import nn
+
+from accelerate.state import PartialState
+from accelerate.test_utils.testing import (
+ require_huggingface_suite,
+ require_non_cpu,
+ require_non_torch_xla,
+ require_torch_min_version,
+ require_tpu,
+ require_triton,
+ torch_device,
+)
+from accelerate.test_utils.training import RegressionModel
+from accelerate.utils import (
+ CannotPadNestedTensorWarning,
+ check_os_kernel,
+ clear_environment,
+ convert_dict_to_env_variables,
+ convert_outputs_to_fp32,
+ convert_to_fp32,
+ extract_model_from_parallel,
+ find_device,
+ is_torch_xla_available,
+ listify,
+ pad_across_processes,
+ pad_input_tensors,
+ patch_environment,
+ recursively_apply,
+ save,
+ send_to_device,
+)
+from accelerate.utils.operations import is_namedtuple
+
+
+if is_torch_xla_available():
+ import torch_xla.distributed.spmd as xs
+ import torch_xla.runtime as xr
+ from torch_xla.experimental.spmd_fully_sharded_data_parallel import SpmdFullyShardedDataParallel as FSDPv2
+
+ExampleNamedTuple = namedtuple("ExampleNamedTuple", "a b c")
+
+
+class UtilsTester(unittest.TestCase):
+ def setUp(self):
+ # logging requires initialized state
+ PartialState()
+
+ def test_send_to_device(self):
+ tensor = torch.randn(5, 2)
+ device = torch.device(f"{torch_device}:0")
+
+ result1 = send_to_device(tensor, device)
+ assert torch.equal(result1.cpu(), tensor)
+
+ result2 = send_to_device((tensor, [tensor, tensor], 1), device)
+ assert isinstance(result2, tuple)
+ assert torch.equal(result2[0].cpu(), tensor)
+ assert isinstance(result2[1], list)
+ assert torch.equal(result2[1][0].cpu(), tensor)
+ assert torch.equal(result2[1][1].cpu(), tensor)
+ assert result2[2] == 1
+
+ result2 = send_to_device({"a": tensor, "b": [tensor, tensor], "c": 1}, device)
+ assert isinstance(result2, dict)
+ assert torch.equal(result2["a"].cpu(), tensor)
+ assert isinstance(result2["b"], list)
+ assert torch.equal(result2["b"][0].cpu(), tensor)
+ assert torch.equal(result2["b"][1].cpu(), tensor)
+ assert result2["c"] == 1
+
+ result3 = send_to_device(ExampleNamedTuple(a=tensor, b=[tensor, tensor], c=1), device)
+ assert isinstance(result3, ExampleNamedTuple)
+ assert torch.equal(result3.a.cpu(), tensor)
+ assert isinstance(result3.b, list)
+ assert torch.equal(result3.b[0].cpu(), tensor)
+ assert torch.equal(result3.b[1].cpu(), tensor)
+ assert result3.c == 1
+
+ result4 = send_to_device(UserDict({"a": tensor, "b": [tensor, tensor], "c": 1}), device)
+ assert isinstance(result4, UserDict)
+ assert torch.equal(result4["a"].cpu(), tensor)
+ assert isinstance(result4["b"], list)
+ assert torch.equal(result4["b"][0].cpu(), tensor)
+ assert torch.equal(result4["b"][1].cpu(), tensor)
+ assert result4["c"] == 1
+
+ def test_honor_type(self):
+ with self.assertRaises(TypeError) as cm:
+ _ = recursively_apply(torch.tensor, (torch.tensor(1), 1), error_on_other_type=True)
+ assert (
+ str(cm.exception)
+ == "Unsupported types () passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed."
+ )
+
+ def test_listify(self):
+ tensor = torch.tensor([1, 2, 3, 4, 5])
+ assert listify(tensor) == [1, 2, 3, 4, 5]
+
+ tensor = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
+ assert listify(tensor) == [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
+
+ tensor = torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]])
+ assert listify(tensor) == [[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]
+
+ def test_patch_environment(self):
+ with patch_environment(aa=1, BB=2):
+ assert os.environ.get("AA") == "1"
+ assert os.environ.get("BB") == "2"
+
+ assert "AA" not in os.environ
+ assert "BB" not in os.environ
+
+ def test_patch_environment_key_exists(self):
+ # check that patch_environment correctly restores pre-existing env vars
+ with patch_environment(aa=1, BB=2):
+ assert os.environ.get("AA") == "1"
+ assert os.environ.get("BB") == "2"
+
+ with patch_environment(Aa=10, bb="20", cC=30):
+ assert os.environ.get("AA") == "10"
+ assert os.environ.get("BB") == "20"
+ assert os.environ.get("CC") == "30"
+
+ assert os.environ.get("AA") == "1"
+ assert os.environ.get("BB") == "2"
+ assert "CC" not in os.environ
+
+ assert "AA" not in os.environ
+ assert "BB" not in os.environ
+ assert "CC" not in os.environ
+
+ def test_patch_environment_restores_on_error(self):
+ # we need to find an upper-case envvar
+ # because `patch_environment upper-cases all keys...
+ key, orig_value = next(kv for kv in os.environ.items() if kv[0].isupper())
+ new_value = f"{orig_value}_foofoofoo"
+ with pytest.raises(RuntimeError), patch_environment(**{key: new_value}):
+ assert os.environ[key] == os.getenv(key) == new_value # noqa: TID251
+ raise RuntimeError("Oopsy daisy!")
+ assert os.environ[key] == os.getenv(key) == orig_value # noqa: TID251
+
+ def test_clear_environment(self):
+ key, value = os.environ.copy().popitem()
+ with pytest.raises(RuntimeError), clear_environment():
+ assert key not in os.environ
+ assert not os.getenv(key) # test the environment is actually cleared # noqa: TID251
+ raise RuntimeError("Oopsy daisy!")
+ # Test values are restored
+ assert os.getenv(key) == os.environ[key] == value # noqa: TID251
+
+ def test_can_undo_convert_outputs(self):
+ model = RegressionModel()
+ model._original_forward = model.forward
+ model.forward = convert_outputs_to_fp32(model.forward)
+ model = extract_model_from_parallel(model, keep_fp32_wrapper=False)
+ _ = pickle.dumps(model)
+
+ @require_non_cpu
+ def test_can_undo_fp16_conversion(self):
+ model = RegressionModel()
+ model._original_forward = model.forward
+ model.forward = torch.autocast(device_type=torch_device, dtype=torch.float16)(model.forward)
+ model.forward = convert_outputs_to_fp32(model.forward)
+ model = extract_model_from_parallel(model, keep_fp32_wrapper=False)
+ _ = pickle.dumps(model)
+
+ @require_triton
+ @require_non_cpu
+ @require_torch_min_version(version="2.0")
+ def test_dynamo(self):
+ model = RegressionModel()
+ model._original_forward = model.forward
+ model.forward = torch.autocast(device_type=torch_device, dtype=torch.float16)(model.forward)
+ model.forward = convert_outputs_to_fp32(model.forward)
+ model.forward = torch.compile(model.forward, backend="inductor")
+ inputs = torch.randn(4, 10).to(torch_device)
+ _ = model(inputs)
+
+ def test_extract_model(self):
+ model = RegressionModel()
+ # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
+ distributed_model = torch.nn.parallel.DataParallel(model)
+ model_unwrapped = extract_model_from_parallel(distributed_model)
+
+ assert model == model_unwrapped
+
+ @require_tpu
+ @require_huggingface_suite
+ def test_extract_model_recursive_fsdpv2(self):
+ # Specifically tests for FSDPv2 extraction
+ # reported in https://github.com/huggingface/transformers/pull/29780
+ xr.use_spmd()
+ from transformers import AutoModelForCausalLM
+
+ model = AutoModelForCausalLM.from_pretrained("gpt2")
+ orig_state_dict_keys = list(model.state_dict().keys())
+ num_devices = xr.global_runtime_device_count()
+ # Set environment for FSDPv2 to be active
+ xs.set_global_mesh(xs.Mesh(np.array(range(num_devices)), (num_devices, 1), axis_names=("fsdp", "tensor")))
+
+ def nested_wrap(model):
+ layer = model.wte
+ wrapped_layer = FSDPv2(layer)
+ model.wte = wrapped_layer
+ return model
+
+ wrapped_model = nested_wrap(model)
+ unwrapped_model = extract_model_from_parallel(wrapped_model, recursive=True)
+ unwrapped_state_dict_keys = list(unwrapped_model.state_dict().keys())
+ for original_key, new_key in zip(orig_state_dict_keys, unwrapped_state_dict_keys):
+ assert original_key == new_key, f"Keys did not align: {original_key} != {new_key}"
+
+ @require_torch_min_version(version="2.0")
+ def test_dynamo_extract_model(self):
+ model = RegressionModel()
+ compiled_model = torch.compile(model)
+
+ # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
+ distributed_model = torch.nn.parallel.DataParallel(model)
+ distributed_compiled_model = torch.compile(distributed_model)
+ compiled_model_unwrapped = extract_model_from_parallel(distributed_compiled_model)
+
+ assert compiled_model._orig_mod == compiled_model_unwrapped._orig_mod
+
+ def test_find_device(self):
+ assert find_device([1, "a", torch.tensor([1, 2, 3])]) == torch.device("cpu")
+ assert find_device({"a": 1, "b": torch.tensor([1, 2, 3])}) == torch.device("cpu")
+ assert find_device([1, "a"]) is None
+
+ def test_check_os_kernel_no_warning_when_release_gt_min(self):
+ # min version is 5.5
+ with patch("platform.uname", return_value=Mock(release="5.15.0-35-generic", system="Linux")):
+ with warnings.catch_warnings(record=True) as w:
+ check_os_kernel()
+ assert len(w) == 0
+
+ def test_check_os_kernel_no_warning_when_not_linux(self):
+ # system must be Linux
+ with patch("platform.uname", return_value=Mock(release="5.4.0-35-generic", system="Darwin")):
+ with warnings.catch_warnings(record=True) as w:
+ check_os_kernel()
+ assert len(w) == 0
+
+ def test_check_os_kernel_warning_when_release_lt_min(self):
+ # min version is 5.5
+ with patch("platform.uname", return_value=Mock(release="5.4.0-35-generic", system="Linux")):
+ with self.assertLogs() as ctx:
+ check_os_kernel()
+ assert len(ctx.records) == 1
+ assert ctx.records[0].levelname == "WARNING"
+ assert "5.4.0" in ctx.records[0].msg
+ assert "5.5.0" in ctx.records[0].msg
+
+ @require_non_torch_xla
+ def test_save_safetensor_shared_memory(self):
+ class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.a = nn.Linear(100, 100)
+ self.b = self.a
+
+ def forward(self, x):
+ return self.b(self.a(x))
+
+ model = Model()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ save_path = os.path.join(tmp_dir, "model.safetensors")
+ with self.assertLogs(level="WARNING") as log:
+ save(model.state_dict(), save_path, safe_serialization=True)
+ assert len(log.records) == 1
+ assert "Removed shared tensor" in log.output[0]
+
+ @require_torch_min_version(version="1.12")
+ def test_pad_across_processes(self):
+ from torch.nested import nested_tensor
+
+ nt = nested_tensor([[1, 2, 3], [1], [1, 2]])
+ with self.assertWarns(CannotPadNestedTensorWarning):
+ nt2 = pad_across_processes(nt)
+ assert nt is nt2
+
+ def test_slice_and_concatenate(self):
+ # First base case: 2 processes, batch size of 1
+ num_processes = 2
+ batch_size = 1
+ batch = torch.rand(batch_size, 4)
+ result = pad_input_tensors(batch, batch_size, num_processes)
+ # We should expect there to be 2 items now
+ assert result.shape == torch.Size([2, 4])
+
+ # Second base case: 2 processes, batch size of 3
+ num_processes = 2
+ batch_size = 3
+ batch = torch.rand(batch_size, 4)
+ result = pad_input_tensors(batch, batch_size, num_processes)
+ # We should expect there to be 4 items now
+ assert result.shape == torch.Size([4, 4])
+
+ # Third base case: 3 processes, batch size of 4
+ num_processes = 3
+ batch_size = 4
+ batch = torch.rand(batch_size, 4, 4)
+ result = pad_input_tensors(batch, batch_size, num_processes)
+ # We should expect there to be 6 items now
+ assert result.shape == torch.Size([6, 4, 4])
+
+ # Fourth base case: 4 processes, batch size of 3
+ num_processes = 4
+ batch_size = 3
+ batch = torch.rand(batch_size, 4, 4)
+ result = pad_input_tensors(batch, batch_size, num_processes)
+ # We should expect there to be 4 items now
+ assert result.shape == torch.Size([4, 4, 4])
+
+ # Fifth base case: 6 processes, batch size of 4
+ num_processes = 6
+ batch_size = 4
+ batch = torch.rand(batch_size, 4, 4)
+ result = pad_input_tensors(batch, batch_size, num_processes)
+ # We should expect there to be 6 items now
+ assert result.shape == torch.Size([6, 4, 4])
+
+ # Sixth base case: 6 processes, batch size of 1
+ num_processes = 6
+ batch_size = 1
+ batch = torch.rand(batch_size, 4, 4)
+ result = pad_input_tensors(batch, batch_size, num_processes)
+ # We should expect there to be 6 items now
+ assert result.shape == torch.Size([6, 4, 4])
+
+ # Seventh base case: 6 processes, batch size of 2
+ num_processes = 6
+ batch_size = 2
+ batch = torch.rand(batch_size, 4, 4)
+ result = pad_input_tensors(batch, batch_size, num_processes)
+ # We should expect there to be 6 items now
+ assert result.shape == torch.Size([6, 4, 4])
+
+ # Eighth base case: 6 processes, batch size of 61
+ num_processes = 6
+ batch_size = 61
+ batch = torch.rand(batch_size, 4, 4)
+ result = pad_input_tensors(batch, batch_size, num_processes)
+ # We should expect there to be 66 items now
+ assert result.shape == torch.Size([66, 4, 4])
+
+ def test_send_to_device_compiles(self):
+ compiled_send_to_device = torch.compile(send_to_device, fullgraph=True)
+ compiled_send_to_device(torch.zeros([1], dtype=torch.bfloat16), "cpu")
+
+ def test_convert_to_fp32(self):
+ compiled_convert_to_fp32 = torch.compile(convert_to_fp32, fullgraph=True)
+ compiled_convert_to_fp32(torch.zeros([1], dtype=torch.bfloat16))
+
+ def test_named_tuples(self):
+ class QuantTensorBase(NamedTuple):
+ value: torch.Tensor
+ scale: Optional[torch.Tensor]
+ zero_point: Optional[torch.Tensor]
+
+ class Second(QuantTensorBase):
+ pass
+
+ a = QuantTensorBase(torch.tensor(1.0), None, None)
+ b = Second(torch.tensor(1.0), None, None)
+
+ point = namedtuple("Point", ["x", "y"])
+ p = point(11, y=22)
+
+ self.assertTrue(is_namedtuple(a))
+ self.assertTrue(is_namedtuple(b))
+ self.assertTrue(is_namedtuple(p))
+ self.assertFalse(is_namedtuple((1, 2)))
+ self.assertFalse(is_namedtuple("hey"))
+ self.assertFalse(is_namedtuple(object()))
+
+ def test_convert_dict_to_env_variables(self):
+ env = {"ACCELERATE_DEBUG_MODE": "1", "BAD_ENV_NAME": ">> python xla_spawn.py --num_cores=NUM_CORES_YOU_HAVE
+ YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other
+ arguments of your training script)
+
+"""
+
+import importlib
+import sys
+from argparse import REMAINDER, ArgumentParser
+from pathlib import Path
+
+import torch_xla.distributed.xla_multiprocessing as xmp
+
+
+def parse_args():
+ """
+ Helper function parsing the command line options
+ @retval ArgumentParser
+ """
+ parser = ArgumentParser(
+ description=(
+ "PyTorch TPU distributed training launch "
+ "helper utility that will spawn up "
+ "multiple distributed processes"
+ )
+ )
+
+ # Optional arguments for the launch helper
+ parser.add_argument("--num_cores", type=int, default=1, help="Number of TPU cores to use (1 or 8).")
+
+ # positional
+ parser.add_argument(
+ "training_script",
+ type=str,
+ help=(
+ "The full path to the single TPU training "
+ "program/script to be launched in parallel, "
+ "followed by all the arguments for the "
+ "training script"
+ ),
+ )
+
+ # rest from the training program
+ parser.add_argument("training_script_args", nargs=REMAINDER)
+
+ return parser.parse_args()
+
+
+def main():
+ args = parse_args()
+
+ # Import training_script as a module.
+ script_fpath = Path(args.training_script)
+ sys.path.append(str(script_fpath.parent.resolve()))
+ mod_name = script_fpath.stem
+ mod = importlib.import_module(mod_name)
+
+ # Patch sys.argv
+ sys.argv = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores)]
+ xmp.spawn(mod._mp_fn, args=(), nprocs=args.num_cores)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/utils/log_reports.py b/tasks/tasksmith-5db757e91a6e/tests/source/utils/log_reports.py
new file mode 100644
index 0000000000000000000000000000000000000000..151643e2d78add8613a49022c34c44467fc8120b
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/utils/log_reports.py
@@ -0,0 +1,177 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import json
+import os
+from datetime import date
+from pathlib import Path
+
+from tabulate import DataRow, TableFormat, tabulate
+
+
+hf_table_format = TableFormat(
+ lineabove=None,
+ linebelowheader=None,
+ linebetweenrows=None,
+ linebelow=None,
+ headerrow=DataRow("", "|", "|"),
+ datarow=DataRow("", "|", "|"),
+ padding=1,
+ with_header_hide=None,
+)
+
+
+failed = []
+group_info = []
+
+no_error_payload = {"type": "section", "text": {"type": "plain_text", "text": "No failed tests! 🤗", "emoji": True}}
+
+payload = [
+ {
+ "type": "header",
+ "text": {
+ "type": "plain_text",
+ "text": f"🤗 Accelerate nightly {os.environ.get('TEST_TYPE', '')} test results",
+ "emoji": True,
+ },
+ }
+]
+
+total_num_failed = 0
+for log in Path().glob("*.log"):
+ section_num_failed = 0
+ with open(log) as f:
+ for line in f:
+ line = json.loads(line)
+ if line.get("nodeid", "") != "":
+ test = line["nodeid"]
+ if line.get("duration", None) is not None:
+ duration = f'{line["duration"]:.4f}'
+ if line.get("outcome", "") == "failed":
+ section_num_failed += 1
+ failed.append([test, duration, log.name.split("_")[0]])
+ total_num_failed += 1
+ group_info.append([str(log), section_num_failed, failed])
+ failed = []
+ log.unlink()
+
+message = ""
+all_files2failed = []
+if total_num_failed > 0:
+ for name, num_failed, failed_tests in group_info:
+ if num_failed > 0:
+ if num_failed == 1:
+ message += f"*{name[1:]}: {num_failed} failed test*\n"
+ else:
+ message += f"*{name[1:]}: {num_failed} failed tests*\n"
+ failed_table = []
+ files2failed = {}
+ for test in failed_tests:
+ data = test[0].split("::")
+ data[0] = data[0].split("/")[-1]
+ if data[0] not in files2failed:
+ files2failed[data[0]] = [data[1:]]
+ else:
+ files2failed[data[0]] += [data[1:]]
+ failed_table.append(data)
+
+ files = [test[0] for test in failed_table]
+ individual_files = list(set(files))
+ # Count number of instances in failed_tests
+ table = []
+ for file in individual_files:
+ table.append([file, len(files2failed[file])])
+
+ failed_table = tabulate(
+ table,
+ headers=["Test Location", "Num Failed"],
+ tablefmt=hf_table_format,
+ stralign="right",
+ )
+ message += f"\n```\n{failed_table}\n```"
+ all_files2failed.append(files2failed)
+ if len(message) > 3000:
+ err = "Too many failed tests, please see the full report in the Action results."
+ offset = len(err) + 10
+ message = message[: 3000 - offset] + f"\n...\n```\n{err}"
+ print(f"### {message}")
+else:
+ message = "No failed tests! 🤗"
+ print(f"## {message}")
+ payload.append(no_error_payload)
+
+if os.environ.get("TEST_TYPE", "") != "":
+ from slack_sdk import WebClient
+
+ client = WebClient(token=os.environ["SLACK_API_TOKEN"])
+ if message != "No failed tests! 🤗":
+ md_report = {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": message,
+ },
+ }
+ payload.append(md_report)
+ action_button = {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": "*For more details:*",
+ },
+ "accessory": {
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": "Check Action results",
+ "emoji": True,
+ },
+ "url": f'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}',
+ },
+ }
+ payload.append(action_button)
+ date_report = {
+ "type": "context",
+ "elements": [
+ {
+ "type": "plain_text",
+ "text": f"Nightly {os.environ.get('TEST_TYPE')} test results for {date.today()}",
+ }
+ ],
+ }
+ payload.append(date_report)
+ response = client.chat_postMessage(channel="#accelerate-ci-daily", text=message, blocks=payload)
+ ts = response.data["ts"]
+ for failed_file in all_files2failed:
+ for test_location, test_failures in failed_file.items():
+ # Keep only the first instance of the test name
+ test_class = ""
+ for i, row in enumerate(test_failures):
+ if row[0] != test_class:
+ test_class = row[0]
+ else:
+ test_failures[i][0] = ""
+
+ payload = {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": f"Test location: {test_location}\n```\n{tabulate(test_failures, headers=['Class', 'Test'], tablefmt=hf_table_format, stralign='right')}\n```",
+ },
+ }
+
+ client.chat_postMessage(
+ channel="#accelerate-ci-daily",
+ thread_ts=ts,
+ blocks=[payload],
+ )
diff --git a/tasks/tasksmith-5db757e91a6e/tests/source/utils/stale.py b/tasks/tasksmith-5db757e91a6e/tests/source/utils/stale.py
new file mode 100644
index 0000000000000000000000000000000000000000..24333fed4c76b34cf895f30a253a9a7042f9d324
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/source/utils/stale.py
@@ -0,0 +1,69 @@
+# Copyright 2022 The HuggingFace Team, the AllenNLP library authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Script to close stale issue. Taken in part from the AllenNLP repository.
+https://github.com/allenai/allennlp.
+"""
+
+import os
+from datetime import datetime as dt
+from datetime import timezone
+
+from github import Github
+
+
+LABELS_TO_EXEMPT = [
+ "good first issue",
+ "feature request",
+ "wip",
+]
+
+
+def main():
+ g = Github(os.environ["GITHUB_TOKEN"])
+ repo = g.get_repo("huggingface/accelerate")
+ open_issues = repo.get_issues(state="open")
+
+ for issue in open_issues:
+ comments = sorted([comment for comment in issue.get_comments()], key=lambda i: i.created_at, reverse=True)
+ last_comment = comments[0] if len(comments) > 0 else None
+ current_time = dt.now(timezone.utc)
+ days_since_updated = (current_time - issue.updated_at).days
+ days_since_creation = (current_time - issue.created_at).days
+ if (
+ last_comment is not None
+ and last_comment.user.login == "github-actions[bot]"
+ and days_since_updated > 7
+ and days_since_creation >= 30
+ and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels())
+ ):
+ # Close issue since it has been 7 days of inactivity since bot mention.
+ issue.edit(state="closed")
+ elif (
+ days_since_updated > 23
+ and days_since_creation >= 30
+ and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels())
+ ):
+ # Add stale comment
+ issue.create_comment(
+ "This issue has been automatically marked as stale because it has not had "
+ "recent activity. If you think this still needs to be addressed "
+ "please comment on this thread.\n\nPlease note that issues that do not follow the "
+ "[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) "
+ "are likely to be ignored."
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5db757e91a6e/tests/test.sh b/tasks/tasksmith-5db757e91a6e/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c92b552378bd5c90e06861fb4c3cf5e93ef8dd72
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+set -eu
+exec /opt/tasksmith-venv/bin/python -I /tests/grade.py
diff --git a/tasks/tasksmith-5db757e91a6e/tests/test_driver.py b/tasks/tasksmith-5db757e91a6e/tests/test_driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d47bdfd18bf0d184d186cb919f64637213b6c60
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/test_driver.py
@@ -0,0 +1,38 @@
+"""Private pytest entry point with a bounded framework-tampering check.
+
+The host still owns reward parsing. This guard detects replacement or in-place
+editing of unittest assertions, a demonstrated attack against repository tests.
+It does not claim to isolate arbitrary test and solution code in one interpreter.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+
+
+def run(arguments: list[str]) -> int:
+ import pytest
+
+ # Capture before pytest imports any repository modules. Retain code objects
+ # too: an attacker can mutate function.__code__ without replacing a method.
+ original = {
+ name: (value, getattr(value, "__code__", None))
+ for name, value in vars(unittest.TestCase).items()
+ if name.startswith("assert") and callable(value)
+ }
+ case = unittest.TestCase
+ code = int(pytest.main(arguments))
+ changed = []
+ for name, (method, implementation) in original.items():
+ current = getattr(case, name, None)
+ if current is not method or getattr(current, "__code__", None) is not implementation:
+ changed.append(name)
+ if unittest.TestCase is not case or changed:
+ sys.stderr.write("Verifier framework was modified: " + ", ".join(changed) + "\n")
+ return 254
+ return code
+
+
+if __name__ == "__main__":
+ raise SystemExit(run(sys.argv[1:]))
diff --git a/tasks/tasksmith-5db757e91a6e/tests/test_results.py b/tasks/tasksmith-5db757e91a6e/tests/test_results.py
new file mode 100644
index 0000000000000000000000000000000000000000..05ce2c730e38e02bad44f2344e88e5f1cb02cb8d
--- /dev/null
+++ b/tasks/tasksmith-5db757e91a6e/tests/test_results.py
@@ -0,0 +1,65 @@
+"""Strict test evidence used by repository recipes and their exported verifiers."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from xml.etree import ElementTree
+
+
+@dataclass(frozen=True)
+class TestResults:
+ __test__ = False
+ statuses: dict[str, str]
+ returncode: int
+
+ @property
+ def passed(self) -> set[str]:
+ return {name for name, status in self.statuses.items() if status == "passed"}
+
+
+def parse_junit(text: str, *, returncode: int) -> TestResults:
+ if " dict[str, list[str]]:
+ if healthy.returncode != 0 or not healthy.passed:
+ raise ValueError("Reference must execute successfully with passing tests")
+ if healthy.statuses.keys() != defective.statuses.keys():
+ raise ValueError("Mutation changed test collection; contrast is not comparable")
+ failing = sorted(
+ name for name in healthy.passed if defective.statuses[name] in {"failed", "error"}
+ )
+ if not failing or defective.returncode != 1:
+ raise ValueError("No intended fail-to-pass contrast")
+ return {"FAIL_TO_PASS": failing, "PASS_TO_PASS": sorted(healthy.passed - set(failing))}
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/Dockerfile b/tasks/tasksmith-5dd11b34cce1/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f688e74ed75f7b36c9012b8f8bb3ff89be96efee
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/Dockerfile
@@ -0,0 +1,9 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu aiohappyeyeballs==2.7.1 aiohttp==3.14.3 aiosignal==1.4.0 attrs==26.1.0 datasets==2.21.0 dill==0.3.8 filelock==3.16.1 frozenlist==1.8.0 fsspec==2024.6.1 huggingface-hub==0.36.2 multidict==6.8.0 multiprocess==0.70.16 numpy==2.5.3 packaging==26.3 pandas==3.0.5 parameterized==0.9.0 propcache==0.5.2 pyarrow==25.0.1 pytest==8.4.2 python-dateutil==2.9.0.post0 pyyaml==6.0.2 regex==2024.11.6 requests==2.32.3 safetensors==0.8.0 setuptools==78.1.0 six==1.17.0 tokenizers==0.21.4 torch==2.11.0+cpu tqdm==4.67.1 wheel==0.48.0 xxhash==4.0.1 yarl==1.24.5
+COPY source /workspace
+RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e .
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
+RUN apt-get update && apt-get install -y --no-install-recommends tmux && rm -rf /var/lib/apt/lists/*
+RUN useradd -m learner && chown -R learner:learner /workspace
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/TROUBLESHOOT.md b/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/TROUBLESHOOT.md
new file mode 100644
index 0000000000000000000000000000000000000000..484d62b46a87f43e3df240823bd9227d8ebd11bc
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/TROUBLESHOOT.md
@@ -0,0 +1,7 @@
+# Troubleshooting
+
+This is a document explaining how to deal with various issues on Circle-CI. The entries may include actual solutions or pointers to Issues that cover those.
+
+## Circle CI
+
+* pytest worker runs out of resident RAM and gets killed by `cgroups`: https://github.com/huggingface/transformers/issues/11408
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/config.yml b/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/config.yml
new file mode 100644
index 0000000000000000000000000000000000000000..75413af8bf5254eadfa532c5637bd1a09c2fc137
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/config.yml
@@ -0,0 +1,217 @@
+version: 2.1
+setup: true
+orbs:
+ continuation: circleci/continuation@0.1.0
+
+parameters:
+ nightly:
+ type: boolean
+ default: false
+
+jobs:
+ # Ensure running with CircleCI/huggingface
+ check_circleci_user:
+ docker:
+ - image: python:3.10-slim
+ parallelism: 1
+ steps:
+ - run: echo $CIRCLE_PROJECT_USERNAME
+ - run: |
+ if [ "$CIRCLE_PROJECT_USERNAME" = "huggingface" ]; then
+ exit 0
+ else
+ echo "The CI is running under $CIRCLE_PROJECT_USERNAME personal account. Please follow https://support.circleci.com/hc/en-us/articles/360008097173-Troubleshooting-why-pull-requests-are-not-triggering-jobs-on-my-organization- to fix it."; exit -1
+ fi
+ # Fetch the tests to run
+ fetch_tests:
+ working_directory: ~/transformers
+ docker:
+ - image: huggingface/transformers-quality
+ parallelism: 1
+ steps:
+ - checkout
+ - run: uv pip install -U -e .
+ - run: echo 'export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)"' >> "$BASH_ENV" && source "$BASH_ENV"
+ - run: mkdir -p test_preparation
+ - run: python utils/tests_fetcher.py | tee tests_fetched_summary.txt
+ - run: python utils/tests_fetcher.py --filter_tests
+ - run: export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)" && echo $GIT_COMMIT_MESSAGE && python .circleci/create_circleci_config.py --fetcher_folder test_preparation
+ - run: |
+ if [ ! -s test_preparation/generated_config.yml ]; then
+ echo "No tests to run, exiting early!"
+ circleci-agent step halt
+ fi
+
+ - store_artifacts:
+ path: test_preparation
+
+ - run:
+ name: "Retrieve Artifact Paths"
+ # [reference] https://circleci.com/docs/api/v2/index.html#operation/getJobArtifacts
+ # `CIRCLE_TOKEN` is defined as an environment variables set within a context, see `https://circleci.com/docs/contexts/`
+ command: |
+ project_slug="gh/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}"
+ job_number=${CIRCLE_BUILD_NUM}
+ url="https://circleci.com/api/v2/project/${project_slug}/${job_number}/artifacts"
+ curl -o test_preparation/artifacts.json ${url} --header "Circle-Token: $CIRCLE_TOKEN"
+ - run:
+ name: "Prepare pipeline parameters"
+ command: |
+ python utils/process_test_artifacts.py
+
+ # To avoid too long generated_config.yaml on the continuation orb, we pass the links to the artifacts as parameters.
+ # Otherwise the list of tests was just too big. Explicit is good but for that it was a limitation.
+ # We used:
+
+ # https://circleci.com/docs/api/v2/index.html#operation/getJobArtifacts : to get the job artifacts
+ # We could not pass a nested dict, which is why we create the test_file_... parameters for every single job
+
+ - store_artifacts:
+ path: test_preparation/transformed_artifacts.json
+ - store_artifacts:
+ path: test_preparation/artifacts.json
+ - continuation/continue:
+ parameters: test_preparation/transformed_artifacts.json
+ configuration_path: test_preparation/generated_config.yml
+
+ # To run all tests for the nightly build
+ fetch_all_tests:
+ working_directory: ~/transformers
+ docker:
+ - image: huggingface/transformers-quality
+ parallelism: 1
+ steps:
+ - checkout
+ - run: uv pip install -U -e .
+ - run: echo 'export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)"' >> "$BASH_ENV" && source "$BASH_ENV"
+ - run: mkdir -p test_preparation
+ - run: python utils/tests_fetcher.py --fetch_all | tee tests_fetched_summary.txt
+ - run: python utils/tests_fetcher.py --filter_tests
+ - run: export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)" && echo $GIT_COMMIT_MESSAGE && python .circleci/create_circleci_config.py --fetcher_folder test_preparation
+ - run: |
+ if [ ! -s test_preparation/generated_config.yml ]; then
+ echo "No tests to run, exiting early!"
+ circleci-agent step halt
+ fi
+
+ - store_artifacts:
+ path: test_preparation
+
+ - run:
+ name: "Retrieve Artifact Paths"
+ env:
+ CIRCLE_TOKEN: ${{ secrets.CI_ARTIFACT_TOKEN }}
+ command: |
+ project_slug="gh/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}"
+ job_number=${CIRCLE_BUILD_NUM}
+ url="https://circleci.com/api/v2/project/${project_slug}/${job_number}/artifacts"
+ curl -o test_preparation/artifacts.json ${url}
+ - run:
+ name: "Prepare pipeline parameters"
+ command: |
+ python utils/process_test_artifacts.py
+
+ # To avoid too long generated_config.yaml on the continuation orb, we pass the links to the artifacts as parameters.
+ # Otherwise the list of tests was just too big. Explicit is good but for that it was a limitation.
+ # We used:
+
+ # https://circleci.com/docs/api/v2/index.html#operation/getJobArtifacts : to get the job artifacts
+ # We could not pass a nested dict, which is why we create the test_file_... parameters for every single job
+
+ - store_artifacts:
+ path: test_preparation/transformed_artifacts.json
+ - store_artifacts:
+ path: test_preparation/artifacts.json
+ - continuation/continue:
+ parameters: test_preparation/transformed_artifacts.json
+ configuration_path: test_preparation/generated_config.yml
+
+ check_code_quality:
+ working_directory: ~/transformers
+ docker:
+ - image: huggingface/transformers-quality
+ resource_class: large
+ environment:
+ TRANSFORMERS_IS_CI: yes
+ PYTEST_TIMEOUT: 120
+ parallelism: 1
+ steps:
+ - checkout
+ - run: uv pip install -e ".[quality]"
+ - run:
+ name: Show installed libraries and their versions
+ command: pip freeze | tee installed.txt
+ - store_artifacts:
+ path: ~/transformers/installed.txt
+ - run: python -c "from transformers import *" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1)
+ - run: ruff check examples tests src utils
+ - run: ruff format tests src utils --check
+ - run: python utils/custom_init_isort.py --check_only
+ - run: python utils/sort_auto_mappings.py --check_only
+ - run: python utils/check_doc_toc.py
+ - run: python utils/check_docstrings.py --check_all
+
+ check_repository_consistency:
+ working_directory: ~/transformers
+ docker:
+ - image: huggingface/transformers-consistency
+ resource_class: large
+ environment:
+ TRANSFORMERS_IS_CI: yes
+ PYTEST_TIMEOUT: 120
+ parallelism: 1
+ steps:
+ - checkout
+ - run: uv pip install -e ".[quality]"
+ - run:
+ name: Show installed libraries and their versions
+ command: pip freeze | tee installed.txt
+ - store_artifacts:
+ path: ~/transformers/installed.txt
+ - run: python utils/check_copies.py
+ - run: python utils/check_modular_conversion.py
+ - run: python utils/check_table.py
+ - run: python utils/check_dummies.py
+ - run: python utils/check_repo.py
+ - run: python utils/check_inits.py
+ - run: python utils/check_config_docstrings.py
+ - run: python utils/check_config_attributes.py
+ - run: python utils/check_doctest_list.py
+ - run: make deps_table_check_updated
+ - run: python utils/update_metadata.py --check-only
+ - run: python utils/check_docstrings.py
+ - run: python utils/check_support_list.py
+
+workflows:
+ version: 2
+ setup_and_quality:
+ when:
+ and:
+ - equal: [<>, https://github.com/huggingface/transformers]
+ - not: <>
+ jobs:
+ - check_circleci_user
+ - check_code_quality
+ - check_repository_consistency
+ - fetch_tests
+
+ setup_and_quality_2:
+ when:
+ not:
+ equal: [<>, https://github.com/huggingface/transformers]
+ jobs:
+ - check_circleci_user
+ - check_code_quality
+ - check_repository_consistency
+ - fetch_tests:
+ # [reference] https://circleci.com/docs/contexts/
+ context:
+ - TRANSFORMERS_CONTEXT
+
+ nightly:
+ when: <>
+ jobs:
+ - check_circleci_user
+ - check_code_quality
+ - check_repository_consistency
+ - fetch_all_tests
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/create_circleci_config.py b/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/create_circleci_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..71c75dac2ff0536380661b8ae9021c1b6d078838
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/create_circleci_config.py
@@ -0,0 +1,408 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+import copy
+import os
+import random
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional
+import glob
+import yaml
+
+
+COMMON_ENV_VARIABLES = {
+ "OMP_NUM_THREADS": 1,
+ "TRANSFORMERS_IS_CI": True,
+ "PYTEST_TIMEOUT": 120,
+ "RUN_PIPELINE_TESTS": False,
+ "RUN_PT_TF_CROSS_TESTS": False,
+ "RUN_PT_FLAX_CROSS_TESTS": False,
+}
+# Disable the use of {"s": None} as the output is way too long, causing the navigation on CircleCI impractical
+COMMON_PYTEST_OPTIONS = {"max-worker-restart": 0, "dist": "loadfile", "vvv": None, "rsfE":None}
+DEFAULT_DOCKER_IMAGE = [{"image": "cimg/python:3.8.12"}]
+
+
+class EmptyJob:
+ job_name = "empty"
+
+ def to_dict(self):
+ steps = [{"run": 'ls -la'}]
+ if self.job_name == "collection_job":
+ steps.extend(
+ [
+ "checkout",
+ {"run": "pip install requests || true"},
+ {"run": """while [[ $(curl --location --request GET "https://circleci.com/api/v2/workflow/$CIRCLE_WORKFLOW_ID/job" --header "Circle-Token: $CCI_TOKEN"| jq -r '.items[]|select(.name != "collection_job")|.status' | grep -c "running") -gt 0 ]]; do sleep 5; done || true"""},
+ {"run": 'python utils/process_circleci_workflow_test_reports.py --workflow_id $CIRCLE_WORKFLOW_ID || true'},
+ {"store_artifacts": {"path": "outputs"}},
+ {"run": 'echo "All required jobs have now completed"'},
+ ]
+ )
+
+ return {
+ "docker": copy.deepcopy(DEFAULT_DOCKER_IMAGE),
+ "resource_class": "small",
+ "steps": steps,
+ }
+
+
+@dataclass
+class CircleCIJob:
+ name: str
+ additional_env: Dict[str, Any] = None
+ docker_image: List[Dict[str, str]] = None
+ install_steps: List[str] = None
+ marker: Optional[str] = None
+ parallelism: Optional[int] = 0
+ pytest_num_workers: int = 8
+ pytest_options: Dict[str, Any] = None
+ resource_class: Optional[str] = "xlarge"
+ tests_to_run: Optional[List[str]] = None
+ num_test_files_per_worker: Optional[int] = 10
+ # This should be only used for doctest job!
+ command_timeout: Optional[int] = None
+
+ def __post_init__(self):
+ # Deal with defaults for mutable attributes.
+ if self.additional_env is None:
+ self.additional_env = {}
+ if self.docker_image is None:
+ # Let's avoid changing the default list and make a copy.
+ self.docker_image = copy.deepcopy(DEFAULT_DOCKER_IMAGE)
+ else:
+ # BIG HACK WILL REMOVE ONCE FETCHER IS UPDATED
+ print(os.environ.get("GIT_COMMIT_MESSAGE"))
+ if "[build-ci-image]" in os.environ.get("GIT_COMMIT_MESSAGE", "") or os.environ.get("GIT_COMMIT_MESSAGE", "") == "dev-ci":
+ self.docker_image[0]["image"] = f"{self.docker_image[0]['image']}:dev"
+ print(f"Using {self.docker_image} docker image")
+ if self.install_steps is None:
+ self.install_steps = ["uv venv && uv pip install ."]
+ if self.pytest_options is None:
+ self.pytest_options = {}
+ if isinstance(self.tests_to_run, str):
+ self.tests_to_run = [self.tests_to_run]
+ else:
+ test_file = os.path.join("test_preparation" , f"{self.job_name}_test_list.txt")
+ print("Looking for ", test_file)
+ if os.path.exists(test_file):
+ with open(test_file) as f:
+ expanded_tests = f.read().strip().split("\n")
+ self.tests_to_run = expanded_tests
+ print("Found:", expanded_tests)
+ else:
+ self.tests_to_run = []
+ print("not Found")
+
+ def to_dict(self):
+ env = COMMON_ENV_VARIABLES.copy()
+ env.update(self.additional_env)
+
+ job = {
+ "docker": self.docker_image,
+ "environment": env,
+ }
+ if self.resource_class is not None:
+ job["resource_class"] = self.resource_class
+
+ all_options = {**COMMON_PYTEST_OPTIONS, **self.pytest_options}
+ pytest_flags = [f"--{key}={value}" if (value is not None or key in ["doctest-modules"]) else f"-{key}" for key, value in all_options.items()]
+ pytest_flags.append(
+ f"--make-reports={self.name}" if "examples" in self.name else f"--make-reports=tests_{self.name}"
+ )
+ # Examples special case: we need to download NLTK files in advance to avoid cuncurrency issues
+ timeout_cmd = f"timeout {self.command_timeout} " if self.command_timeout else ""
+ marker_cmd = f"-m '{self.marker}'" if self.marker is not None else ""
+ additional_flags = f" -p no:warning -o junit_family=xunit1 --junitxml=test-results/junit.xml"
+ parallel = f' << pipeline.parameters.{self.job_name}_parallelism >> '
+ steps = [
+ "checkout",
+ {"attach_workspace": {"at": "test_preparation"}},
+ {"run": "apt-get update && apt-get install -y curl"},
+ {"run": " && ".join(self.install_steps)},
+ {"run": {"name": "Download NLTK files", "command": """python -c "import nltk; nltk.download('punkt', quiet=True)" """} if "example" in self.name else "echo Skipping"},
+ {"run": {
+ "name": "Show installed libraries and their size",
+ "command": """du -h -d 1 "$(pip -V | cut -d ' ' -f 4 | sed 's/pip//g')" | grep -vE "dist-info|_distutils_hack|__pycache__" | sort -h | tee installed.txt || true"""}
+ },
+ {"run": {
+ "name": "Show installed libraries and their versions",
+ "command": """pip list --format=freeze | tee installed.txt || true"""}
+ },
+ {"run": {
+ "name": "Show biggest libraries",
+ "command": """dpkg-query --show --showformat='${Installed-Size}\t${Package}\n' | sort -rh | head -25 | sort -h | awk '{ package=$2; sub(".*/", "", package); printf("%.5f GB %s\n", $1/1024/1024, package)}' || true"""}
+ },
+ {"run": {"name": "Create `test-results` directory", "command": "mkdir test-results"}},
+ {"run": {"name": "Get files to test", "command":f'curl -L -o {self.job_name}_test_list.txt <> --header "Circle-Token: $CIRCLE_TOKEN"' if self.name != "pr_documentation_tests" else 'echo "Skipped"'}},
+ {"run": {"name": "Split tests across parallel nodes: show current parallel tests",
+ "command": f"TESTS=$(circleci tests split --split-by=timings {self.job_name}_test_list.txt) && echo $TESTS > splitted_tests.txt && echo $TESTS | tr ' ' '\n'" if self.parallelism else f"awk '{{printf \"%s \", $0}}' {self.job_name}_test_list.txt > splitted_tests.txt"
+ }
+ },
+ {"run": {
+ "name": "Run tests",
+ "command": f"({timeout_cmd} python3 -m pytest {marker_cmd} -n {self.pytest_num_workers} {additional_flags} {' '.join(pytest_flags)} $(cat splitted_tests.txt) | tee tests_output.txt)"}
+ },
+ {"run": {"name": "Expand to show skipped tests", "when": "always", "command": f"python3 .circleci/parse_test_outputs.py --file tests_output.txt --skip"}},
+ {"run": {"name": "Failed tests: show reasons", "when": "always", "command": f"python3 .circleci/parse_test_outputs.py --file tests_output.txt --fail"}},
+ {"run": {"name": "Errors", "when": "always", "command": f"python3 .circleci/parse_test_outputs.py --file tests_output.txt --errors"}},
+ {"store_test_results": {"path": "test-results"}},
+ {"store_artifacts": {"path": "test-results/junit.xml"}},
+ {"store_artifacts": {"path": "reports"}},
+ {"store_artifacts": {"path": "tests.txt"}},
+ {"store_artifacts": {"path": "splitted_tests.txt"}},
+ {"store_artifacts": {"path": "installed.txt"}},
+ ]
+ if self.parallelism:
+ job["parallelism"] = parallel
+ job["steps"] = steps
+ return job
+
+ @property
+ def job_name(self):
+ return self.name if ("examples" in self.name or "pipeline" in self.name or "pr_documentation" in self.name) else f"tests_{self.name}"
+
+
+# JOBS
+torch_and_tf_job = CircleCIJob(
+ "torch_and_tf",
+ docker_image=[{"image":"huggingface/transformers-torch-tf-light"}],
+ additional_env={"RUN_PT_TF_CROSS_TESTS": True},
+ marker="is_pt_tf_cross_test",
+ pytest_options={"rA": None, "durations": 0},
+)
+
+
+torch_and_flax_job = CircleCIJob(
+ "torch_and_flax",
+ additional_env={"RUN_PT_FLAX_CROSS_TESTS": True},
+ docker_image=[{"image":"huggingface/transformers-torch-jax-light"}],
+ marker="is_pt_flax_cross_test",
+ pytest_options={"rA": None, "durations": 0},
+)
+
+torch_job = CircleCIJob(
+ "torch",
+ docker_image=[{"image": "huggingface/transformers-torch-light"}],
+ marker="not generate",
+ parallelism=6,
+)
+
+generate_job = CircleCIJob(
+ "generate",
+ docker_image=[{"image": "huggingface/transformers-torch-light"}],
+ marker="generate",
+ parallelism=6,
+)
+
+tokenization_job = CircleCIJob(
+ "tokenization",
+ docker_image=[{"image": "huggingface/transformers-torch-light"}],
+ parallelism=8,
+)
+
+processor_job = CircleCIJob(
+ "processors",
+ docker_image=[{"image": "huggingface/transformers-torch-light"}],
+ parallelism=8,
+)
+
+tf_job = CircleCIJob(
+ "tf",
+ docker_image=[{"image":"huggingface/transformers-tf-light"}],
+ parallelism=6,
+)
+
+
+flax_job = CircleCIJob(
+ "flax",
+ docker_image=[{"image":"huggingface/transformers-jax-light"}],
+ parallelism=6,
+ pytest_num_workers=16,
+ resource_class="2xlarge",
+)
+
+
+pipelines_torch_job = CircleCIJob(
+ "pipelines_torch",
+ additional_env={"RUN_PIPELINE_TESTS": True},
+ docker_image=[{"image":"huggingface/transformers-torch-light"}],
+ marker="is_pipeline_test",
+ parallelism=4,
+)
+
+
+pipelines_tf_job = CircleCIJob(
+ "pipelines_tf",
+ additional_env={"RUN_PIPELINE_TESTS": True},
+ docker_image=[{"image":"huggingface/transformers-tf-light"}],
+ marker="is_pipeline_test",
+ parallelism=4,
+)
+
+
+custom_tokenizers_job = CircleCIJob(
+ "custom_tokenizers",
+ additional_env={"RUN_CUSTOM_TOKENIZERS": True},
+ docker_image=[{"image": "huggingface/transformers-custom-tokenizers"}],
+)
+
+
+examples_torch_job = CircleCIJob(
+ "examples_torch",
+ additional_env={"OMP_NUM_THREADS": 8},
+ docker_image=[{"image":"huggingface/transformers-examples-torch"}],
+ # TODO @ArthurZucker remove this once docker is easier to build
+ install_steps=["uv venv && uv pip install . && uv pip install -r examples/pytorch/_tests_requirements.txt"],
+)
+
+
+examples_tensorflow_job = CircleCIJob(
+ "examples_tensorflow",
+ additional_env={"OMP_NUM_THREADS": 8},
+ docker_image=[{"image":"huggingface/transformers-examples-tf"}],
+)
+
+
+hub_job = CircleCIJob(
+ "hub",
+ additional_env={"HUGGINGFACE_CO_STAGING": True},
+ docker_image=[{"image":"huggingface/transformers-torch-light"}],
+ install_steps=[
+ 'uv venv && uv pip install .',
+ 'git config --global user.email "ci@dummy.com"',
+ 'git config --global user.name "ci"',
+ ],
+ marker="is_staging_test",
+ pytest_num_workers=2,
+ resource_class="medium",
+)
+
+
+onnx_job = CircleCIJob(
+ "onnx",
+ docker_image=[{"image":"huggingface/transformers-torch-tf-light"}],
+ install_steps=[
+ "uv venv",
+ "uv pip install .[torch,tf,testing,sentencepiece,onnxruntime,vision,rjieba]",
+ ],
+ pytest_options={"k onnx": None},
+ pytest_num_workers=1,
+ resource_class="small",
+)
+
+
+exotic_models_job = CircleCIJob(
+ "exotic_models",
+ docker_image=[{"image":"huggingface/transformers-exotic-models"}],
+ parallelism=4,
+ pytest_options={"durations": 100},
+)
+
+
+repo_utils_job = CircleCIJob(
+ "repo_utils",
+ docker_image=[{"image":"huggingface/transformers-consistency"}],
+ pytest_num_workers=4,
+ resource_class="large",
+)
+
+
+non_model_job = CircleCIJob(
+ "non_model",
+ docker_image=[{"image": "huggingface/transformers-torch-light"}],
+ marker="not generate",
+ parallelism=6,
+)
+
+
+# We also include a `dummy.py` file in the files to be doc-tested to prevent edge case failure. Otherwise, the pytest
+# hangs forever during test collection while showing `collecting 0 items / 21 errors`. (To see this, we have to remove
+# the bash output redirection.)
+py_command = 'from utils.tests_fetcher import get_doctest_files; to_test = get_doctest_files() + ["dummy.py"]; to_test = " ".join(to_test); print(to_test)'
+py_command = f"$(python3 -c '{py_command}')"
+command = f'echo """{py_command}""" > pr_documentation_tests_temp.txt'
+doc_test_job = CircleCIJob(
+ "pr_documentation_tests",
+ docker_image=[{"image":"huggingface/transformers-consistency"}],
+ additional_env={"TRANSFORMERS_VERBOSITY": "error", "DATASETS_VERBOSITY": "error", "SKIP_CUDA_DOCTEST": "1"},
+ install_steps=[
+ # Add an empty file to keep the test step running correctly even no file is selected to be tested.
+ "uv venv && pip install .",
+ "touch dummy.py",
+ command,
+ "cat pr_documentation_tests_temp.txt",
+ "tail -n1 pr_documentation_tests_temp.txt | tee pr_documentation_tests_test_list.txt"
+ ],
+ tests_to_run="$(cat pr_documentation_tests.txt)", # noqa
+ pytest_options={"-doctest-modules": None, "doctest-glob": "*.md", "dist": "loadfile", "rvsA": None},
+ command_timeout=1200, # test cannot run longer than 1200 seconds
+ pytest_num_workers=1,
+)
+
+REGULAR_TESTS = [torch_and_tf_job, torch_and_flax_job, torch_job, tf_job, flax_job, hub_job, onnx_job, tokenization_job, processor_job, generate_job, non_model_job] # fmt: skip
+EXAMPLES_TESTS = [examples_torch_job, examples_tensorflow_job]
+PIPELINE_TESTS = [pipelines_torch_job, pipelines_tf_job]
+REPO_UTIL_TESTS = [repo_utils_job]
+DOC_TESTS = [doc_test_job]
+ALL_TESTS = REGULAR_TESTS + EXAMPLES_TESTS + PIPELINE_TESTS + REPO_UTIL_TESTS + DOC_TESTS + [custom_tokenizers_job] + [exotic_models_job] # fmt: skip
+
+
+def create_circleci_config(folder=None):
+ if folder is None:
+ folder = os.getcwd()
+ os.environ["test_preparation_dir"] = folder
+ jobs = [k for k in ALL_TESTS if os.path.isfile(os.path.join("test_preparation" , f"{k.job_name}_test_list.txt") )]
+ print("The following jobs will be run ", jobs)
+
+ if len(jobs) == 0:
+ jobs = [EmptyJob()]
+ else:
+ print("Full list of job name inputs", {j.job_name + "_test_list":{"type":"string", "default":''} for j in jobs})
+ # Add a job waiting all the test jobs and aggregate their test summary files at the end
+ collection_job = EmptyJob()
+ collection_job.job_name = "collection_job"
+ jobs = [collection_job] + jobs
+
+ config = {
+ "version": "2.1",
+ "parameters": {
+ # Only used to accept the parameters from the trigger
+ "nightly": {"type": "boolean", "default": False},
+ "tests_to_run": {"type": "string", "default": ''},
+ **{j.job_name + "_test_list":{"type":"string", "default":''} for j in jobs},
+ **{j.job_name + "_parallelism":{"type":"integer", "default":1} for j in jobs},
+ },
+ "jobs": {j.job_name: j.to_dict() for j in jobs}
+ }
+ if "CIRCLE_TOKEN" in os.environ:
+ # For private forked repo. (e.g. new model addition)
+ config["workflows"] = {"version": 2, "run_tests": {"jobs": [{j.job_name: {"context": ["TRANSFORMERS_CONTEXT"]}} for j in jobs]}}
+ else:
+ # For public repo. (e.g. `transformers`)
+ config["workflows"] = {"version": 2, "run_tests": {"jobs": [j.job_name for j in jobs]}}
+ with open(os.path.join(folder, "generated_config.yml"), "w") as f:
+ f.write(yaml.dump(config, sort_keys=False, default_flow_style=False).replace("' << pipeline", " << pipeline").replace(">> '", " >>"))
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "--fetcher_folder", type=str, default=None, help="Only test that all tests and modules are accounted for."
+ )
+ args = parser.parse_args()
+
+ create_circleci_config(args.fetcher_folder)
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/parse_test_outputs.py b/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/parse_test_outputs.py
new file mode 100644
index 0000000000000000000000000000000000000000..a69da1a3eafb27f37ee7115472aad11b8736690b
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/.circleci/parse_test_outputs.py
@@ -0,0 +1,70 @@
+import re
+import argparse
+
+def parse_pytest_output(file_path):
+ skipped_tests = {}
+ skipped_count = 0
+ with open(file_path, 'r') as file:
+ for line in file:
+ match = re.match(r'^SKIPPED \[(\d+)\] (tests/.*): (.*)$', line)
+ if match:
+ skipped_count += 1
+ test_file, test_line, reason = match.groups()
+ skipped_tests[reason] = skipped_tests.get(reason, []) + [(test_file, test_line)]
+ for k,v in sorted(skipped_tests.items(), key=lambda x:len(x[1])):
+ print(f"{len(v):4} skipped because: {k}")
+ print("Number of skipped tests:", skipped_count)
+
+def parse_pytest_failure_output(file_path):
+ failed_tests = {}
+ failed_count = 0
+ with open(file_path, 'r') as file:
+ for line in file:
+ match = re.match(r'^FAILED (tests/.*) - (.*): (.*)$', line)
+ if match:
+ failed_count += 1
+ _, error, reason = match.groups()
+ failed_tests[reason] = failed_tests.get(reason, []) + [error]
+ for k,v in sorted(failed_tests.items(), key=lambda x:len(x[1])):
+ print(f"{len(v):4} failed because `{v[0]}` -> {k}")
+ print("Number of failed tests:", failed_count)
+ if failed_count>0:
+ exit(1)
+
+def parse_pytest_errors_output(file_path):
+ print(file_path)
+ error_tests = {}
+ error_count = 0
+ with open(file_path, 'r') as file:
+ for line in file:
+ match = re.match(r'^ERROR (tests/.*) - (.*): (.*)$', line)
+ if match:
+ error_count += 1
+ _, test_error, reason = match.groups()
+ error_tests[reason] = error_tests.get(reason, []) + [test_error]
+ for k,v in sorted(error_tests.items(), key=lambda x:len(x[1])):
+ print(f"{len(v):4} errored out because of `{v[0]}` -> {k}")
+ print("Number of errors:", error_count)
+ if error_count>0:
+ exit(1)
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--file", help="file to parse")
+ parser.add_argument("--skip", action="store_true", help="show skipped reasons")
+ parser.add_argument("--fail", action="store_true", help="show failed tests")
+ parser.add_argument("--errors", action="store_true", help="show failed tests")
+ args = parser.parse_args()
+
+ if args.skip:
+ parse_pytest_output(args.file)
+
+ if args.fail:
+ parse_pytest_failure_output(args.file)
+
+ if args.errors:
+ parse_pytest_errors_output(args.file)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/.gitattributes b/tasks/tasksmith-5dd11b34cce1/environment/source/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..6505bc7edf9af5694cee1a93b90c565872fbbeb9
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/.gitattributes
@@ -0,0 +1,4 @@
+*.py eol=lf
+*.rst eol=lf
+*.md eol=lf
+*.mdx eol=lf
\ No newline at end of file
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/.gitignore b/tasks/tasksmith-5dd11b34cce1/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..337f2ef2c735e89dc8f76ba3367cc29301264f66
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/.gitignore
@@ -0,0 +1,169 @@
+# Initially taken from Github's Python gitignore file
+
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# tests and logs
+tests/fixtures/cached_*_text.txt
+logs/
+lightning_logs/
+lang_code_data/
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+.hypothesis/
+.pytest_cache/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+.python-version
+
+# celery beat schedule file
+celerybeat-schedule
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# vscode
+.vs
+.vscode
+
+# Pycharm
+.idea
+
+# TF code
+tensorflow_code
+
+# Models
+proc_data
+
+# examples
+runs
+/runs_old
+/wandb
+/examples/runs
+/examples/**/*.args
+/examples/rag/sweep
+
+# data
+/data
+serialization_dir
+
+# emacs
+*.*~
+debug.env
+
+# vim
+.*.swp
+
+#ctags
+tags
+
+# pre-commit
+.pre-commit*
+
+# .lock
+*.lock
+
+# DS_Store (MacOS)
+.DS_Store
+
+# ruff
+.ruff_cache
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/CITATION.cff b/tasks/tasksmith-5dd11b34cce1/environment/source/CITATION.cff
new file mode 100644
index 0000000000000000000000000000000000000000..b4d5156786f94df7ca0aebe5322b17dbb1521cb3
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/CITATION.cff
@@ -0,0 +1,82 @@
+cff-version: "1.2.0"
+date-released: 2020-10
+message: "If you use this software, please cite it using these metadata."
+title: "Transformers: State-of-the-Art Natural Language Processing"
+url: "https://github.com/huggingface/transformers"
+authors:
+ - family-names: Wolf
+ given-names: Thomas
+ - family-names: Debut
+ given-names: Lysandre
+ - family-names: Sanh
+ given-names: Victor
+ - family-names: Chaumond
+ given-names: Julien
+ - family-names: Delangue
+ given-names: Clement
+ - family-names: Moi
+ given-names: Anthony
+ - family-names: Cistac
+ given-names: Perric
+ - family-names: Ma
+ given-names: Clara
+ - family-names: Jernite
+ given-names: Yacine
+ - family-names: Plu
+ given-names: Julien
+ - family-names: Xu
+ given-names: Canwen
+ - family-names: "Le Scao"
+ given-names: Teven
+ - family-names: Gugger
+ given-names: Sylvain
+ - family-names: Drame
+ given-names: Mariama
+ - family-names: Lhoest
+ given-names: Quentin
+ - family-names: Rush
+ given-names: "Alexander M."
+preferred-citation:
+ type: conference-paper
+ authors:
+ - family-names: Wolf
+ given-names: Thomas
+ - family-names: Debut
+ given-names: Lysandre
+ - family-names: Sanh
+ given-names: Victor
+ - family-names: Chaumond
+ given-names: Julien
+ - family-names: Delangue
+ given-names: Clement
+ - family-names: Moi
+ given-names: Anthony
+ - family-names: Cistac
+ given-names: Perric
+ - family-names: Ma
+ given-names: Clara
+ - family-names: Jernite
+ given-names: Yacine
+ - family-names: Plu
+ given-names: Julien
+ - family-names: Xu
+ given-names: Canwen
+ - family-names: "Le Scao"
+ given-names: Teven
+ - family-names: Gugger
+ given-names: Sylvain
+ - family-names: Drame
+ given-names: Mariama
+ - family-names: Lhoest
+ given-names: Quentin
+ - family-names: Rush
+ given-names: "Alexander M."
+ booktitle: "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations"
+ month: 10
+ start: 38
+ end: 45
+ title: "Transformers: State-of-the-Art Natural Language Processing"
+ year: 2020
+ publisher: "Association for Computational Linguistics"
+ url: "https://www.aclweb.org/anthology/2020.emnlp-demos.6"
+ address: "Online"
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/CODE_OF_CONDUCT.md b/tasks/tasksmith-5dd11b34cce1/environment/source/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000000000000000000000000000000000000..b23f3150a5a6987a74acc7bb31df8c9bf1a48d57
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/CODE_OF_CONDUCT.md
@@ -0,0 +1,133 @@
+
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our
+community a harassment-free experience for everyone, regardless of age, body
+size, visible or invisible disability, ethnicity, sex characteristics, gender
+identity and expression, level of experience, education, socio-economic status,
+nationality, personal appearance, race, caste, color, religion, or sexual
+identity and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming,
+diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our
+community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes,
+ and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the overall
+ community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or advances of
+ any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email address,
+ without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of
+acceptable behavior and will take appropriate and fair corrective action in
+response to any behavior that they deem inappropriate, threatening, offensive,
+or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject
+comments, commits, code, wiki edits, issues, and other contributions that are
+not aligned to this Code of Conduct, and will communicate reasons for moderation
+decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when
+an individual is officially representing the community in public spaces.
+Examples of representing our community include using an official e-mail address,
+posting via an official social media account, or acting as an appointed
+representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported to the community leaders responsible for enforcement at
+feedback@huggingface.co.
+All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the
+reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining
+the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed
+unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing
+clarity around the nature of the violation and an explanation of why the
+behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series of
+actions.
+
+**Consequence**: A warning with consequences for continued behavior. No
+interaction with the people involved, including unsolicited interaction with
+those enforcing the Code of Conduct, for a specified period of time. This
+includes avoiding interactions in community spaces as well as external channels
+like social media. Violating these terms may lead to a temporary or permanent
+ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including
+sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public
+communication with the community for a specified period of time. No public or
+private interaction with the people involved, including unsolicited interaction
+with those enforcing the Code of Conduct, is allowed during this period.
+Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community
+standards, including sustained inappropriate behavior, harassment of an
+individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within the
+community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage],
+version 2.1, available at
+[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
+
+Community Impact Guidelines were inspired by
+[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
+
+For answers to common questions about this code of conduct, see the FAQ at
+[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
+[https://www.contributor-covenant.org/translations][translations].
+
+[homepage]: https://www.contributor-covenant.org
+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
+[Mozilla CoC]: https://github.com/mozilla/diversity
+[FAQ]: https://www.contributor-covenant.org/faq
+[translations]: https://www.contributor-covenant.org/translations
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/CONTRIBUTING.md b/tasks/tasksmith-5dd11b34cce1/environment/source/CONTRIBUTING.md
new file mode 100644
index 0000000000000000000000000000000000000000..9eeea997154085b5e0485775826cd1eced6585cb
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/CONTRIBUTING.md
@@ -0,0 +1,397 @@
+
+
+# Contribute to 🤗 Transformers
+
+Everyone is welcome to contribute, and we value everybody's contribution. Code
+contributions are not the only way to help the community. Answering questions, helping
+others, and improving the documentation are also immensely valuable.
+
+It also helps us if you spread the word! Reference the library in blog posts
+about the awesome projects it made possible, shout out on Twitter every time it has
+helped you, or simply ⭐️ the repository to say thank you.
+
+However you choose to contribute, please be mindful and respect our
+[code of conduct](https://github.com/huggingface/transformers/blob/main/CODE_OF_CONDUCT.md).
+
+**This guide was heavily inspired by the awesome [scikit-learn guide to contributing](https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md).**
+
+## Ways to contribute
+
+There are several ways you can contribute to 🤗 Transformers:
+
+* Fix outstanding issues with the existing code.
+* Submit issues related to bugs or desired new features.
+* Implement new models.
+* Contribute to the examples or to the documentation.
+
+If you don't know where to start, there is a special [Good First
+Issue](https://github.com/huggingface/transformers/contribute) listing. It will give you a list of
+open issues that are beginner-friendly and help you start contributing to open-source. The best way to do that is to open a Pull Request and link it to the issue that you'd like to work on. We try to give priority to opened PRs as we can easily track the progress of the fix, and if the contributor does not have time anymore, someone else can take the PR over.
+
+For something slightly more challenging, you can also take a look at the [Good Second Issue](https://github.com/huggingface/transformers/labels/Good%20Second%20Issue) list. In general though, if you feel like you know what you're doing, go for it and we'll help you get there! 🚀
+
+> All contributions are equally valuable to the community. 🥰
+
+## Fixing outstanding issues
+
+If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](#create-a-pull-request) and open a Pull Request!
+
+## Submitting a bug-related issue or feature request
+
+Do your best to follow these guidelines when submitting a bug-related issue or a feature
+request. It will make it easier for us to come back to you quickly and with good
+feedback.
+
+### Did you find a bug?
+
+The 🤗 Transformers library is robust and reliable thanks to users who report the problems they encounter.
+
+Before you report an issue, we would really appreciate it if you could **make sure the bug was not
+already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the library itself, and not your code. If you're unsure whether the bug is in your code or the library, please ask in the [forum](https://discuss.huggingface.co/) or on our [discord](https://discord.com/invite/hugging-face-879548962464493619) first. This helps us respond quicker to fixing issues related to the library versus general questions.
+
+> [!TIP]
+> We have a [docs bot](https://huggingface.co/spaces/huggingchat/hf-docs-chat), and we highly encourage you to ask all your questions there. There is always a chance your bug can be fixed with a simple flag 👾🔫
+
+Once you've confirmed the bug hasn't already been reported, please include the following information in your issue so we can quickly resolve it:
+
+* Your **OS type and version** and **Python**, **PyTorch** and
+ **TensorFlow** versions when applicable.
+* A short, self-contained, code snippet that allows us to reproduce the bug in
+ less than 30s.
+* The *full* traceback if an exception is raised.
+* Attach any other additional information, like screenshots, you think may help.
+
+To get the OS and software versions automatically, run the following command:
+
+```bash
+transformers-cli env
+```
+
+You can also run the same command from the root of the repository:
+
+```bash
+python src/transformers/commands/transformers_cli.py env
+```
+
+### Do you want a new feature?
+
+If there is a new feature you'd like to see in 🤗 Transformers, please open an issue and describe:
+
+1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it a feature related to something you need for a project? Is it something you worked on and think it could benefit the community?
+
+ Whatever it is, we'd love to hear about it!
+
+2. Describe your requested feature in as much detail as possible. The more you can tell us about it, the better we'll be able to help you.
+3. Provide a *code snippet* that demonstrates the features usage.
+4. If the feature is related to a paper, please include a link.
+
+If your issue is well written we're already 80% of the way there by the time you create it.
+
+We have added [templates](https://github.com/huggingface/transformers/tree/main/templates) to help you get started with your issue.
+
+## Do you want to implement a new model?
+
+New models are constantly released and if you want to implement a new model, please provide the following information:
+
+* A short description of the model and a link to the paper.
+* Link to the implementation if it is open-sourced.
+* Link to the model weights if they are available.
+
+If you are willing to contribute the model yourself, let us know so we can help you add it to 🤗 Transformers!
+
+We have a technical guide for [how to add a model to 🤗 Transformers](https://huggingface.co/docs/transformers/add_new_model).
+
+## Do you want to add documentation?
+
+We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know how the documentation can be improved such as typos and any content that is missing, unclear or inaccurate. We'll be happy to make the changes or help you make a contribution if you're interested!
+
+For more details about how to generate, build, and write the documentation, take a look at the documentation [README](https://github.com/huggingface/transformers/tree/main/docs).
+
+## Create a Pull Request
+
+Before writing any code, we strongly advise you to search through the existing PRs or
+issues to make sure nobody is already working on the same thing. If you are
+unsure, it is always a good idea to open an issue to get some feedback.
+
+You will need basic `git` proficiency to contribute to
+🤗 Transformers. While `git` is not the easiest tool to use, it has the greatest
+manual. Type `git --help` in a shell and enjoy! If you prefer books, [Pro
+Git](https://git-scm.com/book/en/v2) is a very good reference.
+
+You'll need **[Python 3.9](https://github.com/huggingface/transformers/blob/main/setup.py#L449)** or above to contribute to 🤗 Transformers. Follow the steps below to start contributing:
+
+1. Fork the [repository](https://github.com/huggingface/transformers) by
+ clicking on the **[Fork](https://github.com/huggingface/transformers/fork)** button on the repository's page. This creates a copy of the code
+ under your GitHub user account.
+
+2. Clone your fork to your local disk, and add the base repository as a remote:
+
+ ```bash
+ git clone git@github.com:/transformers.git
+ cd transformers
+ git remote add upstream https://github.com/huggingface/transformers.git
+ ```
+
+3. Create a new branch to hold your development changes:
+
+ ```bash
+ git checkout -b a-descriptive-name-for-my-changes
+ ```
+
+ 🚨 **Do not** work on the `main` branch!
+
+4. Set up a development environment by running the following command in a virtual environment:
+
+ ```bash
+ pip install -e ".[dev]"
+ ```
+
+ If 🤗 Transformers was already installed in the virtual environment, remove
+ it with `pip uninstall transformers` before reinstalling it in editable
+ mode with the `-e` flag.
+
+ Depending on your OS, and since the number of optional dependencies of Transformers is growing, you might get a
+ failure with this command. If that's the case make sure to install the Deep Learning framework you are working with
+ (PyTorch, TensorFlow and/or Flax) then do:
+
+ ```bash
+ pip install -e ".[quality]"
+ ```
+
+ which should be enough for most use cases.
+
+5. Develop the features in your branch.
+
+ As you work on your code, you should make sure the test suite
+ passes. Run the tests impacted by your changes like this:
+
+ ```bash
+ pytest tests/.py
+ ```
+
+ For more information about tests, check out the
+ [Testing](https://huggingface.co/docs/transformers/testing) guide.
+
+ 🤗 Transformers relies on `black` and `ruff` to format its source code
+ consistently. After you make changes, apply automatic style corrections and code verifications
+ that can't be automated in one go with:
+
+ ```bash
+ make fixup
+ ```
+
+ This target is also optimized to only work with files modified by the PR you're working on.
+
+ If you prefer to run the checks one after the other, the following command applies the
+ style corrections:
+
+ ```bash
+ make style
+ ```
+
+ 🤗 Transformers also uses `ruff` and a few custom scripts to check for coding mistakes. Quality
+ controls are run by the CI, but you can run the same checks with:
+
+ ```bash
+ make quality
+ ```
+
+ Finally, we have a lot of scripts to make sure we don't forget to update
+ some files when adding a new model. You can run these scripts with:
+
+ ```bash
+ make repo-consistency
+ ```
+
+ To learn more about those checks and how to fix any issues with them, check out the
+ [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide.
+
+ If you're modifying documents under the `docs/source` directory, make sure the documentation can still be built. This check will also run in the CI when you open a pull request. To run a local check
+ make sure you install the documentation builder:
+
+ ```bash
+ pip install ".[docs]"
+ ```
+
+ Run the following command from the root of the repository:
+
+ ```bash
+ doc-builder build transformers docs/source/en --build_dir ~/tmp/test-build
+ ```
+
+ This will build the documentation in the `~/tmp/test-build` folder where you can inspect the generated
+ Markdown files with your favorite editor. You can also preview the docs on GitHub when you open a pull request.
+
+ Once you're happy with your changes, add the changed files with `git add` and
+ record your changes locally with `git commit`:
+
+ ```bash
+ git add modified_file.py
+ git commit
+ ```
+
+ Please remember to write [good commit
+ messages](https://chris.beams.io/posts/git-commit/) to clearly communicate the changes you made!
+
+ To keep your copy of the code up to date with the original
+ repository, rebase your branch on `upstream/branch` *before* you open a pull request or if requested by a maintainer:
+
+ ```bash
+ git fetch upstream
+ git rebase upstream/main
+ ```
+
+ Push your changes to your branch:
+
+ ```bash
+ git push -u origin a-descriptive-name-for-my-changes
+ ```
+
+ If you've already opened a pull request, you'll need to force push with the `--force` flag. Otherwise, if the pull request hasn't been opened yet, you can just push your changes normally.
+
+6. Now you can go to your fork of the repository on GitHub and click on **Pull Request** to open a pull request. Make sure you tick off all the boxes on our [checklist](#pull-request-checklist) below. When you're ready, you can send your changes to the project maintainers for review.
+
+7. It's ok if maintainers request changes, it happens to our core contributors
+ too! So everyone can see the changes in the pull request, work in your local
+ branch and push the changes to your fork. They will automatically appear in
+ the pull request.
+
+### Pull request checklist
+
+☐ The pull request title should summarize your contribution.
+☐ If your pull request addresses an issue, please mention the issue number in the pull
+request description to make sure they are linked (and people viewing the issue know you
+are working on it).
+☐ To indicate a work in progress please prefix the title with `[WIP]`. These are
+useful to avoid duplicated work, and to differentiate it from PRs ready to be merged.
+☐ Make sure existing tests pass.
+☐ If adding a new feature, also add tests for it.
+ - If you are adding a new model, make sure you use
+ `ModelTester.all_model_classes = (MyModel, MyModelWithLMHead,...)` to trigger the common tests.
+ - If you are adding new `@slow` tests, make sure they pass using
+ `RUN_SLOW=1 python -m pytest tests/models/my_new_model/test_my_new_model.py`.
+ - If you are adding a new tokenizer, write tests and make sure
+ `RUN_SLOW=1 python -m pytest tests/models/{your_model_name}/test_tokenization_{your_model_name}.py` passes.
+ - CircleCI does not run the slow tests, but GitHub Actions does every night!
+
+☐ All public methods must have informative docstrings (see
+[`modeling_bert.py`](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py)
+for an example).
+☐ Due to the rapidly growing repository, don't add any images, videos and other
+non-text files that'll significantly weigh down the repository. Instead, use a Hub
+repository such as [`hf-internal-testing`](https://huggingface.co/hf-internal-testing)
+to host these files and reference them by URL. We recommend placing documentation
+related images in the following repository:
+[huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images).
+You can open a PR on this dataset repository and ask a Hugging Face member to merge it.
+
+For more information about the checks run on a pull request, take a look at our [Checks on a Pull Request](https://huggingface.co/docs/transformers/pr_checks) guide.
+
+### Tests
+
+An extensive test suite is included to test the library behavior and several examples. Library tests can be found in
+the [tests](https://github.com/huggingface/transformers/tree/main/tests) folder and examples tests in the
+[examples](https://github.com/huggingface/transformers/tree/main/examples) folder.
+
+We like `pytest` and `pytest-xdist` because it's faster. From the root of the
+repository, specify a *path to a subfolder or a test file* to run the test:
+
+```bash
+python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model
+```
+
+Similarly, for the `examples` directory, specify a *path to a subfolder or test file* to run the test. For example, the following command tests the text classification subfolder in the PyTorch `examples` directory:
+
+```bash
+pip install -r examples/xxx/requirements.txt # only needed the first time
+python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification
+```
+
+In fact, this is actually how our `make test` and `make test-examples` commands are implemented (not including the `pip install`)!
+
+You can also specify a smaller set of tests in order to test only the feature
+you're working on.
+
+By default, slow tests are skipped but you can set the `RUN_SLOW` environment variable to
+`yes` to run them. This will download many gigabytes of models so make sure you
+have enough disk space, a good internet connection or a lot of patience!
+
+
+
+Remember to specify a *path to a subfolder or a test file* to run the test. Otherwise, you'll run all the tests in the `tests` or `examples` folder, which will take a very long time!
+
+
+
+```bash
+RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/models/my_new_model
+RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/text-classification
+```
+
+Like the slow tests, there are other environment variables available which are not enabled by default during testing:
+- `RUN_CUSTOM_TOKENIZERS`: Enables tests for custom tokenizers.
+- `RUN_PT_FLAX_CROSS_TESTS`: Enables tests for PyTorch + Flax integration.
+- `RUN_PT_TF_CROSS_TESTS`: Enables tests for TensorFlow + PyTorch integration.
+
+More environment variables and additional information can be found in the [testing_utils.py](https://github.com/huggingface/transformers/blob/main/src/transformers/testing_utils.py).
+
+🤗 Transformers uses `pytest` as a test runner only. It doesn't use any
+`pytest`-specific features in the test suite itself.
+
+This means `unittest` is fully supported. Here's how to run tests with
+`unittest`:
+
+```bash
+python -m unittest discover -s tests -t . -v
+python -m unittest discover -s examples -t examples -v
+```
+
+### Style guide
+
+For documentation strings, 🤗 Transformers follows the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html).
+Check our [documentation writing guide](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification)
+for more information.
+
+### Develop on Windows
+
+On Windows (unless you're working in [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/) or WSL), you need to configure git to transform Windows `CRLF` line endings to Linux `LF` line endings:
+
+```bash
+git config core.autocrlf input
+```
+
+One way to run the `make` command on Windows is with MSYS2:
+
+1. [Download MSYS2](https://www.msys2.org/), and we assume it's installed in `C:\msys64`.
+2. Open the command line `C:\msys64\msys2.exe` (it should be available from the **Start** menu).
+3. Run in the shell: `pacman -Syu` and install `make` with `pacman -S make`.
+4. Add `C:\msys64\usr\bin` to your PATH environment variable.
+
+You can now use `make` from any terminal (PowerShell, cmd.exe, etc.)! 🎉
+
+### Sync a forked repository with upstream main (the Hugging Face repository)
+
+When updating the main branch of a forked repository, please follow these steps to avoid pinging the upstream repository which adds reference notes to each upstream PR, and sends unnecessary notifications to the developers involved in these PRs.
+
+1. When possible, avoid syncing with the upstream using a branch and PR on the forked repository. Instead, merge directly into the forked main.
+2. If a PR is absolutely necessary, use the following steps after checking out your branch:
+
+ ```bash
+ git checkout -b your-branch-for-syncing
+ git pull --squash --no-commit upstream main
+ git commit -m ''
+ git push --set-upstream origin your-branch-for-syncing
+ ```
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/Dockerfile b/tasks/tasksmith-5dd11b34cce1/environment/source/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..7b15c31fcbacbd52f6e12755d49ff62cc2dbcf2b
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/Dockerfile
@@ -0,0 +1,8 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu aiohappyeyeballs==2.7.1 aiohttp==3.14.3 aiosignal==1.4.0 attrs==26.1.0 datasets==2.21.0 dill==0.3.8 filelock==3.16.1 frozenlist==1.8.0 fsspec==2024.6.1 huggingface-hub==0.36.2 multidict==6.8.0 multiprocess==0.70.16 numpy==2.5.3 packaging==26.3 pandas==3.0.5 parameterized==0.9.0 propcache==0.5.2 pyarrow==25.0.1 pytest==8.4.2 python-dateutil==2.9.0.post0 pyyaml==6.0.2 regex==2024.11.6 requests==2.32.3 safetensors==0.8.0 setuptools==78.1.0 six==1.17.0 tokenizers==0.21.4 torch==2.11.0+cpu tqdm==4.67.1 wheel==0.48.0 xxhash==4.0.1 yarl==1.24.5
+COPY . /workspace
+RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e .
+RUN rm -rf /workspace/.git /root/.cache/pip
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/ISSUES.md b/tasks/tasksmith-5dd11b34cce1/environment/source/ISSUES.md
new file mode 100644
index 0000000000000000000000000000000000000000..a5969a3027f86dc1ed20ec1683642a1c723d0d19
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/ISSUES.md
@@ -0,0 +1,277 @@
+
+
+# How To Request Support
+
+This is an Open Source Project so please be mindful that like in any other project of this kind there is no obligation to answer all requests for help.
+
+However, we want to encourage you to ask for help whenever you think it's needed! We are happy about every question we get because it allows us to better understand your needs, possible misunderstandings, and most importantly a way for you to help us make this library better. That being said, this document's main purpose is to provide guidelines at how you can formulate your requests to increase your chances to be understood and to get support.
+
+There are two main venues to receive support: [the forums](https://discuss.huggingface.co/) and [the GitHub issues](https://github.com/huggingface/transformers/issues).
+
+## The Forums
+
+[The user forums](https://discuss.huggingface.co/) are supported by the wide community of the library users and backed up by developers when needed.
+
+If you have a difficulty with deploying this library or some questions, or you'd like to discuss a new feature, please first consider discussing those things at the forums. Only when you feel your subject matter has been crystalized and you still need support from the library developers do proceed to file an [issue](https://github.com/huggingface/transformers/issues).
+
+In particular all "Please explain" questions or objectively very user-specific feature requests belong to the forums. Here are some example of such questions:
+
+* "I would like to use a BertModel within a RL-Agent for a customer support service. How can I use a BertForMaskedLM in my ChatBotModel?"
+
+* "Could you please explain why T5 has no positional embedding matrix under T5Model?"
+
+* "How should I set my generation parameters for translation?"
+
+* "How to train T5 on De->En translation?"
+
+
+## The GitHub Issues
+
+Everything which hints at a bug should be opened as an [issue](https://github.com/huggingface/transformers/issues).
+
+You are not required to read the following guidelines before opening an issue. However, if you notice that your issue doesn't get any replies, chances are that the developers have one or several difficulties with its quality. In this case, reading the following points and adjusting your issue accordingly could help.
+
+1. Before posting an issue, first search for already posted issues, since chances are someone has already asked a similar question before you.
+
+ If you use Google your search query should be:
+
+ ```
+ "huggingface" "transformers" your query
+ ```
+
+ The first two quoted words tell Google to limit the search to the context of the Huggingface Transformers. The remainder is your query - most commonly this would be the error message the software fails with. We will go deeper into details shortly.
+
+ The results of such a query will typically match GitHub issues, Hugging Face forums, StackExchange, and blogs.
+
+ If you find relevant hints, you may choose to continue the discussion there if you have follow up questions.
+
+ If what you found is similar but doesn't quite answer your problem, please, post a new issue and do include links to similar issues or forum discussions you may have found.
+
+ Let's look at some examples:
+
+ The error message, often referred to as an assertion, tells us what went wrong. Here is an example of an assertion:
+
+ ```python
+ Traceback (most recent call last):
+ File "", line 1, in
+ File "/transformers/src/transformers/__init__.py", line 34, in
+ from . import dependency_versions_check
+ File "/transformers/src/transformers/dependency_versions_check.py", line 34, in
+ from .utils import is_tokenizers_available
+ File "/transformers/src/transformers/utils/import_utils.py", line 40, in
+ from tqdm.auto import tqdm
+ ModuleNotFoundError: No module named 'tqdm.auto'
+ ```
+
+ and it typically includes a traceback, so that we can see the full stack of calls the program made before it fails. This gives us the context to know why the program failed.
+
+ Going back to the above example. If you received this error search, look at the very last line of the error which is:
+
+ ```python
+ ModuleNotFoundError: No module named 'tqdm.auto'
+ ```
+
+ And now we can use it to do the searching on your favorite search engine:
+
+ 1. first for `"huggingface" "transformers" "ModuleNotFoundError: No module named 'tqdm.auto'"`
+ 2. if you don't find relevant results, then search for just `"ModuleNotFoundError: No module named 'tqdm.auto'"`
+ 3. and finally if nothing still comes up, then remove the outside quotes: `ModuleNotFoundError: No module named 'tqdm.auto'`
+
+ If the error includes any messages that include bits unique to your filesystem, always remove those in the search query since other users will not have the same filesystem as yours. For example:
+
+ ```bash
+ python -c 'open("/tmp/wrong_path.txt", "r")'
+ Traceback (most recent call last):
+ File "", line 1, in
+ FileNotFoundError: [Errno 2] No such file or directory: '/tmp/wrong_path.txt'
+ ```
+ Here you'd search for just: `"FileNotFoundError: [Errno 2] No such file or directory"`
+
+ If the local information that you removed were inside the error message and you removed them you may need to remove double quotes since your query is no longer exact. So if the error message was something like:
+
+ ```bash
+ ValueError: '/tmp/wrong_path.txt' cannot be found
+ ```
+
+ then you'd search for `"ValueError" "cannot be found"`
+
+ As you search you will notice that when you don't use quotes often the search engines will return a variety of unrelated hits, which may or may not be what you want.
+
+ Experiment with different ways and find which approach gives the most satisfactory results.
+
+2. Keep the issue short, providing the information that you think will aid the developers to understand your situation. Put yourself in the shoes of the person who has never seen your code or knows anything about your custom setup. This mental exercise will help to develop an intuition to what/what not to share"
+
+3. If there is a software failure, always provide the full traceback, for example:
+
+ ```python
+ $ python -c 'import transformers'
+ Traceback (most recent call last):
+ File "", line 1, in
+ File "/transformers/src/transformers/__init__.py", line 34, in
+ from . import dependency_versions_check
+ File "/transformers/src/transformers/dependency_versions_check.py", line 34, in
+ from .utils import is_tokenizers_available
+ File "/transformers/src/transformers/utils/import_utils.py", line 40, in
+ from tqdm.auto import tqdm
+ ModuleNotFoundError: No module named 'tqdm.auto'
+ ```
+
+ As compared to providing just the last line of the error message, e.g.:
+ ```python
+ ModuleNotFoundError: No module named 'tqdm.auto'
+ ```
+ which is not sufficient.
+
+ If your application is running on more than one GPU (e.g. under `DistributedDataParallel`) and typically getting every log and traceback printed multiple times, please make sure that you paste only one copy of it. At times the traceback from parallel processes may get interleaved - so either disentangle these or change the loggers to log only for `local_rank==0` so that only one process logs things.
+
+4. When quoting a traceback, command line instructions and any type of code always enclose it in triple backticks inside the editor window, that is:
+
+ ````
+ ```
+ git clone https://github.com/huggingface/transformers
+ cd transformers
+ pip install .
+ ```
+ ````
+
+ If it's a command line with a long argument list, please consider breaking it down using backslashes and new lines. Here is an example of a good command line quote:
+
+ ```bash
+ cd examples/seq2seq
+ torchrun --nproc_per_node=2 ./finetune_trainer.py \
+ --model_name_or_path sshleifer/distill-mbart-en-ro-12-4 --data_dir wmt_en_ro \
+ --output_dir output_dir --overwrite_output_dir \
+ --do_train --n_train 500 --num_train_epochs 1 \
+ --per_device_train_batch_size 1 --freeze_embeds \
+ --src_lang en_XX --tgt_lang ro_RO --task translation \
+ --fp16
+ ```
+
+ If you don't break it up, one has to scroll horizontally which often makes it quite difficult to quickly see what's happening.
+
+ The backslashes allow us to copy the command directly into the console to run it, without needing to edit it.
+
+5. Include only the important information that you think will help the developer to quickly identify the problem.
+
+ For example applications often create huge amounts of logs. Ask yourself whether providing all or parts of the log is useful.
+
+ Pasting a 100-1000 lines of log into the issue is an immediate turn off, since it will take a lot of time to figure out where the pertinent parts of the log are.
+
+ Attaching a full log can be helpful if it's done as an attachment, if it's enclosed in the following html code in the comment editor window:
+
+ ```
+
+ Full log
+
+
+ many
+ lines
+ go
+ here
+
+
+
+ ```
+
+ which would result in the following entry, which can be opened if desired, but otherwise takes little space.
+
+
+ Full log
+
+ many
+ lines
+ go
+ here
+
+
+
+ You could also provide a link to a pastebin service, but this is less beneficial since those links tend to expire quickly and future readers of your issue might not be able to access that log file anymore and may lack some context.
+
+6. If this is an issue in your code, do try to reduce that code to a minimal example that still demonstrates the problem. Please ask at the forums if you have a hard time figuring how to do that. Please realize that we don't have the luxury of having time to try and understand all of your custom code.
+
+ If you really tried to make a short reproducible code but couldn't figure it out, it might be that having a traceback will give the developer enough information to know what's going on. But if it is not enough and we can't reproduce the problem, we can't really solve it.
+
+ Do not despair if you can't figure it out from the beginning, just share what you can and perhaps someone else will be able to help you at the forums.
+
+ If your setup involves any custom datasets, the best way to help us reproduce the problem is to create a [Google Colab notebook](https://colab.research.google.com/) that demonstrates the issue and once you verify that the issue still exists, include a link to that notebook in the Issue. Just make sure that you don't copy and paste the location bar url of the open notebook - as this is private and we won't be able to open it. Instead, you need to click on `Share` in the right upper corner of the notebook, select `Get Link` and then copy and paste the public link it will give to you.
+
+7. If you forked off some of this project's code or example applications, please, do not ask us to go into your code repository and figure out what you may have done. The code is already very complex and unless there is an easy way to do a diff and it's a small diff, it won't be possible to find someone with time on their hands to make a lengthy investigation. Albeit, you might find someone at the forums who will be generous to do this for you.
+
+8. Before reporting an issue, first, always try to update your environment to the latest official version of this library. We have no resources to go and debug older revisions, which could easily have bugs that have been fixed in the latest released version.
+
+ We understand that this is not always possible, especially when APIs change, in which case file an issue against the highest library version your environment can support.
+
+ Of course, if you upgrade the library, always retest that the problem is still there.
+
+9. Please do not ask us to reproduce an issue with your custom data, since we don't have it. So, either you should use some existing dataset supported by HF datasets or you need to supply a code that generates a small sample on the fly, or some another quick and simple way to get it.
+
+ Please do not send us any non-public domain data that may require a license or a permission to be used.
+
+10. Do not tag multiple developers on the issue unless you know this is expected, either because you asked them and they gave you an explicit permission to tag them or the issue template instructs you to do so.
+
+ The "who to tag for what domain" part of the issue template is there to help users direct their questions to the right developers who are designated maintainers of project's specific domains. They can then decide at their own discretion to tag other developers if they feel it'd help move the issue forward.
+
+ We currently don't have a triage service and we trust your capacity to identify the right domain and thus the persons to tag in your issue. If you are not sure, please use the forums to ask for guidance.
+
+ When in doubt, err on the side of not tagging a given person. If you tag multiple people out of context or permission don't be surprised if you get no response at all. Please remember that every time you tag someone, they get a notification and you're taking their time without their permission. Please be sensitive to that.
+
+ If you got helped by one of the developers in the past please don't tag them in future issues, unless they are listed in the issue template for the domain you are asking about or that developer gave you an explicit permission to tag them in future issues.
+
+ If you see a certain developer doing multiple and/or recent commits into a specific area of the project that you feel is relevant to your issue, it is not a good reason to tag them. Various developers may be fixing things that prevent them from moving forward, but often their work is focused on a totally different domain. And while they may or may not know how to help you with the problem at hand, it would benefit the whole community much more if they focus on the domain of their unique expertise.
+
+11. Use the Edit button. Take your time, and re-read and improve the wording and formatting to make your posts and comments as easy to understand as possible.
+
+ Avoid posting multiple comments in a row, as each comment generates a notification for the developers tagged in that issue. If you happened to post multiple comments in a row, and nobody followed up yet - consider merging those into one or a few comments while editing the combined content to be coherent.
+
+ If you choose to edit your older comments after others posted follow up comments you need to be aware that your modifications might not be noticed, so if it's not a typo fixing, try to write a new comment flagging that something has been changed in the previous comments.
+
+ For example, the very first comment is the most important one. If while the thread unfolds you realize that things aren't as they seemed to you originally you may want to edit the first post to reflect the up-to-date understanding of the issue at hand so that it helps those who read your issue in the future quickly understand what's going on and not need to sift through dozens of comments. It also helps to indicate that the post was edited. So, those reading the thread later can understand why there might be certain discontinuity in the information flow.
+
+ Use bullets and items if you have lists of items and the outcome improves overall readability.
+
+ Use backticks to refer to class and function names, e.g. `BartModel` and `generate` as these stand out and improve the speed of a reader's comprehension.
+
+ Try not use italics and bold text too much as these often make the text more difficult to read.
+
+
+12. If you are cross-referencing a specific comment in a given thread or another issue, always link to that specific comment, rather than using the issue link. If you do the latter it could be quite impossible to find which specific comment you're referring to.
+
+ To get the link to the specific comment do not copy the url from the location bar of your browser, but instead, click the `...` icon in the upper right corner of the comment and then select "Copy Link".
+
+ For example the first link is a link to an issue, and the second to a specific comment in the same issue:
+
+ 1. https://github.com/huggingface/transformers/issues/9257
+ 2. https://github.com/huggingface/transformers/issues/9257#issuecomment-749945162
+
+
+13. If you are replying to a last comment, it's totally fine to make your reply with just your comment in it. The readers can follow the information flow here.
+
+ But if you're replying to a comment that happened some comments back it's always a good practice to quote just the relevant lines you're replying it. The `>` is used for quoting, or you can always use the menu to do so. For example your editor box will look like:
+
+ ```
+ > How big is your gpu cluster?
+
+ Our cluster is made of 256 gpus.
+ ```
+
+ If you are addressing multiple comments, quote the relevant parts of each before your answer. Some people use the same comment to do multiple replies, others separate them into separate comments. Either way works. The latter approach helps for linking to a specific comment.
+
+In general the best way to figure out what works the best is learn from issues posted by other people - see which issues get great responses and which get little to no response - observe what the posters who received great responses did differently from those who did not.
+
+Thank you for reading this somewhat lengthy document. We would like to conclude that these are not absolute rules, but a friendly advice that will help maximize the chances for us to understand what you are trying to communicate, reproduce the problem then resolve it to your satisfaction and the benefit of the whole community.
+
+If after reading this document there are remaining questions on how and why or there is a need for further elucidation, please, don't hesitate to ask your question in [this thread](https://discuss.huggingface.co/t/how-to-request-support/3128).
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/LICENSE b/tasks/tasksmith-5dd11b34cce1/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..68b7d66c97d66c58de883ed0c451af2b3183e6f3
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/LICENSE
@@ -0,0 +1,203 @@
+Copyright 2018- The Hugging Face team. All rights reserved.
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/Makefile b/tasks/tasksmith-5dd11b34cce1/environment/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..710c555b74f6df662a21823351d51c732bda8d2c
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/Makefile
@@ -0,0 +1,130 @@
+.PHONY: deps_table_update modified_only_fixup extra_style_checks quality style fixup fix-copies test test-examples benchmark
+
+# make sure to test the local checkout in scripts and not the pre-installed one (don't use quotes!)
+export PYTHONPATH = src
+
+check_dirs := examples tests src utils
+
+exclude_folders := ""
+
+modified_only_fixup:
+ $(eval modified_py_files := $(shell python utils/get_modified_files.py $(check_dirs)))
+ @if test -n "$(modified_py_files)"; then \
+ echo "Checking/fixing $(modified_py_files)"; \
+ ruff check $(modified_py_files) --fix --exclude $(exclude_folders); \
+ ruff format $(modified_py_files) --exclude $(exclude_folders);\
+ else \
+ echo "No library .py files were modified"; \
+ fi
+
+# Update src/transformers/dependency_versions_table.py
+
+deps_table_update:
+ @python setup.py deps_table_update
+
+deps_table_check_updated:
+ @md5sum src/transformers/dependency_versions_table.py > md5sum.saved
+ @python setup.py deps_table_update
+ @md5sum -c --quiet md5sum.saved || (printf "\nError: the version dependency table is outdated.\nPlease run 'make fixup' or 'make style' and commit the changes.\n\n" && exit 1)
+ @rm md5sum.saved
+
+# autogenerating code
+
+autogenerate_code: deps_table_update
+
+# Check that the repo is in a good state
+
+repo-consistency:
+ python utils/check_copies.py
+ python utils/check_modular_conversion.py
+ python utils/check_table.py
+ python utils/check_dummies.py
+ python utils/check_repo.py
+ python utils/check_inits.py
+ python utils/check_config_docstrings.py
+ python utils/check_config_attributes.py
+ python utils/check_doctest_list.py
+ python utils/update_metadata.py --check-only
+ python utils/check_docstrings.py
+ python utils/check_support_list.py
+
+# this target runs checks on all files
+
+quality:
+ @python -c "from transformers import *" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1)
+ ruff check $(check_dirs) setup.py conftest.py
+ ruff format --check $(check_dirs) setup.py conftest.py
+ python utils/sort_auto_mappings.py --check_only
+ python utils/check_doc_toc.py
+ python utils/check_docstrings.py --check_all
+
+
+# Format source code automatically and check is there are any problems left that need manual fixing
+
+extra_style_checks:
+ python utils/sort_auto_mappings.py
+ python utils/check_doc_toc.py --fix_and_overwrite
+
+# this target runs checks on all files and potentially modifies some of them
+
+style:
+ ruff check $(check_dirs) setup.py conftest.py --fix --exclude $(exclude_folders)
+ ruff format $(check_dirs) setup.py conftest.py --exclude $(exclude_folders)
+ ${MAKE} autogenerate_code
+ ${MAKE} extra_style_checks
+
+# Super fast fix and check target that only works on relevant modified files since the branch was made
+
+fixup: modified_only_fixup extra_style_checks autogenerate_code repo-consistency
+
+# Make marked copies of snippets of codes conform to the original
+
+fix-copies:
+ python utils/check_copies.py --fix_and_overwrite
+ python utils/check_modular_conversion.py --fix_and_overwrite
+ python utils/check_table.py --fix_and_overwrite
+ python utils/check_dummies.py --fix_and_overwrite
+ python utils/check_doctest_list.py --fix_and_overwrite
+ python utils/check_docstrings.py --fix_and_overwrite
+
+# Run tests for the library
+
+test:
+ python -m pytest -n auto --dist=loadfile -s -v ./tests/
+
+# Run tests for examples
+
+test-examples:
+ python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/
+
+# Run benchmark
+
+benchmark:
+ python3 benchmark/benchmark.py --config-dir benchmark/config --config-name generation --commit=diff backend.model=google/gemma-2b backend.cache_implementation=null,static backend.torch_compile=false,true --multirun
+
+# Run tests for SageMaker DLC release
+
+test-sagemaker: # install sagemaker dependencies in advance with pip install .[sagemaker]
+ TEST_SAGEMAKER=True python -m pytest -n auto -s -v ./tests/sagemaker
+
+
+# Release stuff
+
+pre-release:
+ python utils/release.py
+
+pre-patch:
+ python utils/release.py --patch
+
+post-release:
+ python utils/release.py --post_release
+
+post-patch:
+ python utils/release.py --post_release --patch
+
+build-release:
+ rm -rf dist
+ rm -rf build
+ python setup.py bdist_wheel
+ python setup.py sdist
+ python utils/check_build.py
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/README.md b/tasks/tasksmith-5dd11b34cce1/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..42403f84b885daf03378fcc951722259c507b8d6
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/README.md
@@ -0,0 +1,322 @@
+
+
+
State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow
+
+
+
+
+
+
+🤗 Transformers provides thousands of pretrained models to perform tasks on different modalities such as text, vision, and audio.
+
+These models can be applied on:
+
+* 📝 Text, for tasks like text classification, information extraction, question answering, summarization, translation, and text generation, in over 100 languages.
+* 🖼️ Images, for tasks like image classification, object detection, and segmentation.
+* 🗣️ Audio, for tasks like speech recognition and audio classification.
+
+Transformer models can also perform tasks on **several modalities combined**, such as table question answering, optical character recognition, information extraction from scanned documents, video classification, and visual question answering.
+
+🤗 Transformers provides APIs to quickly download and use those pretrained models on a given text, fine-tune them on your own datasets and then share them with the community on our [model hub](https://huggingface.co/models). At the same time, each python module defining an architecture is fully standalone and can be modified to enable quick research experiments.
+
+🤗 Transformers is backed by the three most popular deep learning libraries — [Jax](https://jax.readthedocs.io/en/latest/), [PyTorch](https://pytorch.org/) and [TensorFlow](https://www.tensorflow.org/) — with a seamless integration between them. It's straightforward to train your models with one before loading them for inference with the other.
+
+## Online demos
+
+You can test most of our models directly on their pages from the [model hub](https://huggingface.co/models). We also offer [private model hosting, versioning, & an inference API](https://huggingface.co/pricing) for public and private models.
+
+Here are a few examples:
+
+In Natural Language Processing:
+- [Masked word completion with BERT](https://huggingface.co/google-bert/bert-base-uncased?text=Paris+is+the+%5BMASK%5D+of+France)
+- [Named Entity Recognition with Electra](https://huggingface.co/dbmdz/electra-large-discriminator-finetuned-conll03-english?text=My+name+is+Sarah+and+I+live+in+London+city)
+- [Text generation with Mistral](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2)
+- [Natural Language Inference with RoBERTa](https://huggingface.co/FacebookAI/roberta-large-mnli?text=The+dog+was+lost.+Nobody+lost+any+animal)
+- [Summarization with BART](https://huggingface.co/facebook/bart-large-cnn?text=The+tower+is+324+metres+%281%2C063+ft%29+tall%2C+about+the+same+height+as+an+81-storey+building%2C+and+the+tallest+structure+in+Paris.+Its+base+is+square%2C+measuring+125+metres+%28410+ft%29+on+each+side.+During+its+construction%2C+the+Eiffel+Tower+surpassed+the+Washington+Monument+to+become+the+tallest+man-made+structure+in+the+world%2C+a+title+it+held+for+41+years+until+the+Chrysler+Building+in+New+York+City+was+finished+in+1930.+It+was+the+first+structure+to+reach+a+height+of+300+metres.+Due+to+the+addition+of+a+broadcasting+aerial+at+the+top+of+the+tower+in+1957%2C+it+is+now+taller+than+the+Chrysler+Building+by+5.2+metres+%2817+ft%29.+Excluding+transmitters%2C+the+Eiffel+Tower+is+the+second+tallest+free-standing+structure+in+France+after+the+Millau+Viaduct)
+- [Question answering with DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased-distilled-squad?text=Which+name+is+also+used+to+describe+the+Amazon+rainforest+in+English%3F&context=The+Amazon+rainforest+%28Portuguese%3A+Floresta+Amaz%C3%B4nica+or+Amaz%C3%B4nia%3B+Spanish%3A+Selva+Amaz%C3%B3nica%2C+Amazon%C3%ADa+or+usually+Amazonia%3B+French%3A+For%C3%AAt+amazonienne%3B+Dutch%3A+Amazoneregenwoud%29%2C+also+known+in+English+as+Amazonia+or+the+Amazon+Jungle%2C+is+a+moist+broadleaf+forest+that+covers+most+of+the+Amazon+basin+of+South+America.+This+basin+encompasses+7%2C000%2C000+square+kilometres+%282%2C700%2C000+sq+mi%29%2C+of+which+5%2C500%2C000+square+kilometres+%282%2C100%2C000+sq+mi%29+are+covered+by+the+rainforest.+This+region+includes+territory+belonging+to+nine+nations.+The+majority+of+the+forest+is+contained+within+Brazil%2C+with+60%25+of+the+rainforest%2C+followed+by+Peru+with+13%25%2C+Colombia+with+10%25%2C+and+with+minor+amounts+in+Venezuela%2C+Ecuador%2C+Bolivia%2C+Guyana%2C+Suriname+and+French+Guiana.+States+or+departments+in+four+nations+contain+%22Amazonas%22+in+their+names.+The+Amazon+represents+over+half+of+the+planet%27s+remaining+rainforests%2C+and+comprises+the+largest+and+most+biodiverse+tract+of+tropical+rainforest+in+the+world%2C+with+an+estimated+390+billion+individual+trees+divided+into+16%2C000+species)
+- [Translation with T5](https://huggingface.co/google-t5/t5-base?text=My+name+is+Wolfgang+and+I+live+in+Berlin)
+
+In Computer Vision:
+- [Image classification with ViT](https://huggingface.co/google/vit-base-patch16-224)
+- [Object Detection with DETR](https://huggingface.co/facebook/detr-resnet-50)
+- [Semantic Segmentation with SegFormer](https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512)
+- [Panoptic Segmentation with Mask2Former](https://huggingface.co/facebook/mask2former-swin-large-coco-panoptic)
+- [Depth Estimation with Depth Anything](https://huggingface.co/docs/transformers/main/model_doc/depth_anything)
+- [Video Classification with VideoMAE](https://huggingface.co/docs/transformers/model_doc/videomae)
+- [Universal Segmentation with OneFormer](https://huggingface.co/shi-labs/oneformer_ade20k_dinat_large)
+
+In Audio:
+- [Automatic Speech Recognition with Whisper](https://huggingface.co/openai/whisper-large-v3)
+- [Keyword Spotting with Wav2Vec2](https://huggingface.co/superb/wav2vec2-base-superb-ks)
+- [Audio Classification with Audio Spectrogram Transformer](https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593)
+
+In Multimodal tasks:
+- [Table Question Answering with TAPAS](https://huggingface.co/google/tapas-base-finetuned-wtq)
+- [Visual Question Answering with ViLT](https://huggingface.co/dandelin/vilt-b32-finetuned-vqa)
+- [Image captioning with LLaVa](https://huggingface.co/llava-hf/llava-1.5-7b-hf)
+- [Zero-shot Image Classification with SigLIP](https://huggingface.co/google/siglip-so400m-patch14-384)
+- [Document Question Answering with LayoutLM](https://huggingface.co/impira/layoutlm-document-qa)
+- [Zero-shot Video Classification with X-CLIP](https://huggingface.co/docs/transformers/model_doc/xclip)
+- [Zero-shot Object Detection with OWLv2](https://huggingface.co/docs/transformers/en/model_doc/owlv2)
+- [Zero-shot Image Segmentation with CLIPSeg](https://huggingface.co/docs/transformers/model_doc/clipseg)
+- [Automatic Mask Generation with SAM](https://huggingface.co/docs/transformers/model_doc/sam)
+
+
+## 100 projects using Transformers
+
+Transformers is more than a toolkit to use pretrained models: it's a community of projects built around it and the
+Hugging Face Hub. We want Transformers to enable developers, researchers, students, professors, engineers, and anyone
+else to build their dream projects.
+
+In order to celebrate the 100,000 stars of transformers, we have decided to put the spotlight on the
+community, and we have created the [awesome-transformers](./awesome-transformers.md) page which lists 100
+incredible projects built in the vicinity of transformers.
+
+If you own or use a project that you believe should be part of the list, please open a PR to add it!
+
+## Serious about AI in your organisation? Build faster with the Hugging Face Enterprise Hub.
+
+
+
+
+
+## Quick tour
+
+To immediately use a model on a given input (text, image, audio, ...), we provide the `pipeline` API. Pipelines group together a pretrained model with the preprocessing that was used during that model's training. Here is how to quickly use a pipeline to classify positive versus negative texts:
+
+```python
+>>> from transformers import pipeline
+
+# Allocate a pipeline for sentiment-analysis
+>>> classifier = pipeline('sentiment-analysis')
+>>> classifier('We are very happy to introduce pipeline to the transformers repository.')
+[{'label': 'POSITIVE', 'score': 0.9996980428695679}]
+```
+
+The second line of code downloads and caches the pretrained model used by the pipeline, while the third evaluates it on the given text. Here, the answer is "positive" with a confidence of 99.97%.
+
+Many tasks have a pre-trained `pipeline` ready to go, in NLP but also in computer vision and speech. For example, we can easily extract detected objects in an image:
+
+``` python
+>>> import requests
+>>> from PIL import Image
+>>> from transformers import pipeline
+
+# Download an image with cute cats
+>>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/coco_sample.png"
+>>> image_data = requests.get(url, stream=True).raw
+>>> image = Image.open(image_data)
+
+# Allocate a pipeline for object detection
+>>> object_detector = pipeline('object-detection')
+>>> object_detector(image)
+[{'score': 0.9982201457023621,
+ 'label': 'remote',
+ 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}},
+ {'score': 0.9960021376609802,
+ 'label': 'remote',
+ 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}},
+ {'score': 0.9954745173454285,
+ 'label': 'couch',
+ 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}},
+ {'score': 0.9988006353378296,
+ 'label': 'cat',
+ 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}},
+ {'score': 0.9986783862113953,
+ 'label': 'cat',
+ 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}]
+```
+
+Here, we get a list of objects detected in the image, with a box surrounding the object and a confidence score. Here is the original image on the left, with the predictions displayed on the right:
+
+
+
+
+
+
+You can learn more about the tasks supported by the `pipeline` API in [this tutorial](https://huggingface.co/docs/transformers/task_summary).
+
+In addition to `pipeline`, to download and use any of the pretrained models on your given task, all it takes is three lines of code. Here is the PyTorch version:
+```python
+>>> from transformers import AutoTokenizer, AutoModel
+
+>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
+>>> model = AutoModel.from_pretrained("google-bert/bert-base-uncased")
+
+>>> inputs = tokenizer("Hello world!", return_tensors="pt")
+>>> outputs = model(**inputs)
+```
+
+And here is the equivalent code for TensorFlow:
+```python
+>>> from transformers import AutoTokenizer, TFAutoModel
+
+>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
+>>> model = TFAutoModel.from_pretrained("google-bert/bert-base-uncased")
+
+>>> inputs = tokenizer("Hello world!", return_tensors="tf")
+>>> outputs = model(**inputs)
+```
+
+The tokenizer is responsible for all the preprocessing the pretrained model expects and can be called directly on a single string (as in the above examples) or a list. It will output a dictionary that you can use in downstream code or simply directly pass to your model using the ** argument unpacking operator.
+
+The model itself is a regular [Pytorch `nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) or a [TensorFlow `tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) (depending on your backend) which you can use as usual. [This tutorial](https://huggingface.co/docs/transformers/training) explains how to integrate such a model into a classic PyTorch or TensorFlow training loop, or how to use our `Trainer` API to quickly fine-tune on a new dataset.
+
+## Why should I use transformers?
+
+1. Easy-to-use state-of-the-art models:
+ - High performance on natural language understanding & generation, computer vision, and audio tasks.
+ - Low barrier to entry for educators and practitioners.
+ - Few user-facing abstractions with just three classes to learn.
+ - A unified API for using all our pretrained models.
+
+1. Lower compute costs, smaller carbon footprint:
+ - Researchers can share trained models instead of always retraining.
+ - Practitioners can reduce compute time and production costs.
+ - Dozens of architectures with over 400,000 pretrained models across all modalities.
+
+1. Choose the right framework for every part of a model's lifetime:
+ - Train state-of-the-art models in 3 lines of code.
+ - Move a single model between TF2.0/PyTorch/JAX frameworks at will.
+ - Seamlessly pick the right framework for training, evaluation, and production.
+
+1. Easily customize a model or an example to your needs:
+ - We provide examples for each architecture to reproduce the results published by its original authors.
+ - Model internals are exposed as consistently as possible.
+ - Model files can be used independently of the library for quick experiments.
+
+## Why shouldn't I use transformers?
+
+- This library is not a modular toolbox of building blocks for neural nets. The code in the model files is not refactored with additional abstractions on purpose, so that researchers can quickly iterate on each of the models without diving into additional abstractions/files.
+- The training API is not intended to work on any model but is optimized to work with the models provided by the library. For generic machine learning loops, you should use another library (possibly, [Accelerate](https://huggingface.co/docs/accelerate)).
+- While we strive to present as many use cases as possible, the scripts in our [examples folder](https://github.com/huggingface/transformers/tree/main/examples) are just that: examples. It is expected that they won't work out-of-the-box on your specific problem and that you will be required to change a few lines of code to adapt them to your needs.
+
+## Installation
+
+### With pip
+
+This repository is tested on Python 3.9+, Flax 0.4.1+, PyTorch 2.0+, and TensorFlow 2.6+.
+
+You should install 🤗 Transformers in a [virtual environment](https://docs.python.org/3/library/venv.html). If you're unfamiliar with Python virtual environments, check out the [user guide](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
+
+First, create a virtual environment with the version of Python you're going to use and activate it.
+
+Then, you will need to install at least one of Flax, PyTorch, or TensorFlow.
+Please refer to [TensorFlow installation page](https://www.tensorflow.org/install/), [PyTorch installation page](https://pytorch.org/get-started/locally/#start-locally) and/or [Flax](https://github.com/google/flax#quick-install) and [Jax](https://github.com/google/jax#installation) installation pages regarding the specific installation command for your platform.
+
+When one of those backends has been installed, 🤗 Transformers can be installed using pip as follows:
+
+```bash
+pip install transformers
+```
+
+If you'd like to play with the examples or need the bleeding edge of the code and can't wait for a new release, you must [install the library from source](https://huggingface.co/docs/transformers/installation#installing-from-source).
+
+### With conda
+
+🤗 Transformers can be installed using conda as follows:
+
+```shell script
+conda install conda-forge::transformers
+```
+
+> **_NOTE:_** Installing `transformers` from the `huggingface` channel is deprecated.
+
+Follow the installation pages of Flax, PyTorch or TensorFlow to see how to install them with conda.
+
+> **_NOTE:_** On Windows, you may be prompted to activate Developer Mode in order to benefit from caching. If this is not an option for you, please let us know in [this issue](https://github.com/huggingface/huggingface_hub/issues/1062).
+
+## Model architectures
+
+**[All the model checkpoints](https://huggingface.co/models)** provided by 🤗 Transformers are seamlessly integrated from the huggingface.co [model hub](https://huggingface.co/models), where they are uploaded directly by [users](https://huggingface.co/users) and [organizations](https://huggingface.co/organizations).
+
+Current number of checkpoints: 
+
+🤗 Transformers currently provides the following architectures: see [here](https://huggingface.co/docs/transformers/model_summary) for a high-level summary of each them.
+
+To check if each model has an implementation in Flax, PyTorch or TensorFlow, or has an associated tokenizer backed by the 🤗 Tokenizers library, refer to [this table](https://huggingface.co/docs/transformers/index#supported-frameworks).
+
+These implementations have been tested on several datasets (see the example scripts) and should match the performance of the original implementations. You can find more details on performance in the Examples section of the [documentation](https://github.com/huggingface/transformers/tree/main/examples).
+
+
+## Learn more
+
+| Section | Description |
+|-|-|
+| [Documentation](https://huggingface.co/docs/transformers/) | Full API documentation and tutorials |
+| [Task summary](https://huggingface.co/docs/transformers/task_summary) | Tasks supported by 🤗 Transformers |
+| [Preprocessing tutorial](https://huggingface.co/docs/transformers/preprocessing) | Using the `Tokenizer` class to prepare data for the models |
+| [Training and fine-tuning](https://huggingface.co/docs/transformers/training) | Using the models provided by 🤗 Transformers in a PyTorch/TensorFlow training loop and the `Trainer` API |
+| [Quick tour: Fine-tuning/usage scripts](https://github.com/huggingface/transformers/tree/main/examples) | Example scripts for fine-tuning models on a wide range of tasks |
+| [Model sharing and uploading](https://huggingface.co/docs/transformers/model_sharing) | Upload and share your fine-tuned models with the community |
+
+## Citation
+
+We now have a [paper](https://www.aclweb.org/anthology/2020.emnlp-demos.6/) you can cite for the 🤗 Transformers library:
+```bibtex
+@inproceedings{wolf-etal-2020-transformers,
+ title = "Transformers: State-of-the-Art Natural Language Processing",
+ author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush",
+ booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
+ month = oct,
+ year = "2020",
+ address = "Online",
+ publisher = "Association for Computational Linguistics",
+ url = "https://www.aclweb.org/anthology/2020.emnlp-demos.6",
+ pages = "38--45"
+}
+```
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/SECURITY.md b/tasks/tasksmith-5dd11b34cce1/environment/source/SECURITY.md
new file mode 100644
index 0000000000000000000000000000000000000000..431b17a85042dccdd3062941b0e26099ef38a4b2
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/SECURITY.md
@@ -0,0 +1,39 @@
+# Security Policy
+
+## Hugging Face Hub, remote artefacts, and remote code
+
+Transformers is open-source software that is tightly coupled to the Hugging Face Hub. While you have the ability to use it
+offline with pre-downloaded model weights, it provides a very simple way to download, use, and manage models locally.
+
+When downloading artefacts that have been uploaded by others on any platform, you expose yourself to risks. Please
+read below for the security recommendations in order to keep your runtime and local environment safe.
+
+### Remote artefacts
+
+Models uploaded on the Hugging Face Hub come in different formats. We heavily recommend uploading and downloading
+models in the [`safetensors`](https://github.com/huggingface/safetensors) format (which is the default prioritized
+by the transformers library), as developed specifically to prevent arbitrary code execution on your system.
+
+To avoid loading models from unsafe formats(e.g. [pickle](https://docs.python.org/3/library/pickle.html), you should use the `use_safetensors` parameter. If doing so, in the event that no .safetensors file is present, transformers will error when loading the model.
+
+### Remote code
+
+#### Modeling
+
+Transformers supports many model architectures, but is also the bridge between your Python runtime and models that
+are stored in model repositories on the Hugging Face Hub.
+
+These models require the `trust_remote_code=True` parameter to be set when using them; please **always** verify
+the content of the modeling files when using this argument. We recommend setting a revision in order to ensure you
+protect yourself from updates on the repository.
+
+#### Tools
+
+Through the `Agent` framework, remote tools can be downloaded to be used by the Agent. You're to specify these tools
+yourself, but please keep in mind that their code will be run on your machine if the Agent chooses to run them.
+
+Please inspect the code of the tools before passing them to the Agent to protect your runtime and local setup.
+
+## Reporting a Vulnerability
+
+Feel free to submit vulnerability reports to [security@huggingface.co](mailto:security@huggingface.co), where someone from the HF security team will review and recommend next steps. If reporting a vulnerability specific to open source, please note [Huntr](https://huntr.com) is a vulnerability disclosure program for open source software.
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/awesome-transformers.md b/tasks/tasksmith-5dd11b34cce1/environment/source/awesome-transformers.md
new file mode 100644
index 0000000000000000000000000000000000000000..d55e276841a3b0d532a7b6849d36fb5248d23681
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/awesome-transformers.md
@@ -0,0 +1,609 @@
+# Awesome projects built with Transformers
+
+This page lists awesome projects built on top of Transformers. Transformers is more than a toolkit to use pretrained
+models: it's a community of projects built around it and the Hugging Face Hub. We want Transformers to enable
+developers, researchers, students, professors, engineers, and anyone else to build their dream projects.
+
+In this list, we showcase incredibly impactful and novel projects that have pushed the field forward. We celebrate
+100 of these projects as we reach the milestone of 100k stars as a community; but we're very open to pull requests
+adding other projects to the list. If you believe a project should be here and it's not, then please, open a PR
+to add it.
+
+## [gpt4all](https://github.com/nomic-ai/gpt4all)
+
+[gpt4all](https://github.com/nomic-ai/gpt4all) is an ecosystem of open-source chatbots trained on massive collections of clean assistant data including code, stories and dialogue. It offers open-source, large language models such as LLaMA and GPT-J trained in an assistant-style.
+
+Keywords: Open-source, LLaMa, GPT-J, instruction, assistant
+
+## [recommenders](https://github.com/microsoft/recommenders)
+
+This repository contains examples and best practices for building recommendation systems, provided as Jupyter notebooks. It goes over several aspects required to build efficient recommendation systems: data preparation, modeling, evaluation, model selection & optimization, as well as operationalization
+
+Keywords: Recommender systems, AzureML
+
+## [IOPaint](https://github.com/Sanster/IOPaint)
+
+Image inpainting tool powered by Stable Diffusion. Remove any unwanted object, defect, people from your pictures or erase and replace anything on your pictures.
+
+Keywords: inpainting, SD, Stable Diffusion
+
+## [flair](https://github.com/flairNLP/flair)
+
+FLAIR is a powerful PyTorch NLP framework, convering several important tasks: NER, sentiment-analysis, part-of-speech tagging, text and document embeddings, among other things.
+
+Keywords: NLP, text embedding, document embedding, biomedical, NER, PoS, sentiment-analysis
+
+## [mindsdb](https://github.com/mindsdb/mindsdb)
+
+MindsDB is a low-code ML platform, which automates and integrates several ML frameworks into the data stack as "AI Tables" to streamline the integration of AI into applications, making it accessible to developers of all skill levels.
+
+Keywords: Database, low-code, AI table
+
+## [langchain](https://github.com/hwchase17/langchain)
+
+[langchain](https://github.com/hwchase17/langchain) is aimed at assisting in the development of apps merging both LLMs and other sources of knowledge. The library allows chaining calls to applications, creating a sequence across many tools.
+
+Keywords: LLMs, Large Language Models, Agents, Chains
+
+## [LlamaIndex](https://github.com/jerryjliu/llama_index)
+
+[LlamaIndex](https://github.com/jerryjliu/llama_index) is a project that provides a central interface to connect your LLM's with external data. It provides various kinds of indices and retreival mechanisms to perform different LLM tasks and obtain knowledge-augmented results.
+
+Keywords: LLMs, Large Language Models, Data Retrieval, Indices, Knowledge Augmentation
+
+## [ParlAI](https://github.com/facebookresearch/ParlAI)
+
+[ParlAI](https://github.com/facebookresearch/ParlAI) is a python framework for sharing, training and testing dialogue models, from open-domain chitchat, to task-oriented dialogue, to visual question answering. It provides more than 100 datasets under the same API, a large zoo of pretrained models, a set of agents, and has several integrations.
+
+Keywords: Dialogue, Chatbots, VQA, Datasets, Agents
+
+## [sentence-transformers](https://github.com/UKPLab/sentence-transformers)
+
+This framework provides an easy method to compute dense vector representations for sentences, paragraphs, and images. The models are based on transformer networks like BERT / RoBERTa / XLM-RoBERTa etc. and achieve state-of-the-art performance in various task. Text is embedding in vector space such that similar text is close and can efficiently be found using cosine similarity.
+
+Keywords: Dense vector representations, Text embeddings, Sentence embeddings
+
+## [ludwig](https://github.com/ludwig-ai/ludwig)
+
+Ludwig is a declarative machine learning framework that makes it easy to define machine learning pipelines using a simple and flexible data-driven configuration system. Ludwig is targeted at a wide variety of AI tasks. It provides a data-driven configuration system, training, prediction, and evaluation scripts, as well as a programmatic API.
+
+Keywords: Declarative, Data-driven, ML Framework
+
+## [InvokeAI](https://github.com/invoke-ai/InvokeAI)
+
+[InvokeAI](https://github.com/invoke-ai/InvokeAI) is an engine for Stable Diffusion models, aimed at professionals, artists, and enthusiasts. It leverages the latest AI-driven technologies through CLI as well as a WebUI.
+
+Keywords: Stable-Diffusion, WebUI, CLI
+
+## [PaddleNLP](https://github.com/PaddlePaddle/PaddleNLP)
+
+[PaddleNLP](https://github.com/PaddlePaddle/PaddleNLP) is an easy-to-use and powerful NLP library particularly targeted at the Chinese languages. It has support for multiple pre-trained model zoos, and supports a wide-range of NLP tasks from research to industrial applications.
+
+Keywords: NLP, Chinese, Research, Industry
+
+## [stanza](https://github.com/stanfordnlp/stanza)
+
+The Stanford NLP Group's official Python NLP library. It contains support for running various accurate natural language processing tools on 60+ languages and for accessing the Java Stanford CoreNLP software from Python.
+
+Keywords: NLP, Multilingual, CoreNLP
+
+## [DeepPavlov](https://github.com/deeppavlov/DeepPavlov)
+
+[DeepPavlov](https://github.com/deeppavlov/DeepPavlov) is an open-source conversational AI library. It is designed for the development of production ready chat-bots and complex conversational systems, as well as research in the area of NLP and, particularly, of dialog systems.
+
+Keywords: Conversational, Chatbot, Dialog
+
+## [alpaca-lora](https://github.com/tloen/alpaca-lora)
+
+Alpaca-lora contains code for reproducing the Stanford Alpaca results using low-rank adaptation (LoRA). The repository provides training (fine-tuning) as well as generation scripts.
+
+Keywords: LoRA, Parameter-efficient fine-tuning
+
+## [imagen-pytorch](https://github.com/lucidrains/imagen-pytorch)
+
+An open-source Implementation of Imagen, Google's closed-source Text-to-Image Neural Network that beats DALL-E2. As of release, it is the new SOTA for text-to-image synthesis.
+
+Keywords: Imagen, Text-to-image
+
+## [adapters](https://github.com/adapter-hub/adapters)
+
+[adapters](https://github.com/adapter-hub/adapters) is an extension of HuggingFace's Transformers library, integrating adapters into state-of-the-art language models by incorporating AdapterHub, a central repository for pre-trained adapter modules. It is a drop-in replacement for transformers, which is regularly updated to stay up-to-date with the developments of transformers.
+
+Keywords: Adapters, LoRA, Parameter-efficient fine-tuning, Hub
+
+## [NeMo](https://github.com/NVIDIA/NeMo)
+
+NVIDIA [NeMo](https://github.com/NVIDIA/NeMo) is a conversational AI toolkit built for researchers working on automatic speech recognition (ASR), text-to-speech synthesis (TTS), large language models (LLMs), and natural language processing (NLP). The primary objective of [NeMo](https://github.com/NVIDIA/NeMo) is to help researchers from industry and academia to reuse prior work (code and pretrained models) and make it easier to create new https://developer.nvidia.com/conversational-ai#started.
+
+Keywords: Conversational, ASR, TTS, LLMs, NLP
+
+## [Runhouse](https://github.com/run-house/runhouse)
+
+[Runhouse](https://github.com/run-house/runhouse) allows to send code and data to any of your compute or data infra, all in Python, and continue to interact with them normally from your existing code and environment. Runhouse developers mention:
+
+> Think of it as an expansion pack to your Python interpreter that lets it take detours to remote machines or manipulate remote data.
+
+Keywords: MLOps, Infrastructure, Data storage, Modeling
+
+## [MONAI](https://github.com/Project-MONAI/MONAI)
+
+[MONAI](https://github.com/Project-MONAI/MONAI) is a PyTorch-based, open-source framework for deep learning in healthcare imaging, part of PyTorch Ecosystem. Its ambitions are:
+- developing a community of academic, industrial and clinical researchers collaborating on a common foundation;
+- creating state-of-the-art, end-to-end training workflows for healthcare imaging;
+- providing researchers with the optimized and standardized way to create and evaluate deep learning models.
+
+Keywords: Healthcare imaging, Training, Evaluation
+
+## [simpletransformers](https://github.com/ThilinaRajapakse/simpletransformers)
+
+Simple Transformers lets you quickly train and evaluate Transformer models. Only 3 lines of code are needed to initialize, train, and evaluate a model. It supports a wide variety of NLP tasks.
+
+Keywords: Framework, simplicity, NLP
+
+## [JARVIS](https://github.com/microsoft/JARVIS)
+
+[JARVIS](https://github.com/microsoft/JARVIS) is a system attempting to merge LLMs such as GPT-4 with the rest of the open-source ML community: leveraging up to 60 downstream models in order to perform tasks identified by the LLM.
+
+Keywords: LLM, Agents, HF Hub
+
+## [transformers.js](https://xenova.github.io/transformers.js/)
+
+[transformers.js](https://xenova.github.io/transformers.js/) is a JavaScript library targeted at running models from transformers directly within the browser.
+
+Keywords: Transformers, JavaScript, browser
+
+## [bumblebee](https://github.com/elixir-nx/bumblebee)
+
+Bumblebee provides pre-trained Neural Network models on top of Axon, a neural networks library for the Elixir language. It includes integration with 🤗 Models, allowing anyone to download and perform Machine Learning tasks with few lines of code.
+
+Keywords: Elixir, Axon
+
+## [argilla](https://github.com/argilla-io/argilla)
+
+Argilla is an open-source platform providing advanced NLP labeling, monitoring, and workspaces. It is compatible with many open source ecosystems such as Hugging Face, Stanza, FLAIR, and others.
+
+Keywords: NLP, Labeling, Monitoring, Workspaces
+
+## [haystack](https://github.com/deepset-ai/haystack)
+
+Haystack is an open source NLP framework to interact with your data using Transformer models and LLMs. It offers production-ready tools to quickly build complex decision making, question answering, semantic search, text generation applications, and more.
+
+Keywords: NLP, Framework, LLM
+
+## [spaCy](https://github.com/explosion/spaCy)
+
+[spaCy](https://github.com/explosion/spaCy) is a library for advanced Natural Language Processing in Python and Cython. It's built on the very latest research, and was designed from day one to be used in real products. It offers support for transformers models through its third party package, spacy-transformers.
+
+Keywords: NLP, Framework
+
+## [speechbrain](https://github.com/speechbrain/speechbrain)
+
+SpeechBrain is an open-source and all-in-one conversational AI toolkit based on PyTorch.
+The goal is to create a single, flexible, and user-friendly toolkit that can be used to easily develop state-of-the-art speech technologies, including systems for speech recognition, speaker recognition, speech enhancement, speech separation, language identification, multi-microphone signal processing, and many others.
+
+Keywords: Conversational, Speech
+
+## [skorch](https://github.com/skorch-dev/skorch)
+
+Skorch is a scikit-learn compatible neural network library that wraps PyTorch. It has support for models within transformers, and tokenizers from tokenizers.
+
+Keywords: Scikit-Learn, PyTorch
+
+## [bertviz](https://github.com/jessevig/bertviz)
+
+BertViz is an interactive tool for visualizing attention in Transformer language models such as BERT, GPT2, or T5. It can be run inside a Jupyter or Colab notebook through a simple Python API that supports most Huggingface models.
+
+Keywords: Visualization, Transformers
+
+## [mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax)
+
+[mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax) is a haiku library using the xmap/pjit operators in JAX for model parallelism of transformers. This library is designed for scalability up to approximately 40B parameters on TPUv3s. It was the library used to train the GPT-J model.
+
+Keywords: Haiku, Model parallelism, LLM, TPU
+
+## [deepchem](https://github.com/deepchem/deepchem)
+
+DeepChem aims to provide a high quality open-source toolchain that democratizes the use of deep-learning in drug discovery, materials science, quantum chemistry, and biology.
+
+Keywords: Drug discovery, Materials Science, Quantum Chemistry, Biology
+
+## [OpenNRE](https://github.com/thunlp/OpenNRE)
+
+An Open-Source Package for Neural Relation Extraction (NRE). It is targeted at a wide range of users, from newcomers to relation extraction, to developers, researchers, or students.
+
+Keywords: Neural Relation Extraction, Framework
+
+## [pycorrector](https://github.com/shibing624/pycorrector)
+
+PyCorrector is a Chinese Text Error Correction Tool. It uses a language model to detect errors, pinyin feature and shape feature to correct Chinese text errors. it can be used for Chinese Pinyin and stroke input method.
+
+Keywords: Chinese, Error correction tool, Language model, Pinyin
+
+## [nlpaug](https://github.com/makcedward/nlpaug)
+
+This python library helps you with augmenting nlp for machine learning projects. It is a lightweight library featuring synthetic data generation for improving model performance, support for audio and text, and compatibility with several ecosystems (scikit-learn, pytorch, tensorflow).
+
+Keywords: Data augmentation, Synthetic data generation, Audio, NLP
+
+## [dream-textures](https://github.com/carson-katri/dream-textures)
+
+[dream-textures](https://github.com/carson-katri/dream-textures) is a library targeted at bringing stable-diffusion support within Blender. It supports several use-cases, such as image generation, texture projection, inpainting/outpainting, ControlNet, and upscaling.
+
+Keywords: Stable-Diffusion, Blender
+
+## [seldon-core](https://github.com/SeldonIO/seldon-core)
+
+Seldon core converts your ML models (Tensorflow, Pytorch, H2o, etc.) or language wrappers (Python, Java, etc.) into production REST/GRPC microservices.
+Seldon handles scaling to thousands of production machine learning models and provides advanced machine learning capabilities out of the box including Advanced Metrics, Request Logging, Explainers, Outlier Detectors, A/B Tests, Canaries and more.
+
+Keywords: Microservices, Modeling, Language wrappers
+
+## [open_model_zoo](https://github.com/openvinotoolkit/open_model_zoo)
+
+This repository includes optimized deep learning models and a set of demos to expedite development of high-performance deep learning inference applications. Use these free pre-trained models instead of training your own models to speed-up the development and production deployment process.
+
+Keywords: Optimized models, Demos
+
+## [ml-stable-diffusion](https://github.com/apple/ml-stable-diffusion)
+
+ML-Stable-Diffusion is a repository by Apple bringing Stable Diffusion support to Core ML, on Apple Silicon devices. It supports stable diffusion checkpoints hosted on the Hugging Face Hub.
+
+Keywords: Stable Diffusion, Apple Silicon, Core ML
+
+## [stable-dreamfusion](https://github.com/ashawkey/stable-dreamfusion)
+
+Stable-Dreamfusion is a pytorch implementation of the text-to-3D model Dreamfusion, powered by the Stable Diffusion text-to-2D model.
+
+Keywords: Text-to-3D, Stable Diffusion
+
+## [txtai](https://github.com/neuml/txtai)
+
+[txtai](https://github.com/neuml/txtai) is an open-source platform for semantic search and workflows powered by language models. txtai builds embeddings databases, which are a union of vector indexes and relational databases enabling similarity search with SQL. Semantic workflows connect language models together into unified applications.
+
+Keywords: Semantic search, LLM
+
+## [djl](https://github.com/deepjavalibrary/djl)
+
+Deep Java Library (DJL) is an open-source, high-level, engine-agnostic Java framework for deep learning. DJL is designed to be easy to get started with and simple to use for developers. DJL provides a native Java development experience and functions like any other regular Java library. DJL offers [a Java binding](https://github.com/deepjavalibrary/djl/tree/master/extensions/tokenizers) for HuggingFace Tokenizers and easy conversion toolkit for HuggingFace model to deploy in Java.
+
+Keywords: Java, Framework
+
+## [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness/)
+
+This project provides a unified framework to test generative language models on a large number of different evaluation tasks. It has support for more than 200 tasks, and supports different ecosystems: HF Transformers, GPT-NeoX, DeepSpeed, as well as the OpenAI API.
+
+Keywords: LLM, Evaluation, Few-shot
+
+## [gpt-neox](https://github.com/EleutherAI/gpt-neox)
+
+This repository records EleutherAI's library for training large-scale language models on GPUs. The framework is based on NVIDIA's Megatron Language Model and has been augmented with techniques from DeepSpeed as well as some novel optimizations. It is focused on training multi-billion-parameter models.
+
+Keywords: Training, LLM, Megatron, DeepSpeed
+
+## [muzic](https://github.com/microsoft/muzic)
+
+Muzic is a research project on AI music that empowers music understanding and generation with deep learning and artificial intelligence. Muzic was created by researchers from Microsoft Research Asia.
+
+Keywords: Music understanding, Music generation
+
+## [dalle-flow](https://github.com/jina-ai/dalle-flow)
+
+DALL·E Flow is an interactive workflow for generating high-definition images from a text prompt. Itt leverages DALL·E-Mega, GLID-3 XL, and Stable Diffusion to generate image candidates, and then calls CLIP-as-service to rank the candidates w.r.t. the prompt.
+The preferred candidate is fed to GLID-3 XL for diffusion, which often enriches the texture and background. Finally, the candidate is upscaled to 1024x1024 via SwinIR.
+
+Keywords: High-definition image generation, Stable Diffusion, DALL-E Mega, GLID-3 XL, CLIP, SwinIR
+
+## [lightseq](https://github.com/bytedance/lightseq)
+
+LightSeq is a high performance training and inference library for sequence processing and generation implemented in CUDA. It enables highly efficient computation of modern NLP and CV models such as BERT, GPT, Transformer, etc. It is therefore best useful for machine translation, text generation, image classification, and other sequence related tasks.
+
+Keywords: Training, Inference, Sequence Processing, Sequence Generation
+
+## [LaTeX-OCR](https://github.com/lukas-blecher/LaTeX-OCR)
+
+The goal of this project is to create a learning based system that takes an image of a math formula and returns corresponding LaTeX code.
+
+Keywords: OCR, LaTeX, Math formula
+
+## [open_clip](https://github.com/mlfoundations/open_clip)
+
+OpenCLIP is an open source implementation of OpenAI's CLIP.
+
+The goal of this repository is to enable training models with contrastive image-text supervision, and to investigate their properties such as robustness to distribution shift.
+The starting point is an implementation of CLIP that matches the accuracy of the original CLIP models when trained on the same dataset.
+
+Specifically, a ResNet-50 model trained with this codebase on OpenAI's 15 million image subset of YFCC achieves 32.7% top-1 accuracy on ImageNet.
+
+Keywords: CLIP, Open-source, Contrastive, Image-text
+
+## [dalle-playground](https://github.com/saharmor/dalle-playground)
+
+A playground to generate images from any text prompt using Stable Diffusion and Dall-E mini.
+
+Keywords: WebUI, Stable Diffusion, Dall-E mini
+
+## [FedML](https://github.com/FedML-AI/FedML)
+
+[FedML](https://github.com/FedML-AI/FedML) is a federated learning and analytics library enabling secure and collaborative machine learning on decentralized data anywhere at any scale.
+
+It supports large-scale cross-silo federated learning, and cross-device federated learning on smartphones/IoTs, and research simulation.
+
+Keywords: Federated Learning, Analytics, Collaborative ML, Decentralized
+
+## [gpt-code-clippy](https://github.com/CodedotAl/gpt-code-clippy)
+
+GPT-Code-Clippy (GPT-CC) is an open source version of GitHub Copilot, a language model -- based on GPT-3, called GPT-Codex -- that is fine-tuned on publicly available code from GitHub.
+
+Keywords: LLM, Code
+
+## [TextAttack](https://github.com/QData/TextAttack)
+
+[TextAttack](https://github.com/QData/TextAttack) 🐙 is a Python framework for adversarial attacks, data augmentation, and model training in NLP.
+
+Keywords: Adversarial attacks, Data augmentation, NLP
+
+## [OpenPrompt](https://github.com/thunlp/OpenPrompt)
+
+Prompt-learning is a paradigm to adapt pre-trained language models (PLMs) to downstream NLP tasks, which modify the input text with a textual template and directly uses PLMs to conduct pre-trained tasks. This library provides a standard, flexible and extensible framework to deploy the prompt-learning pipeline. [OpenPrompt](https://github.com/thunlp/OpenPrompt) supports loading PLMs directly from https://github.com/huggingface/transformers.
+
+## [text-generation-webui](https://github.com/oobabooga/text-generation-webui/)
+
+[text-generation-webui](https://github.com/oobabooga/text-generation-webui/) is a Gradio Web UI for running Large Language Models like LLaMA, llama.cpp, GPT-J, Pythia, OPT, and GALACTICA.
+
+Keywords: LLM, WebUI
+
+## [libra](https://github.com/Palashio/libra)
+
+An ergonomic machine learning [libra](https://github.com/Palashio/libra)ry for non-technical users. It focuses on ergonomics and on ensuring that training a model is as simple as it can be.
+
+Keywords: Ergonomic, Non-technical
+
+## [alibi](https://github.com/SeldonIO/alibi)
+
+Alibi is an open source Python library aimed at machine learning model inspection and interpretation. The focus of the library is to provide high-quality implementations of black-box, white-box, local and global explanation methods for classification and regression models.
+
+Keywords: Model inspection, Model interpretation, Black-box, White-box
+
+## [tortoise-tts](https://github.com/neonbjb/tortoise-tts)
+
+Tortoise is a text-to-speech program built with the following priorities: strong multi-voice capabilities, and highly realistic prosody and intonation.
+
+Keywords: Text-to-speech
+
+## [flower](https://github.com/adap/flower)
+
+Flower (flwr) is a framework for building federated learning systems. The design of Flower is based on a few guiding principles: customizability, extendability, framework agnosticity, and ease-of-use.
+
+Keywords: Federated learning systems, Customizable, Extendable, Framework-agnostic, Simplicity
+
+## [fast-bert](https://github.com/utterworks/fast-bert)
+
+Fast-Bert is a deep learning library that allows developers and data scientists to train and deploy BERT and XLNet based models for natural language processing tasks beginning with Text Classification. It is aimed at simplicity.
+
+Keywords: Deployment, BERT, XLNet
+
+## [towhee](https://github.com/towhee-io/towhee)
+
+Towhee makes it easy to build neural data processing pipelines for AI applications. We provide hundreds of models, algorithms, and transformations that can be used as standard pipeline building blocks. Users can use Towhee's Pythonic API to build a prototype of their pipeline and automatically optimize it for production-ready environments.
+
+Keywords: Data processing pipeline, Optimization
+
+## [alibi-detect](https://github.com/SeldonIO/alibi-detect)
+
+Alibi Detect is an open source Python library focused on outlier, adversarial and drift detection. The package aims to cover both online and offline detectors for tabular data, text, images and time series. Both TensorFlow and PyTorch backends are supported for drift detection.
+
+Keywords: Adversarial, Outlier, Drift detection
+
+## [FARM](https://github.com/deepset-ai/FARM)
+
+[FARM](https://github.com/deepset-ai/FARM) makes Transfer Learning with BERT & Co simple, fast and enterprise-ready. It's built upon transformers and provides additional features to simplify the life of developers: Parallelized preprocessing, highly modular design, multi-task learning, experiment tracking, easy debugging and close integration with AWS SageMaker.
+
+Keywords: Transfer Learning, Modular design, Multi-task learning, Experiment tracking
+
+## [aitextgen](https://github.com/minimaxir/aitextgen)
+
+A robust Python tool for text-based AI training and generation using OpenAI's GPT-2 and EleutherAI's GPT Neo/GPT-3 architecture.
+[aitextgen](https://github.com/minimaxir/aitextgen) is a Python package that leverages PyTorch, Hugging Face Transformers and pytorch-lightning with specific optimizations for text generation using GPT-2, plus many added features.
+
+Keywords: Training, Generation
+
+## [diffgram](https://github.com/diffgram/diffgram)
+
+Diffgram aims to integrate human supervision into platforms. We support your team programmatically changing the UI (Schema, layout, etc.) like in Streamlit. This means that you can collect and annotate timely data from users. In other words, we are the platform behind your platform, an integrated part of your application, to ship new & better AI products faster.
+
+Keywords: Human supervision, Platform
+
+## [ecco](https://github.com/jalammar/ecco)
+
+Explain, analyze, and visualize NLP language models. Ecco creates interactive visualizations directly in Jupyter notebooks explaining the behavior of Transformer-based language models (like GPT2, BERT, RoBERTA, T5, and T0).
+
+Keywords: Model explainability
+
+## [s3prl](https://github.com/s3prl/s3prl)
+
+[s3prl](https://github.com/s3prl/s3prl) stands for Self-Supervised Speech Pre-training and Representation Learning. Self-supervised speech pre-trained models are called upstream in this toolkit, and are utilized in various downstream tasks.
+
+Keywords: Speech, Training
+
+## [ru-dalle](https://github.com/ai-forever/ru-dalle)
+
+RuDALL-E aims to be similar to DALL-E, targeted to Russian.
+
+Keywords: DALL-E, Russian
+
+## [DeepKE](https://github.com/zjunlp/DeepKE)
+
+[DeepKE](https://github.com/zjunlp/DeepKE) is a knowledge extraction toolkit for knowledge graph construction supporting cnSchema,low-resource, document-level and multimodal scenarios for entity, relation and attribute extraction.
+
+Keywords: Knowledge Extraction, Knowledge Graphs
+
+## [Nebuly](https://github.com/nebuly-ai/nebuly)
+
+Nebuly is the next-generation platform to monitor and optimize your AI costs in one place. The platform connects to all your AI cost sources (compute, API providers, AI software licenses, etc) and centralizes them in one place to give you full visibility on a model basis. The platform also provides optimization recommendations and a co-pilot model that can guide during the optimization process. The platform builds on top of the open-source tools allowing you to optimize the different steps of your AI stack to squeeze out the best possible cost performances.
+
+Keywords: Optimization, Performance, Monitoring
+
+## [imaginAIry](https://github.com/brycedrennan/imaginAIry)
+
+Offers a CLI and a Python API to generate images with Stable Diffusion. It has support for many tools, like image structure control (controlnet), instruction-based image edits (InstructPix2Pix), prompt-based masking (clipseg), among others.
+
+Keywords: Stable Diffusion, CLI, Python API
+
+## [sparseml](https://github.com/neuralmagic/sparseml)
+
+SparseML is an open-source model optimization toolkit that enables you to create inference-optimized sparse models using pruning, quantization, and distillation algorithms. Models optimized with SparseML can then be exported to the ONNX and deployed with DeepSparse for GPU-class performance on CPU hardware.
+
+Keywords: Model optimization, Pruning, Quantization, Distillation
+
+## [opacus](https://github.com/pytorch/opacus)
+
+Opacus is a library that enables training PyTorch models with differential privacy. It supports training with minimal code changes required on the client, has little impact on training performance, and allows the client to online track the privacy budget expended at any given moment.
+
+Keywords: Differential privacy
+
+## [LAVIS](https://github.com/salesforce/LAVIS)
+
+[LAVIS](https://github.com/salesforce/LAVIS) is a Python deep learning library for LAnguage-and-VISion intelligence research and applications. This library aims to provide engineers and researchers with a one-stop solution to rapidly develop models for their specific multimodal scenarios, and benchmark them across standard and customized datasets. It features a unified interface design to access
+
+Keywords: Multimodal, NLP, Vision
+
+## [buzz](https://github.com/chidiwilliams/buzz)
+
+Buzz transcribes and translates audio offline on your personal computer. Powered by OpenAI's Whisper.
+
+Keywords: Audio transcription, Translation
+
+## [rust-bert](https://github.com/guillaume-be/rust-bert)
+
+Rust-native state-of-the-art Natural Language Processing models and pipelines. Port of Hugging Face's Transformers library, using the tch-rs crate and pre-processing from rust-tokenizers. Supports multi-threaded tokenization and GPU inference. This repository exposes the model base architecture, task-specific heads and ready-to-use pipelines.
+
+Keywords: Rust, BERT, Inference
+
+## [EasyNLP](https://github.com/alibaba/EasyNLP)
+
+[EasyNLP](https://github.com/alibaba/EasyNLP) is an easy-to-use NLP development and application toolkit in PyTorch, first released inside Alibaba in 2021. It is built with scalable distributed training strategies and supports a comprehensive suite of NLP algorithms for various NLP applications. [EasyNLP](https://github.com/alibaba/EasyNLP) integrates knowledge distillation and few-shot learning for landing large pre-trained models, together with various popular multi-modality pre-trained models. It provides a unified framework of model training, inference, and deployment for real-world applications.
+
+Keywords: NLP, Knowledge distillation, Few-shot learning, Multi-modality, Training, Inference, Deployment
+
+## [TurboTransformers](https://github.com/Tencent/TurboTransformers)
+
+A fast and user-friendly runtime for transformer inference (Bert, Albert, GPT2, Decoders, etc) on CPU and GPU.
+
+Keywords: Optimization, Performance
+
+## [hivemind](https://github.com/learning-at-home/hivemind)
+
+Hivemind is a PyTorch library for decentralized deep learning across the Internet. Its intended usage is training one large model on hundreds of computers from different universities, companies, and volunteers.
+
+Keywords: Decentralized training
+
+## [docquery](https://github.com/impira/docquery)
+
+DocQuery is a library and command-line tool that makes it easy to analyze semi-structured and unstructured documents (PDFs, scanned images, etc.) using large language models (LLMs). You simply point DocQuery at one or more documents and specify a question you want to ask. DocQuery is created by the team at Impira.
+
+Keywords: Semi-structured documents, Unstructured documents, LLM, Document Question Answering
+
+## [CodeGeeX](https://github.com/THUDM/CodeGeeX)
+
+[CodeGeeX](https://github.com/THUDM/CodeGeeX) is a large-scale multilingual code generation model with 13 billion parameters, pre-trained on a large code corpus of more than 20 programming languages. It has several unique features:
+- Multilingual code generation
+- Crosslingual code translation
+- Is a customizable programming assistant
+
+Keywords: Code Generation Model
+
+## [ktrain](https://github.com/amaiya/ktrain)
+
+[ktrain](https://github.com/amaiya/ktrain) is a lightweight wrapper for the deep learning library TensorFlow Keras (and other libraries) to help build, train, and deploy neural networks and other machine learning models. Inspired by ML framework extensions like fastai and ludwig, [ktrain](https://github.com/amaiya/ktrain) is designed to make deep learning and AI more accessible and easier to apply for both newcomers and experienced practitioners.
+
+Keywords: Keras wrapper, Model building, Training, Deployment
+
+## [FastDeploy](https://github.com/PaddlePaddle/FastDeploy)
+
+[FastDeploy](https://github.com/PaddlePaddle/FastDeploy) is an Easy-to-use and High Performance AI model deployment toolkit for Cloud, Mobile and Edge with packageout-of-the-box and unified experience, endend-to-end optimization for over fire160+ Text, Vision, Speech and Cross-modal AI models. Including image classification, object detection, OCR, face detection, matting, pp-tracking, NLP, stable diffusion, TTS and other tasks to meet developers' industrial deployment needs for multi-scenario, multi-hardware and multi-platform.
+
+Keywords: Model deployment, CLoud, Mobile, Edge
+
+## [underthesea](https://github.com/undertheseanlp/underthesea)
+
+[underthesea](https://github.com/undertheseanlp/underthesea) is a Vietnamese NLP toolkit. Underthesea is a suite of open source Python modules data sets and tutorials supporting research and development in Vietnamese Natural Language Processing. We provides extremely easy API to quickly apply pretrained NLP models to your Vietnamese text, such as word segmentation, part-of-speech tagging (PoS), named entity recognition (NER), text classification and dependency parsing.
+
+Keywords: Vietnamese, NLP
+
+## [hasktorch](https://github.com/hasktorch/hasktorch)
+
+Hasktorch is a library for tensors and neural networks in Haskell. It is an independent open source community project which leverages the core C++ libraries shared by PyTorch.
+
+Keywords: Haskell, Neural Networks
+
+## [donut](https://github.com/clovaai/donut)
+
+Donut, or Document understanding transformer, is a new method of document understanding that utilizes an OCR-free end-to-end Transformer model.
+
+Donut does not require off-the-shelf OCR engines/APIs, yet it shows state-of-the-art performances on various visual document understanding tasks, such as visual document classification or information extraction (a.k.a. document parsing).
+
+Keywords: Document Understanding
+
+## [transformers-interpret](https://github.com/cdpierse/transformers-interpret)
+
+Transformers Interpret is a model explainability tool designed to work exclusively with the transformers package.
+
+In line with the philosophy of the Transformers package Transformers Interpret allows any transformers model to be explained in just two lines. Explainers are available for both text and computer vision models. Visualizations are also available in notebooks and as savable png and html files
+
+Keywords: Model interpretation, Visualization
+
+## [mlrun](https://github.com/mlrun/mlrun)
+
+MLRun is an open MLOps platform for quickly building and managing continuous ML applications across their lifecycle. MLRun integrates into your development and CI/CD environment and automates the delivery of production data, ML pipelines, and online applications, significantly reducing engineering efforts, time to production, and computation resources. With MLRun, you can choose any IDE on your local machine or on the cloud. MLRun breaks the silos between data, ML, software, and DevOps/MLOps teams, enabling collaboration and fast continuous improvements.
+
+Keywords: MLOps
+
+## [FederatedScope](https://github.com/alibaba/FederatedScope)
+
+[FederatedScope](https://github.com/alibaba/FederatedScope) is a comprehensive federated learning platform that provides convenient usage and flexible customization for various federated learning tasks in both academia and industry. Based on an event-driven architecture, [FederatedScope](https://github.com/alibaba/FederatedScope) integrates rich collections of functionalities to satisfy the burgeoning demands from federated learning, and aims to build up an easy-to-use platform for promoting learning safely and effectively.
+
+Keywords: Federated learning, Event-driven
+
+## [pythainlp](https://github.com/PyThaiNLP/pythainlp)
+
+PyThaiNLP is a Python package for text processing and linguistic analysis, similar to NLTK with focus on Thai language.
+
+Keywords: Thai, NLP, NLTK
+
+## [FlagAI](https://github.com/FlagAI-Open/FlagAI)
+
+[FlagAI](https://github.com/FlagAI-Open/FlagAI) (Fast LArge-scale General AI models) is a fast, easy-to-use and extensible toolkit for large-scale model. Our goal is to support training, fine-tuning, and deployment of large-scale models on various downstream tasks with multi-modality.
+
+Keywords: Large models, Training, Fine-tuning, Deployment, Multi-modal
+
+## [pyserini](https://github.com/castorini/pyserini)
+
+[pyserini](https://github.com/castorini/pyserini) is a Python toolkit for reproducible information retrieval research with sparse and dense representations. Retrieval using sparse representations is provided via integration with the group's Anserini IR toolkit. Retrieval using dense representations is provided via integration with Facebook's Faiss library.
+
+Keywords: IR, Information Retrieval, Dense, Sparse
+
+## [baal](https://github.com/baal-org/baal)
+
+[baal](https://github.com/baal-org/baal) is an active learning library that supports both industrial applications and research usecases. [baal](https://github.com/baal-org/baal) currently supports Monte-Carlo Dropout, MCDropConnect, deep ensembles, and semi-supervised learning.
+
+Keywords: Active Learning, Research, Labeling
+
+## [cleanlab](https://github.com/cleanlab/cleanlab)
+
+[cleanlab](https://github.com/cleanlab/cleanlab) is the standard data-centric AI package for data quality and machine learning with messy, real-world data and labels. For text, image, tabular, audio (among others) datasets, you can use cleanlab to automatically: detect data issues (outliers, label errors, near duplicates, etc), train robust ML models, infer consensus + annotator-quality for multi-annotator data, suggest data to (re)label next (active learning).
+
+Keywords: Data-Centric AI, Data Quality, Noisy Labels, Outlier Detection, Active Learning
+
+## [BentoML](https://github.com/bentoml/BentoML)
+
+[BentoML](https://github.com/bentoml) is the unified framework for building, shipping, and scaling production-ready AI applications incorporating traditional ML, pre-trained AI models, Generative and Large Language Models.
+All Hugging Face models and pipelines can be seamlessly integrated into BentoML applications, enabling the running of models on the most suitable hardware and independent scaling based on usage.
+
+Keywords: BentoML, Framework, Deployment, AI Applications
+
+## [LLaMA Factory](https://github.com/hiyouga/LLaMA-Factory)
+
+[LLaMA Factory](https://github.com/hiyouga/LLaMA-Factory) offers a user-friendly fine-tuning framework that incorporates PEFT. The repository includes training(fine-tuning) and inference examples for LLaMA-2, BLOOM, Falcon, Baichuan, Qwen, and other LLMs. A ChatGLM version is also available in [ChatGLM-Efficient-Tuning](https://github.com/hiyouga/ChatGLM-Efficient-Tuning).
+
+Keywords: PEFT, fine-tuning, LLaMA-2, ChatGLM, Qwen
+
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/conftest.py b/tasks/tasksmith-5dd11b34cce1/environment/source/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..40e43f25e8933d6ab59ab15f9d40fdcc9f507328
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/conftest.py
@@ -0,0 +1,142 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# tests directory-specific settings - this file is run automatically
+# by pytest before any tests are run
+
+import doctest
+import sys
+import warnings
+from os.path import abspath, dirname, join
+
+import _pytest
+import pytest
+
+from transformers.testing_utils import HfDoctestModule, HfDocTestParser
+
+
+NOT_DEVICE_TESTS = {
+ "test_tokenization",
+ "test_processor",
+ "test_processing",
+ "test_beam_constraints",
+ "test_configuration_utils",
+ "test_data_collator",
+ "test_trainer_callback",
+ "test_trainer_utils",
+ "test_feature_extraction",
+ "test_image_processing",
+ "test_image_processor",
+ "test_image_transforms",
+ "test_optimization",
+ "test_retrieval",
+ "test_config",
+ "test_from_pretrained_no_checkpoint",
+ "test_keep_in_fp32_modules",
+ "test_gradient_checkpointing_backward_compatibility",
+ "test_gradient_checkpointing_enable_disable",
+ "test_save_load_fast_init_from_base",
+ "test_fast_init_context_manager",
+ "test_fast_init_tied_embeddings",
+ "test_save_load_fast_init_to_base",
+ "test_torch_save_load",
+ "test_initialization",
+ "test_forward_signature",
+ "test_model_get_set_embeddings",
+ "test_model_main_input_name",
+ "test_correct_missing_keys",
+ "test_tie_model_weights",
+ "test_can_use_safetensors",
+ "test_load_save_without_tied_weights",
+ "test_tied_weights_keys",
+ "test_model_weights_reload_no_missing_tied_weights",
+ "test_pt_tf_model_equivalence",
+ "test_mismatched_shapes_have_properly_initialized_weights",
+ "test_matched_shapes_have_loaded_weights_when_some_mismatched_shapes_exist",
+ "test_model_is_small",
+ "test_tf_from_pt_safetensors",
+ "test_flax_from_pt_safetensors",
+ "ModelTest::test_pipeline_", # None of the pipeline tests from PipelineTesterMixin (of which XxxModelTest inherits from) are running on device
+ "ModelTester::test_pipeline_",
+ "/repo_utils/",
+ "/utils/",
+ "/agents/",
+}
+
+# allow having multiple repository checkouts and not needing to remember to rerun
+# `pip install -e '.[dev]'` when switching between checkouts and running tests.
+git_repo_path = abspath(join(dirname(__file__), "src"))
+sys.path.insert(1, git_repo_path)
+
+# silence FutureWarning warnings in tests since often we can't act on them until
+# they become normal warnings - i.e. the tests still need to test the current functionality
+warnings.simplefilter(action="ignore", category=FutureWarning)
+
+
+def pytest_configure(config):
+ config.addinivalue_line(
+ "markers", "is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested"
+ )
+ config.addinivalue_line(
+ "markers", "is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested"
+ )
+ config.addinivalue_line("markers", "is_pipeline_test: mark test to run only when pipelines are tested")
+ config.addinivalue_line("markers", "is_staging_test: mark test to run only in the staging environment")
+ config.addinivalue_line("markers", "accelerate_tests: mark test that require accelerate")
+ config.addinivalue_line("markers", "agent_tests: mark the agent tests that are run on their specific schedule")
+ config.addinivalue_line("markers", "not_device_test: mark the tests always running on cpu")
+
+
+def pytest_collection_modifyitems(items):
+ for item in items:
+ if any(test_name in item.nodeid for test_name in NOT_DEVICE_TESTS):
+ item.add_marker(pytest.mark.not_device_test)
+
+
+def pytest_addoption(parser):
+ from transformers.testing_utils import pytest_addoption_shared
+
+ pytest_addoption_shared(parser)
+
+
+def pytest_terminal_summary(terminalreporter):
+ from transformers.testing_utils import pytest_terminal_summary_main
+
+ make_reports = terminalreporter.config.getoption("--make-reports")
+ if make_reports:
+ pytest_terminal_summary_main(terminalreporter, id=make_reports)
+
+
+def pytest_sessionfinish(session, exitstatus):
+ # If no tests are collected, pytest exists with code 5, which makes the CI fail.
+ if exitstatus == 5:
+ session.exitstatus = 0
+
+
+# Doctest custom flag to ignore output.
+IGNORE_RESULT = doctest.register_optionflag("IGNORE_RESULT")
+
+OutputChecker = doctest.OutputChecker
+
+
+class CustomOutputChecker(OutputChecker):
+ def check_output(self, want, got, optionflags):
+ if IGNORE_RESULT & optionflags:
+ return True
+ return OutputChecker.check_output(self, want, got, optionflags)
+
+
+doctest.OutputChecker = CustomOutputChecker
+_pytest.doctest.DoctestModule = HfDoctestModule
+doctest.DocTestParser = HfDocTestParser
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/hubconf.py b/tasks/tasksmith-5dd11b34cce1/environment/source/hubconf.py
new file mode 100644
index 0000000000000000000000000000000000000000..412cb27f6380dfb3c2c6119bde21a64fa97c02dc
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/hubconf.py
@@ -0,0 +1,162 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import sys
+
+
+SRC_DIR = os.path.join(os.path.dirname(__file__), "src")
+sys.path.append(SRC_DIR)
+
+
+from transformers import (
+ AutoConfig,
+ AutoModel,
+ AutoModelForCausalLM,
+ AutoModelForMaskedLM,
+ AutoModelForQuestionAnswering,
+ AutoModelForSequenceClassification,
+ AutoTokenizer,
+ add_start_docstrings,
+)
+
+
+dependencies = ["torch", "numpy", "tokenizers", "filelock", "requests", "tqdm", "regex", "sentencepiece", "sacremoses", "importlib_metadata", "huggingface_hub"]
+
+
+@add_start_docstrings(AutoConfig.__doc__)
+def config(*args, **kwargs):
+ r"""
+ # Using torch.hub !
+ import torch
+
+ config = torch.hub.load('huggingface/transformers', 'config', 'google-bert/bert-base-uncased') # Download configuration from huggingface.co and cache.
+ config = torch.hub.load('huggingface/transformers', 'config', './test/bert_saved_model/') # E.g. config (or model) was saved using `save_pretrained('./test/saved_model/')`
+ config = torch.hub.load('huggingface/transformers', 'config', './test/bert_saved_model/my_configuration.json')
+ config = torch.hub.load('huggingface/transformers', 'config', 'google-bert/bert-base-uncased', output_attentions=True, foo=False)
+ assert config.output_attentions == True
+ config, unused_kwargs = torch.hub.load('huggingface/transformers', 'config', 'google-bert/bert-base-uncased', output_attentions=True, foo=False, return_unused_kwargs=True)
+ assert config.output_attentions == True
+ assert unused_kwargs == {'foo': False}
+
+ """
+
+ return AutoConfig.from_pretrained(*args, **kwargs)
+
+
+@add_start_docstrings(AutoTokenizer.__doc__)
+def tokenizer(*args, **kwargs):
+ r"""
+ # Using torch.hub !
+ import torch
+
+ tokenizer = torch.hub.load('huggingface/transformers', 'tokenizer', 'google-bert/bert-base-uncased') # Download vocabulary from huggingface.co and cache.
+ tokenizer = torch.hub.load('huggingface/transformers', 'tokenizer', './test/bert_saved_model/') # E.g. tokenizer was saved using `save_pretrained('./test/saved_model/')`
+
+ """
+
+ return AutoTokenizer.from_pretrained(*args, **kwargs)
+
+
+@add_start_docstrings(AutoModel.__doc__)
+def model(*args, **kwargs):
+ r"""
+ # Using torch.hub !
+ import torch
+
+ model = torch.hub.load('huggingface/transformers', 'model', 'google-bert/bert-base-uncased') # Download model and configuration from huggingface.co and cache.
+ model = torch.hub.load('huggingface/transformers', 'model', './test/bert_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`
+ model = torch.hub.load('huggingface/transformers', 'model', 'google-bert/bert-base-uncased', output_attentions=True) # Update configuration during loading
+ assert model.config.output_attentions == True
+ # Loading from a TF checkpoint file instead of a PyTorch model (slower)
+ config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json')
+ model = torch.hub.load('huggingface/transformers', 'model', './tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
+
+ """
+
+ return AutoModel.from_pretrained(*args, **kwargs)
+
+
+@add_start_docstrings(AutoModelForCausalLM.__doc__)
+def modelForCausalLM(*args, **kwargs):
+ r"""
+ # Using torch.hub !
+ import torch
+
+ model = torch.hub.load('huggingface/transformers', 'modelForCausalLM', 'openai-community/gpt2') # Download model and configuration from huggingface.co and cache.
+ model = torch.hub.load('huggingface/transformers', 'modelForCausalLM', './test/saved_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`
+ model = torch.hub.load('huggingface/transformers', 'modelForCausalLM', 'openai-community/gpt2', output_attentions=True) # Update configuration during loading
+ assert model.config.output_attentions == True
+ # Loading from a TF checkpoint file instead of a PyTorch model (slower)
+ config = AutoConfig.from_pretrained('./tf_model/gpt_tf_model_config.json')
+ model = torch.hub.load('huggingface/transformers', 'modelForCausalLM', './tf_model/gpt_tf_checkpoint.ckpt.index', from_tf=True, config=config)
+
+ """
+ return AutoModelForCausalLM.from_pretrained(*args, **kwargs)
+
+
+@add_start_docstrings(AutoModelForMaskedLM.__doc__)
+def modelForMaskedLM(*args, **kwargs):
+ r"""
+ # Using torch.hub !
+ import torch
+
+ model = torch.hub.load('huggingface/transformers', 'modelForMaskedLM', 'google-bert/bert-base-uncased') # Download model and configuration from huggingface.co and cache.
+ model = torch.hub.load('huggingface/transformers', 'modelForMaskedLM', './test/bert_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`
+ model = torch.hub.load('huggingface/transformers', 'modelForMaskedLM', 'google-bert/bert-base-uncased', output_attentions=True) # Update configuration during loading
+ assert model.config.output_attentions == True
+ # Loading from a TF checkpoint file instead of a PyTorch model (slower)
+ config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json')
+ model = torch.hub.load('huggingface/transformers', 'modelForMaskedLM', './tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
+
+ """
+
+ return AutoModelForMaskedLM.from_pretrained(*args, **kwargs)
+
+
+@add_start_docstrings(AutoModelForSequenceClassification.__doc__)
+def modelForSequenceClassification(*args, **kwargs):
+ r"""
+ # Using torch.hub !
+ import torch
+
+ model = torch.hub.load('huggingface/transformers', 'modelForSequenceClassification', 'google-bert/bert-base-uncased') # Download model and configuration from huggingface.co and cache.
+ model = torch.hub.load('huggingface/transformers', 'modelForSequenceClassification', './test/bert_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`
+ model = torch.hub.load('huggingface/transformers', 'modelForSequenceClassification', 'google-bert/bert-base-uncased', output_attentions=True) # Update configuration during loading
+ assert model.config.output_attentions == True
+ # Loading from a TF checkpoint file instead of a PyTorch model (slower)
+ config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json')
+ model = torch.hub.load('huggingface/transformers', 'modelForSequenceClassification', './tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
+
+ """
+
+ return AutoModelForSequenceClassification.from_pretrained(*args, **kwargs)
+
+
+@add_start_docstrings(AutoModelForQuestionAnswering.__doc__)
+def modelForQuestionAnswering(*args, **kwargs):
+ r"""
+ # Using torch.hub !
+ import torch
+
+ model = torch.hub.load('huggingface/transformers', 'modelForQuestionAnswering', 'google-bert/bert-base-uncased') # Download model and configuration from huggingface.co and cache.
+ model = torch.hub.load('huggingface/transformers', 'modelForQuestionAnswering', './test/bert_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`
+ model = torch.hub.load('huggingface/transformers', 'modelForQuestionAnswering', 'google-bert/bert-base-uncased', output_attentions=True) # Update configuration during loading
+ assert model.config.output_attentions == True
+ # Loading from a TF checkpoint file instead of a PyTorch model (slower)
+ config = AutoConfig.from_pretrained('./tf_model/bert_tf_model_config.json')
+ model = torch.hub.load('huggingface/transformers', 'modelForQuestionAnswering', './tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
+
+ """
+ return AutoModelForQuestionAnswering.from_pretrained(*args, **kwargs)
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/notebooks/README.md b/tasks/tasksmith-5dd11b34cce1/environment/source/notebooks/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..e701ca0a8887deffd9bedcd1e7c86afd490e8120
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/notebooks/README.md
@@ -0,0 +1,154 @@
+
+
+# 🤗 Transformers Notebooks
+
+You can find here a list of the official notebooks provided by Hugging Face.
+
+Also, we would like to list here interesting content created by the community.
+If you wrote some notebook(s) leveraging 🤗 Transformers and would like to be listed here, please open a
+Pull Request so it can be included under the Community notebooks.
+
+
+## Hugging Face's notebooks 🤗
+
+### Documentation notebooks
+
+You can open any page of the documentation as a notebook in Colab (there is a button directly on said pages) but they are also listed here if you need them:
+
+| Notebook | Description | | |
+|:----------|:-------------|:-------------|------:|
+| [Quicktour of the library](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/quicktour.ipynb) | A presentation of the various APIs in Transformers |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/quicktour.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/en/transformers_doc/quicktour.ipynb)|
+| [Summary of the tasks](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb) | How to run the models of the Transformers library task by task |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb)|
+| [Preprocessing data](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb) | How to use a tokenizer to preprocess your data |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb)|
+| [Fine-tuning a pretrained model](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb) | How to use the Trainer to fine-tune a pretrained model |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb)|
+| [Summary of the tokenizers](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb) | The differences between the tokenizers algorithm |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb)|
+| [Multilingual models](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb) | How to use the multilingual models of the library |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb)|
+
+
+### PyTorch Examples
+
+#### Natural Language Processing[[pytorch-nlp]]
+
+| Notebook | Description | | |
+|:----------|:-------------|:-------------|------:|
+| [Train your tokenizer](https://github.com/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb) | How to train and use your very own tokenizer |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)|
+| [Train your language model](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch.ipynb) | How to easily start using transformers |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch.ipynb)|
+| [How to fine-tune a model on text classification](https://github.com/huggingface/notebooks/blob/main/examples/text_classification.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on any GLUE task. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb)|
+| [How to fine-tune a model on language modeling](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on a causal or masked LM task. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)|
+| [How to fine-tune a model on token classification](https://github.com/huggingface/notebooks/blob/main/examples/token_classification.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on a token classification task (NER, PoS). | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)|
+| [How to fine-tune a model on question answering](https://github.com/huggingface/notebooks/blob/main/examples/question_answering.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on SQUAD. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb)|
+| [How to fine-tune a model on multiple choice](https://github.com/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on SWAG. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)|
+| [How to fine-tune a model on translation](https://github.com/huggingface/notebooks/blob/main/examples/translation.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on WMT. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/translation.ipynb)|
+| [How to fine-tune a model on summarization](https://github.com/huggingface/notebooks/blob/main/examples/summarization.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on XSUM. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/summarization.ipynb)|
+| [How to train a language model from scratch](https://github.com/huggingface/blog/blob/main/notebooks/01_how_to_train.ipynb)| Highlight all the steps to effectively train Transformer model on custom data | [](https://colab.research.google.com/github/huggingface/blog/blob/main/notebooks/01_how_to_train.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/blog/blob/main/notebooks/01_how_to_train.ipynb)|
+| [How to generate text](https://github.com/huggingface/blog/blob/main/notebooks/02_how_to_generate.ipynb)| How to use different decoding methods for language generation with transformers | [](https://colab.research.google.com/github/huggingface/blog/blob/main/notebooks/02_how_to_generate.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/blog/blob/main/notebooks/02_how_to_generate.ipynb)|
+| [How to generate text (with constraints)](https://github.com/huggingface/blog/blob/main/notebooks/53_constrained_beam_search.ipynb)| How to guide language generation with user-provided constraints | [](https://colab.research.google.com/github/huggingface/blog/blob/main/notebooks/53_constrained_beam_search.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/blog/blob/main/notebooks/53_constrained_beam_search.ipynb)|
+| [Reformer](https://github.com/huggingface/blog/blob/main/notebooks/03_reformer.ipynb)| How Reformer pushes the limits of language modeling | [](https://colab.research.google.com/github/patrickvonplaten/blog/blob/main/notebooks/03_reformer.ipynb)| [](https://studiolab.sagemaker.aws/import/github/patrickvonplaten/blog/blob/main/notebooks/03_reformer.ipynb)|
+
+#### Computer Vision[[pytorch-cv]]
+
+| Notebook | Description | | |
+|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------:|
+| [How to fine-tune a model on image classification (Torchvision)](https://github.com/huggingface/notebooks/blob/main/examples/image_classification.ipynb) | Show how to preprocess the data using Torchvision and fine-tune any pretrained Vision model on Image Classification | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)|
+| [How to fine-tune a model on image classification (Albumentations)](https://github.com/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb) | Show how to preprocess the data using Albumentations and fine-tune any pretrained Vision model on Image Classification | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb)|
+| [How to fine-tune a model on image classification (Kornia)](https://github.com/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb) | Show how to preprocess the data using Kornia and fine-tune any pretrained Vision model on Image Classification | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb)|
+| [How to perform zero-shot object detection with OWL-ViT](https://github.com/huggingface/notebooks/blob/main/examples/zeroshot_object_detection_with_owlvit.ipynb) | Show how to perform zero-shot object detection on images with text queries | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/zeroshot_object_detection_with_owlvit.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/zeroshot_object_detection_with_owlvit.ipynb)|
+| [How to fine-tune an image captioning model](https://github.com/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb) | Show how to fine-tune BLIP for image captioning on a custom dataset | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb)|
+| [How to build an image similarity system with Transformers](https://github.com/huggingface/notebooks/blob/main/examples/image_similarity.ipynb) | Show how to build an image similarity system | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_similarity.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_similarity.ipynb)|
+| [How to fine-tune a SegFormer model on semantic segmentation](https://github.com/huggingface/notebooks/blob/main/examples/semantic_segmentation.ipynb) | Show how to preprocess the data and fine-tune a pretrained SegFormer model on Semantic Segmentation | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/semantic_segmentation.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/semantic_segmentation.ipynb)|
+| [How to fine-tune a VideoMAE model on video classification](https://github.com/huggingface/notebooks/blob/main/examples/video_classification.ipynb) | Show how to preprocess the data and fine-tune a pretrained VideoMAE model on Video Classification | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/video_classification.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/video_classification.ipynb)|
+
+#### Audio[[pytorch-audio]]
+
+| Notebook | Description | | |
+|:----------|:-------------|:-------------|------:|
+| [How to fine-tune a speech recognition model in English](https://github.com/huggingface/notebooks/blob/main/examples/speech_recognition.ipynb)| Show how to preprocess the data and fine-tune a pretrained Speech model on TIMIT | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/speech_recognition.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/speech_recognition.ipynb)|
+| [How to fine-tune a speech recognition model in any language](https://github.com/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)| Show how to preprocess the data and fine-tune a multi-lingually pretrained speech model on Common Voice | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)|
+| [How to fine-tune a model on audio classification](https://github.com/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)| Show how to preprocess the data and fine-tune a pretrained Speech model on Keyword Spotting | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)|
+
+#### Biological Sequences[[pytorch-bio]]
+
+| Notebook | Description | | |
+|:----------|:----------------------------------------------------------------------------------------|:-------------|------:|
+| [How to fine-tune a pre-trained protein model](https://github.com/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) | See how to tokenize proteins and fine-tune a large pre-trained protein "language" model | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) |
+| [How to generate protein folds](https://github.com/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) | See how to go from protein sequence to a full protein model and PDB file | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) |
+| [How to fine-tune a Nucleotide Transformer model](https://github.com/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) | See how to tokenize DNA and fine-tune a large pre-trained DNA "language" model | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) |
+| [Fine-tune a Nucleotide Transformer model with LoRA](https://github.com/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) | Train even larger DNA models in a memory-efficient way | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) |
+
+
+#### Other modalities[[pytorch-other]]
+
+| Notebook | Description | | |
+|:----------|:----------------------------------------------------------------------------------------|:-------------|------:|
+| [Probabilistic Time Series Forecasting](https://github.com/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) | See how to train Time Series Transformer on a custom dataset | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) |
+
+#### Utility notebooks[[pytorch-utility]]
+
+| Notebook | Description | | |
+|:----------|:-------------|:-------------|------:|
+| [How to export model to ONNX](https://github.com/huggingface/notebooks/blob/main/examples/onnx-export.ipynb)| Highlight how to export and run inference workloads through ONNX | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/onnx-export.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/onnx-export.ipynb)|
+| [How to use Benchmarks](https://github.com/huggingface/notebooks/blob/main/examples/benchmark.ipynb)| How to benchmark models with transformers | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/benchmark.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/benchmark.ipynb)|
+
+### TensorFlow Examples
+
+#### Natural Language Processing[[tensorflow-nlp]]
+
+| Notebook | Description | | |
+|:----------|:-------------|:-------------|------:|
+| [Train your tokenizer](https://github.com/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb) | How to train and use your very own tokenizer |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb)|
+| [Train your language model](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch-tf.ipynb) | How to easily start using transformers |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling_from_scratch-tf.ipynb)|
+| [How to fine-tune a model on text classification](https://github.com/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on any GLUE task. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb)|
+| [How to fine-tune a model on language modeling](https://github.com/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on a causal or masked LM task. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)|
+| [How to fine-tune a model on token classification](https://github.com/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on a token classification task (NER, PoS). | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)|
+| [How to fine-tune a model on question answering](https://github.com/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on SQUAD. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)|
+| [How to fine-tune a model on multiple choice](https://github.com/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on SWAG. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb)|
+| [How to fine-tune a model on translation](https://github.com/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on WMT. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)|
+| [How to fine-tune a model on summarization](https://github.com/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)| Show how to preprocess the data and fine-tune a pretrained model on XSUM. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)|
+
+#### Computer Vision[[tensorflow-cv]]
+
+| Notebook | Description | | |
+|:---------------------------------------------------------------------------------------------------------------------------------------------------------|:----------------------------------------------------------------------------------------------------|:-------------|------:|
+| [How to fine-tune a model on image classification](https://github.com/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb) | Show how to preprocess the data and fine-tune any pretrained Vision model on Image Classification | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb)|
+| [How to fine-tune a SegFormer model on semantic segmentation](https://github.com/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb) | Show how to preprocess the data and fine-tune a pretrained SegFormer model on Semantic Segmentation | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb)|
+
+#### Biological Sequences[[tensorflow-bio]]
+
+| Notebook | Description | | |
+|:----------|:-------------|:-------------|------:|
+| [How to fine-tune a pre-trained protein model](https://github.com/huggingface/notebooks/blob/main/examples/protein_language_modeling-tf.ipynb) | See how to tokenize proteins and fine-tune a large pre-trained protein "language" model | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_language_modeling-tf.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/protein_language_modeling-tf.ipynb) |
+
+#### Utility notebooks[[tensorflow-utility]]
+
+| Notebook | Description | | |
+|:----------|:-------------|:-------------|------:|
+| [How to train TF/Keras models on TPU](https://github.com/huggingface/notebooks/blob/main/examples/tpu_training-tf.ipynb) | See how to train at high speed on Google's TPU hardware | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/tpu_training-tf.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/tpu_training-tf.ipynb) |
+
+### Optimum notebooks
+
+🤗 [Optimum](https://github.com/huggingface/optimum) is an extension of 🤗 Transformers, providing a set of performance optimization tools enabling maximum efficiency to train and run models on targeted hardwares.
+
+| Notebook | Description | | |
+|:----------|:-------------|:-------------|------:|
+| [How to quantize a model with ONNX Runtime for text classification](https://github.com/huggingface/notebooks/blob/main/examples/text_classification_quantization_ort.ipynb)| Show how to apply static and dynamic quantization on a model using [ONNX Runtime](https://github.com/microsoft/onnxruntime) for any GLUE task. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_quantization_ort.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification_quantization_ort.ipynb)|
+| [How to quantize a model with Intel Neural Compressor for text classification](https://github.com/huggingface/notebooks/blob/main/examples/text_classification_quantization_inc.ipynb)| Show how to apply static, dynamic and aware training quantization on a model using [Intel Neural Compressor (INC)](https://github.com/intel/neural-compressor) for any GLUE task. | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_quantization_inc.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification_quantization_inc.ipynb)|
+| [How to fine-tune a model on text classification with ONNX Runtime](https://github.com/huggingface/notebooks/blob/main/examples/text_classification_ort.ipynb)| Show how to preprocess the data and fine-tune a model on any GLUE task using [ONNX Runtime](https://github.com/microsoft/onnxruntime). | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_ort.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/text_classification_ort.ipynb)|
+| [How to fine-tune a model on summarization with ONNX Runtime](https://github.com/huggingface/notebooks/blob/main/examples/summarization_ort.ipynb)| Show how to preprocess the data and fine-tune a model on XSUM using [ONNX Runtime](https://github.com/microsoft/onnxruntime). | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization_ort.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/summarization_ort.ipynb)|
+
+## Community notebooks:
+
+More notebooks developed by the community are available [here](https://hf.co/docs/transformers/community#community-notebooks).
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/pyproject.toml b/tasks/tasksmith-5dd11b34cce1/environment/source/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..bf78e0174394f51a5267bd2619ac6bfc403bf2e9
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/pyproject.toml
@@ -0,0 +1,54 @@
+[tool.coverage.run]
+source = ["transformers"]
+omit = [
+ "*/convert_*",
+ "*/__main__.py"
+]
+
+[tool.coverage.report]
+exclude_lines = [
+ "pragma: no cover",
+ "raise",
+ "except",
+ "register_parameter"
+]
+
+[tool.ruff]
+line-length = 119
+
+[tool.ruff.lint]
+# Never enforce `E501` (line length violations).
+ignore = ["C901", "E501", "E741", "F402", "F823" ]
+select = ["C", "E", "F", "I", "W"]
+
+# Ignore import violations in all `__init__.py` files.
+[tool.ruff.lint.per-file-ignores]
+"__init__.py" = ["E402", "F401", "F403", "F811"]
+"src/transformers/file_utils.py" = ["F401"]
+"src/transformers/utils/dummy_*.py" = ["F401"]
+
+[tool.ruff.lint.isort]
+lines-after-imports = 2
+known-first-party = ["transformers"]
+
+[tool.ruff.format]
+# Like Black, use double quotes for strings.
+quote-style = "double"
+
+# Like Black, indent with spaces, rather than tabs.
+indent-style = "space"
+
+# Like Black, respect magic trailing commas.
+skip-magic-trailing-comma = false
+
+# Like Black, automatically detect the appropriate line ending.
+line-ending = "auto"
+
+[tool.pytest.ini_options]
+addopts = "--doctest-glob='**/*.md'"
+doctest_optionflags="NUMBER NORMALIZE_WHITESPACE ELLIPSIS"
+markers = [
+ "flash_attn_test: marks tests related to flash attention (deselect with '-m \"not flash_attn_test\"')",
+ "bitsandbytes: select (or deselect with `not`) bitsandbytes integration tests",
+ "generate: marks tests that use the GenerationTesterMixin"
+]
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/benchmark/trainer-benchmark.py b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/benchmark/trainer-benchmark.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9470eeeae8548ef1e3035a842f6bd06f2bf7774
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/benchmark/trainer-benchmark.py
@@ -0,0 +1,448 @@
+#!/usr/bin/env python
+
+# HF Trainer benchmarking tool
+#
+# This tool can be used to run and compare multiple dimensions of the HF Trainers args.
+#
+# It then prints a report once in github format with all the information that needs to be shared
+# with others and second time in a console-friendly format, so it's easier to use for tuning things up.
+#
+# The main idea is:
+#
+# ./trainer-benchmark.py --base-cmd '' \
+# --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \
+# --target-metric-key train_samples_per_second
+#
+# The variations can be any command line argument that you want to compare and not just dtype as in
+# the example.
+#
+# --variations allows you to compare variations in multiple dimensions.
+#
+# as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6
+# times adding one of:
+#
+# 1. --tf32 0 --fp16 0
+# 2. --tf32 0 --fp16 1
+# 3. --tf32 0 --bf16 1
+# 4. --tf32 1 --fp16 0
+# 5. --tf32 1 --fp16 1
+# 6. --tf32 1 --bf16 1
+#
+# and print the results. This is just a cartesian product - and more than 2 dimensions can be used.
+#
+# If you want to rely on defaults, this:
+# --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1'
+# is identical to this:
+# --variations '--tf32 0|--tf32 1' '|--fp16|--bf16'
+#
+# the leading empty variation in the 2nd dimension is a valid variation.
+#
+# So here we get the following 6 variations:
+#
+# 1. --tf32 0
+# 2. --tf32 0 --fp16
+# 3. --tf32 0 --bf16
+# 4. --tf32 1
+# 5. --tf32 1 --fp16
+# 6. --tf32 1 --bf16
+#
+# In this particular case we don't know what the default tf32 setting is as it's normally
+# pytorch-version dependent). That's why it's best to do an explicit setting of each variation:
+# `--tf32 0|--tf32 1`
+#
+# Here is a full example of a train:
+#
+# CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \
+# --base-cmd \
+# ' examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small \
+# --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \
+# --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \
+# --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \
+# --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \
+# --source_prefix "translate English to Romanian: " --warmup_steps 50 \
+# --max_train_samples 20000 --dataloader_num_workers 2 ' \
+# --target-metric-key train_samples_per_second --repeat-times 1 --variations \
+# '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \
+# --repeat-times 1 --base-variation '--tf32 0'
+#
+# and here is a possible output:
+#
+#
+# | Variation | Train | Diff | Train |
+# | | samples | % | loss |
+# | | per | | |
+# | | second | | |
+# |:----------------|----------:|-------:|--------:|
+# | --tf32 0 | 285.11 | 0 | 2.51 |
+# | --tf32 1 | 342.09 | 20 | 2.51 |
+# | --fp16 --tf32 0 | 423.49 | 49 | 2.51 |
+# | --fp16 --tf32 1 | 423.13 | 48 | 2.51 |
+# | --bf16 --tf32 0 | 416.80 | 46 | 2.52 |
+# | --bf16 --tf32 1 | 415.87 | 46 | 2.52 |
+#
+#
+# So you can quickly compare the different outcomes.
+#
+# Typically running each experiment once is enough, but if the environment is unstable you can
+# re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results.
+#
+# By default it'll use the lowest result as the base line to use as 100% and then compare the rest to
+# it as can be seen from the table above, but you can also specify which combination is the one to use as
+# the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0'
+#
+# --target-metric-key is there to tell the program which metrics to compare - the different metric keys are
+# inside output_dir/all_results.json. e.g., to measure eval performance instead of train use:
+# --target-metric-key eval_samples_per_second
+# but of course you will need to adjust the --base-cmd value in the example to perform evaluation as
+# well (as currently it doesn't)
+#
+
+import argparse
+import datetime
+import io
+import itertools
+import json
+import math
+import os
+import platform
+import re
+import shlex
+import subprocess
+import sys
+from pathlib import Path
+from statistics import fmean
+
+import pandas as pd
+import torch
+from tqdm import tqdm
+
+import transformers
+
+
+nan = float("nan")
+
+
+class Tee:
+ """
+ A helper class to tee print's output into a file.
+ Usage:
+ sys.stdout = Tee(filename)
+ """
+
+ def __init__(self, filename):
+ self.stdout = sys.stdout
+ self.file = open(filename, "a")
+
+ def __getattr__(self, attr):
+ return getattr(self.stdout, attr)
+
+ def write(self, msg):
+ self.stdout.write(msg)
+ # strip tqdm codes
+ self.file.write(re.sub(r"^.*\r", "", msg, 0, re.M))
+
+
+def get_original_command(max_width=80, full_python_path=False):
+ """
+ Return the original command line string that can be replayed nicely and wrapped for 80 char width.
+
+ Args:
+ max_width (`int`, *optional*, defaults to 80):
+ The width to wrap for.
+ full_python_path (`bool`, `optional`, defaults to `False`):
+ Whether to replicate the full path or just the last segment (i.e. `python`).
+ """
+
+ cmd = []
+
+ # deal with critical env vars
+ env_keys = ["CUDA_VISIBLE_DEVICES"]
+ for key in env_keys:
+ val = os.environ.get(key, None)
+ if val is not None:
+ cmd.append(f"{key}={val}")
+
+ # python executable (not always needed if the script is executable)
+ python = sys.executable if full_python_path else sys.executable.split("/")[-1]
+ cmd.append(python)
+
+ # now the normal args
+ cmd += list(map(shlex.quote, sys.argv))
+
+ # split up into up to MAX_WIDTH lines with shell multi-line escapes
+ lines = []
+ current_line = ""
+ while len(cmd) > 0:
+ current_line += f"{cmd.pop(0)} "
+ if len(cmd) == 0 or len(current_line) + len(cmd[0]) + 1 > max_width - 1:
+ lines.append(current_line)
+ current_line = ""
+ return "\\\n".join(lines)
+
+
+def get_base_command(args, output_dir):
+
+ # unwrap multi-line input
+ args.base_cmd = re.sub(r"[\\\n]+", " ", args.base_cmd)
+
+ # remove --output_dir if any and set our own
+ args.base_cmd = re.sub("--output_dir\s+[^\s]+", "", args.base_cmd)
+ args.base_cmd += f" --output_dir {output_dir}"
+
+ # ensure we have --overwrite_output_dir
+ args.base_cmd = re.sub("--overwrite_output_dir\s+", "", args.base_cmd)
+ args.base_cmd += " --overwrite_output_dir"
+
+ return [sys.executable] + shlex.split(args.base_cmd)
+
+
+def process_run_single(id, cmd, variation, output_dir, target_metric_key, metric_keys, verbose):
+
+ # Enable to debug everything but the run itself, to do it fast and see the progress.
+ # This is useful for debugging the output formatting quickly - we can remove it later once
+ # everybody is happy with the output
+ if 0:
+ import random
+ from time import sleep
+
+ sleep(0)
+ return dict(
+ {k: random.uniform(0, 100) for k in metric_keys},
+ **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.22222222])},
+ )
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if verbose:
+ print("STDOUT", result.stdout)
+ print("STDERR", result.stderr)
+
+ # save the streams
+ prefix = variation.replace(" ", "-")
+ with open(Path(output_dir) / f"log.{prefix}.stdout.txt", "w") as f:
+ f.write(result.stdout)
+ with open(Path(output_dir) / f"log.{prefix}.stderr.txt", "w") as f:
+ f.write(result.stderr)
+
+ if result.returncode != 0:
+ if verbose:
+ print("failed")
+ return {target_metric_key: nan}
+
+ with io.open(f"{output_dir}/all_results.json", "r", encoding="utf-8") as f:
+ metrics = json.load(f)
+
+ # filter out just the keys we want
+ return {k: v for k, v in metrics.items() if k in metric_keys}
+
+
+def process_run(
+ id,
+ cmd,
+ variation_key,
+ variation,
+ longest_variation_len,
+ target_metric_key,
+ report_metric_keys,
+ repeat_times,
+ output_dir,
+ verbose,
+):
+ results = []
+ metrics = []
+ preamble = f"{id}: {variation:<{longest_variation_len}}"
+ outcome = f"{preamble}: "
+ metric_keys = set(report_metric_keys + [target_metric_key])
+ for i in tqdm(range(repeat_times), desc=preamble, leave=False):
+ single_run_metrics = process_run_single(
+ id, cmd, variation, output_dir, target_metric_key, metric_keys, verbose
+ )
+ result = single_run_metrics[target_metric_key]
+ if not math.isnan(result):
+ metrics.append(single_run_metrics)
+ results.append(result)
+ outcome += "✓"
+ else:
+ outcome += "✘"
+ outcome = f"\33[2K\r{outcome}"
+ if len(metrics) > 0:
+ mean_metrics = {k: fmean([x[k] for x in metrics]) for k in metrics[0].keys()}
+ mean_target = round(mean_metrics[target_metric_key], 2)
+ results_str = f"{outcome} {mean_target}"
+ if len(metrics) > 1:
+ results_str += f" {tuple(round(x, 2) for x in results)}"
+ print(results_str)
+ mean_metrics[variation_key] = variation
+ return mean_metrics
+ else:
+ print(outcome)
+ return {variation_key: variation, target_metric_key: nan}
+
+
+def get_versions():
+ properties = torch.cuda.get_device_properties(torch.device("cuda"))
+ return f"""
+Datetime : {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
+
+Software:
+transformers: {transformers.__version__}
+torch : {torch.__version__}
+cuda : {torch.version.cuda}
+python : {platform.python_version()}
+
+Hardware:
+{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB
+"""
+
+
+def process_results(results, target_metric_key, report_metric_keys, base_variation, output_dir):
+
+ df = pd.DataFrame(results)
+ variation_key = "variation"
+ diff_key = "diff_%"
+
+ sentinel_value = nan
+ if base_variation is not None and len(df[df[variation_key] == base_variation]):
+ # this may still return nan
+ sentinel_value = df.loc[df[variation_key] == base_variation][target_metric_key].item()
+ if math.isnan(sentinel_value):
+ # as a fallback, use the minimal value as the sentinel
+ sentinel_value = df.loc[df[target_metric_key] != nan][target_metric_key].min()
+
+ # create diff column if possible
+ if not math.isnan(sentinel_value):
+ df[diff_key] = df.apply(
+ lambda r: round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value)
+ if not math.isnan(r[target_metric_key])
+ else 0,
+ axis="columns",
+ )
+
+ # re-order columns
+ cols = [variation_key, target_metric_key, diff_key, *report_metric_keys]
+ df = df.reindex(cols, axis="columns") # reorder cols
+
+ # capitalize
+ df = df.rename(str.capitalize, axis="columns")
+
+ # make the cols as narrow as possible
+ df_github = df.rename(lambda c: c.replace("_", " "), axis="columns")
+ df_console = df.rename(lambda c: c.replace("_", "\n"), axis="columns")
+
+ report = ["", "Copy between the cut-here-lines and paste as is to github or a forum"]
+ report += ["----------8<-----------------8<--------"]
+ report += ["*** Results:", df_github.to_markdown(index=False, floatfmt=".2f")]
+ report += ["```"]
+ report += ["*** Setup:", get_versions()]
+ report += ["*** The benchmark command line was:", get_original_command()]
+ report += ["```"]
+ report += ["----------8<-----------------8<--------"]
+ report += ["*** Results (console):", df_console.to_markdown(index=False, floatfmt=".2f")]
+
+ print("\n\n".join(report))
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "--base-cmd",
+ default=None,
+ type=str,
+ required=True,
+ help="Base cmd",
+ )
+ parser.add_argument(
+ "--variations",
+ default=None,
+ type=str,
+ nargs="+",
+ required=True,
+ help="Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'",
+ )
+ parser.add_argument(
+ "--base-variation",
+ default=None,
+ type=str,
+ help="Baseline variation to compare to. if None the minimal target value will be used to compare against",
+ )
+ parser.add_argument(
+ "--target-metric-key",
+ default=None,
+ type=str,
+ required=True,
+ help="Target metric key in output_dir/all_results.json, e.g., train_samples_per_second",
+ )
+ parser.add_argument(
+ "--report-metric-keys",
+ default="",
+ type=str,
+ help="Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., 'train_loss train_samples",
+ )
+ parser.add_argument(
+ "--repeat-times",
+ default=1,
+ type=int,
+ help="How many times to re-run each variation - an average will be reported",
+ )
+ parser.add_argument(
+ "--output_dir",
+ default="output_benchmark",
+ type=str,
+ help="The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked",
+ )
+ parser.add_argument(
+ "--verbose",
+ default=False,
+ action="store_true",
+ help="Whether to show the outputs of each run or just the benchmark progress",
+ )
+ args = parser.parse_args()
+
+ output_dir = args.output_dir
+ Path(output_dir).mkdir(exist_ok=True)
+ base_cmd = get_base_command(args, output_dir)
+
+ # split each dimension into its --foo variations
+ dims = [list(map(str.strip, re.split(r"\|", x))) for x in args.variations]
+ # build a cartesian product of dimensions and convert those back into cmd-line arg strings,
+ # while stripping white space for inputs that were empty
+ variations = list(map(str.strip, map(" ".join, itertools.product(*dims))))
+ longest_variation_len = max(len(x) for x in variations)
+
+ # split wanted keys
+ report_metric_keys = args.report_metric_keys.split()
+
+ # capture prints into a log file for convenience
+ report_fn = f"benchmark-report-{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.txt"
+ print(f"\nNote: each run's output is also logged under {output_dir}/log.*.std*.txt")
+ print(f"and this script's output is also piped into {report_fn}")
+
+ sys.stdout = Tee(report_fn)
+
+ print(f"\n*** Running {len(variations)} benchmarks:")
+ print(f"Base command: {' '.join(base_cmd)}")
+
+ variation_key = "variation"
+ results = []
+ for id, variation in enumerate(tqdm(variations, desc="Total completion: ", leave=False)):
+ cmd = base_cmd + variation.split()
+ results.append(
+ process_run(
+ id + 1,
+ cmd,
+ variation_key,
+ variation,
+ longest_variation_len,
+ args.target_metric_key,
+ report_metric_keys,
+ args.repeat_times,
+ output_dir,
+ args.verbose,
+ )
+ )
+
+ process_results(results, args.target_metric_key, report_metric_keys, args.base_variation, output_dir)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/check_tokenizers.py b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/check_tokenizers.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba73460ce4d60b0d1d99ae317723b9016348ea31
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/check_tokenizers.py
@@ -0,0 +1,171 @@
+from collections import Counter
+
+import datasets
+
+import transformers
+from transformers.convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS
+from transformers.utils import logging
+
+
+logging.set_verbosity_info()
+
+TOKENIZER_CLASSES = {
+ name: (getattr(transformers, name), getattr(transformers, name + "Fast")) for name in SLOW_TO_FAST_CONVERTERS
+}
+
+dataset = datasets.load_dataset("facebook/xnli", split="test+validation") # no-script
+
+total = 0
+perfect = 0
+imperfect = 0
+wrong = 0
+
+
+def check_diff(spm_diff, tok_diff, slow, fast):
+ if spm_diff == list(reversed(tok_diff)):
+ # AAA -> AA+A vs A+AA case.
+ return True
+ elif len(spm_diff) == len(tok_diff) and fast.decode(spm_diff) == fast.decode(tok_diff):
+ # Second order OK
+ # Barrich -> Barr + ich vs Bar + rich
+ return True
+ spm_reencoded = slow.encode(slow.decode(spm_diff))
+ tok_reencoded = fast.encode(fast.decode(spm_diff))
+ if spm_reencoded != spm_diff and spm_reencoded == tok_reencoded:
+ # Type 3 error.
+ # Snehagatha ->
+ # Sne, h, aga, th, a
+ # Sne, ha, gat, ha
+ # Encoding the wrong with sp does not even recover what spm gave us
+ # It fits tokenizer however...
+ return True
+ return False
+
+
+def check_LTR_mark(line, idx, fast):
+ enc = fast.encode_plus(line)[0]
+ offsets = enc.offsets
+ curr, prev = offsets[idx], offsets[idx - 1]
+ if curr is not None and line[curr[0] : curr[1]] == "\u200f":
+ return True
+ if prev is not None and line[prev[0] : prev[1]] == "\u200f":
+ return True
+
+
+def check_details(line, spm_ids, tok_ids, slow, fast):
+ # Encoding can be the same with same result AAA -> A + AA vs AA + A
+ # We can check that we use at least exactly the same number of tokens.
+ for i, (spm_id, tok_id) in enumerate(zip(spm_ids, tok_ids)):
+ if spm_id != tok_id:
+ break
+ first = i
+ for i, (spm_id, tok_id) in enumerate(zip(reversed(spm_ids), reversed(tok_ids))):
+ if spm_id != tok_id:
+ break
+ last = len(spm_ids) - i
+
+ spm_diff = spm_ids[first:last]
+ tok_diff = tok_ids[first:last]
+
+ if check_diff(spm_diff, tok_diff, slow, fast):
+ return True
+
+ if check_LTR_mark(line, first, fast):
+ return True
+
+ if last - first > 5:
+ # We might have twice a single problem, attempt to subdivide the disjointed tokens into smaller problems
+ spms = Counter(spm_ids[first:last])
+ toks = Counter(tok_ids[first:last])
+
+ removable_tokens = {spm_ for (spm_, si) in spms.items() if toks.get(spm_, 0) == si}
+ min_width = 3
+ for i in range(last - first - min_width):
+ if all(spm_ids[first + i + j] in removable_tokens for j in range(min_width)):
+ possible_matches = [
+ k
+ for k in range(last - first - min_width)
+ if tok_ids[first + k : first + k + min_width] == spm_ids[first + i : first + i + min_width]
+ ]
+ for j in possible_matches:
+ if check_diff(spm_ids[first : first + i], tok_ids[first : first + j], slow, fast) and check_details(
+ line,
+ spm_ids[first + i : last],
+ tok_ids[first + j : last],
+ slow,
+ fast,
+ ):
+ return True
+
+ print(f"Spm: {[fast.decode([spm_ids[i]]) for i in range(first, last)]}")
+ try:
+ print(f"Tok: {[fast.decode([tok_ids[i]]) for i in range(first, last)]}")
+ except Exception:
+ pass
+
+ fast.decode(spm_ids[:first])
+ fast.decode(spm_ids[last:])
+ wrong = fast.decode(spm_ids[first:last])
+ print()
+ print(wrong)
+ return False
+
+
+def test_string(slow, fast, text):
+ global perfect
+ global imperfect
+ global wrong
+ global total
+
+ slow_ids = slow.encode(text)
+ fast_ids = fast.encode(text)
+
+ skip_assert = False
+ total += 1
+
+ if slow_ids != fast_ids:
+ if check_details(text, slow_ids, fast_ids, slow, fast):
+ skip_assert = True
+ imperfect += 1
+ else:
+ wrong += 1
+ else:
+ perfect += 1
+
+ if total % 10000 == 0:
+ print(f"({perfect} / {imperfect} / {wrong} ----- {perfect + imperfect + wrong})")
+
+ if skip_assert:
+ return
+
+ assert (
+ slow_ids == fast_ids
+ ), f"line {text} : \n\n{slow_ids}\n{fast_ids}\n\n{slow.tokenize(text)}\n{fast.tokenize(text)}"
+
+
+def test_tokenizer(slow, fast):
+ global batch_total
+ for i in range(len(dataset)):
+ # premise, all languages
+ for text in dataset[i]["premise"].values():
+ test_string(slow, fast, text)
+
+ # hypothesis, all languages
+ for text in dataset[i]["hypothesis"]["translation"]:
+ test_string(slow, fast, text)
+
+
+if __name__ == "__main__":
+ for name, (slow_class, fast_class) in TOKENIZER_CLASSES.items():
+ checkpoint_names = list(slow_class.max_model_input_sizes.keys())
+ for checkpoint in checkpoint_names:
+ imperfect = 0
+ perfect = 0
+ wrong = 0
+ total = 0
+
+ print(f"========================== Checking {name}: {checkpoint} ==========================")
+ slow = slow_class.from_pretrained(checkpoint, force_download=True)
+ fast = fast_class.from_pretrained(checkpoint, force_download=True)
+ test_tokenizer(slow, fast)
+ print(f"Accuracy {perfect * 100 / total:.2f}")
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/deberta_scrtipt.py b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/deberta_scrtipt.py
new file mode 100644
index 0000000000000000000000000000000000000000..b910d8de3f52b5ec66bbfad1b91dea26c940d521
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/deberta_scrtipt.py
@@ -0,0 +1,82 @@
+import torch
+from transformers import pipeline, AutoTokenizer, AutoModel, AutoModelForMaskedLM
+import time
+
+test_sentence = 'Do you [MASK] the muffin man?'
+
+# for comparison
+bert = pipeline('fill-mask', model = 'bert-base-uncased')
+print('\n'.join([d['sequence'] for d in bert(test_sentence)]))
+
+
+deberta = pipeline('fill-mask', model = 'microsoft/deberta-v3-base', model_kwargs={"legacy": False})
+print('\n'.join([d['sequence'] for d in deberta(test_sentence)]))
+
+
+tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-v3-base")
+
+tokenized_dict = tokenizer(
+ ["Is this working",], ["Not yet",],
+ return_tensors="pt"
+)
+
+deberta.model.forward = torch.compile(deberta.model.forward)
+start=time.time()
+deberta.model(**tokenized_dict)
+end=time.time()
+print(end-start)
+
+
+start=time.time()
+deberta.model(**tokenized_dict)
+end=time.time()
+print(end-start)
+
+
+start=time.time()
+deberta.model(**tokenized_dict)
+end=time.time()
+print(end-start)
+
+
+model = AutoModel.from_pretrained('microsoft/deberta-base')
+model.config.return_dict = False
+model.config.output_hidden_states=False
+input_tuple = (tokenized_dict['input_ids'], tokenized_dict['attention_mask'])
+
+
+start=time.time()
+traced_model = torch.jit.trace(model, input_tuple)
+end=time.time()
+print(end-start)
+
+
+start=time.time()
+traced_model(tokenized_dict['input_ids'], tokenized_dict['attention_mask'])
+end=time.time()
+print(end-start)
+
+
+start=time.time()
+traced_model(tokenized_dict['input_ids'], tokenized_dict['attention_mask'])
+end=time.time()
+print(end-start)
+
+
+start=time.time()
+traced_model(tokenized_dict['input_ids'], tokenized_dict['attention_mask'])
+end=time.time()
+print(end-start)
+
+
+start=time.time()
+traced_model(tokenized_dict['input_ids'], tokenized_dict['attention_mask'])
+end=time.time()
+print(end-start)
+
+
+torch.jit.save(traced_model, "compiled_deberta.pt")
+
+
+
+# my_script_module = torch.jit.script(model)
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/distributed/torch-distributed-gpu-test.py b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/distributed/torch-distributed-gpu-test.py
new file mode 100644
index 0000000000000000000000000000000000000000..22a99d570e4f85ba4fcbaf470fbbda1856fc8edd
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/distributed/torch-distributed-gpu-test.py
@@ -0,0 +1,92 @@
+#!/usr/bin/env python
+
+#
+# This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or
+# many nodes) can talk to each other via nccl and allocate gpu memory.
+#
+# To run first adjust the number of processes and nodes:
+#
+# python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
+#
+# You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port
+#
+# You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d
+#
+# use torch.distributed.launch instead of torch.distributed.run for torch < 1.9
+#
+# If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with:
+#
+# NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
+#
+# which should tell you what's going on behind the scenes.
+#
+#
+# This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that
+# runs on 2 nodes of 4 gpus per node:
+#
+# #SBATCH --job-name=test-nodes # name
+# #SBATCH --nodes=2 # nodes
+# #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node!
+# #SBATCH --cpus-per-task=10 # number of cores per tasks
+# #SBATCH --gres=gpu:4 # number of gpus
+# #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS)
+# #SBATCH --output=%x-%j.out # output file name
+#
+# GPUS_PER_NODE=4
+# MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)
+# MASTER_PORT=6000
+#
+# srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \
+# --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \
+# --master_addr $MASTER_ADDR --master_port $MASTER_PORT \
+# torch-distributed-gpu-test.py'
+#
+
+import fcntl
+import os
+import socket
+
+import torch
+import torch.distributed as dist
+
+
+def printflock(*msgs):
+ """solves multi-process interleaved print problem"""
+ with open(__file__, "r") as fh:
+ fcntl.flock(fh, fcntl.LOCK_EX)
+ try:
+ print(*msgs)
+ finally:
+ fcntl.flock(fh, fcntl.LOCK_UN)
+
+
+local_rank = int(os.environ["LOCAL_RANK"])
+torch.cuda.set_device(local_rank)
+device = torch.device("cuda", local_rank)
+hostname = socket.gethostname()
+
+gpu = f"[{hostname}-{local_rank}]"
+
+try:
+ # test distributed
+ dist.init_process_group("nccl")
+ dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM)
+ dist.barrier()
+
+ # test cuda is available and can allocate memory
+ torch.cuda.is_available()
+ torch.ones(1).cuda(local_rank)
+
+ # global rank
+ rank = dist.get_rank()
+ world_size = dist.get_world_size()
+
+ printflock(f"{gpu} is OK (global rank: {rank}/{world_size})")
+
+ dist.barrier()
+ if rank == 0:
+ printflock(f"pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}")
+
+except Exception:
+ printflock(f"{gpu} is broken")
+ raise
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/convert-allenai-wmt16.sh b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/convert-allenai-wmt16.sh
new file mode 100644
index 0000000000000000000000000000000000000000..30983c410164f3b6c96b9a1f69d631515614d724
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/convert-allenai-wmt16.sh
@@ -0,0 +1,71 @@
+#!/usr/bin/env bash
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# this script acquires data and converts it to fsmt model
+# it covers:
+# - allenai/wmt16-en-de-dist-12-1
+# - allenai/wmt16-en-de-dist-6-1
+# - allenai/wmt16-en-de-12-1
+
+# this script needs to be run from the top level of the transformers repo
+if [ ! -d "src/transformers" ]; then
+ echo "Error: This script needs to be run from the top of the transformers repo"
+ exit 1
+fi
+
+mkdir data
+
+# get data (run once)
+
+cd data
+gdown 'https://drive.google.com/uc?id=1x_G2cjvM1nW5hjAB8-vWxRqtQTlmIaQU'
+gdown 'https://drive.google.com/uc?id=1oA2aqZlVNj5FarxBlNXEHpBS4lRetTzU'
+gdown 'https://drive.google.com/uc?id=1Wup2D318QYBFPW_NKI1mfP_hXOfmUI9r'
+tar -xvzf trans_ende_12-1_0.2.tar.gz
+tar -xvzf trans_ende-dist_12-1_0.2.tar.gz
+tar -xvzf trans_ende-dist_6-1_0.2.tar.gz
+gdown 'https://drive.google.com/uc?id=1mNufoynJ9-Zy1kJh2TA_lHm2squji0i9'
+gdown 'https://drive.google.com/uc?id=1iO7um-HWoNoRKDtw27YUSgyeubn9uXqj'
+tar -xvzf wmt16.en-de.deep-shallow.dist.tar.gz
+tar -xvzf wmt16.en-de.deep-shallow.tar.gz
+cp wmt16.en-de.deep-shallow/data-bin/dict.*.txt trans_ende_12-1_0.2
+cp wmt16.en-de.deep-shallow.dist/data-bin/dict.*.txt trans_ende-dist_12-1_0.2
+cp wmt16.en-de.deep-shallow.dist/data-bin/dict.*.txt trans_ende-dist_6-1_0.2
+cp wmt16.en-de.deep-shallow/bpecodes trans_ende_12-1_0.2
+cp wmt16.en-de.deep-shallow.dist/bpecodes trans_ende-dist_12-1_0.2
+cp wmt16.en-de.deep-shallow.dist/bpecodes trans_ende-dist_6-1_0.2
+cd -
+
+# run conversions and uploads
+
+PYTHONPATH="src" python src/transformers/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py --fsmt_checkpoint_path data/trans_ende-dist_12-1_0.2/checkpoint_top5_average.pt --pytorch_dump_folder_path data/wmt16-en-de-dist-12-1
+
+PYTHONPATH="src" python src/transformers/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py --fsmt_checkpoint_path data/trans_ende-dist_6-1_0.2/checkpoint_top5_average.pt --pytorch_dump_folder_path data/wmt16-en-de-dist-6-1
+
+PYTHONPATH="src" python src/transformers/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py --fsmt_checkpoint_path data/trans_ende_12-1_0.2/checkpoint_top5_average.pt --pytorch_dump_folder_path data/wmt16-en-de-12-1
+
+
+# upload
+cd data
+transformers-cli upload -y wmt16-en-de-dist-12-1
+transformers-cli upload -y wmt16-en-de-dist-6-1
+transformers-cli upload -y wmt16-en-de-12-1
+cd -
+
+
+# if updating just small files and not the large models, here is a script to generate the right commands:
+perl -le 'for $f (@ARGV) { print qq[transformers-cli upload -y $_/$f --filename $_/$f] for ("wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1")}' vocab-src.json vocab-tgt.json tokenizer_config.json config.json
+# add/remove files as needed
+
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/convert-allenai-wmt19.sh b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/convert-allenai-wmt19.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ef8fa3d4186de1b25d841fc3f8d0a8c0b7c99995
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/convert-allenai-wmt19.sh
@@ -0,0 +1,59 @@
+#!/usr/bin/env bash
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# this script acquires data and converts it to fsmt model
+# it covers:
+# - allenai/wmt19-de-en-6-6-base
+# - allenai/wmt19-de-en-6-6-big
+
+# this script needs to be run from the top level of the transformers repo
+if [ ! -d "src/transformers" ]; then
+ echo "Error: This script needs to be run from the top of the transformers repo"
+ exit 1
+fi
+
+mkdir data
+
+# get data (run once)
+
+cd data
+gdown 'https://drive.google.com/uc?id=1j6z9fYdlUyOYsh7KJoumRlr1yHczxR5T'
+gdown 'https://drive.google.com/uc?id=1yT7ZjqfvUYOBXvMjeY8uGRHQFWoSo8Q5'
+gdown 'https://drive.google.com/uc?id=15gAzHeRUCs-QV8vHeTReMPEh1j8excNE'
+tar -xvzf wmt19.de-en.tar.gz
+tar -xvzf wmt19_deen_base_dr0.1_1.tar.gz
+tar -xvzf wmt19_deen_big_dr0.1_2.tar.gz
+cp wmt19.de-en/data-bin/dict.*.txt wmt19_deen_base_dr0.1_1
+cp wmt19.de-en/data-bin/dict.*.txt wmt19_deen_big_dr0.1_2
+cd -
+
+# run conversions and uploads
+
+PYTHONPATH="src" python src/transformers/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py --fsmt_checkpoint_path data/wmt19_deen_base_dr0.1_1/checkpoint_last3_avg.pt --pytorch_dump_folder_path data/wmt19-de-en-6-6-base
+
+PYTHONPATH="src" python src/transformers/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py --fsmt_checkpoint_path data/wmt19_deen_big_dr0.1_2/checkpoint_last3_avg.pt --pytorch_dump_folder_path data/wmt19-de-en-6-6-big
+
+
+# upload
+cd data
+transformers-cli upload -y wmt19-de-en-6-6-base
+transformers-cli upload -y wmt19-de-en-6-6-big
+cd -
+
+
+# if updating just small files and not the large models, here is a script to generate the right commands:
+perl -le 'for $f (@ARGV) { print qq[transformers-cli upload -y $_/$f --filename $_/$f] for ("wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big")}' vocab-src.json vocab-tgt.json tokenizer_config.json config.json
+# add/remove files as needed
+
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/convert-facebook-wmt19.sh b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/convert-facebook-wmt19.sh
new file mode 100644
index 0000000000000000000000000000000000000000..293522f0e881cdb1636ebc5d85f0f9a9f52c8466
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/convert-facebook-wmt19.sh
@@ -0,0 +1,70 @@
+#!/usr/bin/env bash
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# this script acquires data and converts it to fsmt model
+# it covers:
+# - facebook/wmt19-ru-en
+# - facebook/wmt19-en-ru
+# - facebook/wmt19-de-en
+# - facebook/wmt19-en-de
+
+# this script needs to be run from the top level of the transformers repo
+if [ ! -d "src/transformers" ]; then
+ echo "Error: This script needs to be run from the top of the transformers repo"
+ exit 1
+fi
+
+mkdir data
+
+# get data (run once)
+
+cd data
+wget https://dl.fbaipublicfiles.com/fairseq/models/wmt19.en-de.joined-dict.ensemble.tar.gz
+wget https://dl.fbaipublicfiles.com/fairseq/models/wmt19.de-en.joined-dict.ensemble.tar.gz
+wget https://dl.fbaipublicfiles.com/fairseq/models/wmt19.en-ru.ensemble.tar.gz
+wget https://dl.fbaipublicfiles.com/fairseq/models/wmt19.ru-en.ensemble.tar.gz
+tar -xvzf wmt19.en-de.joined-dict.ensemble.tar.gz
+tar -xvzf wmt19.de-en.joined-dict.ensemble.tar.gz
+tar -xvzf wmt19.en-ru.ensemble.tar.gz
+tar -xvzf wmt19.ru-en.ensemble.tar.gz
+cd -
+
+# run conversions and uploads
+
+export PAIR=ru-en
+PYTHONPATH="src" python src/transformers/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py --fsmt_checkpoint_path data/wmt19.$PAIR.ensemble/model4.pt --pytorch_dump_folder_path data/wmt19-$PAIR
+
+export PAIR=en-ru
+PYTHONPATH="src" python src/transformers/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py --fsmt_checkpoint_path data/wmt19.$PAIR.ensemble/model4.pt --pytorch_dump_folder_path data/wmt19-$PAIR
+
+export PAIR=de-en
+PYTHONPATH="src" python src/transformers/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py --fsmt_checkpoint_path data/wmt19.$PAIR.joined-dict.ensemble/model4.pt --pytorch_dump_folder_path data/wmt19-$PAIR
+
+export PAIR=en-de
+PYTHONPATH="src" python src/transformers/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py --fsmt_checkpoint_path data/wmt19.$PAIR.joined-dict.ensemble/model4.pt --pytorch_dump_folder_path data/wmt19-$PAIR
+
+
+# upload
+cd data
+transformers-cli upload -y wmt19-ru-en
+transformers-cli upload -y wmt19-en-ru
+transformers-cli upload -y wmt19-de-en
+transformers-cli upload -y wmt19-en-de
+cd -
+
+# if updating just small files and not the large models, here is a script to generate the right commands:
+perl -le 'for $f (@ARGV) { print qq[transformers-cli upload -y $_/$f --filename $_/$f] for map { "wmt19-$_" } ("en-ru", "ru-en", "de-en", "en-de")}' vocab-src.json vocab-tgt.json tokenizer_config.json config.json
+# add/remove files as needed
+
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/eval-allenai-wmt16.sh b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/eval-allenai-wmt16.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3db46e17ce621ea205b9e0e45a7f5e2e83360f26
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/eval-allenai-wmt16.sh
@@ -0,0 +1,79 @@
+#!/usr/bin/env bash
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# this script evals the following fsmt models
+# it covers:
+# - allenai/wmt16-en-de-dist-12-1
+# - allenai/wmt16-en-de-dist-6-1
+# - allenai/wmt16-en-de-12-1
+
+# this script needs to be run from the top level of the transformers repo
+if [ ! -d "src/transformers" ]; then
+ echo "Error: This script needs to be run from the top of the transformers repo"
+ exit 1
+fi
+
+# In these scripts you may have to lower BS if you get CUDA OOM (or increase it if you have a large GPU)
+
+### Normal eval ###
+
+export PAIR=en-de
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=64
+export NUM_BEAMS=5
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+
+MODEL_PATH=allenai/wmt16-en-de-dist-12-1
+echo $PAIR $MODEL_PATH
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py $MODEL_PATH $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+MODEL_PATH=allenai/wmt16-en-de-dist-6-1
+echo $PAIR $MODEL_PATH
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py $MODEL_PATH $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+MODEL_PATH=allenai/wmt16-en-de-12-1
+echo $PAIR $MODEL_PATH
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py $MODEL_PATH $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+
+
+### Searching hparams eval ###
+
+
+export PAIR=en-de
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=32
+export NUM_BEAMS=5
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+
+MODEL_PATH=allenai/wmt16-en-de-dist-12-1
+echo $PAIR $MODEL_PATH
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval_search.py $MODEL_PATH $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --search="num_beams=5:10:15 length_penalty=0.6:0.7:0.8:0.9:1.0:1.1"
+
+
+MODEL_PATH=allenai/wmt16-en-de-dist-6-1
+echo $PAIR $MODEL_PATH
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval_search.py $MODEL_PATH $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --search="num_beams=5:10:15 length_penalty=0.6:0.7:0.8:0.9:1.0:1.1"
+
+
+MODEL_PATH=allenai/wmt16-en-de-12-1
+echo $PAIR $MODEL_PATH
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval_search.py $MODEL_PATH $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --search="num_beams=5:10:15 length_penalty=0.6:0.7:0.8:0.9:1.0:1.1"
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/eval-allenai-wmt19.sh b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/eval-allenai-wmt19.sh
new file mode 100644
index 0000000000000000000000000000000000000000..84740e2f5940d237f0aa40f5b4fbac7c1ff86454
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/eval-allenai-wmt19.sh
@@ -0,0 +1,67 @@
+#!/usr/bin/env bash
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# this script evals the following fsmt models
+# it covers:
+# - allenai/wmt19-de-en-6-6-base
+# - allenai/wmt19-de-en-6-6-big
+
+# this script needs to be run from the top level of the transformers repo
+if [ ! -d "src/transformers" ]; then
+ echo "Error: This script needs to be run from the top of the transformers repo"
+ exit 1
+fi
+
+# In these scripts you may have to lower BS if you get CUDA OOM (or increase it if you have a large GPU)
+
+### Normal eval ###
+
+export PAIR=de-en
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=64
+export NUM_BEAMS=5
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+
+MODEL_PATH=allenai/wmt19-de-en-6-6-base
+echo $PAIR $MODEL_PATH
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py $MODEL_PATH $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+MODEL_PATH=allenai/wmt19-de-en-6-6-big
+echo $PAIR $MODEL_PATH
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py $MODEL_PATH $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+
+
+### Searching hparams eval ###
+
+export PAIR=de-en
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=16
+export NUM_BEAMS=5
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+
+MODEL_PATH=allenai/wmt19-de-en-6-6-base
+echo $PAIR $MODEL_PATH
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval_search.py $MODEL_PATH $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --search="num_beams=5:10:15 length_penalty=0.6:0.7:0.8:0.9:1.0:1.1"
+
+MODEL_PATH=allenai/wmt19-de-en-6-6-big
+echo $PAIR $MODEL_PATH
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval_search.py $MODEL_PATH $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --search="num_beams=5:10:15 length_penalty=0.6:0.7:0.8:0.9:1.0:1.1"
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/eval-facebook-wmt19.sh b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/eval-facebook-wmt19.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4578df1afa91b794c44cb16a85963fdff4cebc82
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/eval-facebook-wmt19.sh
@@ -0,0 +1,161 @@
+#!/usr/bin/env bash
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# this script evals the following fsmt models
+# it covers:
+# - facebook/wmt19-ru-en
+# - facebook/wmt19-en-ru
+# - facebook/wmt19-de-en
+# - facebook/wmt19-en-de
+
+
+# this script needs to be run from the top level of the transformers repo
+if [ ! -d "src/transformers" ]; then
+ echo "Error: This script needs to be run from the top of the transformers repo"
+ exit 1
+fi
+
+
+# In these scripts you may have to lower BS if you get CUDA OOM (or increase it if you have a large GPU)
+
+### a short estimate version for quick testing ###
+
+export PAIR=en-ru
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+export NUM_BEAMS=8
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src | head -10 > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref | head -10 > $DATA_DIR/val.target
+echo $PAIR
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+
+
+### Normal eval ###
+
+# ru-en
+
+export PAIR=ru-en
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+export NUM_BEAMS=50
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+
+# (target BLEU: 41.3 http://matrix.statmt.org/matrix/output/1907?run_id=6937)
+
+
+# en-ru
+
+export PAIR=en-ru
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+export NUM_BEAMS=50
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+echo $PAIR
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+# (target BLEU: 36.4 http://matrix.statmt.org/matrix/output/1914?score_id=37605)
+
+
+
+# en-de
+
+export PAIR=en-de
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+echo $PAIR
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+# (target BLEU: 43.1 http://matrix.statmt.org/matrix/output/1909?run_id=6862)
+
+
+# de-en
+
+export PAIR=de-en
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+export NUM_BEAMS=50
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+echo $PAIR
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+
+# (target BLEU: 42.3 http://matrix.statmt.org/matrix/output/1902?run_id=6750)
+
+
+### Searching hparams eval ###
+
+# en-ru
+
+export PAIR=ru-en
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=32
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+CUDA_VISIBLE_DEVICES="0" PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval_search.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --search="num_beams=5 length_penalty=0.6:0.7:0.8:0.9:1.0:1.1"
+
+
+# en-ru
+
+export PAIR=en-ru
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=16
+mkdir -p $DATA_DIR
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+CUDA_VISIBLE_DEVICES="0" PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval_search.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --search="num_beams=5:8:11:15 length_penalty=0.6:0.7:0.8:0.9:1.0:1.1 early_stopping=true:false"
+
+# en-de
+
+export PAIR=en-de
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=16
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+CUDA_VISIBLE_DEVICES="1" PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval_search.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --search="num_beams=5:8:11:15 length_penalty=0.6:0.7:0.8:0.9:1.0:1.1 early_stopping=true:false"
+
+# de-en
+
+export PAIR=de-en
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=16
+mkdir -p $DATA_DIR
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+CUDA_VISIBLE_DEVICES="1" PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval_search.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --search="num_beams=5:8:11:15 length_penalty=0.6:0.7:0.8:0.9:1.0:1.1 early_stopping=true:false"
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/fsmt-make-super-tiny-model.py b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/fsmt-make-super-tiny-model.py
new file mode 100644
index 0000000000000000000000000000000000000000..a70f40ee6ca4d68410ccd0ecb151e0eb8367703b
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/fsmt-make-super-tiny-model.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+# coding: utf-8
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# This script creates a super tiny model that is useful inside tests, when we just want to test that
+# the machinery works, without needing to the check the quality of the outcomes.
+#
+# This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny -
+# all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and
+# emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files.
+# The latter is done by `fsmt-make-super-tiny-model.py`.
+#
+# It will be used then as "stas/tiny-wmt19-en-ru"
+
+import json
+import tempfile
+from pathlib import Path
+
+from transformers import FSMTConfig, FSMTForConditionalGeneration, FSMTTokenizer
+from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES
+
+
+mname_tiny = "tiny-wmt19-en-ru"
+
+# Build
+
+# borrowed from a test
+vocab = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "w", "r", "t", "lo", "low", "er", "low", "lowest", "newer", "wider", "", ]
+vocab_tokens = dict(zip(vocab, range(len(vocab))))
+merges = ["l o 123", "lo w 1456", "e r 1789", ""]
+
+with tempfile.TemporaryDirectory() as tmpdirname:
+ build_dir = Path(tmpdirname)
+ src_vocab_file = build_dir / VOCAB_FILES_NAMES["src_vocab_file"]
+ tgt_vocab_file = build_dir / VOCAB_FILES_NAMES["tgt_vocab_file"]
+ merges_file = build_dir / VOCAB_FILES_NAMES["merges_file"]
+ with open(src_vocab_file, "w") as fp: fp.write(json.dumps(vocab_tokens))
+ with open(tgt_vocab_file, "w") as fp: fp.write(json.dumps(vocab_tokens))
+ with open(merges_file, "w") as fp : fp.write("\n".join(merges))
+
+ tokenizer = FSMTTokenizer(
+ langs=["en", "ru"],
+ src_vocab_size = len(vocab),
+ tgt_vocab_size = len(vocab),
+ src_vocab_file=src_vocab_file,
+ tgt_vocab_file=tgt_vocab_file,
+ merges_file=merges_file,
+ )
+
+config = FSMTConfig(
+ langs=['ru', 'en'],
+ src_vocab_size=1000, tgt_vocab_size=1000,
+ d_model=4,
+ encoder_layers=1, decoder_layers=1,
+ encoder_ffn_dim=4, decoder_ffn_dim=4,
+ encoder_attention_heads=1, decoder_attention_heads=1,
+)
+
+tiny_model = FSMTForConditionalGeneration(config)
+print(f"num of params {tiny_model.num_parameters()}")
+
+# Test
+batch = tokenizer(["Making tiny model"], return_tensors="pt")
+outputs = tiny_model(**batch)
+
+print("test output:", len(outputs.logits[0]))
+
+# Save
+tiny_model.half() # makes it smaller
+tiny_model.save_pretrained(mname_tiny)
+tokenizer.save_pretrained(mname_tiny)
+
+print(f"Generated {mname_tiny}")
+
+# Upload
+# transformers-cli upload tiny-wmt19-en-ru
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/fsmt-make-tiny-model.py b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/fsmt-make-tiny-model.py
new file mode 100644
index 0000000000000000000000000000000000000000..b737cc61cea3c07eef4390186ea9a17fb66ac927
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/fsmt-make-tiny-model.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+# coding: utf-8
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# This script creates a super tiny model that is useful inside tests, when we just want to test that
+# the machinery works, without needing to the check the quality of the outcomes.
+#
+# This version creates a tiny model through reduction of a normal pre-trained model, but keeping the
+# full vocab, merges file, and thus also resulting in a larger model due to a large vocab size.
+# This gives ~3MB in total for all files.
+#
+# If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated
+#
+#
+# It will be used then as "stas/tiny-wmt19-en-de"
+
+# Build
+from transformers import FSMTConfig, FSMTForConditionalGeneration, FSMTTokenizer
+
+
+mname = "facebook/wmt19-en-de"
+tokenizer = FSMTTokenizer.from_pretrained(mname)
+# get the correct vocab sizes, etc. from the master model
+config = FSMTConfig.from_pretrained(mname)
+config.update({
+ "d_model": 4,
+ "encoder_layers": 1, "decoder_layers": 1,
+ "encoder_ffn_dim": 4, "decoder_ffn_dim": 4,
+ "encoder_attention_heads": 1, "decoder_attention_heads": 1})
+
+tiny_model = FSMTForConditionalGeneration(config)
+print(f"num of params {tiny_model.num_parameters()}")
+
+# Test
+batch = tokenizer(["Making tiny model"], return_tensors="pt")
+outputs = tiny_model(**batch)
+
+print("test output:", len(outputs.logits[0]))
+
+# Save
+mname_tiny = "tiny-wmt19-en-de"
+tiny_model.half() # makes it smaller
+tiny_model.save_pretrained(mname_tiny)
+tokenizer.save_pretrained(mname_tiny)
+
+print(f"Generated {mname_tiny}")
+
+# Upload
+# transformers-cli upload tiny-wmt19-en-de
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/gen-card-allenai-wmt16.py b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/gen-card-allenai-wmt16.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b5fe1cda8b2ca293019142283874641903b4a08
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/gen-card-allenai-wmt16.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Usage:
+# ./gen-card-allenai-wmt16.py
+
+import os
+from pathlib import Path
+
+
+def write_model_card(model_card_dir, src_lang, tgt_lang, model_name):
+
+ texts = {
+ "en": "Machine learning is great, isn't it?",
+ "ru": "Машинное обучение - это здорово, не так ли?",
+ "de": "Maschinelles Lernen ist großartig, nicht wahr?",
+ }
+
+ # BLUE scores as follows:
+ # "pair": [fairseq, transformers]
+ scores = {
+ "wmt16-en-de-dist-12-1": [28.3, 27.52],
+ "wmt16-en-de-dist-6-1": [27.4, 27.11],
+ "wmt16-en-de-12-1": [26.9, 25.75],
+ }
+ pair = f"{src_lang}-{tgt_lang}"
+
+ readme = f"""
+---
+language:
+- {src_lang}
+- {tgt_lang}
+thumbnail:
+tags:
+- translation
+- wmt16
+- allenai
+license: apache-2.0
+datasets:
+- wmt16
+metrics:
+- bleu
+---
+
+# FSMT
+
+## Model description
+
+This is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.
+
+For more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).
+
+All 3 models are available:
+
+* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)
+* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)
+* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)
+
+
+## Intended uses & limitations
+
+#### How to use
+
+```python
+from transformers import FSMTForConditionalGeneration, FSMTTokenizer
+mname = "allenai/{model_name}"
+tokenizer = FSMTTokenizer.from_pretrained(mname)
+model = FSMTForConditionalGeneration.from_pretrained(mname)
+
+input = "{texts[src_lang]}"
+input_ids = tokenizer.encode(input, return_tensors="pt")
+outputs = model.generate(input_ids)
+decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
+print(decoded) # {texts[tgt_lang]}
+
+```
+
+#### Limitations and bias
+
+
+## Training data
+
+Pretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).
+
+## Eval results
+
+Here are the BLEU scores:
+
+model | fairseq | transformers
+-------|---------|----------
+{model_name} | {scores[model_name][0]} | {scores[model_name][1]}
+
+The score is slightly below the score reported in the paper, as the researchers don't use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.
+
+The score was calculated using this code:
+
+```bash
+git clone https://github.com/huggingface/transformers
+cd transformers
+export PAIR={pair}
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+export NUM_BEAMS=5
+mkdir -p $DATA_DIR
+sacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target
+echo $PAIR
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+```
+
+## Data Sources
+
+- [training, etc.](http://www.statmt.org/wmt16/)
+- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)
+
+
+### BibTeX entry and citation info
+
+```
+@misc{{kasai2020deep,
+ title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},
+ author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},
+ year={{2020}},
+ eprint={{2006.10369}},
+ archivePrefix={{arXiv}},
+ primaryClass={{cs.CL}}
+}}
+```
+
+"""
+ model_card_dir.mkdir(parents=True, exist_ok=True)
+ path = os.path.join(model_card_dir, "README.md")
+ print(f"Generating {path}")
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(readme)
+
+# make sure we are under the root of the project
+repo_dir = Path(__file__).resolve().parent.parent.parent
+model_cards_dir = repo_dir / "model_cards"
+
+for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]:
+ model_card_dir = model_cards_dir / "allenai" / model_name
+ write_model_card(model_card_dir, src_lang="en", tgt_lang="de", model_name=model_name)
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/gen-card-allenai-wmt19.py b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/gen-card-allenai-wmt19.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7d727ff2a149f5a2912af28e0707fb974f9b267
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/gen-card-allenai-wmt19.py
@@ -0,0 +1,153 @@
+#!/usr/bin/env python
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Usage:
+# ./gen-card-allenai-wmt19.py
+
+import os
+from pathlib import Path
+
+
+def write_model_card(model_card_dir, src_lang, tgt_lang, model_name):
+
+ texts = {
+ "en": "Machine learning is great, isn't it?",
+ "ru": "Машинное обучение - это здорово, не так ли?",
+ "de": "Maschinelles Lernen ist großartig, nicht wahr?",
+ }
+
+ # BLUE scores as follows:
+ # "pair": [fairseq, transformers]
+ scores = {
+ "wmt19-de-en-6-6-base": [0, 38.37],
+ "wmt19-de-en-6-6-big": [0, 39.90],
+ }
+ pair = f"{src_lang}-{tgt_lang}"
+
+ readme = f"""
+---
+
+language:
+- {src_lang}
+- {tgt_lang}
+thumbnail:
+tags:
+- translation
+- wmt19
+- allenai
+license: apache-2.0
+datasets:
+- wmt19
+metrics:
+- bleu
+---
+
+# FSMT
+
+## Model description
+
+This is a ported version of fairseq-based [wmt19 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.
+
+For more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).
+
+2 models are available:
+
+* [wmt19-de-en-6-6-big](https://huggingface.co/allenai/wmt19-de-en-6-6-big)
+* [wmt19-de-en-6-6-base](https://huggingface.co/allenai/wmt19-de-en-6-6-base)
+
+
+## Intended uses & limitations
+
+#### How to use
+
+```python
+from transformers import FSMTForConditionalGeneration, FSMTTokenizer
+mname = "allenai/{model_name}"
+tokenizer = FSMTTokenizer.from_pretrained(mname)
+model = FSMTForConditionalGeneration.from_pretrained(mname)
+
+input = "{texts[src_lang]}"
+input_ids = tokenizer.encode(input, return_tensors="pt")
+outputs = model.generate(input_ids)
+decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
+print(decoded) # {texts[tgt_lang]}
+
+```
+
+#### Limitations and bias
+
+
+## Training data
+
+Pretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).
+
+## Eval results
+
+Here are the BLEU scores:
+
+model | transformers
+-------|---------
+{model_name} | {scores[model_name][1]}
+
+The score was calculated using this code:
+
+```bash
+git clone https://github.com/huggingface/transformers
+cd transformers
+export PAIR={pair}
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+export NUM_BEAMS=5
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+echo $PAIR
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+```
+
+## Data Sources
+
+- [training, etc.](http://www.statmt.org/wmt19/)
+- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)
+
+
+### BibTeX entry and citation info
+
+```
+@misc{{kasai2020deep,
+ title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},
+ author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},
+ year={{2020}},
+ eprint={{2006.10369}},
+ archivePrefix={{arXiv}},
+ primaryClass={{cs.CL}}
+}}
+```
+
+"""
+ model_card_dir.mkdir(parents=True, exist_ok=True)
+ path = os.path.join(model_card_dir, "README.md")
+ print(f"Generating {path}")
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(readme)
+
+# make sure we are under the root of the project
+repo_dir = Path(__file__).resolve().parent.parent.parent
+model_cards_dir = repo_dir / "model_cards"
+
+for model_name in ["wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big"]:
+ model_card_dir = model_cards_dir / "allenai" / model_name
+ write_model_card(model_card_dir, src_lang="de", tgt_lang="en", model_name=model_name)
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/gen-card-facebook-wmt19.py b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/gen-card-facebook-wmt19.py
new file mode 100644
index 0000000000000000000000000000000000000000..58df676cbc9493dfd7d589b6b725f51ba2fc548c
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/gen-card-facebook-wmt19.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Usage:
+# ./gen-card-facebook-wmt19.py
+
+import os
+from pathlib import Path
+
+
+def write_model_card(model_card_dir, src_lang, tgt_lang):
+
+ texts = {
+ "en": "Machine learning is great, isn't it?",
+ "ru": "Машинное обучение - это здорово, не так ли?",
+ "de": "Maschinelles Lernen ist großartig, oder?",
+ }
+
+ # BLUE scores as follows:
+ # "pair": [fairseq, transformers]
+ scores = {
+ "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"],
+ "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"],
+ "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"],
+ "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"],
+ }
+ pair = f"{src_lang}-{tgt_lang}"
+
+ readme = f"""
+---
+language:
+- {src_lang}
+- {tgt_lang}
+thumbnail:
+tags:
+- translation
+- wmt19
+- facebook
+license: apache-2.0
+datasets:
+- wmt19
+metrics:
+- bleu
+---
+
+# FSMT
+
+## Model description
+
+This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.
+
+For more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).
+
+The abbreviation FSMT stands for FairSeqMachineTranslation
+
+All four models are available:
+
+* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)
+* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)
+* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)
+* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)
+
+## Intended uses & limitations
+
+#### How to use
+
+```python
+from transformers import FSMTForConditionalGeneration, FSMTTokenizer
+mname = "facebook/wmt19-{src_lang}-{tgt_lang}"
+tokenizer = FSMTTokenizer.from_pretrained(mname)
+model = FSMTForConditionalGeneration.from_pretrained(mname)
+
+input = "{texts[src_lang]}"
+input_ids = tokenizer.encode(input, return_tensors="pt")
+outputs = model.generate(input_ids)
+decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
+print(decoded) # {texts[tgt_lang]}
+
+```
+
+#### Limitations and bias
+
+- The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)
+
+## Training data
+
+Pretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).
+
+## Eval results
+
+pair | fairseq | transformers
+-------|---------|----------
+{pair} | {scores[pair][0]} | {scores[pair][1]}
+
+The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:
+- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).
+- re-ranking
+
+The score was calculated using this code:
+
+```bash
+git clone https://github.com/huggingface/transformers
+cd transformers
+export PAIR={pair}
+export DATA_DIR=data/$PAIR
+export SAVE_DIR=data/$PAIR
+export BS=8
+export NUM_BEAMS=15
+mkdir -p $DATA_DIR
+sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
+sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
+echo $PAIR
+PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
+```
+note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.
+
+## Data Sources
+
+- [training, etc.](http://www.statmt.org/wmt19/)
+- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)
+
+
+### BibTeX entry and citation info
+
+```bibtex
+@inproceedings{{...,
+ year={{2020}},
+ title={{Facebook FAIR's WMT19 News Translation Task Submission}},
+ author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},
+ booktitle={{Proc. of WMT}},
+}}
+```
+
+
+## TODO
+
+- port model ensemble (fairseq uses 4 model checkpoints)
+
+"""
+ os.makedirs(model_card_dir, exist_ok=True)
+ path = os.path.join(model_card_dir, "README.md")
+ print(f"Generating {path}")
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(readme)
+
+# make sure we are under the root of the project
+repo_dir = Path(__file__).resolve().parent.parent.parent
+model_cards_dir = repo_dir / "model_cards"
+
+for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
+ base, src_lang, tgt_lang = model_name.split("-")
+ model_card_dir = model_cards_dir / "facebook" / model_name
+ write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/s3-move.sh b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/s3-move.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1041ca25d8df4fc96408a868abecedeed8c8a048
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/s3-move.sh
@@ -0,0 +1,116 @@
+
+# this is the process of uploading the updated models to s3. As I can't upload them directly to the correct orgs, this script shows how this is done
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+1. upload updated models to my account
+
+transformers-cli upload -y wmt19-ru-en
+transformers-cli upload -y wmt19-en-ru
+transformers-cli upload -y wmt19-de-en
+transformers-cli upload -y wmt19-en-de
+transformers-cli upload -y wmt19-de-en-6-6-base
+transformers-cli upload -y wmt19-de-en-6-6-big
+transformers-cli upload -y wmt16-en-de-dist-12-1
+transformers-cli upload -y wmt16-en-de-dist-6-1
+transformers-cli upload -y wmt16-en-de-12-1
+
+
+2. ask someone to move them to:
+
+* to facebook: "wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"
+* to allenai: "wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1", "wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big"
+
+export b="s3://models.huggingface.co/bert"
+stas_to_fb () {
+ src=$1
+ shift
+ aws s3 sync $b/stas/$src $b/facebook/$src $@
+}
+
+stas_to_allenai () {
+ src=$1
+ shift
+ aws s3 sync $b/stas/$src $b/allenai/$src $@
+}
+
+stas_to_fb wmt19-en-ru
+stas_to_fb wmt19-ru-en
+stas_to_fb wmt19-en-de
+stas_to_fb wmt19-de-en
+
+stas_to_allenai wmt16-en-de-dist-12-1
+stas_to_allenai wmt16-en-de-dist-6-1
+stas_to_allenai wmt16-en-de-6-1
+stas_to_allenai wmt16-en-de-12-1
+stas_to_allenai wmt19-de-en-6-6-base
+stas_to_allenai wmt19-de-en-6-6-big
+
+
+3. and then remove all these model files from my account
+
+transformers-cli s3 rm wmt16-en-de-12-1/config.json
+transformers-cli s3 rm wmt16-en-de-12-1/merges.txt
+transformers-cli s3 rm wmt16-en-de-12-1/pytorch_model.bin
+transformers-cli s3 rm wmt16-en-de-12-1/tokenizer_config.json
+transformers-cli s3 rm wmt16-en-de-12-1/vocab-src.json
+transformers-cli s3 rm wmt16-en-de-12-1/vocab-tgt.json
+transformers-cli s3 rm wmt16-en-de-dist-12-1/config.json
+transformers-cli s3 rm wmt16-en-de-dist-12-1/merges.txt
+transformers-cli s3 rm wmt16-en-de-dist-12-1/pytorch_model.bin
+transformers-cli s3 rm wmt16-en-de-dist-12-1/tokenizer_config.json
+transformers-cli s3 rm wmt16-en-de-dist-12-1/vocab-src.json
+transformers-cli s3 rm wmt16-en-de-dist-12-1/vocab-tgt.json
+transformers-cli s3 rm wmt16-en-de-dist-6-1/config.json
+transformers-cli s3 rm wmt16-en-de-dist-6-1/merges.txt
+transformers-cli s3 rm wmt16-en-de-dist-6-1/pytorch_model.bin
+transformers-cli s3 rm wmt16-en-de-dist-6-1/tokenizer_config.json
+transformers-cli s3 rm wmt16-en-de-dist-6-1/vocab-src.json
+transformers-cli s3 rm wmt16-en-de-dist-6-1/vocab-tgt.json
+transformers-cli s3 rm wmt19-de-en-6-6-base/config.json
+transformers-cli s3 rm wmt19-de-en-6-6-base/merges.txt
+transformers-cli s3 rm wmt19-de-en-6-6-base/pytorch_model.bin
+transformers-cli s3 rm wmt19-de-en-6-6-base/tokenizer_config.json
+transformers-cli s3 rm wmt19-de-en-6-6-base/vocab-src.json
+transformers-cli s3 rm wmt19-de-en-6-6-base/vocab-tgt.json
+transformers-cli s3 rm wmt19-de-en-6-6-big/config.json
+transformers-cli s3 rm wmt19-de-en-6-6-big/merges.txt
+transformers-cli s3 rm wmt19-de-en-6-6-big/pytorch_model.bin
+transformers-cli s3 rm wmt19-de-en-6-6-big/tokenizer_config.json
+transformers-cli s3 rm wmt19-de-en-6-6-big/vocab-src.json
+transformers-cli s3 rm wmt19-de-en-6-6-big/vocab-tgt.json
+transformers-cli s3 rm wmt19-de-en/config.json
+transformers-cli s3 rm wmt19-de-en/merges.txt
+transformers-cli s3 rm wmt19-de-en/pytorch_model.bin
+transformers-cli s3 rm wmt19-de-en/tokenizer_config.json
+transformers-cli s3 rm wmt19-de-en/vocab-src.json
+transformers-cli s3 rm wmt19-de-en/vocab-tgt.json
+transformers-cli s3 rm wmt19-en-de/config.json
+transformers-cli s3 rm wmt19-en-de/merges.txt
+transformers-cli s3 rm wmt19-en-de/pytorch_model.bin
+transformers-cli s3 rm wmt19-en-de/tokenizer_config.json
+transformers-cli s3 rm wmt19-en-de/vocab-src.json
+transformers-cli s3 rm wmt19-en-de/vocab-tgt.json
+transformers-cli s3 rm wmt19-en-ru/config.json
+transformers-cli s3 rm wmt19-en-ru/merges.txt
+transformers-cli s3 rm wmt19-en-ru/pytorch_model.bin
+transformers-cli s3 rm wmt19-en-ru/tokenizer_config.json
+transformers-cli s3 rm wmt19-en-ru/vocab-src.json
+transformers-cli s3 rm wmt19-en-ru/vocab-tgt.json
+transformers-cli s3 rm wmt19-ru-en/config.json
+transformers-cli s3 rm wmt19-ru-en/merges.txt
+transformers-cli s3 rm wmt19-ru-en/pytorch_model.bin
+transformers-cli s3 rm wmt19-ru-en/tokenizer_config.json
+transformers-cli s3 rm wmt19-ru-en/vocab-src.json
+transformers-cli s3 rm wmt19-ru-en/vocab-tgt.json
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/tests-to-run.sh b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/tests-to-run.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c4e08039ed10920950a2dd1d8de761dba7e58b55
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/fsmt/tests-to-run.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# these scripts need to be run before any changes to FSMT-related code - it should cover all bases
+
+CUDA_VISIBLE_DEVICES="" RUN_SLOW=1 pytest --disable-warnings tests/test_tokenization_fsmt.py tests/test_configuration_auto.py tests/test_modeling_fsmt.py examples/seq2seq/test_fsmt_bleu_score.py
+RUN_SLOW=1 pytest --disable-warnings tests/test_tokenization_fsmt.py tests/test_configuration_auto.py tests/test_modeling_fsmt.py examples/seq2seq/test_fsmt_bleu_score.py
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/pegasus/build_test_sample_spm_no_bos.py b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/pegasus/build_test_sample_spm_no_bos.py
new file mode 100644
index 0000000000000000000000000000000000000000..f223304a7717892d3ef422fa6fc44327f002b5b5
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/pegasus/build_test_sample_spm_no_bos.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# this script builds a small sample spm file tests/fixtures/test_sentencepiece_no_bos.model, with features needed by pegasus
+
+# 1. pip install sentencepiece
+#
+# 2. wget https://raw.githubusercontent.com/google/sentencepiece/master/data/botchan.txt
+
+# 3. build
+import sentencepiece as spm
+
+
+# pegasus:
+# 1. no bos
+# 2. eos_id is 1
+# 3. unk_id is 2
+# build a sample spm file accordingly
+spm.SentencePieceTrainer.train('--input=botchan.txt --model_prefix=test_sentencepiece_no_bos --bos_id=-1 --unk_id=2 --eos_id=1 --vocab_size=1000')
+
+# 4. now update the fixture
+# mv test_sentencepiece_no_bos.model ../../tests/fixtures/
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/stale.py b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/stale.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf7c6670c431e152b63d3ea772e1a3523cee3d37
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/stale.py
@@ -0,0 +1,74 @@
+# Copyright 2021 The HuggingFace Team, the AllenNLP library authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Script to close stale issue. Taken in part from the AllenNLP repository.
+https://github.com/allenai/allennlp.
+"""
+import os
+from datetime import datetime as dt
+
+import github.GithubException
+from github import Github
+
+
+LABELS_TO_EXEMPT = [
+ "good first issue",
+ "good second issue",
+ "good difficult issue",
+ "feature request",
+ "new model",
+ "wip",
+]
+
+
+def main():
+ g = Github(os.environ["GITHUB_TOKEN"])
+ repo = g.get_repo("huggingface/transformers")
+ open_issues = repo.get_issues(state="open")
+
+ for i, issue in enumerate(open_issues):
+ print(i, issue)
+ comments = sorted(list(issue.get_comments()), key=lambda i: i.created_at, reverse=True)
+ last_comment = comments[0] if len(comments) > 0 else None
+ if (
+ last_comment is not None and last_comment.user.login == "github-actions[bot]"
+ and (dt.utcnow() - issue.updated_at.replace(tzinfo=None)).days > 7
+ and (dt.utcnow() - issue.created_at.replace(tzinfo=None)).days >= 30
+ and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels())
+ ):
+ # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.")
+ try:
+ issue.edit(state="closed")
+ except github.GithubException as e:
+ print("Couldn't close the issue:", repr(e))
+ elif (
+ (dt.utcnow() - issue.updated_at.replace(tzinfo=None)).days > 23
+ and (dt.utcnow() - issue.created_at.replace(tzinfo=None)).days >= 30
+ and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels())
+ ):
+ # print(f"Would add stale comment to {issue.number}")
+ try:
+ issue.create_comment(
+ "This issue has been automatically marked as stale because it has not had "
+ "recent activity. If you think this still needs to be addressed "
+ "please comment on this thread.\n\nPlease note that issues that do not follow the "
+ "[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) "
+ "are likely to be ignored."
+ )
+ except github.GithubException as e:
+ print("Couldn't create comment:", repr(e))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/tatoeba/README.md b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/tatoeba/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..b142039b246ee62ba0a2f01883112e85881c57f8
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/tatoeba/README.md
@@ -0,0 +1,72 @@
+
+
+Setup transformers following instructions in README.md, (I would fork first).
+```bash
+git clone git@github.com:huggingface/transformers.git
+cd transformers
+pip install -e .
+pip install pandas GitPython wget
+```
+
+Get required metadata
+```bash
+curl https://cdn-datasets.huggingface.co/language_codes/language-codes-3b2.csv > language-codes-3b2.csv
+curl https://cdn-datasets.huggingface.co/language_codes/iso-639-3.csv > iso-639-3.csv
+```
+
+Install Tatoeba-Challenge repo inside transformers
+```bash
+git clone git@github.com:Helsinki-NLP/Tatoeba-Challenge.git
+```
+
+To convert a few models, call the conversion script from command line:
+```bash
+python src/transformers/models/marian/convert_marian_tatoeba_to_pytorch.py --models heb-eng eng-heb --save_dir converted
+```
+
+To convert lots of models you can pass your list of Tatoeba model names to `resolver.convert_models` in a python client or script.
+
+```python
+from transformers.convert_marian_tatoeba_to_pytorch import TatoebaConverter
+resolver = TatoebaConverter(save_dir='converted')
+resolver.convert_models(['heb-eng', 'eng-heb'])
+```
+
+
+### Upload converted models
+Since version v3.5.0, the model sharing workflow is switched to git-based system . Refer to [model sharing doc](https://huggingface.co/transformers/main/model_sharing.html#model-sharing-and-uploading) for more details.
+
+To upload all converted models,
+
+1. Install [git-lfs](https://git-lfs.github.com/).
+
+2. Login to `huggingface-cli`
+
+```bash
+huggingface-cli login
+```
+
+3. Run the `upload_models` script
+
+```bash
+./scripts/tatoeba/upload_models.sh
+```
+
+
+### Modifications
+- To change naming logic, change the code near `os.rename`. The model card creation code may also need to change.
+- To change model card content, you must modify `TatoebaCodeResolver.write_model_card`
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/tatoeba/upload_models.sh b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/tatoeba/upload_models.sh
new file mode 100644
index 0000000000000000000000000000000000000000..536eb5bc68c4c47cbf152a028af367003aff5349
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/scripts/tatoeba/upload_models.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+
+for FILE in converted/*; do
+ model_name=`basename $FILE`
+ huggingface-cli repo create $model_name -y
+ git clone https://huggingface.co/Helsinki-NLP/$model_name
+ mv $FILE/* $model_name/
+ cd $model_name
+ git add . && git commit -m "initial commit"
+ git push
+ cd ..
+done
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/setup.py b/tasks/tasksmith-5dd11b34cce1/environment/source/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..a78bb20dd0a4b0f30a0dff5969497b9cf53e1745
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/setup.py
@@ -0,0 +1,486 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+Simple check list from AllenNLP repo: https://github.com/allenai/allennlp/blob/main/setup.py
+
+To create the package for pypi.
+
+1. Create the release branch named: v-release, for example v4.19-release. For a patch release checkout the
+ current release branch.
+
+ If releasing on a special branch, copy the updated README.md on the main branch for the commit you will make
+ for the post-release and run `make fix-copies` on the main branch as well.
+
+2. Run `make pre-release` (or `make pre-patch` for a patch release) and commit these changes with the message:
+ "Release: " and push.
+
+3. Go back to the main branch and run `make post-release` then `make fix-copies`. Commit these changes with the
+ message "v.dev.0" and push to main.
+
+# If you were just cutting the branch in preparation for a release, you can stop here for now.
+
+4. Wait for the tests on the release branch to be completed and be green (otherwise revert and fix bugs)
+
+5. On the release branch, add a tag in git to mark the release: "git tag v -m 'Adds tag v for pypi' "
+ Push the tag to git: git push --tags origin v-release
+
+6. Build both the sources and the wheel. Do not change anything in setup.py between
+ creating the wheel and the source distribution (obviously).
+
+ Run `make build-release`. This will build the release and do some sanity checks for you. If this ends with an error
+ message, you need to fix things before going further.
+
+ You should now have a /dist directory with both .whl and .tar.gz source versions.
+
+7. Check that everything looks correct by uploading the package to the pypi test server:
+
+ twine upload dist/* -r testpypi
+ (pypi suggest using twine as other methods upload files via plaintext.)
+ You may have to specify the repository url, use the following command then:
+ twine upload dist/* -r testpypi --repository-url=https://test.pypi.org/legacy/
+
+ Check that you can install it in a virtualenv by running:
+ pip install -i https://testpypi.python.org/pypi transformers
+
+ Check you can run the following commands:
+ python -c "from transformers import pipeline; classifier = pipeline('text-classification'); print(classifier('What a nice release'))"
+ python -c "from transformers import *"
+ python utils/check_build.py --check_lib
+
+ If making a patch release, double check the bug you are patching is indeed resolved.
+
+8. Upload the final version to actual pypi:
+ twine upload dist/* -r pypi
+
+9. Copy the release notes from RELEASE.md to the tag in github once everything is looking hunky-dory.
+"""
+
+import os
+import re
+import shutil
+from pathlib import Path
+
+from setuptools import Command, find_packages, setup
+
+
+# Remove stale transformers.egg-info directory to avoid https://github.com/pypa/pip/issues/5466
+stale_egg_info = Path(__file__).parent / "transformers.egg-info"
+if stale_egg_info.exists():
+ print(
+ (
+ "Warning: {} exists.\n\n"
+ "If you recently updated transformers to 3.0 or later, this is expected,\n"
+ "but it may prevent transformers from installing in editable mode.\n\n"
+ "This directory is automatically generated by Python's packaging tools.\n"
+ "I will remove it now.\n\n"
+ "See https://github.com/pypa/pip/issues/5466 for details.\n"
+ ).format(stale_egg_info)
+ )
+ shutil.rmtree(stale_egg_info)
+
+
+# IMPORTANT:
+# 1. all dependencies should be listed here with their version requirements if any
+# 2. once modified, run: `make deps_table_update` to update src/transformers/dependency_versions_table.py
+_deps = [
+ "Pillow>=10.0.1,<=15.0",
+ "accelerate>=0.26.0",
+ "av==9.2.0", # Latest version of PyAV (10.0.0) has issues with audio stream.
+ "beautifulsoup4",
+ "blobfile",
+ "codecarbon>=2.8.1",
+ "cookiecutter==1.7.3",
+ "dataclasses",
+ "datasets!=2.5.0",
+ "deepspeed>=0.9.3",
+ "diffusers",
+ "dill<0.3.5",
+ "evaluate>=0.2.0",
+ "faiss-cpu",
+ "fastapi",
+ "filelock",
+ "flax>=0.4.1,<=0.7.0",
+ "fsspec<2023.10.0",
+ "ftfy",
+ "fugashi>=1.0",
+ "GitPython<3.1.19",
+ "hf-doc-builder>=0.3.0",
+ "huggingface-hub>=0.24.0,<1.0",
+ "importlib_metadata",
+ "ipadic>=1.0.0,<2.0",
+ "isort>=5.5.4",
+ "jax>=0.4.1,<=0.4.13",
+ "jaxlib>=0.4.1,<=0.4.13",
+ "jieba",
+ "jinja2>=3.1.0",
+ "kenlm",
+ # Keras pin - this is to make sure Keras 3 doesn't destroy us. Remove or change when we have proper support.
+ "keras>2.9,<2.16",
+ "keras-nlp>=0.3.1,<0.14.0", # keras-nlp 0.14 doesn't support keras 2, see pin on keras.
+ "librosa",
+ "nltk<=3.8.1",
+ "natten>=0.14.6,<0.15.0",
+ "numpy>=1.17",
+ "onnxconverter-common",
+ "onnxruntime-tools>=1.4.2",
+ "onnxruntime>=1.4.0",
+ "opencv-python",
+ "optimum-benchmark>=0.3.0",
+ "optuna",
+ "optax>=0.0.8,<=0.1.4",
+ "packaging>=20.0",
+ "parameterized",
+ "phonemizer",
+ "protobuf",
+ "psutil",
+ "pyyaml>=5.1",
+ "pydantic",
+ "pytest>=7.2.0,<8.0.0",
+ "pytest-asyncio",
+ "pytest-timeout",
+ "pytest-xdist",
+ "python>=3.9.0",
+ "ray[tune]>=2.7.0",
+ "regex!=2019.12.17",
+ "requests",
+ "rhoknp>=1.1.0,<1.3.1",
+ "rjieba",
+ "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1",
+ "ruff==0.5.1",
+ "sacrebleu>=1.4.12,<2.0.0",
+ "sacremoses",
+ "safetensors>=0.4.1",
+ "sagemaker>=2.31.0",
+ "schedulefree>=1.2.6",
+ "scikit-learn",
+ "scipy<1.13.0", # SciPy >= 1.13.0 is not supported with the current jax pin (`jax>=0.4.1,<=0.4.13`)
+ "sentencepiece>=0.1.91,!=0.1.92",
+ "sigopt",
+ "starlette",
+ "sudachipy>=0.6.6",
+ "sudachidict_core>=20220729",
+ "tensorboard",
+ # TensorFlow pin. When changing this value, update examples/tensorflow/_tests_requirements.txt accordingly
+ "tensorflow-cpu>2.9,<2.16",
+ "tensorflow>2.9,<2.16",
+ "tensorflow-text<2.16",
+ "tensorflow-probability<0.24",
+ "tf2onnx",
+ "timeout-decorator",
+ "tiktoken",
+ "timm<=1.0.11",
+ "tokenizers>=0.21,<0.22",
+ "torch",
+ "torchaudio",
+ "torchvision",
+ "pyctcdecode>=0.4.0",
+ "tqdm>=4.27",
+ "unidic>=1.0.2",
+ "unidic_lite>=1.0.7",
+ "urllib3<2.0.0",
+ "uvicorn",
+ "pytest-rich",
+ "libcst",
+ "rich",
+]
+
+
+# this is a lookup table with items like:
+#
+# tokenizers: "tokenizers==0.9.4"
+# packaging: "packaging"
+#
+# some of the values are versioned whereas others aren't.
+deps = {b: a for a, b in (re.findall(r"^(([^!=<>~ ]+)(?:[!=<>~ ].*)?$)", x)[0] for x in _deps)}
+
+# since we save this data in src/transformers/dependency_versions_table.py it can be easily accessed from
+# anywhere. If you need to quickly access the data from this table in a shell, you can do so easily with:
+#
+# python -c 'import sys; from transformers.dependency_versions_table import deps; \
+# print(" ".join([ deps[x] for x in sys.argv[1:]]))' tokenizers datasets
+#
+# Just pass the desired package names to that script as it's shown with 2 packages above.
+#
+# If transformers is not yet installed and the work is done from the cloned repo remember to add `PYTHONPATH=src` to the script above
+#
+# You can then feed this for example to `pip`:
+#
+# pip install -U $(python -c 'import sys; from transformers.dependency_versions_table import deps; \
+# print(" ".join([deps[x] for x in sys.argv[1:]]))' tokenizers datasets)
+#
+
+
+def deps_list(*pkgs):
+ return [deps[pkg] for pkg in pkgs]
+
+
+class DepsTableUpdateCommand(Command):
+ """
+ A custom distutils command that updates the dependency table.
+ usage: python setup.py deps_table_update
+ """
+
+ description = "build runtime dependency table"
+ user_options = [
+ # format: (long option, short option, description).
+ ("dep-table-update", None, "updates src/transformers/dependency_versions_table.py"),
+ ]
+
+ def initialize_options(self):
+ pass
+
+ def finalize_options(self):
+ pass
+
+ def run(self):
+ entries = "\n".join([f' "{k}": "{v}",' for k, v in deps.items()])
+ content = [
+ "# THIS FILE HAS BEEN AUTOGENERATED. To update:",
+ "# 1. modify the `_deps` dict in setup.py",
+ "# 2. run `make deps_table_update``",
+ "deps = {",
+ entries,
+ "}",
+ "",
+ ]
+ target = "src/transformers/dependency_versions_table.py"
+ print(f"updating {target}")
+ with open(target, "w", encoding="utf-8", newline="\n") as f:
+ f.write("\n".join(content))
+
+
+extras = {}
+
+extras["ja"] = deps_list("fugashi", "ipadic", "unidic_lite", "unidic", "sudachipy", "sudachidict_core", "rhoknp")
+extras["sklearn"] = deps_list("scikit-learn")
+
+extras["tf"] = deps_list("tensorflow", "onnxconverter-common", "tf2onnx", "tensorflow-text", "keras-nlp")
+extras["tf-cpu"] = deps_list(
+ "keras",
+ "tensorflow-cpu",
+ "onnxconverter-common",
+ "tf2onnx",
+ "tensorflow-text",
+ "keras-nlp",
+ "tensorflow-probability",
+)
+
+extras["torch"] = deps_list("torch", "accelerate")
+extras["accelerate"] = deps_list("accelerate")
+
+if os.name == "nt": # windows
+ extras["retrieval"] = deps_list("datasets") # faiss is not supported on windows
+ extras["flax"] = [] # jax is not supported on windows
+else:
+ extras["retrieval"] = deps_list("faiss-cpu", "datasets")
+ extras["flax"] = deps_list("jax", "jaxlib", "flax", "optax", "scipy")
+
+extras["tokenizers"] = deps_list("tokenizers")
+extras["ftfy"] = deps_list("ftfy")
+extras["onnxruntime"] = deps_list("onnxruntime", "onnxruntime-tools")
+extras["onnx"] = deps_list("onnxconverter-common", "tf2onnx") + extras["onnxruntime"]
+extras["modelcreation"] = deps_list("cookiecutter")
+
+extras["sagemaker"] = deps_list("sagemaker")
+extras["deepspeed"] = deps_list("deepspeed") + extras["accelerate"]
+extras["optuna"] = deps_list("optuna")
+extras["ray"] = deps_list("ray[tune]")
+extras["sigopt"] = deps_list("sigopt")
+
+extras["integrations"] = extras["optuna"] + extras["ray"] + extras["sigopt"]
+
+extras["serving"] = deps_list("pydantic", "uvicorn", "fastapi", "starlette")
+extras["audio"] = deps_list("librosa", "pyctcdecode", "phonemizer", "kenlm")
+# `pip install ".[speech]"` is deprecated and `pip install ".[torch-speech]"` should be used instead
+extras["speech"] = deps_list("torchaudio") + extras["audio"]
+extras["torch-speech"] = deps_list("torchaudio") + extras["audio"]
+extras["tf-speech"] = extras["audio"]
+extras["flax-speech"] = extras["audio"]
+extras["vision"] = deps_list("Pillow")
+extras["timm"] = deps_list("timm")
+extras["torch-vision"] = deps_list("torchvision") + extras["vision"]
+extras["natten"] = deps_list("natten")
+extras["codecarbon"] = deps_list("codecarbon")
+extras["video"] = deps_list("av")
+
+extras["sentencepiece"] = deps_list("sentencepiece", "protobuf")
+extras["tiktoken"] = deps_list("tiktoken", "blobfile")
+extras["testing"] = (
+ deps_list(
+ "pytest",
+ "pytest-asyncio",
+ "pytest-rich",
+ "pytest-xdist",
+ "timeout-decorator",
+ "parameterized",
+ "psutil",
+ "datasets",
+ "dill",
+ "evaluate",
+ "pytest-timeout",
+ "ruff",
+ "sacrebleu",
+ "rouge-score",
+ "nltk",
+ "GitPython",
+ "sacremoses",
+ "rjieba",
+ "beautifulsoup4",
+ "tensorboard",
+ "pydantic",
+ "sentencepiece",
+ )
+ + extras["retrieval"]
+ + extras["modelcreation"]
+)
+
+extras["deepspeed-testing"] = extras["deepspeed"] + extras["testing"] + extras["optuna"] + extras["sentencepiece"]
+extras["ruff"] = deps_list("ruff")
+extras["quality"] = deps_list("datasets", "isort", "ruff", "GitPython", "urllib3", "libcst", "rich")
+
+extras["all"] = (
+ extras["tf"]
+ + extras["torch"]
+ + extras["flax"]
+ + extras["sentencepiece"]
+ + extras["tokenizers"]
+ + extras["torch-speech"]
+ + extras["vision"]
+ + extras["integrations"]
+ + extras["timm"]
+ + extras["torch-vision"]
+ + extras["codecarbon"]
+ + extras["accelerate"]
+ + extras["video"]
+)
+
+
+extras["dev-torch"] = (
+ extras["testing"]
+ + extras["torch"]
+ + extras["sentencepiece"]
+ + extras["tokenizers"]
+ + extras["torch-speech"]
+ + extras["vision"]
+ + extras["integrations"]
+ + extras["timm"]
+ + extras["torch-vision"]
+ + extras["codecarbon"]
+ + extras["quality"]
+ + extras["ja"]
+ + extras["sklearn"]
+ + extras["modelcreation"]
+ + extras["onnxruntime"]
+)
+extras["dev-tensorflow"] = (
+ extras["testing"]
+ + extras["tf"]
+ + extras["sentencepiece"]
+ + extras["tokenizers"]
+ + extras["vision"]
+ + extras["quality"]
+ + extras["sklearn"]
+ + extras["modelcreation"]
+ + extras["onnx"]
+ + extras["tf-speech"]
+)
+extras["dev"] = (
+ extras["all"] + extras["testing"] + extras["quality"] + extras["ja"] + extras["sklearn"] + extras["modelcreation"]
+)
+
+extras["torchhub"] = deps_list(
+ "filelock",
+ "huggingface-hub",
+ "importlib_metadata",
+ "numpy",
+ "packaging",
+ "protobuf",
+ "regex",
+ "requests",
+ "sentencepiece",
+ "torch",
+ "tokenizers",
+ "tqdm",
+)
+
+extras["agents"] = deps_list(
+ "diffusers", "accelerate", "datasets", "torch", "sentencepiece", "opencv-python", "Pillow"
+)
+
+extras["benchmark"] = deps_list("optimum-benchmark")
+
+# when modifying the following list, make sure to update src/transformers/dependency_versions_check.py
+install_requires = [
+ deps["filelock"], # filesystem locks, e.g., to prevent parallel downloads
+ deps["huggingface-hub"],
+ deps["numpy"],
+ deps["packaging"], # utilities from PyPA to e.g., compare versions
+ deps["pyyaml"], # used for the model cards metadata
+ deps["regex"], # for OpenAI GPT
+ deps["requests"], # for downloading models over HTTPS
+ deps["tokenizers"],
+ deps["safetensors"],
+ deps["tqdm"], # progress bars in model download and training scripts
+]
+
+setup(
+ name="transformers",
+ version="4.48.0.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots)
+ author="The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)",
+ author_email="transformers@huggingface.co",
+ description="State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow",
+ long_description=open("README.md", "r", encoding="utf-8").read(),
+ long_description_content_type="text/markdown",
+ keywords="NLP vision speech deep learning transformer pytorch tensorflow jax BERT GPT-2 Wav2Vec2 ViT",
+ license="Apache 2.0 License",
+ url="https://github.com/huggingface/transformers",
+ package_dir={"": "src"},
+ packages=find_packages("src"),
+ include_package_data=True,
+ package_data={"": ["**/*.cu", "**/*.cpp", "**/*.cuh", "**/*.h", "**/*.pyx"]},
+ zip_safe=False,
+ extras_require=extras,
+ entry_points={"console_scripts": ["transformers-cli=transformers.commands.transformers_cli:main"]},
+ python_requires=">=3.9.0",
+ install_requires=list(install_requires),
+ classifiers=[
+ "Development Status :: 5 - Production/Stable",
+ "Intended Audience :: Developers",
+ "Intended Audience :: Education",
+ "Intended Audience :: Science/Research",
+ "License :: OSI Approved :: Apache Software License",
+ "Operating System :: OS Independent",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.9",
+ "Programming Language :: Python :: 3.10",
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
+ ],
+ cmdclass={"deps_table_update": DepsTableUpdateCommand},
+)
+
+extras["tests_torch"] = deps_list()
+extras["tests_tf"] = deps_list()
+extras["tests_flax"] = deps_list()
+extras["tests_torch_and_tf"] = deps_list()
+extras["tests_torch_and_flax"] = deps_list()
+extras["tests_hub"] = deps_list()
+extras["tests_pipelines_torch"] = deps_list()
+extras["tests_pipelines_tf"] = deps_list()
+extras["tests_onnx"] = deps_list()
+extras["tests_examples_torch"] = deps_list()
+extras["tests_examples_tf"] = deps_list()
+extras["tests_custom_tokenizers"] = deps_list()
+extras["tests_exotic_models"] = deps_list()
+extras["consistency"] = deps_list()
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/__init__.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef140cc6d3a843c88c0e1ec9951fe30202542755
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/__init__.py
@@ -0,0 +1,9315 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# When adding a new object to this init, remember to add it twice: once inside the `_import_structure` dictionary and
+# once inside the `if TYPE_CHECKING` branch. The `TYPE_CHECKING` should have import statements as usual, but they are
+# only there for type checking. The `_import_structure` is a dictionary submodule to list of object names, and is used
+# to defer the actual importing for when the objects are requested. This way `import transformers` provides the names
+# in the namespace without actually importing anything (and especially none of the backends).
+
+__version__ = "4.48.0.dev0"
+
+from typing import TYPE_CHECKING
+
+# Check the dependencies satisfy the minimal versions required.
+from . import dependency_versions_check
+from .utils import (
+ OptionalDependencyNotAvailable,
+ _LazyModule,
+ is_bitsandbytes_available,
+ is_essentia_available,
+ is_flax_available,
+ is_g2p_en_available,
+ is_keras_nlp_available,
+ is_librosa_available,
+ is_pretty_midi_available,
+ is_scipy_available,
+ is_sentencepiece_available,
+ is_speech_available,
+ is_tensorflow_text_available,
+ is_tf_available,
+ is_timm_available,
+ is_tokenizers_available,
+ is_torch_available,
+ is_torchaudio_available,
+ is_torchvision_available,
+ is_vision_available,
+ logging,
+)
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+# Base objects, independent of any specific backend
+_import_structure = {
+ "agents": [
+ "Agent",
+ "CodeAgent",
+ "HfApiEngine",
+ "ManagedAgent",
+ "PipelineTool",
+ "ReactAgent",
+ "ReactCodeAgent",
+ "ReactJsonAgent",
+ "Tool",
+ "Toolbox",
+ "ToolCollection",
+ "TransformersEngine",
+ "launch_gradio_demo",
+ "load_tool",
+ "stream_to_gradio",
+ "tool",
+ ],
+ "audio_utils": [],
+ "benchmark": [],
+ "commands": [],
+ "configuration_utils": ["PretrainedConfig"],
+ "convert_graph_to_onnx": [],
+ "convert_slow_tokenizers_checkpoints_to_fast": [],
+ "convert_tf_hub_seq_to_seq_bert_to_pytorch": [],
+ "data": [
+ "DataProcessor",
+ "InputExample",
+ "InputFeatures",
+ "SingleSentenceClassificationProcessor",
+ "SquadExample",
+ "SquadFeatures",
+ "SquadV1Processor",
+ "SquadV2Processor",
+ "glue_compute_metrics",
+ "glue_convert_examples_to_features",
+ "glue_output_modes",
+ "glue_processors",
+ "glue_tasks_num_labels",
+ "squad_convert_examples_to_features",
+ "xnli_compute_metrics",
+ "xnli_output_modes",
+ "xnli_processors",
+ "xnli_tasks_num_labels",
+ ],
+ "data.data_collator": [
+ "DataCollator",
+ "DataCollatorForLanguageModeling",
+ "DataCollatorForPermutationLanguageModeling",
+ "DataCollatorForSeq2Seq",
+ "DataCollatorForSOP",
+ "DataCollatorForTokenClassification",
+ "DataCollatorForWholeWordMask",
+ "DataCollatorWithFlattening",
+ "DataCollatorWithPadding",
+ "DefaultDataCollator",
+ "default_data_collator",
+ ],
+ "data.metrics": [],
+ "data.processors": [],
+ "debug_utils": [],
+ "dependency_versions_check": [],
+ "dependency_versions_table": [],
+ "dynamic_module_utils": [],
+ "feature_extraction_sequence_utils": ["SequenceFeatureExtractor"],
+ "feature_extraction_utils": ["BatchFeature", "FeatureExtractionMixin"],
+ "file_utils": [],
+ "generation": [
+ "AsyncTextIteratorStreamer",
+ "CompileConfig",
+ "GenerationConfig",
+ "TextIteratorStreamer",
+ "TextStreamer",
+ "WatermarkingConfig",
+ ],
+ "hf_argparser": ["HfArgumentParser"],
+ "hyperparameter_search": [],
+ "image_transforms": [],
+ "integrations": [
+ "is_clearml_available",
+ "is_comet_available",
+ "is_dvclive_available",
+ "is_neptune_available",
+ "is_optuna_available",
+ "is_ray_available",
+ "is_ray_tune_available",
+ "is_sigopt_available",
+ "is_tensorboard_available",
+ "is_wandb_available",
+ ],
+ "loss": [],
+ "modelcard": ["ModelCard"],
+ # Losses
+ "modeling_tf_pytorch_utils": [
+ "convert_tf_weight_name_to_pt_weight_name",
+ "load_pytorch_checkpoint_in_tf2_model",
+ "load_pytorch_model_in_tf2_model",
+ "load_pytorch_weights_in_tf2_model",
+ "load_tf2_checkpoint_in_pytorch_model",
+ "load_tf2_model_in_pytorch_model",
+ "load_tf2_weights_in_pytorch_model",
+ ],
+ # Models
+ "models": [],
+ "models.albert": ["AlbertConfig"],
+ "models.align": [
+ "AlignConfig",
+ "AlignProcessor",
+ "AlignTextConfig",
+ "AlignVisionConfig",
+ ],
+ "models.altclip": [
+ "AltCLIPConfig",
+ "AltCLIPProcessor",
+ "AltCLIPTextConfig",
+ "AltCLIPVisionConfig",
+ ],
+ "models.aria": [
+ "AriaConfig",
+ "AriaProcessor",
+ "AriaTextConfig",
+ ],
+ "models.audio_spectrogram_transformer": [
+ "ASTConfig",
+ "ASTFeatureExtractor",
+ ],
+ "models.auto": [
+ "CONFIG_MAPPING",
+ "FEATURE_EXTRACTOR_MAPPING",
+ "IMAGE_PROCESSOR_MAPPING",
+ "MODEL_NAMES_MAPPING",
+ "PROCESSOR_MAPPING",
+ "TOKENIZER_MAPPING",
+ "AutoConfig",
+ "AutoFeatureExtractor",
+ "AutoImageProcessor",
+ "AutoProcessor",
+ "AutoTokenizer",
+ ],
+ "models.autoformer": ["AutoformerConfig"],
+ "models.bamba": ["BambaConfig"],
+ "models.bark": [
+ "BarkCoarseConfig",
+ "BarkConfig",
+ "BarkFineConfig",
+ "BarkProcessor",
+ "BarkSemanticConfig",
+ ],
+ "models.bart": ["BartConfig", "BartTokenizer"],
+ "models.barthez": [],
+ "models.bartpho": [],
+ "models.beit": ["BeitConfig"],
+ "models.bert": [
+ "BasicTokenizer",
+ "BertConfig",
+ "BertTokenizer",
+ "WordpieceTokenizer",
+ ],
+ "models.bert_generation": ["BertGenerationConfig"],
+ "models.bert_japanese": [
+ "BertJapaneseTokenizer",
+ "CharacterTokenizer",
+ "MecabTokenizer",
+ ],
+ "models.bertweet": ["BertweetTokenizer"],
+ "models.big_bird": ["BigBirdConfig"],
+ "models.bigbird_pegasus": ["BigBirdPegasusConfig"],
+ "models.biogpt": [
+ "BioGptConfig",
+ "BioGptTokenizer",
+ ],
+ "models.bit": ["BitConfig"],
+ "models.blenderbot": [
+ "BlenderbotConfig",
+ "BlenderbotTokenizer",
+ ],
+ "models.blenderbot_small": [
+ "BlenderbotSmallConfig",
+ "BlenderbotSmallTokenizer",
+ ],
+ "models.blip": [
+ "BlipConfig",
+ "BlipProcessor",
+ "BlipTextConfig",
+ "BlipVisionConfig",
+ ],
+ "models.blip_2": [
+ "Blip2Config",
+ "Blip2Processor",
+ "Blip2QFormerConfig",
+ "Blip2VisionConfig",
+ ],
+ "models.bloom": ["BloomConfig"],
+ "models.bridgetower": [
+ "BridgeTowerConfig",
+ "BridgeTowerProcessor",
+ "BridgeTowerTextConfig",
+ "BridgeTowerVisionConfig",
+ ],
+ "models.bros": [
+ "BrosConfig",
+ "BrosProcessor",
+ ],
+ "models.byt5": ["ByT5Tokenizer"],
+ "models.camembert": ["CamembertConfig"],
+ "models.canine": [
+ "CanineConfig",
+ "CanineTokenizer",
+ ],
+ "models.chameleon": [
+ "ChameleonConfig",
+ "ChameleonProcessor",
+ "ChameleonVQVAEConfig",
+ ],
+ "models.chinese_clip": [
+ "ChineseCLIPConfig",
+ "ChineseCLIPProcessor",
+ "ChineseCLIPTextConfig",
+ "ChineseCLIPVisionConfig",
+ ],
+ "models.clap": [
+ "ClapAudioConfig",
+ "ClapConfig",
+ "ClapProcessor",
+ "ClapTextConfig",
+ ],
+ "models.clip": [
+ "CLIPConfig",
+ "CLIPProcessor",
+ "CLIPTextConfig",
+ "CLIPTokenizer",
+ "CLIPVisionConfig",
+ ],
+ "models.clipseg": [
+ "CLIPSegConfig",
+ "CLIPSegProcessor",
+ "CLIPSegTextConfig",
+ "CLIPSegVisionConfig",
+ ],
+ "models.clvp": [
+ "ClvpConfig",
+ "ClvpDecoderConfig",
+ "ClvpEncoderConfig",
+ "ClvpFeatureExtractor",
+ "ClvpProcessor",
+ "ClvpTokenizer",
+ ],
+ "models.code_llama": [],
+ "models.codegen": [
+ "CodeGenConfig",
+ "CodeGenTokenizer",
+ ],
+ "models.cohere": ["CohereConfig"],
+ "models.cohere2": ["Cohere2Config"],
+ "models.colpali": [
+ "ColPaliConfig",
+ "ColPaliProcessor",
+ ],
+ "models.conditional_detr": ["ConditionalDetrConfig"],
+ "models.convbert": [
+ "ConvBertConfig",
+ "ConvBertTokenizer",
+ ],
+ "models.convnext": ["ConvNextConfig"],
+ "models.convnextv2": ["ConvNextV2Config"],
+ "models.cpm": [],
+ "models.cpmant": [
+ "CpmAntConfig",
+ "CpmAntTokenizer",
+ ],
+ "models.ctrl": [
+ "CTRLConfig",
+ "CTRLTokenizer",
+ ],
+ "models.cvt": ["CvtConfig"],
+ "models.dac": ["DacConfig", "DacFeatureExtractor"],
+ "models.data2vec": [
+ "Data2VecAudioConfig",
+ "Data2VecTextConfig",
+ "Data2VecVisionConfig",
+ ],
+ "models.dbrx": ["DbrxConfig"],
+ "models.deberta": [
+ "DebertaConfig",
+ "DebertaTokenizer",
+ ],
+ "models.deberta_v2": ["DebertaV2Config"],
+ "models.decision_transformer": ["DecisionTransformerConfig"],
+ "models.deformable_detr": ["DeformableDetrConfig"],
+ "models.deit": ["DeiTConfig"],
+ "models.deprecated": [],
+ "models.deprecated.bort": [],
+ "models.deprecated.deta": ["DetaConfig"],
+ "models.deprecated.efficientformer": ["EfficientFormerConfig"],
+ "models.deprecated.ernie_m": ["ErnieMConfig"],
+ "models.deprecated.gptsan_japanese": [
+ "GPTSanJapaneseConfig",
+ "GPTSanJapaneseTokenizer",
+ ],
+ "models.deprecated.graphormer": ["GraphormerConfig"],
+ "models.deprecated.jukebox": [
+ "JukeboxConfig",
+ "JukeboxPriorConfig",
+ "JukeboxTokenizer",
+ "JukeboxVQVAEConfig",
+ ],
+ "models.deprecated.mctct": [
+ "MCTCTConfig",
+ "MCTCTFeatureExtractor",
+ "MCTCTProcessor",
+ ],
+ "models.deprecated.mega": ["MegaConfig"],
+ "models.deprecated.mmbt": ["MMBTConfig"],
+ "models.deprecated.nat": ["NatConfig"],
+ "models.deprecated.nezha": ["NezhaConfig"],
+ "models.deprecated.open_llama": ["OpenLlamaConfig"],
+ "models.deprecated.qdqbert": ["QDQBertConfig"],
+ "models.deprecated.realm": [
+ "RealmConfig",
+ "RealmTokenizer",
+ ],
+ "models.deprecated.retribert": [
+ "RetriBertConfig",
+ "RetriBertTokenizer",
+ ],
+ "models.deprecated.speech_to_text_2": [
+ "Speech2Text2Config",
+ "Speech2Text2Processor",
+ "Speech2Text2Tokenizer",
+ ],
+ "models.deprecated.tapex": ["TapexTokenizer"],
+ "models.deprecated.trajectory_transformer": ["TrajectoryTransformerConfig"],
+ "models.deprecated.transfo_xl": [
+ "TransfoXLConfig",
+ "TransfoXLCorpus",
+ "TransfoXLTokenizer",
+ ],
+ "models.deprecated.tvlt": [
+ "TvltConfig",
+ "TvltFeatureExtractor",
+ "TvltProcessor",
+ ],
+ "models.deprecated.van": ["VanConfig"],
+ "models.deprecated.vit_hybrid": ["ViTHybridConfig"],
+ "models.deprecated.xlm_prophetnet": ["XLMProphetNetConfig"],
+ "models.depth_anything": ["DepthAnythingConfig"],
+ "models.detr": ["DetrConfig"],
+ "models.dialogpt": [],
+ "models.dinat": ["DinatConfig"],
+ "models.dinov2": ["Dinov2Config"],
+ "models.distilbert": [
+ "DistilBertConfig",
+ "DistilBertTokenizer",
+ ],
+ "models.dit": [],
+ "models.donut": [
+ "DonutProcessor",
+ "DonutSwinConfig",
+ ],
+ "models.dpr": [
+ "DPRConfig",
+ "DPRContextEncoderTokenizer",
+ "DPRQuestionEncoderTokenizer",
+ "DPRReaderOutput",
+ "DPRReaderTokenizer",
+ ],
+ "models.dpt": ["DPTConfig"],
+ "models.efficientnet": ["EfficientNetConfig"],
+ "models.electra": [
+ "ElectraConfig",
+ "ElectraTokenizer",
+ ],
+ "models.encodec": [
+ "EncodecConfig",
+ "EncodecFeatureExtractor",
+ ],
+ "models.encoder_decoder": ["EncoderDecoderConfig"],
+ "models.ernie": ["ErnieConfig"],
+ "models.esm": ["EsmConfig", "EsmTokenizer"],
+ "models.falcon": ["FalconConfig"],
+ "models.falcon_mamba": ["FalconMambaConfig"],
+ "models.fastspeech2_conformer": [
+ "FastSpeech2ConformerConfig",
+ "FastSpeech2ConformerHifiGanConfig",
+ "FastSpeech2ConformerTokenizer",
+ "FastSpeech2ConformerWithHifiGanConfig",
+ ],
+ "models.flaubert": ["FlaubertConfig", "FlaubertTokenizer"],
+ "models.flava": [
+ "FlavaConfig",
+ "FlavaImageCodebookConfig",
+ "FlavaImageConfig",
+ "FlavaMultimodalConfig",
+ "FlavaTextConfig",
+ ],
+ "models.fnet": ["FNetConfig"],
+ "models.focalnet": ["FocalNetConfig"],
+ "models.fsmt": [
+ "FSMTConfig",
+ "FSMTTokenizer",
+ ],
+ "models.funnel": [
+ "FunnelConfig",
+ "FunnelTokenizer",
+ ],
+ "models.fuyu": ["FuyuConfig"],
+ "models.gemma": ["GemmaConfig"],
+ "models.gemma2": ["Gemma2Config"],
+ "models.git": [
+ "GitConfig",
+ "GitProcessor",
+ "GitVisionConfig",
+ ],
+ "models.glm": ["GlmConfig"],
+ "models.glpn": ["GLPNConfig"],
+ "models.gpt2": [
+ "GPT2Config",
+ "GPT2Tokenizer",
+ ],
+ "models.gpt_bigcode": ["GPTBigCodeConfig"],
+ "models.gpt_neo": ["GPTNeoConfig"],
+ "models.gpt_neox": ["GPTNeoXConfig"],
+ "models.gpt_neox_japanese": ["GPTNeoXJapaneseConfig"],
+ "models.gpt_sw3": [],
+ "models.gptj": ["GPTJConfig"],
+ "models.granite": ["GraniteConfig"],
+ "models.granitemoe": ["GraniteMoeConfig"],
+ "models.grounding_dino": [
+ "GroundingDinoConfig",
+ "GroundingDinoProcessor",
+ ],
+ "models.groupvit": [
+ "GroupViTConfig",
+ "GroupViTTextConfig",
+ "GroupViTVisionConfig",
+ ],
+ "models.herbert": ["HerbertTokenizer"],
+ "models.hiera": ["HieraConfig"],
+ "models.hubert": ["HubertConfig"],
+ "models.ibert": ["IBertConfig"],
+ "models.idefics": ["IdeficsConfig"],
+ "models.idefics2": ["Idefics2Config"],
+ "models.idefics3": ["Idefics3Config"],
+ "models.ijepa": ["IJepaConfig"],
+ "models.imagegpt": ["ImageGPTConfig"],
+ "models.informer": ["InformerConfig"],
+ "models.instructblip": [
+ "InstructBlipConfig",
+ "InstructBlipProcessor",
+ "InstructBlipQFormerConfig",
+ "InstructBlipVisionConfig",
+ ],
+ "models.instructblipvideo": [
+ "InstructBlipVideoConfig",
+ "InstructBlipVideoProcessor",
+ "InstructBlipVideoQFormerConfig",
+ "InstructBlipVideoVisionConfig",
+ ],
+ "models.jamba": ["JambaConfig"],
+ "models.jetmoe": ["JetMoeConfig"],
+ "models.kosmos2": [
+ "Kosmos2Config",
+ "Kosmos2Processor",
+ ],
+ "models.layoutlm": [
+ "LayoutLMConfig",
+ "LayoutLMTokenizer",
+ ],
+ "models.layoutlmv2": [
+ "LayoutLMv2Config",
+ "LayoutLMv2FeatureExtractor",
+ "LayoutLMv2ImageProcessor",
+ "LayoutLMv2Processor",
+ "LayoutLMv2Tokenizer",
+ ],
+ "models.layoutlmv3": [
+ "LayoutLMv3Config",
+ "LayoutLMv3FeatureExtractor",
+ "LayoutLMv3ImageProcessor",
+ "LayoutLMv3Processor",
+ "LayoutLMv3Tokenizer",
+ ],
+ "models.layoutxlm": ["LayoutXLMProcessor"],
+ "models.led": ["LEDConfig", "LEDTokenizer"],
+ "models.levit": ["LevitConfig"],
+ "models.lilt": ["LiltConfig"],
+ "models.llama": ["LlamaConfig"],
+ "models.llava": [
+ "LlavaConfig",
+ "LlavaProcessor",
+ ],
+ "models.llava_next": [
+ "LlavaNextConfig",
+ "LlavaNextProcessor",
+ ],
+ "models.llava_next_video": [
+ "LlavaNextVideoConfig",
+ "LlavaNextVideoProcessor",
+ ],
+ "models.llava_onevision": ["LlavaOnevisionConfig", "LlavaOnevisionProcessor"],
+ "models.longformer": [
+ "LongformerConfig",
+ "LongformerTokenizer",
+ ],
+ "models.longt5": ["LongT5Config"],
+ "models.luke": [
+ "LukeConfig",
+ "LukeTokenizer",
+ ],
+ "models.lxmert": [
+ "LxmertConfig",
+ "LxmertTokenizer",
+ ],
+ "models.m2m_100": ["M2M100Config"],
+ "models.mamba": ["MambaConfig"],
+ "models.mamba2": ["Mamba2Config"],
+ "models.marian": ["MarianConfig"],
+ "models.markuplm": [
+ "MarkupLMConfig",
+ "MarkupLMFeatureExtractor",
+ "MarkupLMProcessor",
+ "MarkupLMTokenizer",
+ ],
+ "models.mask2former": ["Mask2FormerConfig"],
+ "models.maskformer": [
+ "MaskFormerConfig",
+ "MaskFormerSwinConfig",
+ ],
+ "models.mbart": ["MBartConfig"],
+ "models.mbart50": [],
+ "models.megatron_bert": ["MegatronBertConfig"],
+ "models.megatron_gpt2": [],
+ "models.mgp_str": [
+ "MgpstrConfig",
+ "MgpstrProcessor",
+ "MgpstrTokenizer",
+ ],
+ "models.mimi": ["MimiConfig"],
+ "models.mistral": ["MistralConfig"],
+ "models.mixtral": ["MixtralConfig"],
+ "models.mllama": [
+ "MllamaConfig",
+ "MllamaProcessor",
+ ],
+ "models.mluke": [],
+ "models.mobilebert": [
+ "MobileBertConfig",
+ "MobileBertTokenizer",
+ ],
+ "models.mobilenet_v1": ["MobileNetV1Config"],
+ "models.mobilenet_v2": ["MobileNetV2Config"],
+ "models.mobilevit": ["MobileViTConfig"],
+ "models.mobilevitv2": ["MobileViTV2Config"],
+ "models.modernbert": ["ModernBertConfig"],
+ "models.moshi": [
+ "MoshiConfig",
+ "MoshiDepthConfig",
+ ],
+ "models.mpnet": [
+ "MPNetConfig",
+ "MPNetTokenizer",
+ ],
+ "models.mpt": ["MptConfig"],
+ "models.mra": ["MraConfig"],
+ "models.mt5": ["MT5Config"],
+ "models.musicgen": [
+ "MusicgenConfig",
+ "MusicgenDecoderConfig",
+ ],
+ "models.musicgen_melody": [
+ "MusicgenMelodyConfig",
+ "MusicgenMelodyDecoderConfig",
+ ],
+ "models.mvp": ["MvpConfig", "MvpTokenizer"],
+ "models.myt5": ["MyT5Tokenizer"],
+ "models.nemotron": ["NemotronConfig"],
+ "models.nllb": [],
+ "models.nllb_moe": ["NllbMoeConfig"],
+ "models.nougat": ["NougatProcessor"],
+ "models.nystromformer": ["NystromformerConfig"],
+ "models.olmo": ["OlmoConfig"],
+ "models.olmo2": ["Olmo2Config"],
+ "models.olmoe": ["OlmoeConfig"],
+ "models.omdet_turbo": [
+ "OmDetTurboConfig",
+ "OmDetTurboProcessor",
+ ],
+ "models.oneformer": [
+ "OneFormerConfig",
+ "OneFormerProcessor",
+ ],
+ "models.openai": [
+ "OpenAIGPTConfig",
+ "OpenAIGPTTokenizer",
+ ],
+ "models.opt": ["OPTConfig"],
+ "models.owlv2": [
+ "Owlv2Config",
+ "Owlv2Processor",
+ "Owlv2TextConfig",
+ "Owlv2VisionConfig",
+ ],
+ "models.owlvit": [
+ "OwlViTConfig",
+ "OwlViTProcessor",
+ "OwlViTTextConfig",
+ "OwlViTVisionConfig",
+ ],
+ "models.paligemma": ["PaliGemmaConfig"],
+ "models.patchtsmixer": ["PatchTSMixerConfig"],
+ "models.patchtst": ["PatchTSTConfig"],
+ "models.pegasus": [
+ "PegasusConfig",
+ "PegasusTokenizer",
+ ],
+ "models.pegasus_x": ["PegasusXConfig"],
+ "models.perceiver": [
+ "PerceiverConfig",
+ "PerceiverTokenizer",
+ ],
+ "models.persimmon": ["PersimmonConfig"],
+ "models.phi": ["PhiConfig"],
+ "models.phi3": ["Phi3Config"],
+ "models.phimoe": ["PhimoeConfig"],
+ "models.phobert": ["PhobertTokenizer"],
+ "models.pix2struct": [
+ "Pix2StructConfig",
+ "Pix2StructProcessor",
+ "Pix2StructTextConfig",
+ "Pix2StructVisionConfig",
+ ],
+ "models.pixtral": ["PixtralProcessor", "PixtralVisionConfig"],
+ "models.plbart": ["PLBartConfig"],
+ "models.poolformer": ["PoolFormerConfig"],
+ "models.pop2piano": ["Pop2PianoConfig"],
+ "models.prophetnet": [
+ "ProphetNetConfig",
+ "ProphetNetTokenizer",
+ ],
+ "models.pvt": ["PvtConfig"],
+ "models.pvt_v2": ["PvtV2Config"],
+ "models.qwen2": [
+ "Qwen2Config",
+ "Qwen2Tokenizer",
+ ],
+ "models.qwen2_audio": [
+ "Qwen2AudioConfig",
+ "Qwen2AudioEncoderConfig",
+ "Qwen2AudioProcessor",
+ ],
+ "models.qwen2_moe": ["Qwen2MoeConfig"],
+ "models.qwen2_vl": [
+ "Qwen2VLConfig",
+ "Qwen2VLProcessor",
+ ],
+ "models.rag": ["RagConfig", "RagRetriever", "RagTokenizer"],
+ "models.recurrent_gemma": ["RecurrentGemmaConfig"],
+ "models.reformer": ["ReformerConfig"],
+ "models.regnet": ["RegNetConfig"],
+ "models.rembert": ["RemBertConfig"],
+ "models.resnet": ["ResNetConfig"],
+ "models.roberta": [
+ "RobertaConfig",
+ "RobertaTokenizer",
+ ],
+ "models.roberta_prelayernorm": ["RobertaPreLayerNormConfig"],
+ "models.roc_bert": [
+ "RoCBertConfig",
+ "RoCBertTokenizer",
+ ],
+ "models.roformer": [
+ "RoFormerConfig",
+ "RoFormerTokenizer",
+ ],
+ "models.rt_detr": ["RTDetrConfig", "RTDetrResNetConfig"],
+ "models.rwkv": ["RwkvConfig"],
+ "models.sam": [
+ "SamConfig",
+ "SamMaskDecoderConfig",
+ "SamProcessor",
+ "SamPromptEncoderConfig",
+ "SamVisionConfig",
+ ],
+ "models.seamless_m4t": [
+ "SeamlessM4TConfig",
+ "SeamlessM4TFeatureExtractor",
+ "SeamlessM4TProcessor",
+ ],
+ "models.seamless_m4t_v2": ["SeamlessM4Tv2Config"],
+ "models.segformer": ["SegformerConfig"],
+ "models.seggpt": ["SegGptConfig"],
+ "models.sew": ["SEWConfig"],
+ "models.sew_d": ["SEWDConfig"],
+ "models.siglip": [
+ "SiglipConfig",
+ "SiglipProcessor",
+ "SiglipTextConfig",
+ "SiglipVisionConfig",
+ ],
+ "models.speech_encoder_decoder": ["SpeechEncoderDecoderConfig"],
+ "models.speech_to_text": [
+ "Speech2TextConfig",
+ "Speech2TextFeatureExtractor",
+ "Speech2TextProcessor",
+ ],
+ "models.speecht5": [
+ "SpeechT5Config",
+ "SpeechT5FeatureExtractor",
+ "SpeechT5HifiGanConfig",
+ "SpeechT5Processor",
+ ],
+ "models.splinter": [
+ "SplinterConfig",
+ "SplinterTokenizer",
+ ],
+ "models.squeezebert": [
+ "SqueezeBertConfig",
+ "SqueezeBertTokenizer",
+ ],
+ "models.stablelm": ["StableLmConfig"],
+ "models.starcoder2": ["Starcoder2Config"],
+ "models.superpoint": ["SuperPointConfig"],
+ "models.swiftformer": ["SwiftFormerConfig"],
+ "models.swin": ["SwinConfig"],
+ "models.swin2sr": ["Swin2SRConfig"],
+ "models.swinv2": ["Swinv2Config"],
+ "models.switch_transformers": ["SwitchTransformersConfig"],
+ "models.t5": ["T5Config"],
+ "models.table_transformer": ["TableTransformerConfig"],
+ "models.tapas": [
+ "TapasConfig",
+ "TapasTokenizer",
+ ],
+ "models.time_series_transformer": ["TimeSeriesTransformerConfig"],
+ "models.timesformer": ["TimesformerConfig"],
+ "models.timm_backbone": ["TimmBackboneConfig"],
+ "models.timm_wrapper": ["TimmWrapperConfig"],
+ "models.trocr": [
+ "TrOCRConfig",
+ "TrOCRProcessor",
+ ],
+ "models.tvp": [
+ "TvpConfig",
+ "TvpProcessor",
+ ],
+ "models.udop": [
+ "UdopConfig",
+ "UdopProcessor",
+ ],
+ "models.umt5": ["UMT5Config"],
+ "models.unispeech": ["UniSpeechConfig"],
+ "models.unispeech_sat": ["UniSpeechSatConfig"],
+ "models.univnet": [
+ "UnivNetConfig",
+ "UnivNetFeatureExtractor",
+ ],
+ "models.upernet": ["UperNetConfig"],
+ "models.video_llava": ["VideoLlavaConfig"],
+ "models.videomae": ["VideoMAEConfig"],
+ "models.vilt": [
+ "ViltConfig",
+ "ViltFeatureExtractor",
+ "ViltImageProcessor",
+ "ViltProcessor",
+ ],
+ "models.vipllava": ["VipLlavaConfig"],
+ "models.vision_encoder_decoder": ["VisionEncoderDecoderConfig"],
+ "models.vision_text_dual_encoder": [
+ "VisionTextDualEncoderConfig",
+ "VisionTextDualEncoderProcessor",
+ ],
+ "models.visual_bert": ["VisualBertConfig"],
+ "models.vit": ["ViTConfig"],
+ "models.vit_mae": ["ViTMAEConfig"],
+ "models.vit_msn": ["ViTMSNConfig"],
+ "models.vitdet": ["VitDetConfig"],
+ "models.vitmatte": ["VitMatteConfig"],
+ "models.vits": [
+ "VitsConfig",
+ "VitsTokenizer",
+ ],
+ "models.vivit": ["VivitConfig"],
+ "models.wav2vec2": [
+ "Wav2Vec2Config",
+ "Wav2Vec2CTCTokenizer",
+ "Wav2Vec2FeatureExtractor",
+ "Wav2Vec2Processor",
+ "Wav2Vec2Tokenizer",
+ ],
+ "models.wav2vec2_bert": [
+ "Wav2Vec2BertConfig",
+ "Wav2Vec2BertProcessor",
+ ],
+ "models.wav2vec2_conformer": ["Wav2Vec2ConformerConfig"],
+ "models.wav2vec2_phoneme": ["Wav2Vec2PhonemeCTCTokenizer"],
+ "models.wav2vec2_with_lm": ["Wav2Vec2ProcessorWithLM"],
+ "models.wavlm": ["WavLMConfig"],
+ "models.whisper": [
+ "WhisperConfig",
+ "WhisperFeatureExtractor",
+ "WhisperProcessor",
+ "WhisperTokenizer",
+ ],
+ "models.x_clip": [
+ "XCLIPConfig",
+ "XCLIPProcessor",
+ "XCLIPTextConfig",
+ "XCLIPVisionConfig",
+ ],
+ "models.xglm": ["XGLMConfig"],
+ "models.xlm": ["XLMConfig", "XLMTokenizer"],
+ "models.xlm_roberta": ["XLMRobertaConfig"],
+ "models.xlm_roberta_xl": ["XLMRobertaXLConfig"],
+ "models.xlnet": ["XLNetConfig"],
+ "models.xmod": ["XmodConfig"],
+ "models.yolos": ["YolosConfig"],
+ "models.yoso": ["YosoConfig"],
+ "models.zamba": ["ZambaConfig"],
+ "models.zoedepth": ["ZoeDepthConfig"],
+ "onnx": [],
+ "pipelines": [
+ "AudioClassificationPipeline",
+ "AutomaticSpeechRecognitionPipeline",
+ "CsvPipelineDataFormat",
+ "DepthEstimationPipeline",
+ "DocumentQuestionAnsweringPipeline",
+ "FeatureExtractionPipeline",
+ "FillMaskPipeline",
+ "ImageClassificationPipeline",
+ "ImageFeatureExtractionPipeline",
+ "ImageSegmentationPipeline",
+ "ImageTextToTextPipeline",
+ "ImageToImagePipeline",
+ "ImageToTextPipeline",
+ "JsonPipelineDataFormat",
+ "MaskGenerationPipeline",
+ "NerPipeline",
+ "ObjectDetectionPipeline",
+ "PipedPipelineDataFormat",
+ "Pipeline",
+ "PipelineDataFormat",
+ "QuestionAnsweringPipeline",
+ "SummarizationPipeline",
+ "TableQuestionAnsweringPipeline",
+ "Text2TextGenerationPipeline",
+ "TextClassificationPipeline",
+ "TextGenerationPipeline",
+ "TextToAudioPipeline",
+ "TokenClassificationPipeline",
+ "TranslationPipeline",
+ "VideoClassificationPipeline",
+ "VisualQuestionAnsweringPipeline",
+ "ZeroShotAudioClassificationPipeline",
+ "ZeroShotClassificationPipeline",
+ "ZeroShotImageClassificationPipeline",
+ "ZeroShotObjectDetectionPipeline",
+ "pipeline",
+ ],
+ "processing_utils": ["ProcessorMixin"],
+ "quantizers": [],
+ "testing_utils": [],
+ "tokenization_utils": ["PreTrainedTokenizer"],
+ "tokenization_utils_base": [
+ "AddedToken",
+ "BatchEncoding",
+ "CharSpan",
+ "PreTrainedTokenizerBase",
+ "SpecialTokensMixin",
+ "TokenSpan",
+ ],
+ "trainer_callback": [
+ "DefaultFlowCallback",
+ "EarlyStoppingCallback",
+ "PrinterCallback",
+ "ProgressCallback",
+ "TrainerCallback",
+ "TrainerControl",
+ "TrainerState",
+ ],
+ "trainer_utils": [
+ "EvalPrediction",
+ "IntervalStrategy",
+ "SchedulerType",
+ "enable_full_determinism",
+ "set_seed",
+ ],
+ "training_args": ["TrainingArguments"],
+ "training_args_seq2seq": ["Seq2SeqTrainingArguments"],
+ "training_args_tf": ["TFTrainingArguments"],
+ "utils": [
+ "CONFIG_NAME",
+ "MODEL_CARD_NAME",
+ "PYTORCH_PRETRAINED_BERT_CACHE",
+ "PYTORCH_TRANSFORMERS_CACHE",
+ "SPIECE_UNDERLINE",
+ "TF2_WEIGHTS_NAME",
+ "TF_WEIGHTS_NAME",
+ "TRANSFORMERS_CACHE",
+ "WEIGHTS_NAME",
+ "TensorType",
+ "add_end_docstrings",
+ "add_start_docstrings",
+ "is_apex_available",
+ "is_av_available",
+ "is_bitsandbytes_available",
+ "is_datasets_available",
+ "is_faiss_available",
+ "is_flax_available",
+ "is_keras_nlp_available",
+ "is_phonemizer_available",
+ "is_psutil_available",
+ "is_py3nvml_available",
+ "is_pyctcdecode_available",
+ "is_sacremoses_available",
+ "is_safetensors_available",
+ "is_scipy_available",
+ "is_sentencepiece_available",
+ "is_sklearn_available",
+ "is_speech_available",
+ "is_tensorflow_text_available",
+ "is_tf_available",
+ "is_timm_available",
+ "is_tokenizers_available",
+ "is_torch_available",
+ "is_torch_mlu_available",
+ "is_torch_musa_available",
+ "is_torch_neuroncore_available",
+ "is_torch_npu_available",
+ "is_torch_tpu_available",
+ "is_torchvision_available",
+ "is_torch_xla_available",
+ "is_torch_xpu_available",
+ "is_vision_available",
+ "logging",
+ ],
+ "utils.quantization_config": [
+ "AqlmConfig",
+ "AwqConfig",
+ "BitNetConfig",
+ "BitsAndBytesConfig",
+ "CompressedTensorsConfig",
+ "EetqConfig",
+ "FbgemmFp8Config",
+ "GPTQConfig",
+ "HiggsConfig",
+ "HqqConfig",
+ "QuantoConfig",
+ "TorchAoConfig",
+ "VptqConfig",
+ ],
+}
+
+# sentencepiece-backed objects
+try:
+ if not is_sentencepiece_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import dummy_sentencepiece_objects
+
+ _import_structure["utils.dummy_sentencepiece_objects"] = [
+ name for name in dir(dummy_sentencepiece_objects) if not name.startswith("_")
+ ]
+else:
+ _import_structure["models.albert"].append("AlbertTokenizer")
+ _import_structure["models.barthez"].append("BarthezTokenizer")
+ _import_structure["models.bartpho"].append("BartphoTokenizer")
+ _import_structure["models.bert_generation"].append("BertGenerationTokenizer")
+ _import_structure["models.big_bird"].append("BigBirdTokenizer")
+ _import_structure["models.camembert"].append("CamembertTokenizer")
+ _import_structure["models.code_llama"].append("CodeLlamaTokenizer")
+ _import_structure["models.cpm"].append("CpmTokenizer")
+ _import_structure["models.deberta_v2"].append("DebertaV2Tokenizer")
+ _import_structure["models.deprecated.ernie_m"].append("ErnieMTokenizer")
+ _import_structure["models.deprecated.xlm_prophetnet"].append("XLMProphetNetTokenizer")
+ _import_structure["models.fnet"].append("FNetTokenizer")
+ _import_structure["models.gemma"].append("GemmaTokenizer")
+ _import_structure["models.gpt_sw3"].append("GPTSw3Tokenizer")
+ _import_structure["models.layoutxlm"].append("LayoutXLMTokenizer")
+ _import_structure["models.llama"].append("LlamaTokenizer")
+ _import_structure["models.m2m_100"].append("M2M100Tokenizer")
+ _import_structure["models.marian"].append("MarianTokenizer")
+ _import_structure["models.mbart"].append("MBartTokenizer")
+ _import_structure["models.mbart50"].append("MBart50Tokenizer")
+ _import_structure["models.mluke"].append("MLukeTokenizer")
+ _import_structure["models.mt5"].append("MT5Tokenizer")
+ _import_structure["models.nllb"].append("NllbTokenizer")
+ _import_structure["models.pegasus"].append("PegasusTokenizer")
+ _import_structure["models.plbart"].append("PLBartTokenizer")
+ _import_structure["models.reformer"].append("ReformerTokenizer")
+ _import_structure["models.rembert"].append("RemBertTokenizer")
+ _import_structure["models.seamless_m4t"].append("SeamlessM4TTokenizer")
+ _import_structure["models.siglip"].append("SiglipTokenizer")
+ _import_structure["models.speech_to_text"].append("Speech2TextTokenizer")
+ _import_structure["models.speecht5"].append("SpeechT5Tokenizer")
+ _import_structure["models.t5"].append("T5Tokenizer")
+ _import_structure["models.udop"].append("UdopTokenizer")
+ _import_structure["models.xglm"].append("XGLMTokenizer")
+ _import_structure["models.xlm_roberta"].append("XLMRobertaTokenizer")
+ _import_structure["models.xlnet"].append("XLNetTokenizer")
+
+# tokenizers-backed objects
+try:
+ if not is_tokenizers_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import dummy_tokenizers_objects
+
+ _import_structure["utils.dummy_tokenizers_objects"] = [
+ name for name in dir(dummy_tokenizers_objects) if not name.startswith("_")
+ ]
+else:
+ # Fast tokenizers structure
+ _import_structure["models.albert"].append("AlbertTokenizerFast")
+ _import_structure["models.bart"].append("BartTokenizerFast")
+ _import_structure["models.barthez"].append("BarthezTokenizerFast")
+ _import_structure["models.bert"].append("BertTokenizerFast")
+ _import_structure["models.big_bird"].append("BigBirdTokenizerFast")
+ _import_structure["models.blenderbot"].append("BlenderbotTokenizerFast")
+ _import_structure["models.blenderbot_small"].append("BlenderbotSmallTokenizerFast")
+ _import_structure["models.bloom"].append("BloomTokenizerFast")
+ _import_structure["models.camembert"].append("CamembertTokenizerFast")
+ _import_structure["models.clip"].append("CLIPTokenizerFast")
+ _import_structure["models.code_llama"].append("CodeLlamaTokenizerFast")
+ _import_structure["models.codegen"].append("CodeGenTokenizerFast")
+ _import_structure["models.cohere"].append("CohereTokenizerFast")
+ _import_structure["models.convbert"].append("ConvBertTokenizerFast")
+ _import_structure["models.cpm"].append("CpmTokenizerFast")
+ _import_structure["models.deberta"].append("DebertaTokenizerFast")
+ _import_structure["models.deberta_v2"].append("DebertaV2TokenizerFast")
+ _import_structure["models.deprecated.realm"].append("RealmTokenizerFast")
+ _import_structure["models.deprecated.retribert"].append("RetriBertTokenizerFast")
+ _import_structure["models.distilbert"].append("DistilBertTokenizerFast")
+ _import_structure["models.dpr"].extend(
+ [
+ "DPRContextEncoderTokenizerFast",
+ "DPRQuestionEncoderTokenizerFast",
+ "DPRReaderTokenizerFast",
+ ]
+ )
+ _import_structure["models.electra"].append("ElectraTokenizerFast")
+ _import_structure["models.fnet"].append("FNetTokenizerFast")
+ _import_structure["models.funnel"].append("FunnelTokenizerFast")
+ _import_structure["models.gemma"].append("GemmaTokenizerFast")
+ _import_structure["models.gpt2"].append("GPT2TokenizerFast")
+ _import_structure["models.gpt_neox"].append("GPTNeoXTokenizerFast")
+ _import_structure["models.gpt_neox_japanese"].append("GPTNeoXJapaneseTokenizer")
+ _import_structure["models.herbert"].append("HerbertTokenizerFast")
+ _import_structure["models.layoutlm"].append("LayoutLMTokenizerFast")
+ _import_structure["models.layoutlmv2"].append("LayoutLMv2TokenizerFast")
+ _import_structure["models.layoutlmv3"].append("LayoutLMv3TokenizerFast")
+ _import_structure["models.layoutxlm"].append("LayoutXLMTokenizerFast")
+ _import_structure["models.led"].append("LEDTokenizerFast")
+ _import_structure["models.llama"].append("LlamaTokenizerFast")
+ _import_structure["models.longformer"].append("LongformerTokenizerFast")
+ _import_structure["models.lxmert"].append("LxmertTokenizerFast")
+ _import_structure["models.markuplm"].append("MarkupLMTokenizerFast")
+ _import_structure["models.mbart"].append("MBartTokenizerFast")
+ _import_structure["models.mbart50"].append("MBart50TokenizerFast")
+ _import_structure["models.mobilebert"].append("MobileBertTokenizerFast")
+ _import_structure["models.mpnet"].append("MPNetTokenizerFast")
+ _import_structure["models.mt5"].append("MT5TokenizerFast")
+ _import_structure["models.mvp"].append("MvpTokenizerFast")
+ _import_structure["models.nllb"].append("NllbTokenizerFast")
+ _import_structure["models.nougat"].append("NougatTokenizerFast")
+ _import_structure["models.openai"].append("OpenAIGPTTokenizerFast")
+ _import_structure["models.pegasus"].append("PegasusTokenizerFast")
+ _import_structure["models.qwen2"].append("Qwen2TokenizerFast")
+ _import_structure["models.reformer"].append("ReformerTokenizerFast")
+ _import_structure["models.rembert"].append("RemBertTokenizerFast")
+ _import_structure["models.roberta"].append("RobertaTokenizerFast")
+ _import_structure["models.roformer"].append("RoFormerTokenizerFast")
+ _import_structure["models.seamless_m4t"].append("SeamlessM4TTokenizerFast")
+ _import_structure["models.splinter"].append("SplinterTokenizerFast")
+ _import_structure["models.squeezebert"].append("SqueezeBertTokenizerFast")
+ _import_structure["models.t5"].append("T5TokenizerFast")
+ _import_structure["models.udop"].append("UdopTokenizerFast")
+ _import_structure["models.whisper"].append("WhisperTokenizerFast")
+ _import_structure["models.xglm"].append("XGLMTokenizerFast")
+ _import_structure["models.xlm_roberta"].append("XLMRobertaTokenizerFast")
+ _import_structure["models.xlnet"].append("XLNetTokenizerFast")
+ _import_structure["tokenization_utils_fast"] = ["PreTrainedTokenizerFast"]
+
+
+try:
+ if not (is_sentencepiece_available() and is_tokenizers_available()):
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import dummy_sentencepiece_and_tokenizers_objects
+
+ _import_structure["utils.dummy_sentencepiece_and_tokenizers_objects"] = [
+ name for name in dir(dummy_sentencepiece_and_tokenizers_objects) if not name.startswith("_")
+ ]
+else:
+ _import_structure["convert_slow_tokenizer"] = [
+ "SLOW_TO_FAST_CONVERTERS",
+ "convert_slow_tokenizer",
+ ]
+
+# Tensorflow-text-specific objects
+try:
+ if not is_tensorflow_text_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import dummy_tensorflow_text_objects
+
+ _import_structure["utils.dummy_tensorflow_text_objects"] = [
+ name for name in dir(dummy_tensorflow_text_objects) if not name.startswith("_")
+ ]
+else:
+ _import_structure["models.bert"].append("TFBertTokenizer")
+
+# keras-nlp-specific objects
+try:
+ if not is_keras_nlp_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import dummy_keras_nlp_objects
+
+ _import_structure["utils.dummy_keras_nlp_objects"] = [
+ name for name in dir(dummy_keras_nlp_objects) if not name.startswith("_")
+ ]
+else:
+ _import_structure["models.gpt2"].append("TFGPT2Tokenizer")
+
+# Vision-specific objects
+try:
+ if not is_vision_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import dummy_vision_objects
+
+ _import_structure["utils.dummy_vision_objects"] = [
+ name for name in dir(dummy_vision_objects) if not name.startswith("_")
+ ]
+else:
+ _import_structure["image_processing_base"] = ["ImageProcessingMixin"]
+ _import_structure["image_processing_utils"] = ["BaseImageProcessor"]
+ _import_structure["image_utils"] = ["ImageFeatureExtractionMixin"]
+ _import_structure["models.aria"].extend(["AriaImageProcessor"])
+ _import_structure["models.beit"].extend(["BeitFeatureExtractor", "BeitImageProcessor"])
+ _import_structure["models.bit"].extend(["BitImageProcessor"])
+ _import_structure["models.blip"].extend(["BlipImageProcessor"])
+ _import_structure["models.bridgetower"].append("BridgeTowerImageProcessor")
+ _import_structure["models.chameleon"].append("ChameleonImageProcessor")
+ _import_structure["models.chinese_clip"].extend(["ChineseCLIPFeatureExtractor", "ChineseCLIPImageProcessor"])
+ _import_structure["models.clip"].extend(["CLIPFeatureExtractor", "CLIPImageProcessor"])
+ _import_structure["models.conditional_detr"].extend(
+ ["ConditionalDetrFeatureExtractor", "ConditionalDetrImageProcessor"]
+ )
+ _import_structure["models.convnext"].extend(["ConvNextFeatureExtractor", "ConvNextImageProcessor"])
+ _import_structure["models.deformable_detr"].extend(
+ ["DeformableDetrFeatureExtractor", "DeformableDetrImageProcessor"]
+ )
+ _import_structure["models.deit"].extend(["DeiTFeatureExtractor", "DeiTImageProcessor"])
+ _import_structure["models.deprecated.deta"].append("DetaImageProcessor")
+ _import_structure["models.deprecated.efficientformer"].append("EfficientFormerImageProcessor")
+ _import_structure["models.deprecated.tvlt"].append("TvltImageProcessor")
+ _import_structure["models.deprecated.vit_hybrid"].extend(["ViTHybridImageProcessor"])
+ _import_structure["models.detr"].extend(["DetrFeatureExtractor", "DetrImageProcessor"])
+ _import_structure["models.donut"].extend(["DonutFeatureExtractor", "DonutImageProcessor"])
+ _import_structure["models.dpt"].extend(["DPTFeatureExtractor", "DPTImageProcessor"])
+ _import_structure["models.efficientnet"].append("EfficientNetImageProcessor")
+ _import_structure["models.flava"].extend(["FlavaFeatureExtractor", "FlavaImageProcessor", "FlavaProcessor"])
+ _import_structure["models.fuyu"].extend(["FuyuImageProcessor", "FuyuProcessor"])
+ _import_structure["models.glpn"].extend(["GLPNFeatureExtractor", "GLPNImageProcessor"])
+ _import_structure["models.grounding_dino"].extend(["GroundingDinoImageProcessor"])
+ _import_structure["models.idefics"].extend(["IdeficsImageProcessor"])
+ _import_structure["models.idefics2"].extend(["Idefics2ImageProcessor"])
+ _import_structure["models.idefics3"].extend(["Idefics3ImageProcessor"])
+ _import_structure["models.imagegpt"].extend(["ImageGPTFeatureExtractor", "ImageGPTImageProcessor"])
+ _import_structure["models.instructblipvideo"].extend(["InstructBlipVideoImageProcessor"])
+ _import_structure["models.layoutlmv2"].extend(["LayoutLMv2FeatureExtractor", "LayoutLMv2ImageProcessor"])
+ _import_structure["models.layoutlmv3"].extend(["LayoutLMv3FeatureExtractor", "LayoutLMv3ImageProcessor"])
+ _import_structure["models.levit"].extend(["LevitFeatureExtractor", "LevitImageProcessor"])
+ _import_structure["models.llava_next"].append("LlavaNextImageProcessor")
+ _import_structure["models.llava_next_video"].append("LlavaNextVideoImageProcessor")
+ _import_structure["models.llava_onevision"].extend(
+ ["LlavaOnevisionImageProcessor", "LlavaOnevisionVideoProcessor"]
+ )
+ _import_structure["models.mask2former"].append("Mask2FormerImageProcessor")
+ _import_structure["models.maskformer"].extend(["MaskFormerFeatureExtractor", "MaskFormerImageProcessor"])
+ _import_structure["models.mllama"].extend(["MllamaImageProcessor"])
+ _import_structure["models.mobilenet_v1"].extend(["MobileNetV1FeatureExtractor", "MobileNetV1ImageProcessor"])
+ _import_structure["models.mobilenet_v2"].extend(["MobileNetV2FeatureExtractor", "MobileNetV2ImageProcessor"])
+ _import_structure["models.mobilevit"].extend(["MobileViTFeatureExtractor", "MobileViTImageProcessor"])
+ _import_structure["models.nougat"].append("NougatImageProcessor")
+ _import_structure["models.oneformer"].extend(["OneFormerImageProcessor"])
+ _import_structure["models.owlv2"].append("Owlv2ImageProcessor")
+ _import_structure["models.owlvit"].extend(["OwlViTFeatureExtractor", "OwlViTImageProcessor"])
+ _import_structure["models.perceiver"].extend(["PerceiverFeatureExtractor", "PerceiverImageProcessor"])
+ _import_structure["models.pix2struct"].extend(["Pix2StructImageProcessor"])
+ _import_structure["models.pixtral"].append("PixtralImageProcessor")
+ _import_structure["models.poolformer"].extend(["PoolFormerFeatureExtractor", "PoolFormerImageProcessor"])
+ _import_structure["models.pvt"].extend(["PvtImageProcessor"])
+ _import_structure["models.qwen2_vl"].extend(["Qwen2VLImageProcessor"])
+ _import_structure["models.rt_detr"].extend(["RTDetrImageProcessor"])
+ _import_structure["models.sam"].extend(["SamImageProcessor"])
+ _import_structure["models.segformer"].extend(["SegformerFeatureExtractor", "SegformerImageProcessor"])
+ _import_structure["models.seggpt"].extend(["SegGptImageProcessor"])
+ _import_structure["models.siglip"].append("SiglipImageProcessor")
+ _import_structure["models.superpoint"].extend(["SuperPointImageProcessor"])
+ _import_structure["models.swin2sr"].append("Swin2SRImageProcessor")
+ _import_structure["models.tvp"].append("TvpImageProcessor")
+ _import_structure["models.video_llava"].append("VideoLlavaImageProcessor")
+ _import_structure["models.videomae"].extend(["VideoMAEFeatureExtractor", "VideoMAEImageProcessor"])
+ _import_structure["models.vilt"].extend(["ViltFeatureExtractor", "ViltImageProcessor", "ViltProcessor"])
+ _import_structure["models.vit"].extend(["ViTFeatureExtractor", "ViTImageProcessor"])
+ _import_structure["models.vitmatte"].append("VitMatteImageProcessor")
+ _import_structure["models.vivit"].append("VivitImageProcessor")
+ _import_structure["models.yolos"].extend(["YolosFeatureExtractor", "YolosImageProcessor"])
+ _import_structure["models.zoedepth"].append("ZoeDepthImageProcessor")
+
+try:
+ if not is_torchvision_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import dummy_torchvision_objects
+
+ _import_structure["utils.dummy_torchvision_objects"] = [
+ name for name in dir(dummy_torchvision_objects) if not name.startswith("_")
+ ]
+else:
+ _import_structure["image_processing_utils_fast"] = ["BaseImageProcessorFast"]
+ _import_structure["models.deformable_detr"].append("DeformableDetrImageProcessorFast")
+ _import_structure["models.detr"].append("DetrImageProcessorFast")
+ _import_structure["models.pixtral"].append("PixtralImageProcessorFast")
+ _import_structure["models.rt_detr"].append("RTDetrImageProcessorFast")
+ _import_structure["models.vit"].append("ViTImageProcessorFast")
+
+try:
+ if not is_torchvision_available() and not is_timm_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import dummy_timm_and_torchvision_objects
+
+ _import_structure["utils.dummy_timm_and_torchvision_objects"] = [
+ name for name in dir(dummy_timm_and_torchvision_objects) if not name.startswith("_")
+ ]
+else:
+ _import_structure["models.timm_wrapper"].extend(["TimmWrapperImageProcessor"])
+
+# PyTorch-backed objects
+try:
+ if not is_torch_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import dummy_pt_objects
+
+ _import_structure["utils.dummy_pt_objects"] = [name for name in dir(dummy_pt_objects) if not name.startswith("_")]
+else:
+ _import_structure["activations"] = []
+ _import_structure["benchmark.benchmark"] = ["PyTorchBenchmark"]
+ _import_structure["benchmark.benchmark_args"] = ["PyTorchBenchmarkArguments"]
+ _import_structure["cache_utils"] = [
+ "Cache",
+ "CacheConfig",
+ "DynamicCache",
+ "EncoderDecoderCache",
+ "HQQQuantizedCache",
+ "HybridCache",
+ "MambaCache",
+ "OffloadedCache",
+ "OffloadedStaticCache",
+ "QuantizedCache",
+ "QuantizedCacheConfig",
+ "QuantoQuantizedCache",
+ "SinkCache",
+ "SlidingWindowCache",
+ "StaticCache",
+ ]
+ _import_structure["data.datasets"] = [
+ "GlueDataset",
+ "GlueDataTrainingArguments",
+ "LineByLineTextDataset",
+ "LineByLineWithRefDataset",
+ "LineByLineWithSOPTextDataset",
+ "SquadDataset",
+ "SquadDataTrainingArguments",
+ "TextDataset",
+ "TextDatasetForNextSentencePrediction",
+ ]
+ _import_structure["generation"].extend(
+ [
+ "AlternatingCodebooksLogitsProcessor",
+ "BayesianDetectorConfig",
+ "BayesianDetectorModel",
+ "BeamScorer",
+ "BeamSearchScorer",
+ "ClassifierFreeGuidanceLogitsProcessor",
+ "ConstrainedBeamSearchScorer",
+ "Constraint",
+ "ConstraintListState",
+ "DisjunctiveConstraint",
+ "EncoderNoRepeatNGramLogitsProcessor",
+ "EncoderRepetitionPenaltyLogitsProcessor",
+ "EosTokenCriteria",
+ "EpsilonLogitsWarper",
+ "EtaLogitsWarper",
+ "ExponentialDecayLengthPenalty",
+ "ForcedBOSTokenLogitsProcessor",
+ "ForcedEOSTokenLogitsProcessor",
+ "GenerationMixin",
+ "HammingDiversityLogitsProcessor",
+ "InfNanRemoveLogitsProcessor",
+ "LogitNormalization",
+ "LogitsProcessor",
+ "LogitsProcessorList",
+ "LogitsWarper",
+ "MaxLengthCriteria",
+ "MaxTimeCriteria",
+ "MinLengthLogitsProcessor",
+ "MinNewTokensLengthLogitsProcessor",
+ "MinPLogitsWarper",
+ "NoBadWordsLogitsProcessor",
+ "NoRepeatNGramLogitsProcessor",
+ "PhrasalConstraint",
+ "PrefixConstrainedLogitsProcessor",
+ "RepetitionPenaltyLogitsProcessor",
+ "SequenceBiasLogitsProcessor",
+ "StoppingCriteria",
+ "StoppingCriteriaList",
+ "StopStringCriteria",
+ "SuppressTokensAtBeginLogitsProcessor",
+ "SuppressTokensLogitsProcessor",
+ "SynthIDTextWatermarkDetector",
+ "SynthIDTextWatermarkingConfig",
+ "SynthIDTextWatermarkLogitsProcessor",
+ "TemperatureLogitsWarper",
+ "TopKLogitsWarper",
+ "TopPLogitsWarper",
+ "TypicalLogitsWarper",
+ "UnbatchedClassifierFreeGuidanceLogitsProcessor",
+ "WatermarkDetector",
+ "WatermarkLogitsProcessor",
+ "WhisperTimeStampLogitsProcessor",
+ ]
+ )
+
+ # PyTorch domain libraries integration
+ _import_structure["integrations.executorch"] = [
+ "TorchExportableModuleWithStaticCache",
+ "convert_and_export_with_cache",
+ ]
+
+ _import_structure["modeling_flash_attention_utils"] = []
+ _import_structure["modeling_outputs"] = []
+ _import_structure["modeling_rope_utils"] = ["ROPE_INIT_FUNCTIONS"]
+ _import_structure["modeling_utils"] = ["PreTrainedModel"]
+
+ # PyTorch models structure
+
+ _import_structure["models.albert"].extend(
+ [
+ "AlbertForMaskedLM",
+ "AlbertForMultipleChoice",
+ "AlbertForPreTraining",
+ "AlbertForQuestionAnswering",
+ "AlbertForSequenceClassification",
+ "AlbertForTokenClassification",
+ "AlbertModel",
+ "AlbertPreTrainedModel",
+ "load_tf_weights_in_albert",
+ ]
+ )
+
+ _import_structure["models.align"].extend(
+ [
+ "AlignModel",
+ "AlignPreTrainedModel",
+ "AlignTextModel",
+ "AlignVisionModel",
+ ]
+ )
+ _import_structure["models.altclip"].extend(
+ [
+ "AltCLIPModel",
+ "AltCLIPPreTrainedModel",
+ "AltCLIPTextModel",
+ "AltCLIPVisionModel",
+ ]
+ )
+ _import_structure["models.aria"].extend(
+ [
+ "AriaForConditionalGeneration",
+ "AriaPreTrainedModel",
+ "AriaTextForCausalLM",
+ "AriaTextModel",
+ "AriaTextPreTrainedModel",
+ ]
+ )
+ _import_structure["models.audio_spectrogram_transformer"].extend(
+ [
+ "ASTForAudioClassification",
+ "ASTModel",
+ "ASTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.auto"].extend(
+ [
+ "MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING",
+ "MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING",
+ "MODEL_FOR_AUDIO_XVECTOR_MAPPING",
+ "MODEL_FOR_BACKBONE_MAPPING",
+ "MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING",
+ "MODEL_FOR_CAUSAL_LM_MAPPING",
+ "MODEL_FOR_CTC_MAPPING",
+ "MODEL_FOR_DEPTH_ESTIMATION_MAPPING",
+ "MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING",
+ "MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
+ "MODEL_FOR_IMAGE_MAPPING",
+ "MODEL_FOR_IMAGE_SEGMENTATION_MAPPING",
+ "MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING",
+ "MODEL_FOR_IMAGE_TO_IMAGE_MAPPING",
+ "MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING",
+ "MODEL_FOR_KEYPOINT_DETECTION_MAPPING",
+ "MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING",
+ "MODEL_FOR_MASKED_LM_MAPPING",
+ "MODEL_FOR_MASK_GENERATION_MAPPING",
+ "MODEL_FOR_MULTIPLE_CHOICE_MAPPING",
+ "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING",
+ "MODEL_FOR_OBJECT_DETECTION_MAPPING",
+ "MODEL_FOR_PRETRAINING_MAPPING",
+ "MODEL_FOR_QUESTION_ANSWERING_MAPPING",
+ "MODEL_FOR_RETRIEVAL_MAPPING",
+ "MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING",
+ "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING",
+ "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
+ "MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
+ "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING",
+ "MODEL_FOR_TEXT_ENCODING_MAPPING",
+ "MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING",
+ "MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING",
+ "MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING",
+ "MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING",
+ "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
+ "MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING",
+ "MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING",
+ "MODEL_FOR_VISION_2_SEQ_MAPPING",
+ "MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING",
+ "MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING",
+ "MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING",
+ "MODEL_MAPPING",
+ "MODEL_WITH_LM_HEAD_MAPPING",
+ "AutoBackbone",
+ "AutoModel",
+ "AutoModelForAudioClassification",
+ "AutoModelForAudioFrameClassification",
+ "AutoModelForAudioXVector",
+ "AutoModelForCausalLM",
+ "AutoModelForCTC",
+ "AutoModelForDepthEstimation",
+ "AutoModelForDocumentQuestionAnswering",
+ "AutoModelForImageClassification",
+ "AutoModelForImageSegmentation",
+ "AutoModelForImageTextToText",
+ "AutoModelForImageToImage",
+ "AutoModelForInstanceSegmentation",
+ "AutoModelForKeypointDetection",
+ "AutoModelForMaskedImageModeling",
+ "AutoModelForMaskedLM",
+ "AutoModelForMaskGeneration",
+ "AutoModelForMultipleChoice",
+ "AutoModelForNextSentencePrediction",
+ "AutoModelForObjectDetection",
+ "AutoModelForPreTraining",
+ "AutoModelForQuestionAnswering",
+ "AutoModelForSemanticSegmentation",
+ "AutoModelForSeq2SeqLM",
+ "AutoModelForSequenceClassification",
+ "AutoModelForSpeechSeq2Seq",
+ "AutoModelForTableQuestionAnswering",
+ "AutoModelForTextEncoding",
+ "AutoModelForTextToSpectrogram",
+ "AutoModelForTextToWaveform",
+ "AutoModelForTokenClassification",
+ "AutoModelForUniversalSegmentation",
+ "AutoModelForVideoClassification",
+ "AutoModelForVision2Seq",
+ "AutoModelForVisualQuestionAnswering",
+ "AutoModelForZeroShotImageClassification",
+ "AutoModelForZeroShotObjectDetection",
+ "AutoModelWithLMHead",
+ ]
+ )
+ _import_structure["models.autoformer"].extend(
+ [
+ "AutoformerForPrediction",
+ "AutoformerModel",
+ "AutoformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.bamba"].extend(
+ [
+ "BambaForCausalLM",
+ "BambaModel",
+ "BambaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.bark"].extend(
+ [
+ "BarkCausalModel",
+ "BarkCoarseModel",
+ "BarkFineModel",
+ "BarkModel",
+ "BarkPreTrainedModel",
+ "BarkSemanticModel",
+ ]
+ )
+ _import_structure["models.bart"].extend(
+ [
+ "BartForCausalLM",
+ "BartForConditionalGeneration",
+ "BartForQuestionAnswering",
+ "BartForSequenceClassification",
+ "BartModel",
+ "BartPretrainedModel",
+ "BartPreTrainedModel",
+ "PretrainedBartModel",
+ ]
+ )
+ _import_structure["models.beit"].extend(
+ [
+ "BeitBackbone",
+ "BeitForImageClassification",
+ "BeitForMaskedImageModeling",
+ "BeitForSemanticSegmentation",
+ "BeitModel",
+ "BeitPreTrainedModel",
+ ]
+ )
+ _import_structure["models.bert"].extend(
+ [
+ "BertForMaskedLM",
+ "BertForMultipleChoice",
+ "BertForNextSentencePrediction",
+ "BertForPreTraining",
+ "BertForQuestionAnswering",
+ "BertForSequenceClassification",
+ "BertForTokenClassification",
+ "BertLMHeadModel",
+ "BertModel",
+ "BertPreTrainedModel",
+ "load_tf_weights_in_bert",
+ ]
+ )
+ _import_structure["models.bert_generation"].extend(
+ [
+ "BertGenerationDecoder",
+ "BertGenerationEncoder",
+ "BertGenerationPreTrainedModel",
+ "load_tf_weights_in_bert_generation",
+ ]
+ )
+ _import_structure["models.big_bird"].extend(
+ [
+ "BigBirdForCausalLM",
+ "BigBirdForMaskedLM",
+ "BigBirdForMultipleChoice",
+ "BigBirdForPreTraining",
+ "BigBirdForQuestionAnswering",
+ "BigBirdForSequenceClassification",
+ "BigBirdForTokenClassification",
+ "BigBirdModel",
+ "BigBirdPreTrainedModel",
+ "load_tf_weights_in_big_bird",
+ ]
+ )
+ _import_structure["models.bigbird_pegasus"].extend(
+ [
+ "BigBirdPegasusForCausalLM",
+ "BigBirdPegasusForConditionalGeneration",
+ "BigBirdPegasusForQuestionAnswering",
+ "BigBirdPegasusForSequenceClassification",
+ "BigBirdPegasusModel",
+ "BigBirdPegasusPreTrainedModel",
+ ]
+ )
+ _import_structure["models.biogpt"].extend(
+ [
+ "BioGptForCausalLM",
+ "BioGptForSequenceClassification",
+ "BioGptForTokenClassification",
+ "BioGptModel",
+ "BioGptPreTrainedModel",
+ ]
+ )
+ _import_structure["models.bit"].extend(
+ [
+ "BitBackbone",
+ "BitForImageClassification",
+ "BitModel",
+ "BitPreTrainedModel",
+ ]
+ )
+ _import_structure["models.blenderbot"].extend(
+ [
+ "BlenderbotForCausalLM",
+ "BlenderbotForConditionalGeneration",
+ "BlenderbotModel",
+ "BlenderbotPreTrainedModel",
+ ]
+ )
+ _import_structure["models.blenderbot_small"].extend(
+ [
+ "BlenderbotSmallForCausalLM",
+ "BlenderbotSmallForConditionalGeneration",
+ "BlenderbotSmallModel",
+ "BlenderbotSmallPreTrainedModel",
+ ]
+ )
+ _import_structure["models.blip"].extend(
+ [
+ "BlipForConditionalGeneration",
+ "BlipForImageTextRetrieval",
+ "BlipForQuestionAnswering",
+ "BlipModel",
+ "BlipPreTrainedModel",
+ "BlipTextModel",
+ "BlipVisionModel",
+ ]
+ )
+ _import_structure["models.blip_2"].extend(
+ [
+ "Blip2ForConditionalGeneration",
+ "Blip2ForImageTextRetrieval",
+ "Blip2Model",
+ "Blip2PreTrainedModel",
+ "Blip2QFormerModel",
+ "Blip2TextModelWithProjection",
+ "Blip2VisionModel",
+ "Blip2VisionModelWithProjection",
+ ]
+ )
+ _import_structure["models.bloom"].extend(
+ [
+ "BloomForCausalLM",
+ "BloomForQuestionAnswering",
+ "BloomForSequenceClassification",
+ "BloomForTokenClassification",
+ "BloomModel",
+ "BloomPreTrainedModel",
+ ]
+ )
+ _import_structure["models.bridgetower"].extend(
+ [
+ "BridgeTowerForContrastiveLearning",
+ "BridgeTowerForImageAndTextRetrieval",
+ "BridgeTowerForMaskedLM",
+ "BridgeTowerModel",
+ "BridgeTowerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.bros"].extend(
+ [
+ "BrosForTokenClassification",
+ "BrosModel",
+ "BrosPreTrainedModel",
+ "BrosProcessor",
+ "BrosSpadeEEForTokenClassification",
+ "BrosSpadeELForTokenClassification",
+ ]
+ )
+ _import_structure["models.camembert"].extend(
+ [
+ "CamembertForCausalLM",
+ "CamembertForMaskedLM",
+ "CamembertForMultipleChoice",
+ "CamembertForQuestionAnswering",
+ "CamembertForSequenceClassification",
+ "CamembertForTokenClassification",
+ "CamembertModel",
+ "CamembertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.canine"].extend(
+ [
+ "CanineForMultipleChoice",
+ "CanineForQuestionAnswering",
+ "CanineForSequenceClassification",
+ "CanineForTokenClassification",
+ "CanineModel",
+ "CaninePreTrainedModel",
+ "load_tf_weights_in_canine",
+ ]
+ )
+ _import_structure["models.chameleon"].extend(
+ [
+ "ChameleonForConditionalGeneration",
+ "ChameleonModel",
+ "ChameleonPreTrainedModel",
+ "ChameleonProcessor",
+ "ChameleonVQVAE",
+ ]
+ )
+ _import_structure["models.chinese_clip"].extend(
+ [
+ "ChineseCLIPModel",
+ "ChineseCLIPPreTrainedModel",
+ "ChineseCLIPTextModel",
+ "ChineseCLIPVisionModel",
+ ]
+ )
+ _import_structure["models.clap"].extend(
+ [
+ "ClapAudioModel",
+ "ClapAudioModelWithProjection",
+ "ClapFeatureExtractor",
+ "ClapModel",
+ "ClapPreTrainedModel",
+ "ClapTextModel",
+ "ClapTextModelWithProjection",
+ ]
+ )
+ _import_structure["models.clip"].extend(
+ [
+ "CLIPForImageClassification",
+ "CLIPModel",
+ "CLIPPreTrainedModel",
+ "CLIPTextModel",
+ "CLIPTextModelWithProjection",
+ "CLIPVisionModel",
+ "CLIPVisionModelWithProjection",
+ ]
+ )
+ _import_structure["models.clipseg"].extend(
+ [
+ "CLIPSegForImageSegmentation",
+ "CLIPSegModel",
+ "CLIPSegPreTrainedModel",
+ "CLIPSegTextModel",
+ "CLIPSegVisionModel",
+ ]
+ )
+ _import_structure["models.clvp"].extend(
+ [
+ "ClvpDecoder",
+ "ClvpEncoder",
+ "ClvpForCausalLM",
+ "ClvpModel",
+ "ClvpModelForConditionalGeneration",
+ "ClvpPreTrainedModel",
+ ]
+ )
+ _import_structure["models.codegen"].extend(
+ [
+ "CodeGenForCausalLM",
+ "CodeGenModel",
+ "CodeGenPreTrainedModel",
+ ]
+ )
+ _import_structure["models.cohere"].extend(["CohereForCausalLM", "CohereModel", "CoherePreTrainedModel"])
+ _import_structure["models.cohere2"].extend(["Cohere2ForCausalLM", "Cohere2Model", "Cohere2PreTrainedModel"])
+ _import_structure["models.colpali"].extend(
+ [
+ "ColPaliForRetrieval",
+ "ColPaliPreTrainedModel",
+ ]
+ )
+ _import_structure["models.conditional_detr"].extend(
+ [
+ "ConditionalDetrForObjectDetection",
+ "ConditionalDetrForSegmentation",
+ "ConditionalDetrModel",
+ "ConditionalDetrPreTrainedModel",
+ ]
+ )
+ _import_structure["models.convbert"].extend(
+ [
+ "ConvBertForMaskedLM",
+ "ConvBertForMultipleChoice",
+ "ConvBertForQuestionAnswering",
+ "ConvBertForSequenceClassification",
+ "ConvBertForTokenClassification",
+ "ConvBertModel",
+ "ConvBertPreTrainedModel",
+ "load_tf_weights_in_convbert",
+ ]
+ )
+ _import_structure["models.convnext"].extend(
+ [
+ "ConvNextBackbone",
+ "ConvNextForImageClassification",
+ "ConvNextModel",
+ "ConvNextPreTrainedModel",
+ ]
+ )
+ _import_structure["models.convnextv2"].extend(
+ [
+ "ConvNextV2Backbone",
+ "ConvNextV2ForImageClassification",
+ "ConvNextV2Model",
+ "ConvNextV2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.cpmant"].extend(
+ [
+ "CpmAntForCausalLM",
+ "CpmAntModel",
+ "CpmAntPreTrainedModel",
+ ]
+ )
+ _import_structure["models.ctrl"].extend(
+ [
+ "CTRLForSequenceClassification",
+ "CTRLLMHeadModel",
+ "CTRLModel",
+ "CTRLPreTrainedModel",
+ ]
+ )
+ _import_structure["models.cvt"].extend(
+ [
+ "CvtForImageClassification",
+ "CvtModel",
+ "CvtPreTrainedModel",
+ ]
+ )
+ _import_structure["models.dac"].extend(
+ [
+ "DacModel",
+ "DacPreTrainedModel",
+ ]
+ )
+ _import_structure["models.data2vec"].extend(
+ [
+ "Data2VecAudioForAudioFrameClassification",
+ "Data2VecAudioForCTC",
+ "Data2VecAudioForSequenceClassification",
+ "Data2VecAudioForXVector",
+ "Data2VecAudioModel",
+ "Data2VecAudioPreTrainedModel",
+ "Data2VecTextForCausalLM",
+ "Data2VecTextForMaskedLM",
+ "Data2VecTextForMultipleChoice",
+ "Data2VecTextForQuestionAnswering",
+ "Data2VecTextForSequenceClassification",
+ "Data2VecTextForTokenClassification",
+ "Data2VecTextModel",
+ "Data2VecTextPreTrainedModel",
+ "Data2VecVisionForImageClassification",
+ "Data2VecVisionForSemanticSegmentation",
+ "Data2VecVisionModel",
+ "Data2VecVisionPreTrainedModel",
+ ]
+ )
+ _import_structure["models.dbrx"].extend(
+ [
+ "DbrxForCausalLM",
+ "DbrxModel",
+ "DbrxPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deberta"].extend(
+ [
+ "DebertaForMaskedLM",
+ "DebertaForQuestionAnswering",
+ "DebertaForSequenceClassification",
+ "DebertaForTokenClassification",
+ "DebertaModel",
+ "DebertaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deberta_v2"].extend(
+ [
+ "DebertaV2ForMaskedLM",
+ "DebertaV2ForMultipleChoice",
+ "DebertaV2ForQuestionAnswering",
+ "DebertaV2ForSequenceClassification",
+ "DebertaV2ForTokenClassification",
+ "DebertaV2Model",
+ "DebertaV2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.decision_transformer"].extend(
+ [
+ "DecisionTransformerGPT2Model",
+ "DecisionTransformerGPT2PreTrainedModel",
+ "DecisionTransformerModel",
+ "DecisionTransformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deformable_detr"].extend(
+ [
+ "DeformableDetrForObjectDetection",
+ "DeformableDetrModel",
+ "DeformableDetrPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deit"].extend(
+ [
+ "DeiTForImageClassification",
+ "DeiTForImageClassificationWithTeacher",
+ "DeiTForMaskedImageModeling",
+ "DeiTModel",
+ "DeiTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.deta"].extend(
+ [
+ "DetaForObjectDetection",
+ "DetaModel",
+ "DetaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.efficientformer"].extend(
+ [
+ "EfficientFormerForImageClassification",
+ "EfficientFormerForImageClassificationWithTeacher",
+ "EfficientFormerModel",
+ "EfficientFormerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.ernie_m"].extend(
+ [
+ "ErnieMForInformationExtraction",
+ "ErnieMForMultipleChoice",
+ "ErnieMForQuestionAnswering",
+ "ErnieMForSequenceClassification",
+ "ErnieMForTokenClassification",
+ "ErnieMModel",
+ "ErnieMPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.gptsan_japanese"].extend(
+ [
+ "GPTSanJapaneseForConditionalGeneration",
+ "GPTSanJapaneseModel",
+ "GPTSanJapanesePreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.graphormer"].extend(
+ [
+ "GraphormerForGraphClassification",
+ "GraphormerModel",
+ "GraphormerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.jukebox"].extend(
+ [
+ "JukeboxModel",
+ "JukeboxPreTrainedModel",
+ "JukeboxPrior",
+ "JukeboxVQVAE",
+ ]
+ )
+ _import_structure["models.deprecated.mctct"].extend(
+ [
+ "MCTCTForCTC",
+ "MCTCTModel",
+ "MCTCTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.mega"].extend(
+ [
+ "MegaForCausalLM",
+ "MegaForMaskedLM",
+ "MegaForMultipleChoice",
+ "MegaForQuestionAnswering",
+ "MegaForSequenceClassification",
+ "MegaForTokenClassification",
+ "MegaModel",
+ "MegaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.mmbt"].extend(["MMBTForClassification", "MMBTModel", "ModalEmbeddings"])
+ _import_structure["models.deprecated.nat"].extend(
+ [
+ "NatBackbone",
+ "NatForImageClassification",
+ "NatModel",
+ "NatPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.nezha"].extend(
+ [
+ "NezhaForMaskedLM",
+ "NezhaForMultipleChoice",
+ "NezhaForNextSentencePrediction",
+ "NezhaForPreTraining",
+ "NezhaForQuestionAnswering",
+ "NezhaForSequenceClassification",
+ "NezhaForTokenClassification",
+ "NezhaModel",
+ "NezhaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.open_llama"].extend(
+ [
+ "OpenLlamaForCausalLM",
+ "OpenLlamaForSequenceClassification",
+ "OpenLlamaModel",
+ "OpenLlamaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.qdqbert"].extend(
+ [
+ "QDQBertForMaskedLM",
+ "QDQBertForMultipleChoice",
+ "QDQBertForNextSentencePrediction",
+ "QDQBertForQuestionAnswering",
+ "QDQBertForSequenceClassification",
+ "QDQBertForTokenClassification",
+ "QDQBertLMHeadModel",
+ "QDQBertModel",
+ "QDQBertPreTrainedModel",
+ "load_tf_weights_in_qdqbert",
+ ]
+ )
+ _import_structure["models.deprecated.realm"].extend(
+ [
+ "RealmEmbedder",
+ "RealmForOpenQA",
+ "RealmKnowledgeAugEncoder",
+ "RealmPreTrainedModel",
+ "RealmReader",
+ "RealmRetriever",
+ "RealmScorer",
+ "load_tf_weights_in_realm",
+ ]
+ )
+ _import_structure["models.deprecated.retribert"].extend(
+ [
+ "RetriBertModel",
+ "RetriBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.speech_to_text_2"].extend(
+ ["Speech2Text2ForCausalLM", "Speech2Text2PreTrainedModel"]
+ )
+ _import_structure["models.deprecated.trajectory_transformer"].extend(
+ [
+ "TrajectoryTransformerModel",
+ "TrajectoryTransformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.transfo_xl"].extend(
+ [
+ "AdaptiveEmbedding",
+ "TransfoXLForSequenceClassification",
+ "TransfoXLLMHeadModel",
+ "TransfoXLModel",
+ "TransfoXLPreTrainedModel",
+ "load_tf_weights_in_transfo_xl",
+ ]
+ )
+ _import_structure["models.deprecated.tvlt"].extend(
+ [
+ "TvltForAudioVisualClassification",
+ "TvltForPreTraining",
+ "TvltModel",
+ "TvltPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.van"].extend(
+ [
+ "VanForImageClassification",
+ "VanModel",
+ "VanPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.vit_hybrid"].extend(
+ [
+ "ViTHybridForImageClassification",
+ "ViTHybridModel",
+ "ViTHybridPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.xlm_prophetnet"].extend(
+ [
+ "XLMProphetNetDecoder",
+ "XLMProphetNetEncoder",
+ "XLMProphetNetForCausalLM",
+ "XLMProphetNetForConditionalGeneration",
+ "XLMProphetNetModel",
+ "XLMProphetNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.depth_anything"].extend(
+ [
+ "DepthAnythingForDepthEstimation",
+ "DepthAnythingPreTrainedModel",
+ ]
+ )
+ _import_structure["models.detr"].extend(
+ [
+ "DetrForObjectDetection",
+ "DetrForSegmentation",
+ "DetrModel",
+ "DetrPreTrainedModel",
+ ]
+ )
+ _import_structure["models.dinat"].extend(
+ [
+ "DinatBackbone",
+ "DinatForImageClassification",
+ "DinatModel",
+ "DinatPreTrainedModel",
+ ]
+ )
+ _import_structure["models.dinov2"].extend(
+ [
+ "Dinov2Backbone",
+ "Dinov2ForImageClassification",
+ "Dinov2Model",
+ "Dinov2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.distilbert"].extend(
+ [
+ "DistilBertForMaskedLM",
+ "DistilBertForMultipleChoice",
+ "DistilBertForQuestionAnswering",
+ "DistilBertForSequenceClassification",
+ "DistilBertForTokenClassification",
+ "DistilBertModel",
+ "DistilBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.donut"].extend(
+ [
+ "DonutSwinModel",
+ "DonutSwinPreTrainedModel",
+ ]
+ )
+ _import_structure["models.dpr"].extend(
+ [
+ "DPRContextEncoder",
+ "DPRPretrainedContextEncoder",
+ "DPRPreTrainedModel",
+ "DPRPretrainedQuestionEncoder",
+ "DPRPretrainedReader",
+ "DPRQuestionEncoder",
+ "DPRReader",
+ ]
+ )
+ _import_structure["models.dpt"].extend(
+ [
+ "DPTForDepthEstimation",
+ "DPTForSemanticSegmentation",
+ "DPTModel",
+ "DPTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.efficientnet"].extend(
+ [
+ "EfficientNetForImageClassification",
+ "EfficientNetModel",
+ "EfficientNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.electra"].extend(
+ [
+ "ElectraForCausalLM",
+ "ElectraForMaskedLM",
+ "ElectraForMultipleChoice",
+ "ElectraForPreTraining",
+ "ElectraForQuestionAnswering",
+ "ElectraForSequenceClassification",
+ "ElectraForTokenClassification",
+ "ElectraModel",
+ "ElectraPreTrainedModel",
+ "load_tf_weights_in_electra",
+ ]
+ )
+ _import_structure["models.encodec"].extend(
+ [
+ "EncodecModel",
+ "EncodecPreTrainedModel",
+ ]
+ )
+ _import_structure["models.encoder_decoder"].append("EncoderDecoderModel")
+ _import_structure["models.ernie"].extend(
+ [
+ "ErnieForCausalLM",
+ "ErnieForMaskedLM",
+ "ErnieForMultipleChoice",
+ "ErnieForNextSentencePrediction",
+ "ErnieForPreTraining",
+ "ErnieForQuestionAnswering",
+ "ErnieForSequenceClassification",
+ "ErnieForTokenClassification",
+ "ErnieModel",
+ "ErniePreTrainedModel",
+ ]
+ )
+ _import_structure["models.esm"].extend(
+ [
+ "EsmFoldPreTrainedModel",
+ "EsmForMaskedLM",
+ "EsmForProteinFolding",
+ "EsmForSequenceClassification",
+ "EsmForTokenClassification",
+ "EsmModel",
+ "EsmPreTrainedModel",
+ ]
+ )
+ _import_structure["models.falcon"].extend(
+ [
+ "FalconForCausalLM",
+ "FalconForQuestionAnswering",
+ "FalconForSequenceClassification",
+ "FalconForTokenClassification",
+ "FalconModel",
+ "FalconPreTrainedModel",
+ ]
+ )
+ _import_structure["models.falcon_mamba"].extend(
+ [
+ "FalconMambaForCausalLM",
+ "FalconMambaModel",
+ "FalconMambaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.fastspeech2_conformer"].extend(
+ [
+ "FastSpeech2ConformerHifiGan",
+ "FastSpeech2ConformerModel",
+ "FastSpeech2ConformerPreTrainedModel",
+ "FastSpeech2ConformerWithHifiGan",
+ ]
+ )
+ _import_structure["models.flaubert"].extend(
+ [
+ "FlaubertForMultipleChoice",
+ "FlaubertForQuestionAnswering",
+ "FlaubertForQuestionAnsweringSimple",
+ "FlaubertForSequenceClassification",
+ "FlaubertForTokenClassification",
+ "FlaubertModel",
+ "FlaubertPreTrainedModel",
+ "FlaubertWithLMHeadModel",
+ ]
+ )
+ _import_structure["models.flava"].extend(
+ [
+ "FlavaForPreTraining",
+ "FlavaImageCodebook",
+ "FlavaImageModel",
+ "FlavaModel",
+ "FlavaMultimodalModel",
+ "FlavaPreTrainedModel",
+ "FlavaTextModel",
+ ]
+ )
+ _import_structure["models.fnet"].extend(
+ [
+ "FNetForMaskedLM",
+ "FNetForMultipleChoice",
+ "FNetForNextSentencePrediction",
+ "FNetForPreTraining",
+ "FNetForQuestionAnswering",
+ "FNetForSequenceClassification",
+ "FNetForTokenClassification",
+ "FNetModel",
+ "FNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.focalnet"].extend(
+ [
+ "FocalNetBackbone",
+ "FocalNetForImageClassification",
+ "FocalNetForMaskedImageModeling",
+ "FocalNetModel",
+ "FocalNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.fsmt"].extend(["FSMTForConditionalGeneration", "FSMTModel", "PretrainedFSMTModel"])
+ _import_structure["models.funnel"].extend(
+ [
+ "FunnelBaseModel",
+ "FunnelForMaskedLM",
+ "FunnelForMultipleChoice",
+ "FunnelForPreTraining",
+ "FunnelForQuestionAnswering",
+ "FunnelForSequenceClassification",
+ "FunnelForTokenClassification",
+ "FunnelModel",
+ "FunnelPreTrainedModel",
+ "load_tf_weights_in_funnel",
+ ]
+ )
+ _import_structure["models.fuyu"].extend(["FuyuForCausalLM", "FuyuPreTrainedModel"])
+ _import_structure["models.gemma"].extend(
+ [
+ "GemmaForCausalLM",
+ "GemmaForSequenceClassification",
+ "GemmaForTokenClassification",
+ "GemmaModel",
+ "GemmaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.gemma2"].extend(
+ [
+ "Gemma2ForCausalLM",
+ "Gemma2ForSequenceClassification",
+ "Gemma2ForTokenClassification",
+ "Gemma2Model",
+ "Gemma2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.git"].extend(
+ [
+ "GitForCausalLM",
+ "GitModel",
+ "GitPreTrainedModel",
+ "GitVisionModel",
+ ]
+ )
+ _import_structure["models.glm"].extend(
+ [
+ "GlmForCausalLM",
+ "GlmForSequenceClassification",
+ "GlmForTokenClassification",
+ "GlmModel",
+ "GlmPreTrainedModel",
+ ]
+ )
+ _import_structure["models.glpn"].extend(
+ [
+ "GLPNForDepthEstimation",
+ "GLPNModel",
+ "GLPNPreTrainedModel",
+ ]
+ )
+ _import_structure["models.gpt2"].extend(
+ [
+ "GPT2DoubleHeadsModel",
+ "GPT2ForQuestionAnswering",
+ "GPT2ForSequenceClassification",
+ "GPT2ForTokenClassification",
+ "GPT2LMHeadModel",
+ "GPT2Model",
+ "GPT2PreTrainedModel",
+ "load_tf_weights_in_gpt2",
+ ]
+ )
+ _import_structure["models.gpt_bigcode"].extend(
+ [
+ "GPTBigCodeForCausalLM",
+ "GPTBigCodeForSequenceClassification",
+ "GPTBigCodeForTokenClassification",
+ "GPTBigCodeModel",
+ "GPTBigCodePreTrainedModel",
+ ]
+ )
+ _import_structure["models.gpt_neo"].extend(
+ [
+ "GPTNeoForCausalLM",
+ "GPTNeoForQuestionAnswering",
+ "GPTNeoForSequenceClassification",
+ "GPTNeoForTokenClassification",
+ "GPTNeoModel",
+ "GPTNeoPreTrainedModel",
+ "load_tf_weights_in_gpt_neo",
+ ]
+ )
+ _import_structure["models.gpt_neox"].extend(
+ [
+ "GPTNeoXForCausalLM",
+ "GPTNeoXForQuestionAnswering",
+ "GPTNeoXForSequenceClassification",
+ "GPTNeoXForTokenClassification",
+ "GPTNeoXModel",
+ "GPTNeoXPreTrainedModel",
+ ]
+ )
+ _import_structure["models.gpt_neox_japanese"].extend(
+ [
+ "GPTNeoXJapaneseForCausalLM",
+ "GPTNeoXJapaneseModel",
+ "GPTNeoXJapanesePreTrainedModel",
+ ]
+ )
+ _import_structure["models.gptj"].extend(
+ [
+ "GPTJForCausalLM",
+ "GPTJForQuestionAnswering",
+ "GPTJForSequenceClassification",
+ "GPTJModel",
+ "GPTJPreTrainedModel",
+ ]
+ )
+ _import_structure["models.granite"].extend(
+ [
+ "GraniteForCausalLM",
+ "GraniteModel",
+ "GranitePreTrainedModel",
+ ]
+ )
+ _import_structure["models.granitemoe"].extend(
+ [
+ "GraniteMoeForCausalLM",
+ "GraniteMoeModel",
+ "GraniteMoePreTrainedModel",
+ ]
+ )
+ _import_structure["models.grounding_dino"].extend(
+ [
+ "GroundingDinoForObjectDetection",
+ "GroundingDinoModel",
+ "GroundingDinoPreTrainedModel",
+ ]
+ )
+ _import_structure["models.groupvit"].extend(
+ [
+ "GroupViTModel",
+ "GroupViTPreTrainedModel",
+ "GroupViTTextModel",
+ "GroupViTVisionModel",
+ ]
+ )
+ _import_structure["models.hiera"].extend(
+ [
+ "HieraBackbone",
+ "HieraForImageClassification",
+ "HieraForPreTraining",
+ "HieraModel",
+ "HieraPreTrainedModel",
+ ]
+ )
+ _import_structure["models.hubert"].extend(
+ [
+ "HubertForCTC",
+ "HubertForSequenceClassification",
+ "HubertModel",
+ "HubertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.ibert"].extend(
+ [
+ "IBertForMaskedLM",
+ "IBertForMultipleChoice",
+ "IBertForQuestionAnswering",
+ "IBertForSequenceClassification",
+ "IBertForTokenClassification",
+ "IBertModel",
+ "IBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.idefics"].extend(
+ [
+ "IdeficsForVisionText2Text",
+ "IdeficsModel",
+ "IdeficsPreTrainedModel",
+ "IdeficsProcessor",
+ ]
+ )
+ _import_structure["models.idefics2"].extend(
+ [
+ "Idefics2ForConditionalGeneration",
+ "Idefics2Model",
+ "Idefics2PreTrainedModel",
+ "Idefics2Processor",
+ ]
+ )
+ _import_structure["models.idefics3"].extend(
+ [
+ "Idefics3ForConditionalGeneration",
+ "Idefics3Model",
+ "Idefics3PreTrainedModel",
+ "Idefics3Processor",
+ "Idefics3VisionConfig",
+ "Idefics3VisionTransformer",
+ ]
+ )
+ _import_structure["models.ijepa"].extend(
+ [
+ "IJepaForImageClassification",
+ "IJepaModel",
+ "IJepaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.imagegpt"].extend(
+ [
+ "ImageGPTForCausalImageModeling",
+ "ImageGPTForImageClassification",
+ "ImageGPTModel",
+ "ImageGPTPreTrainedModel",
+ "load_tf_weights_in_imagegpt",
+ ]
+ )
+ _import_structure["models.informer"].extend(
+ [
+ "InformerForPrediction",
+ "InformerModel",
+ "InformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.instructblip"].extend(
+ [
+ "InstructBlipForConditionalGeneration",
+ "InstructBlipPreTrainedModel",
+ "InstructBlipQFormerModel",
+ "InstructBlipVisionModel",
+ ]
+ )
+ _import_structure["models.instructblipvideo"].extend(
+ [
+ "InstructBlipVideoForConditionalGeneration",
+ "InstructBlipVideoPreTrainedModel",
+ "InstructBlipVideoQFormerModel",
+ "InstructBlipVideoVisionModel",
+ ]
+ )
+ _import_structure["models.jamba"].extend(
+ [
+ "JambaForCausalLM",
+ "JambaForSequenceClassification",
+ "JambaModel",
+ "JambaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.jetmoe"].extend(
+ [
+ "JetMoeForCausalLM",
+ "JetMoeForSequenceClassification",
+ "JetMoeModel",
+ "JetMoePreTrainedModel",
+ ]
+ )
+ _import_structure["models.kosmos2"].extend(
+ [
+ "Kosmos2ForConditionalGeneration",
+ "Kosmos2Model",
+ "Kosmos2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.layoutlm"].extend(
+ [
+ "LayoutLMForMaskedLM",
+ "LayoutLMForQuestionAnswering",
+ "LayoutLMForSequenceClassification",
+ "LayoutLMForTokenClassification",
+ "LayoutLMModel",
+ "LayoutLMPreTrainedModel",
+ ]
+ )
+ _import_structure["models.layoutlmv2"].extend(
+ [
+ "LayoutLMv2ForQuestionAnswering",
+ "LayoutLMv2ForSequenceClassification",
+ "LayoutLMv2ForTokenClassification",
+ "LayoutLMv2Model",
+ "LayoutLMv2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.layoutlmv3"].extend(
+ [
+ "LayoutLMv3ForQuestionAnswering",
+ "LayoutLMv3ForSequenceClassification",
+ "LayoutLMv3ForTokenClassification",
+ "LayoutLMv3Model",
+ "LayoutLMv3PreTrainedModel",
+ ]
+ )
+ _import_structure["models.led"].extend(
+ [
+ "LEDForConditionalGeneration",
+ "LEDForQuestionAnswering",
+ "LEDForSequenceClassification",
+ "LEDModel",
+ "LEDPreTrainedModel",
+ ]
+ )
+ _import_structure["models.levit"].extend(
+ [
+ "LevitForImageClassification",
+ "LevitForImageClassificationWithTeacher",
+ "LevitModel",
+ "LevitPreTrainedModel",
+ ]
+ )
+ _import_structure["models.lilt"].extend(
+ [
+ "LiltForQuestionAnswering",
+ "LiltForSequenceClassification",
+ "LiltForTokenClassification",
+ "LiltModel",
+ "LiltPreTrainedModel",
+ ]
+ )
+ _import_structure["models.llama"].extend(
+ [
+ "LlamaForCausalLM",
+ "LlamaForQuestionAnswering",
+ "LlamaForSequenceClassification",
+ "LlamaForTokenClassification",
+ "LlamaModel",
+ "LlamaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.llava"].extend(
+ [
+ "LlavaForConditionalGeneration",
+ "LlavaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.llava_next"].extend(
+ [
+ "LlavaNextForConditionalGeneration",
+ "LlavaNextPreTrainedModel",
+ ]
+ )
+ _import_structure["models.llava_next_video"].extend(
+ [
+ "LlavaNextVideoForConditionalGeneration",
+ "LlavaNextVideoPreTrainedModel",
+ ]
+ )
+ _import_structure["models.llava_onevision"].extend(
+ [
+ "LlavaOnevisionForConditionalGeneration",
+ "LlavaOnevisionPreTrainedModel",
+ ]
+ )
+ _import_structure["models.longformer"].extend(
+ [
+ "LongformerForMaskedLM",
+ "LongformerForMultipleChoice",
+ "LongformerForQuestionAnswering",
+ "LongformerForSequenceClassification",
+ "LongformerForTokenClassification",
+ "LongformerModel",
+ "LongformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.longt5"].extend(
+ [
+ "LongT5EncoderModel",
+ "LongT5ForConditionalGeneration",
+ "LongT5Model",
+ "LongT5PreTrainedModel",
+ ]
+ )
+ _import_structure["models.luke"].extend(
+ [
+ "LukeForEntityClassification",
+ "LukeForEntityPairClassification",
+ "LukeForEntitySpanClassification",
+ "LukeForMaskedLM",
+ "LukeForMultipleChoice",
+ "LukeForQuestionAnswering",
+ "LukeForSequenceClassification",
+ "LukeForTokenClassification",
+ "LukeModel",
+ "LukePreTrainedModel",
+ ]
+ )
+ _import_structure["models.lxmert"].extend(
+ [
+ "LxmertEncoder",
+ "LxmertForPreTraining",
+ "LxmertForQuestionAnswering",
+ "LxmertModel",
+ "LxmertPreTrainedModel",
+ "LxmertVisualFeatureEncoder",
+ ]
+ )
+ _import_structure["models.m2m_100"].extend(
+ [
+ "M2M100ForConditionalGeneration",
+ "M2M100Model",
+ "M2M100PreTrainedModel",
+ ]
+ )
+ _import_structure["models.mamba"].extend(
+ [
+ "MambaForCausalLM",
+ "MambaModel",
+ "MambaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mamba2"].extend(
+ [
+ "Mamba2ForCausalLM",
+ "Mamba2Model",
+ "Mamba2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.marian"].extend(
+ ["MarianForCausalLM", "MarianModel", "MarianMTModel", "MarianPreTrainedModel"]
+ )
+ _import_structure["models.markuplm"].extend(
+ [
+ "MarkupLMForQuestionAnswering",
+ "MarkupLMForSequenceClassification",
+ "MarkupLMForTokenClassification",
+ "MarkupLMModel",
+ "MarkupLMPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mask2former"].extend(
+ [
+ "Mask2FormerForUniversalSegmentation",
+ "Mask2FormerModel",
+ "Mask2FormerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.maskformer"].extend(
+ [
+ "MaskFormerForInstanceSegmentation",
+ "MaskFormerModel",
+ "MaskFormerPreTrainedModel",
+ "MaskFormerSwinBackbone",
+ ]
+ )
+ _import_structure["models.mbart"].extend(
+ [
+ "MBartForCausalLM",
+ "MBartForConditionalGeneration",
+ "MBartForQuestionAnswering",
+ "MBartForSequenceClassification",
+ "MBartModel",
+ "MBartPreTrainedModel",
+ ]
+ )
+ _import_structure["models.megatron_bert"].extend(
+ [
+ "MegatronBertForCausalLM",
+ "MegatronBertForMaskedLM",
+ "MegatronBertForMultipleChoice",
+ "MegatronBertForNextSentencePrediction",
+ "MegatronBertForPreTraining",
+ "MegatronBertForQuestionAnswering",
+ "MegatronBertForSequenceClassification",
+ "MegatronBertForTokenClassification",
+ "MegatronBertModel",
+ "MegatronBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mgp_str"].extend(
+ [
+ "MgpstrForSceneTextRecognition",
+ "MgpstrModel",
+ "MgpstrPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mimi"].extend(
+ [
+ "MimiModel",
+ "MimiPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mistral"].extend(
+ [
+ "MistralForCausalLM",
+ "MistralForQuestionAnswering",
+ "MistralForSequenceClassification",
+ "MistralForTokenClassification",
+ "MistralModel",
+ "MistralPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mixtral"].extend(
+ [
+ "MixtralForCausalLM",
+ "MixtralForQuestionAnswering",
+ "MixtralForSequenceClassification",
+ "MixtralForTokenClassification",
+ "MixtralModel",
+ "MixtralPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mllama"].extend(
+ [
+ "MllamaForCausalLM",
+ "MllamaForConditionalGeneration",
+ "MllamaPreTrainedModel",
+ "MllamaProcessor",
+ "MllamaTextModel",
+ "MllamaVisionModel",
+ ]
+ )
+ _import_structure["models.mobilebert"].extend(
+ [
+ "MobileBertForMaskedLM",
+ "MobileBertForMultipleChoice",
+ "MobileBertForNextSentencePrediction",
+ "MobileBertForPreTraining",
+ "MobileBertForQuestionAnswering",
+ "MobileBertForSequenceClassification",
+ "MobileBertForTokenClassification",
+ "MobileBertModel",
+ "MobileBertPreTrainedModel",
+ "load_tf_weights_in_mobilebert",
+ ]
+ )
+ _import_structure["models.mobilenet_v1"].extend(
+ [
+ "MobileNetV1ForImageClassification",
+ "MobileNetV1Model",
+ "MobileNetV1PreTrainedModel",
+ "load_tf_weights_in_mobilenet_v1",
+ ]
+ )
+ _import_structure["models.mobilenet_v2"].extend(
+ [
+ "MobileNetV2ForImageClassification",
+ "MobileNetV2ForSemanticSegmentation",
+ "MobileNetV2Model",
+ "MobileNetV2PreTrainedModel",
+ "load_tf_weights_in_mobilenet_v2",
+ ]
+ )
+ _import_structure["models.mobilevit"].extend(
+ [
+ "MobileViTForImageClassification",
+ "MobileViTForSemanticSegmentation",
+ "MobileViTModel",
+ "MobileViTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mobilevitv2"].extend(
+ [
+ "MobileViTV2ForImageClassification",
+ "MobileViTV2ForSemanticSegmentation",
+ "MobileViTV2Model",
+ "MobileViTV2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.modernbert"].extend(
+ [
+ "ModernBertForMaskedLM",
+ "ModernBertForSequenceClassification",
+ "ModernBertForTokenClassification",
+ "ModernBertModel",
+ "ModernBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.moshi"].extend(
+ [
+ "MoshiForCausalLM",
+ "MoshiForConditionalGeneration",
+ "MoshiModel",
+ "MoshiPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mpnet"].extend(
+ [
+ "MPNetForMaskedLM",
+ "MPNetForMultipleChoice",
+ "MPNetForQuestionAnswering",
+ "MPNetForSequenceClassification",
+ "MPNetForTokenClassification",
+ "MPNetModel",
+ "MPNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mpt"].extend(
+ [
+ "MptForCausalLM",
+ "MptForQuestionAnswering",
+ "MptForSequenceClassification",
+ "MptForTokenClassification",
+ "MptModel",
+ "MptPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mra"].extend(
+ [
+ "MraForMaskedLM",
+ "MraForMultipleChoice",
+ "MraForQuestionAnswering",
+ "MraForSequenceClassification",
+ "MraForTokenClassification",
+ "MraModel",
+ "MraPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mt5"].extend(
+ [
+ "MT5EncoderModel",
+ "MT5ForConditionalGeneration",
+ "MT5ForQuestionAnswering",
+ "MT5ForSequenceClassification",
+ "MT5ForTokenClassification",
+ "MT5Model",
+ "MT5PreTrainedModel",
+ ]
+ )
+ _import_structure["models.musicgen"].extend(
+ [
+ "MusicgenForCausalLM",
+ "MusicgenForConditionalGeneration",
+ "MusicgenModel",
+ "MusicgenPreTrainedModel",
+ "MusicgenProcessor",
+ ]
+ )
+ _import_structure["models.musicgen_melody"].extend(
+ [
+ "MusicgenMelodyForCausalLM",
+ "MusicgenMelodyForConditionalGeneration",
+ "MusicgenMelodyModel",
+ "MusicgenMelodyPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mvp"].extend(
+ [
+ "MvpForCausalLM",
+ "MvpForConditionalGeneration",
+ "MvpForQuestionAnswering",
+ "MvpForSequenceClassification",
+ "MvpModel",
+ "MvpPreTrainedModel",
+ ]
+ )
+ _import_structure["models.nemotron"].extend(
+ [
+ "NemotronForCausalLM",
+ "NemotronForQuestionAnswering",
+ "NemotronForSequenceClassification",
+ "NemotronForTokenClassification",
+ "NemotronModel",
+ "NemotronPreTrainedModel",
+ ]
+ )
+ _import_structure["models.nllb_moe"].extend(
+ [
+ "NllbMoeForConditionalGeneration",
+ "NllbMoeModel",
+ "NllbMoePreTrainedModel",
+ "NllbMoeSparseMLP",
+ "NllbMoeTop2Router",
+ ]
+ )
+ _import_structure["models.nystromformer"].extend(
+ [
+ "NystromformerForMaskedLM",
+ "NystromformerForMultipleChoice",
+ "NystromformerForQuestionAnswering",
+ "NystromformerForSequenceClassification",
+ "NystromformerForTokenClassification",
+ "NystromformerModel",
+ "NystromformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.olmo"].extend(
+ [
+ "OlmoForCausalLM",
+ "OlmoModel",
+ "OlmoPreTrainedModel",
+ ]
+ )
+ _import_structure["models.olmo2"].extend(
+ [
+ "Olmo2ForCausalLM",
+ "Olmo2Model",
+ "Olmo2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.olmoe"].extend(
+ [
+ "OlmoeForCausalLM",
+ "OlmoeModel",
+ "OlmoePreTrainedModel",
+ ]
+ )
+ _import_structure["models.omdet_turbo"].extend(
+ [
+ "OmDetTurboForObjectDetection",
+ "OmDetTurboPreTrainedModel",
+ ]
+ )
+ _import_structure["models.oneformer"].extend(
+ [
+ "OneFormerForUniversalSegmentation",
+ "OneFormerModel",
+ "OneFormerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.openai"].extend(
+ [
+ "OpenAIGPTDoubleHeadsModel",
+ "OpenAIGPTForSequenceClassification",
+ "OpenAIGPTLMHeadModel",
+ "OpenAIGPTModel",
+ "OpenAIGPTPreTrainedModel",
+ "load_tf_weights_in_openai_gpt",
+ ]
+ )
+ _import_structure["models.opt"].extend(
+ [
+ "OPTForCausalLM",
+ "OPTForQuestionAnswering",
+ "OPTForSequenceClassification",
+ "OPTModel",
+ "OPTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.owlv2"].extend(
+ [
+ "Owlv2ForObjectDetection",
+ "Owlv2Model",
+ "Owlv2PreTrainedModel",
+ "Owlv2TextModel",
+ "Owlv2VisionModel",
+ ]
+ )
+ _import_structure["models.owlvit"].extend(
+ [
+ "OwlViTForObjectDetection",
+ "OwlViTModel",
+ "OwlViTPreTrainedModel",
+ "OwlViTTextModel",
+ "OwlViTVisionModel",
+ ]
+ )
+ _import_structure["models.paligemma"].extend(
+ [
+ "PaliGemmaForConditionalGeneration",
+ "PaliGemmaPreTrainedModel",
+ "PaliGemmaProcessor",
+ ]
+ )
+ _import_structure["models.patchtsmixer"].extend(
+ [
+ "PatchTSMixerForPrediction",
+ "PatchTSMixerForPretraining",
+ "PatchTSMixerForRegression",
+ "PatchTSMixerForTimeSeriesClassification",
+ "PatchTSMixerModel",
+ "PatchTSMixerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.patchtst"].extend(
+ [
+ "PatchTSTForClassification",
+ "PatchTSTForPrediction",
+ "PatchTSTForPretraining",
+ "PatchTSTForRegression",
+ "PatchTSTModel",
+ "PatchTSTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.pegasus"].extend(
+ [
+ "PegasusForCausalLM",
+ "PegasusForConditionalGeneration",
+ "PegasusModel",
+ "PegasusPreTrainedModel",
+ ]
+ )
+ _import_structure["models.pegasus_x"].extend(
+ [
+ "PegasusXForConditionalGeneration",
+ "PegasusXModel",
+ "PegasusXPreTrainedModel",
+ ]
+ )
+ _import_structure["models.perceiver"].extend(
+ [
+ "PerceiverForImageClassificationConvProcessing",
+ "PerceiverForImageClassificationFourier",
+ "PerceiverForImageClassificationLearned",
+ "PerceiverForMaskedLM",
+ "PerceiverForMultimodalAutoencoding",
+ "PerceiverForOpticalFlow",
+ "PerceiverForSequenceClassification",
+ "PerceiverModel",
+ "PerceiverPreTrainedModel",
+ ]
+ )
+ _import_structure["models.persimmon"].extend(
+ [
+ "PersimmonForCausalLM",
+ "PersimmonForSequenceClassification",
+ "PersimmonForTokenClassification",
+ "PersimmonModel",
+ "PersimmonPreTrainedModel",
+ ]
+ )
+ _import_structure["models.phi"].extend(
+ [
+ "PhiForCausalLM",
+ "PhiForSequenceClassification",
+ "PhiForTokenClassification",
+ "PhiModel",
+ "PhiPreTrainedModel",
+ ]
+ )
+ _import_structure["models.phi3"].extend(
+ [
+ "Phi3ForCausalLM",
+ "Phi3ForSequenceClassification",
+ "Phi3ForTokenClassification",
+ "Phi3Model",
+ "Phi3PreTrainedModel",
+ ]
+ )
+ _import_structure["models.phimoe"].extend(
+ [
+ "PhimoeForCausalLM",
+ "PhimoeForSequenceClassification",
+ "PhimoeModel",
+ "PhimoePreTrainedModel",
+ ]
+ )
+ _import_structure["models.pix2struct"].extend(
+ [
+ "Pix2StructForConditionalGeneration",
+ "Pix2StructPreTrainedModel",
+ "Pix2StructTextModel",
+ "Pix2StructVisionModel",
+ ]
+ )
+ _import_structure["models.pixtral"].extend(["PixtralPreTrainedModel", "PixtralVisionModel"])
+ _import_structure["models.plbart"].extend(
+ [
+ "PLBartForCausalLM",
+ "PLBartForConditionalGeneration",
+ "PLBartForSequenceClassification",
+ "PLBartModel",
+ "PLBartPreTrainedModel",
+ ]
+ )
+ _import_structure["models.poolformer"].extend(
+ [
+ "PoolFormerForImageClassification",
+ "PoolFormerModel",
+ "PoolFormerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.pop2piano"].extend(
+ [
+ "Pop2PianoForConditionalGeneration",
+ "Pop2PianoPreTrainedModel",
+ ]
+ )
+ _import_structure["models.prophetnet"].extend(
+ [
+ "ProphetNetDecoder",
+ "ProphetNetEncoder",
+ "ProphetNetForCausalLM",
+ "ProphetNetForConditionalGeneration",
+ "ProphetNetModel",
+ "ProphetNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.pvt"].extend(
+ [
+ "PvtForImageClassification",
+ "PvtModel",
+ "PvtPreTrainedModel",
+ ]
+ )
+ _import_structure["models.pvt_v2"].extend(
+ [
+ "PvtV2Backbone",
+ "PvtV2ForImageClassification",
+ "PvtV2Model",
+ "PvtV2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.qwen2"].extend(
+ [
+ "Qwen2ForCausalLM",
+ "Qwen2ForQuestionAnswering",
+ "Qwen2ForSequenceClassification",
+ "Qwen2ForTokenClassification",
+ "Qwen2Model",
+ "Qwen2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.qwen2_audio"].extend(
+ [
+ "Qwen2AudioEncoder",
+ "Qwen2AudioForConditionalGeneration",
+ "Qwen2AudioPreTrainedModel",
+ ]
+ )
+ _import_structure["models.qwen2_moe"].extend(
+ [
+ "Qwen2MoeForCausalLM",
+ "Qwen2MoeForQuestionAnswering",
+ "Qwen2MoeForSequenceClassification",
+ "Qwen2MoeForTokenClassification",
+ "Qwen2MoeModel",
+ "Qwen2MoePreTrainedModel",
+ ]
+ )
+ _import_structure["models.qwen2_vl"].extend(
+ [
+ "Qwen2VLForConditionalGeneration",
+ "Qwen2VLModel",
+ "Qwen2VLPreTrainedModel",
+ ]
+ )
+ _import_structure["models.rag"].extend(
+ [
+ "RagModel",
+ "RagPreTrainedModel",
+ "RagSequenceForGeneration",
+ "RagTokenForGeneration",
+ ]
+ )
+ _import_structure["models.recurrent_gemma"].extend(
+ [
+ "RecurrentGemmaForCausalLM",
+ "RecurrentGemmaModel",
+ "RecurrentGemmaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.reformer"].extend(
+ [
+ "ReformerForMaskedLM",
+ "ReformerForQuestionAnswering",
+ "ReformerForSequenceClassification",
+ "ReformerModel",
+ "ReformerModelWithLMHead",
+ "ReformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.regnet"].extend(
+ [
+ "RegNetForImageClassification",
+ "RegNetModel",
+ "RegNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.rembert"].extend(
+ [
+ "RemBertForCausalLM",
+ "RemBertForMaskedLM",
+ "RemBertForMultipleChoice",
+ "RemBertForQuestionAnswering",
+ "RemBertForSequenceClassification",
+ "RemBertForTokenClassification",
+ "RemBertModel",
+ "RemBertPreTrainedModel",
+ "load_tf_weights_in_rembert",
+ ]
+ )
+ _import_structure["models.resnet"].extend(
+ [
+ "ResNetBackbone",
+ "ResNetForImageClassification",
+ "ResNetModel",
+ "ResNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.roberta"].extend(
+ [
+ "RobertaForCausalLM",
+ "RobertaForMaskedLM",
+ "RobertaForMultipleChoice",
+ "RobertaForQuestionAnswering",
+ "RobertaForSequenceClassification",
+ "RobertaForTokenClassification",
+ "RobertaModel",
+ "RobertaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.roberta_prelayernorm"].extend(
+ [
+ "RobertaPreLayerNormForCausalLM",
+ "RobertaPreLayerNormForMaskedLM",
+ "RobertaPreLayerNormForMultipleChoice",
+ "RobertaPreLayerNormForQuestionAnswering",
+ "RobertaPreLayerNormForSequenceClassification",
+ "RobertaPreLayerNormForTokenClassification",
+ "RobertaPreLayerNormModel",
+ "RobertaPreLayerNormPreTrainedModel",
+ ]
+ )
+ _import_structure["models.roc_bert"].extend(
+ [
+ "RoCBertForCausalLM",
+ "RoCBertForMaskedLM",
+ "RoCBertForMultipleChoice",
+ "RoCBertForPreTraining",
+ "RoCBertForQuestionAnswering",
+ "RoCBertForSequenceClassification",
+ "RoCBertForTokenClassification",
+ "RoCBertModel",
+ "RoCBertPreTrainedModel",
+ "load_tf_weights_in_roc_bert",
+ ]
+ )
+ _import_structure["models.roformer"].extend(
+ [
+ "RoFormerForCausalLM",
+ "RoFormerForMaskedLM",
+ "RoFormerForMultipleChoice",
+ "RoFormerForQuestionAnswering",
+ "RoFormerForSequenceClassification",
+ "RoFormerForTokenClassification",
+ "RoFormerModel",
+ "RoFormerPreTrainedModel",
+ "load_tf_weights_in_roformer",
+ ]
+ )
+ _import_structure["models.rt_detr"].extend(
+ [
+ "RTDetrForObjectDetection",
+ "RTDetrModel",
+ "RTDetrPreTrainedModel",
+ "RTDetrResNetBackbone",
+ "RTDetrResNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.rwkv"].extend(
+ [
+ "RwkvForCausalLM",
+ "RwkvModel",
+ "RwkvPreTrainedModel",
+ ]
+ )
+ _import_structure["models.sam"].extend(
+ [
+ "SamModel",
+ "SamPreTrainedModel",
+ ]
+ )
+ _import_structure["models.seamless_m4t"].extend(
+ [
+ "SeamlessM4TCodeHifiGan",
+ "SeamlessM4TForSpeechToSpeech",
+ "SeamlessM4TForSpeechToText",
+ "SeamlessM4TForTextToSpeech",
+ "SeamlessM4TForTextToText",
+ "SeamlessM4THifiGan",
+ "SeamlessM4TModel",
+ "SeamlessM4TPreTrainedModel",
+ "SeamlessM4TTextToUnitForConditionalGeneration",
+ "SeamlessM4TTextToUnitModel",
+ ]
+ )
+ _import_structure["models.seamless_m4t_v2"].extend(
+ [
+ "SeamlessM4Tv2ForSpeechToSpeech",
+ "SeamlessM4Tv2ForSpeechToText",
+ "SeamlessM4Tv2ForTextToSpeech",
+ "SeamlessM4Tv2ForTextToText",
+ "SeamlessM4Tv2Model",
+ "SeamlessM4Tv2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.segformer"].extend(
+ [
+ "SegformerDecodeHead",
+ "SegformerForImageClassification",
+ "SegformerForSemanticSegmentation",
+ "SegformerModel",
+ "SegformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.seggpt"].extend(
+ [
+ "SegGptForImageSegmentation",
+ "SegGptModel",
+ "SegGptPreTrainedModel",
+ ]
+ )
+ _import_structure["models.sew"].extend(
+ [
+ "SEWForCTC",
+ "SEWForSequenceClassification",
+ "SEWModel",
+ "SEWPreTrainedModel",
+ ]
+ )
+ _import_structure["models.sew_d"].extend(
+ [
+ "SEWDForCTC",
+ "SEWDForSequenceClassification",
+ "SEWDModel",
+ "SEWDPreTrainedModel",
+ ]
+ )
+ _import_structure["models.siglip"].extend(
+ [
+ "SiglipForImageClassification",
+ "SiglipModel",
+ "SiglipPreTrainedModel",
+ "SiglipTextModel",
+ "SiglipVisionModel",
+ ]
+ )
+ _import_structure["models.speech_encoder_decoder"].extend(["SpeechEncoderDecoderModel"])
+ _import_structure["models.speech_to_text"].extend(
+ [
+ "Speech2TextForConditionalGeneration",
+ "Speech2TextModel",
+ "Speech2TextPreTrainedModel",
+ ]
+ )
+ _import_structure["models.speecht5"].extend(
+ [
+ "SpeechT5ForSpeechToSpeech",
+ "SpeechT5ForSpeechToText",
+ "SpeechT5ForTextToSpeech",
+ "SpeechT5HifiGan",
+ "SpeechT5Model",
+ "SpeechT5PreTrainedModel",
+ ]
+ )
+ _import_structure["models.splinter"].extend(
+ [
+ "SplinterForPreTraining",
+ "SplinterForQuestionAnswering",
+ "SplinterModel",
+ "SplinterPreTrainedModel",
+ ]
+ )
+ _import_structure["models.squeezebert"].extend(
+ [
+ "SqueezeBertForMaskedLM",
+ "SqueezeBertForMultipleChoice",
+ "SqueezeBertForQuestionAnswering",
+ "SqueezeBertForSequenceClassification",
+ "SqueezeBertForTokenClassification",
+ "SqueezeBertModel",
+ "SqueezeBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.stablelm"].extend(
+ [
+ "StableLmForCausalLM",
+ "StableLmForSequenceClassification",
+ "StableLmForTokenClassification",
+ "StableLmModel",
+ "StableLmPreTrainedModel",
+ ]
+ )
+ _import_structure["models.starcoder2"].extend(
+ [
+ "Starcoder2ForCausalLM",
+ "Starcoder2ForSequenceClassification",
+ "Starcoder2ForTokenClassification",
+ "Starcoder2Model",
+ "Starcoder2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.superpoint"].extend(
+ [
+ "SuperPointForKeypointDetection",
+ "SuperPointPreTrainedModel",
+ ]
+ )
+ _import_structure["models.swiftformer"].extend(
+ [
+ "SwiftFormerForImageClassification",
+ "SwiftFormerModel",
+ "SwiftFormerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.swin"].extend(
+ [
+ "SwinBackbone",
+ "SwinForImageClassification",
+ "SwinForMaskedImageModeling",
+ "SwinModel",
+ "SwinPreTrainedModel",
+ ]
+ )
+ _import_structure["models.swin2sr"].extend(
+ [
+ "Swin2SRForImageSuperResolution",
+ "Swin2SRModel",
+ "Swin2SRPreTrainedModel",
+ ]
+ )
+ _import_structure["models.swinv2"].extend(
+ [
+ "Swinv2Backbone",
+ "Swinv2ForImageClassification",
+ "Swinv2ForMaskedImageModeling",
+ "Swinv2Model",
+ "Swinv2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.switch_transformers"].extend(
+ [
+ "SwitchTransformersEncoderModel",
+ "SwitchTransformersForConditionalGeneration",
+ "SwitchTransformersModel",
+ "SwitchTransformersPreTrainedModel",
+ "SwitchTransformersSparseMLP",
+ "SwitchTransformersTop1Router",
+ ]
+ )
+ _import_structure["models.t5"].extend(
+ [
+ "T5EncoderModel",
+ "T5ForConditionalGeneration",
+ "T5ForQuestionAnswering",
+ "T5ForSequenceClassification",
+ "T5ForTokenClassification",
+ "T5Model",
+ "T5PreTrainedModel",
+ "load_tf_weights_in_t5",
+ ]
+ )
+ _import_structure["models.table_transformer"].extend(
+ [
+ "TableTransformerForObjectDetection",
+ "TableTransformerModel",
+ "TableTransformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.tapas"].extend(
+ [
+ "TapasForMaskedLM",
+ "TapasForQuestionAnswering",
+ "TapasForSequenceClassification",
+ "TapasModel",
+ "TapasPreTrainedModel",
+ "load_tf_weights_in_tapas",
+ ]
+ )
+ _import_structure["models.time_series_transformer"].extend(
+ [
+ "TimeSeriesTransformerForPrediction",
+ "TimeSeriesTransformerModel",
+ "TimeSeriesTransformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.timesformer"].extend(
+ [
+ "TimesformerForVideoClassification",
+ "TimesformerModel",
+ "TimesformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.timm_backbone"].extend(["TimmBackbone"])
+ _import_structure["models.timm_wrapper"].extend(
+ ["TimmWrapperForImageClassification", "TimmWrapperModel", "TimmWrapperPreTrainedModel"]
+ )
+ _import_structure["models.trocr"].extend(
+ [
+ "TrOCRForCausalLM",
+ "TrOCRPreTrainedModel",
+ ]
+ )
+ _import_structure["models.tvp"].extend(
+ [
+ "TvpForVideoGrounding",
+ "TvpModel",
+ "TvpPreTrainedModel",
+ ]
+ )
+ _import_structure["models.udop"].extend(
+ [
+ "UdopEncoderModel",
+ "UdopForConditionalGeneration",
+ "UdopModel",
+ "UdopPreTrainedModel",
+ ],
+ )
+ _import_structure["models.umt5"].extend(
+ [
+ "UMT5EncoderModel",
+ "UMT5ForConditionalGeneration",
+ "UMT5ForQuestionAnswering",
+ "UMT5ForSequenceClassification",
+ "UMT5ForTokenClassification",
+ "UMT5Model",
+ "UMT5PreTrainedModel",
+ ]
+ )
+ _import_structure["models.unispeech"].extend(
+ [
+ "UniSpeechForCTC",
+ "UniSpeechForPreTraining",
+ "UniSpeechForSequenceClassification",
+ "UniSpeechModel",
+ "UniSpeechPreTrainedModel",
+ ]
+ )
+ _import_structure["models.unispeech_sat"].extend(
+ [
+ "UniSpeechSatForAudioFrameClassification",
+ "UniSpeechSatForCTC",
+ "UniSpeechSatForPreTraining",
+ "UniSpeechSatForSequenceClassification",
+ "UniSpeechSatForXVector",
+ "UniSpeechSatModel",
+ "UniSpeechSatPreTrainedModel",
+ ]
+ )
+ _import_structure["models.univnet"].extend(
+ [
+ "UnivNetModel",
+ ]
+ )
+ _import_structure["models.upernet"].extend(
+ [
+ "UperNetForSemanticSegmentation",
+ "UperNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.video_llava"].extend(
+ [
+ "VideoLlavaForConditionalGeneration",
+ "VideoLlavaPreTrainedModel",
+ "VideoLlavaProcessor",
+ ]
+ )
+ _import_structure["models.videomae"].extend(
+ [
+ "VideoMAEForPreTraining",
+ "VideoMAEForVideoClassification",
+ "VideoMAEModel",
+ "VideoMAEPreTrainedModel",
+ ]
+ )
+ _import_structure["models.vilt"].extend(
+ [
+ "ViltForImageAndTextRetrieval",
+ "ViltForImagesAndTextClassification",
+ "ViltForMaskedLM",
+ "ViltForQuestionAnswering",
+ "ViltForTokenClassification",
+ "ViltModel",
+ "ViltPreTrainedModel",
+ ]
+ )
+ _import_structure["models.vipllava"].extend(
+ [
+ "VipLlavaForConditionalGeneration",
+ "VipLlavaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.vision_encoder_decoder"].extend(["VisionEncoderDecoderModel"])
+ _import_structure["models.vision_text_dual_encoder"].extend(["VisionTextDualEncoderModel"])
+ _import_structure["models.visual_bert"].extend(
+ [
+ "VisualBertForMultipleChoice",
+ "VisualBertForPreTraining",
+ "VisualBertForQuestionAnswering",
+ "VisualBertForRegionToPhraseAlignment",
+ "VisualBertForVisualReasoning",
+ "VisualBertModel",
+ "VisualBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.vit"].extend(
+ [
+ "ViTForImageClassification",
+ "ViTForMaskedImageModeling",
+ "ViTModel",
+ "ViTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.vit_mae"].extend(
+ [
+ "ViTMAEForPreTraining",
+ "ViTMAEModel",
+ "ViTMAEPreTrainedModel",
+ ]
+ )
+ _import_structure["models.vit_msn"].extend(
+ [
+ "ViTMSNForImageClassification",
+ "ViTMSNModel",
+ "ViTMSNPreTrainedModel",
+ ]
+ )
+ _import_structure["models.vitdet"].extend(
+ [
+ "VitDetBackbone",
+ "VitDetModel",
+ "VitDetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.vitmatte"].extend(
+ [
+ "VitMatteForImageMatting",
+ "VitMattePreTrainedModel",
+ ]
+ )
+ _import_structure["models.vits"].extend(
+ [
+ "VitsModel",
+ "VitsPreTrainedModel",
+ ]
+ )
+ _import_structure["models.vivit"].extend(
+ [
+ "VivitForVideoClassification",
+ "VivitModel",
+ "VivitPreTrainedModel",
+ ]
+ )
+ _import_structure["models.wav2vec2"].extend(
+ [
+ "Wav2Vec2ForAudioFrameClassification",
+ "Wav2Vec2ForCTC",
+ "Wav2Vec2ForMaskedLM",
+ "Wav2Vec2ForPreTraining",
+ "Wav2Vec2ForSequenceClassification",
+ "Wav2Vec2ForXVector",
+ "Wav2Vec2Model",
+ "Wav2Vec2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.wav2vec2_bert"].extend(
+ [
+ "Wav2Vec2BertForAudioFrameClassification",
+ "Wav2Vec2BertForCTC",
+ "Wav2Vec2BertForSequenceClassification",
+ "Wav2Vec2BertForXVector",
+ "Wav2Vec2BertModel",
+ "Wav2Vec2BertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.wav2vec2_conformer"].extend(
+ [
+ "Wav2Vec2ConformerForAudioFrameClassification",
+ "Wav2Vec2ConformerForCTC",
+ "Wav2Vec2ConformerForPreTraining",
+ "Wav2Vec2ConformerForSequenceClassification",
+ "Wav2Vec2ConformerForXVector",
+ "Wav2Vec2ConformerModel",
+ "Wav2Vec2ConformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.wavlm"].extend(
+ [
+ "WavLMForAudioFrameClassification",
+ "WavLMForCTC",
+ "WavLMForSequenceClassification",
+ "WavLMForXVector",
+ "WavLMModel",
+ "WavLMPreTrainedModel",
+ ]
+ )
+ _import_structure["models.whisper"].extend(
+ [
+ "WhisperForAudioClassification",
+ "WhisperForCausalLM",
+ "WhisperForConditionalGeneration",
+ "WhisperModel",
+ "WhisperPreTrainedModel",
+ ]
+ )
+ _import_structure["models.x_clip"].extend(
+ [
+ "XCLIPModel",
+ "XCLIPPreTrainedModel",
+ "XCLIPTextModel",
+ "XCLIPVisionModel",
+ ]
+ )
+ _import_structure["models.xglm"].extend(
+ [
+ "XGLMForCausalLM",
+ "XGLMModel",
+ "XGLMPreTrainedModel",
+ ]
+ )
+ _import_structure["models.xlm"].extend(
+ [
+ "XLMForMultipleChoice",
+ "XLMForQuestionAnswering",
+ "XLMForQuestionAnsweringSimple",
+ "XLMForSequenceClassification",
+ "XLMForTokenClassification",
+ "XLMModel",
+ "XLMPreTrainedModel",
+ "XLMWithLMHeadModel",
+ ]
+ )
+ _import_structure["models.xlm_roberta"].extend(
+ [
+ "XLMRobertaForCausalLM",
+ "XLMRobertaForMaskedLM",
+ "XLMRobertaForMultipleChoice",
+ "XLMRobertaForQuestionAnswering",
+ "XLMRobertaForSequenceClassification",
+ "XLMRobertaForTokenClassification",
+ "XLMRobertaModel",
+ "XLMRobertaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.xlm_roberta_xl"].extend(
+ [
+ "XLMRobertaXLForCausalLM",
+ "XLMRobertaXLForMaskedLM",
+ "XLMRobertaXLForMultipleChoice",
+ "XLMRobertaXLForQuestionAnswering",
+ "XLMRobertaXLForSequenceClassification",
+ "XLMRobertaXLForTokenClassification",
+ "XLMRobertaXLModel",
+ "XLMRobertaXLPreTrainedModel",
+ ]
+ )
+ _import_structure["models.xlnet"].extend(
+ [
+ "XLNetForMultipleChoice",
+ "XLNetForQuestionAnswering",
+ "XLNetForQuestionAnsweringSimple",
+ "XLNetForSequenceClassification",
+ "XLNetForTokenClassification",
+ "XLNetLMHeadModel",
+ "XLNetModel",
+ "XLNetPreTrainedModel",
+ "load_tf_weights_in_xlnet",
+ ]
+ )
+ _import_structure["models.xmod"].extend(
+ [
+ "XmodForCausalLM",
+ "XmodForMaskedLM",
+ "XmodForMultipleChoice",
+ "XmodForQuestionAnswering",
+ "XmodForSequenceClassification",
+ "XmodForTokenClassification",
+ "XmodModel",
+ "XmodPreTrainedModel",
+ ]
+ )
+ _import_structure["models.yolos"].extend(
+ [
+ "YolosForObjectDetection",
+ "YolosModel",
+ "YolosPreTrainedModel",
+ ]
+ )
+ _import_structure["models.yoso"].extend(
+ [
+ "YosoForMaskedLM",
+ "YosoForMultipleChoice",
+ "YosoForQuestionAnswering",
+ "YosoForSequenceClassification",
+ "YosoForTokenClassification",
+ "YosoModel",
+ "YosoPreTrainedModel",
+ ]
+ )
+ _import_structure["models.zamba"].extend(
+ [
+ "ZambaForCausalLM",
+ "ZambaForSequenceClassification",
+ "ZambaModel",
+ "ZambaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.zoedepth"].extend(
+ [
+ "ZoeDepthForDepthEstimation",
+ "ZoeDepthPreTrainedModel",
+ ]
+ )
+ _import_structure["optimization"] = [
+ "Adafactor",
+ "AdamW",
+ "get_constant_schedule",
+ "get_constant_schedule_with_warmup",
+ "get_cosine_schedule_with_warmup",
+ "get_cosine_with_hard_restarts_schedule_with_warmup",
+ "get_inverse_sqrt_schedule",
+ "get_linear_schedule_with_warmup",
+ "get_polynomial_decay_schedule_with_warmup",
+ "get_scheduler",
+ "get_wsd_schedule",
+ ]
+ _import_structure["pytorch_utils"] = [
+ "Conv1D",
+ "apply_chunking_to_forward",
+ "prune_layer",
+ ]
+ _import_structure["sagemaker"] = []
+ _import_structure["time_series_utils"] = []
+ _import_structure["trainer"] = ["Trainer"]
+ _import_structure["trainer_pt_utils"] = ["torch_distributed_zero_first"]
+ _import_structure["trainer_seq2seq"] = ["Seq2SeqTrainer"]
+
+# TensorFlow-backed objects
+try:
+ if not is_tf_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import dummy_tf_objects
+
+ _import_structure["utils.dummy_tf_objects"] = [name for name in dir(dummy_tf_objects) if not name.startswith("_")]
+else:
+ _import_structure["activations_tf"] = []
+ _import_structure["benchmark.benchmark_args_tf"] = ["TensorFlowBenchmarkArguments"]
+ _import_structure["benchmark.benchmark_tf"] = ["TensorFlowBenchmark"]
+ _import_structure["generation"].extend(
+ [
+ "TFForcedBOSTokenLogitsProcessor",
+ "TFForcedEOSTokenLogitsProcessor",
+ "TFForceTokensLogitsProcessor",
+ "TFGenerationMixin",
+ "TFLogitsProcessor",
+ "TFLogitsProcessorList",
+ "TFLogitsWarper",
+ "TFMinLengthLogitsProcessor",
+ "TFNoBadWordsLogitsProcessor",
+ "TFNoRepeatNGramLogitsProcessor",
+ "TFRepetitionPenaltyLogitsProcessor",
+ "TFSuppressTokensAtBeginLogitsProcessor",
+ "TFSuppressTokensLogitsProcessor",
+ "TFTemperatureLogitsWarper",
+ "TFTopKLogitsWarper",
+ "TFTopPLogitsWarper",
+ ]
+ )
+ _import_structure["keras_callbacks"] = ["KerasMetricCallback", "PushToHubCallback"]
+ _import_structure["modeling_tf_outputs"] = []
+ _import_structure["modeling_tf_utils"] = [
+ "TFPreTrainedModel",
+ "TFSequenceSummary",
+ "TFSharedEmbeddings",
+ "shape_list",
+ ]
+ # TensorFlow models structure
+ _import_structure["models.albert"].extend(
+ [
+ "TFAlbertForMaskedLM",
+ "TFAlbertForMultipleChoice",
+ "TFAlbertForPreTraining",
+ "TFAlbertForQuestionAnswering",
+ "TFAlbertForSequenceClassification",
+ "TFAlbertForTokenClassification",
+ "TFAlbertMainLayer",
+ "TFAlbertModel",
+ "TFAlbertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.auto"].extend(
+ [
+ "TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING",
+ "TF_MODEL_FOR_CAUSAL_LM_MAPPING",
+ "TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING",
+ "TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
+ "TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING",
+ "TF_MODEL_FOR_MASKED_LM_MAPPING",
+ "TF_MODEL_FOR_MASK_GENERATION_MAPPING",
+ "TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING",
+ "TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING",
+ "TF_MODEL_FOR_PRETRAINING_MAPPING",
+ "TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING",
+ "TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING",
+ "TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING",
+ "TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
+ "TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
+ "TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING",
+ "TF_MODEL_FOR_TEXT_ENCODING_MAPPING",
+ "TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
+ "TF_MODEL_FOR_VISION_2_SEQ_MAPPING",
+ "TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING",
+ "TF_MODEL_MAPPING",
+ "TF_MODEL_WITH_LM_HEAD_MAPPING",
+ "TFAutoModel",
+ "TFAutoModelForAudioClassification",
+ "TFAutoModelForCausalLM",
+ "TFAutoModelForDocumentQuestionAnswering",
+ "TFAutoModelForImageClassification",
+ "TFAutoModelForMaskedImageModeling",
+ "TFAutoModelForMaskedLM",
+ "TFAutoModelForMaskGeneration",
+ "TFAutoModelForMultipleChoice",
+ "TFAutoModelForNextSentencePrediction",
+ "TFAutoModelForPreTraining",
+ "TFAutoModelForQuestionAnswering",
+ "TFAutoModelForSemanticSegmentation",
+ "TFAutoModelForSeq2SeqLM",
+ "TFAutoModelForSequenceClassification",
+ "TFAutoModelForSpeechSeq2Seq",
+ "TFAutoModelForTableQuestionAnswering",
+ "TFAutoModelForTextEncoding",
+ "TFAutoModelForTokenClassification",
+ "TFAutoModelForVision2Seq",
+ "TFAutoModelForZeroShotImageClassification",
+ "TFAutoModelWithLMHead",
+ ]
+ )
+ _import_structure["models.bart"].extend(
+ [
+ "TFBartForConditionalGeneration",
+ "TFBartForSequenceClassification",
+ "TFBartModel",
+ "TFBartPretrainedModel",
+ ]
+ )
+ _import_structure["models.bert"].extend(
+ [
+ "TFBertForMaskedLM",
+ "TFBertForMultipleChoice",
+ "TFBertForNextSentencePrediction",
+ "TFBertForPreTraining",
+ "TFBertForQuestionAnswering",
+ "TFBertForSequenceClassification",
+ "TFBertForTokenClassification",
+ "TFBertLMHeadModel",
+ "TFBertMainLayer",
+ "TFBertModel",
+ "TFBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.blenderbot"].extend(
+ [
+ "TFBlenderbotForConditionalGeneration",
+ "TFBlenderbotModel",
+ "TFBlenderbotPreTrainedModel",
+ ]
+ )
+ _import_structure["models.blenderbot_small"].extend(
+ [
+ "TFBlenderbotSmallForConditionalGeneration",
+ "TFBlenderbotSmallModel",
+ "TFBlenderbotSmallPreTrainedModel",
+ ]
+ )
+ _import_structure["models.blip"].extend(
+ [
+ "TFBlipForConditionalGeneration",
+ "TFBlipForImageTextRetrieval",
+ "TFBlipForQuestionAnswering",
+ "TFBlipModel",
+ "TFBlipPreTrainedModel",
+ "TFBlipTextModel",
+ "TFBlipVisionModel",
+ ]
+ )
+ _import_structure["models.camembert"].extend(
+ [
+ "TFCamembertForCausalLM",
+ "TFCamembertForMaskedLM",
+ "TFCamembertForMultipleChoice",
+ "TFCamembertForQuestionAnswering",
+ "TFCamembertForSequenceClassification",
+ "TFCamembertForTokenClassification",
+ "TFCamembertModel",
+ "TFCamembertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.clip"].extend(
+ [
+ "TFCLIPModel",
+ "TFCLIPPreTrainedModel",
+ "TFCLIPTextModel",
+ "TFCLIPVisionModel",
+ ]
+ )
+ _import_structure["models.convbert"].extend(
+ [
+ "TFConvBertForMaskedLM",
+ "TFConvBertForMultipleChoice",
+ "TFConvBertForQuestionAnswering",
+ "TFConvBertForSequenceClassification",
+ "TFConvBertForTokenClassification",
+ "TFConvBertModel",
+ "TFConvBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.convnext"].extend(
+ [
+ "TFConvNextForImageClassification",
+ "TFConvNextModel",
+ "TFConvNextPreTrainedModel",
+ ]
+ )
+ _import_structure["models.convnextv2"].extend(
+ [
+ "TFConvNextV2ForImageClassification",
+ "TFConvNextV2Model",
+ "TFConvNextV2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.ctrl"].extend(
+ [
+ "TFCTRLForSequenceClassification",
+ "TFCTRLLMHeadModel",
+ "TFCTRLModel",
+ "TFCTRLPreTrainedModel",
+ ]
+ )
+ _import_structure["models.cvt"].extend(
+ [
+ "TFCvtForImageClassification",
+ "TFCvtModel",
+ "TFCvtPreTrainedModel",
+ ]
+ )
+ _import_structure["models.data2vec"].extend(
+ [
+ "TFData2VecVisionForImageClassification",
+ "TFData2VecVisionForSemanticSegmentation",
+ "TFData2VecVisionModel",
+ "TFData2VecVisionPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deberta"].extend(
+ [
+ "TFDebertaForMaskedLM",
+ "TFDebertaForQuestionAnswering",
+ "TFDebertaForSequenceClassification",
+ "TFDebertaForTokenClassification",
+ "TFDebertaModel",
+ "TFDebertaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deberta_v2"].extend(
+ [
+ "TFDebertaV2ForMaskedLM",
+ "TFDebertaV2ForMultipleChoice",
+ "TFDebertaV2ForQuestionAnswering",
+ "TFDebertaV2ForSequenceClassification",
+ "TFDebertaV2ForTokenClassification",
+ "TFDebertaV2Model",
+ "TFDebertaV2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.deit"].extend(
+ [
+ "TFDeiTForImageClassification",
+ "TFDeiTForImageClassificationWithTeacher",
+ "TFDeiTForMaskedImageModeling",
+ "TFDeiTModel",
+ "TFDeiTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.efficientformer"].extend(
+ [
+ "TFEfficientFormerForImageClassification",
+ "TFEfficientFormerForImageClassificationWithTeacher",
+ "TFEfficientFormerModel",
+ "TFEfficientFormerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.transfo_xl"].extend(
+ [
+ "TFAdaptiveEmbedding",
+ "TFTransfoXLForSequenceClassification",
+ "TFTransfoXLLMHeadModel",
+ "TFTransfoXLMainLayer",
+ "TFTransfoXLModel",
+ "TFTransfoXLPreTrainedModel",
+ ]
+ )
+ _import_structure["models.distilbert"].extend(
+ [
+ "TFDistilBertForMaskedLM",
+ "TFDistilBertForMultipleChoice",
+ "TFDistilBertForQuestionAnswering",
+ "TFDistilBertForSequenceClassification",
+ "TFDistilBertForTokenClassification",
+ "TFDistilBertMainLayer",
+ "TFDistilBertModel",
+ "TFDistilBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.dpr"].extend(
+ [
+ "TFDPRContextEncoder",
+ "TFDPRPretrainedContextEncoder",
+ "TFDPRPretrainedQuestionEncoder",
+ "TFDPRPretrainedReader",
+ "TFDPRQuestionEncoder",
+ "TFDPRReader",
+ ]
+ )
+ _import_structure["models.electra"].extend(
+ [
+ "TFElectraForMaskedLM",
+ "TFElectraForMultipleChoice",
+ "TFElectraForPreTraining",
+ "TFElectraForQuestionAnswering",
+ "TFElectraForSequenceClassification",
+ "TFElectraForTokenClassification",
+ "TFElectraModel",
+ "TFElectraPreTrainedModel",
+ ]
+ )
+ _import_structure["models.encoder_decoder"].append("TFEncoderDecoderModel")
+ _import_structure["models.esm"].extend(
+ [
+ "TFEsmForMaskedLM",
+ "TFEsmForSequenceClassification",
+ "TFEsmForTokenClassification",
+ "TFEsmModel",
+ "TFEsmPreTrainedModel",
+ ]
+ )
+ _import_structure["models.flaubert"].extend(
+ [
+ "TFFlaubertForMultipleChoice",
+ "TFFlaubertForQuestionAnsweringSimple",
+ "TFFlaubertForSequenceClassification",
+ "TFFlaubertForTokenClassification",
+ "TFFlaubertModel",
+ "TFFlaubertPreTrainedModel",
+ "TFFlaubertWithLMHeadModel",
+ ]
+ )
+ _import_structure["models.funnel"].extend(
+ [
+ "TFFunnelBaseModel",
+ "TFFunnelForMaskedLM",
+ "TFFunnelForMultipleChoice",
+ "TFFunnelForPreTraining",
+ "TFFunnelForQuestionAnswering",
+ "TFFunnelForSequenceClassification",
+ "TFFunnelForTokenClassification",
+ "TFFunnelModel",
+ "TFFunnelPreTrainedModel",
+ ]
+ )
+ _import_structure["models.gpt2"].extend(
+ [
+ "TFGPT2DoubleHeadsModel",
+ "TFGPT2ForSequenceClassification",
+ "TFGPT2LMHeadModel",
+ "TFGPT2MainLayer",
+ "TFGPT2Model",
+ "TFGPT2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.gptj"].extend(
+ [
+ "TFGPTJForCausalLM",
+ "TFGPTJForQuestionAnswering",
+ "TFGPTJForSequenceClassification",
+ "TFGPTJModel",
+ "TFGPTJPreTrainedModel",
+ ]
+ )
+ _import_structure["models.groupvit"].extend(
+ [
+ "TFGroupViTModel",
+ "TFGroupViTPreTrainedModel",
+ "TFGroupViTTextModel",
+ "TFGroupViTVisionModel",
+ ]
+ )
+ _import_structure["models.hubert"].extend(
+ [
+ "TFHubertForCTC",
+ "TFHubertModel",
+ "TFHubertPreTrainedModel",
+ ]
+ )
+
+ _import_structure["models.idefics"].extend(
+ [
+ "TFIdeficsForVisionText2Text",
+ "TFIdeficsModel",
+ "TFIdeficsPreTrainedModel",
+ ]
+ )
+
+ _import_structure["models.layoutlm"].extend(
+ [
+ "TFLayoutLMForMaskedLM",
+ "TFLayoutLMForQuestionAnswering",
+ "TFLayoutLMForSequenceClassification",
+ "TFLayoutLMForTokenClassification",
+ "TFLayoutLMMainLayer",
+ "TFLayoutLMModel",
+ "TFLayoutLMPreTrainedModel",
+ ]
+ )
+ _import_structure["models.layoutlmv3"].extend(
+ [
+ "TFLayoutLMv3ForQuestionAnswering",
+ "TFLayoutLMv3ForSequenceClassification",
+ "TFLayoutLMv3ForTokenClassification",
+ "TFLayoutLMv3Model",
+ "TFLayoutLMv3PreTrainedModel",
+ ]
+ )
+ _import_structure["models.led"].extend(["TFLEDForConditionalGeneration", "TFLEDModel", "TFLEDPreTrainedModel"])
+ _import_structure["models.longformer"].extend(
+ [
+ "TFLongformerForMaskedLM",
+ "TFLongformerForMultipleChoice",
+ "TFLongformerForQuestionAnswering",
+ "TFLongformerForSequenceClassification",
+ "TFLongformerForTokenClassification",
+ "TFLongformerModel",
+ "TFLongformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.lxmert"].extend(
+ [
+ "TFLxmertForPreTraining",
+ "TFLxmertMainLayer",
+ "TFLxmertModel",
+ "TFLxmertPreTrainedModel",
+ "TFLxmertVisualFeatureEncoder",
+ ]
+ )
+ _import_structure["models.marian"].extend(["TFMarianModel", "TFMarianMTModel", "TFMarianPreTrainedModel"])
+ _import_structure["models.mbart"].extend(
+ ["TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel"]
+ )
+ _import_structure["models.mistral"].extend(
+ ["TFMistralForCausalLM", "TFMistralForSequenceClassification", "TFMistralModel", "TFMistralPreTrainedModel"]
+ )
+ _import_structure["models.mobilebert"].extend(
+ [
+ "TFMobileBertForMaskedLM",
+ "TFMobileBertForMultipleChoice",
+ "TFMobileBertForNextSentencePrediction",
+ "TFMobileBertForPreTraining",
+ "TFMobileBertForQuestionAnswering",
+ "TFMobileBertForSequenceClassification",
+ "TFMobileBertForTokenClassification",
+ "TFMobileBertMainLayer",
+ "TFMobileBertModel",
+ "TFMobileBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mobilevit"].extend(
+ [
+ "TFMobileViTForImageClassification",
+ "TFMobileViTForSemanticSegmentation",
+ "TFMobileViTModel",
+ "TFMobileViTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mpnet"].extend(
+ [
+ "TFMPNetForMaskedLM",
+ "TFMPNetForMultipleChoice",
+ "TFMPNetForQuestionAnswering",
+ "TFMPNetForSequenceClassification",
+ "TFMPNetForTokenClassification",
+ "TFMPNetMainLayer",
+ "TFMPNetModel",
+ "TFMPNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mt5"].extend(["TFMT5EncoderModel", "TFMT5ForConditionalGeneration", "TFMT5Model"])
+ _import_structure["models.openai"].extend(
+ [
+ "TFOpenAIGPTDoubleHeadsModel",
+ "TFOpenAIGPTForSequenceClassification",
+ "TFOpenAIGPTLMHeadModel",
+ "TFOpenAIGPTMainLayer",
+ "TFOpenAIGPTModel",
+ "TFOpenAIGPTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.opt"].extend(
+ [
+ "TFOPTForCausalLM",
+ "TFOPTModel",
+ "TFOPTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.pegasus"].extend(
+ [
+ "TFPegasusForConditionalGeneration",
+ "TFPegasusModel",
+ "TFPegasusPreTrainedModel",
+ ]
+ )
+ _import_structure["models.rag"].extend(
+ [
+ "TFRagModel",
+ "TFRagPreTrainedModel",
+ "TFRagSequenceForGeneration",
+ "TFRagTokenForGeneration",
+ ]
+ )
+ _import_structure["models.regnet"].extend(
+ [
+ "TFRegNetForImageClassification",
+ "TFRegNetModel",
+ "TFRegNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.rembert"].extend(
+ [
+ "TFRemBertForCausalLM",
+ "TFRemBertForMaskedLM",
+ "TFRemBertForMultipleChoice",
+ "TFRemBertForQuestionAnswering",
+ "TFRemBertForSequenceClassification",
+ "TFRemBertForTokenClassification",
+ "TFRemBertModel",
+ "TFRemBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.resnet"].extend(
+ [
+ "TFResNetForImageClassification",
+ "TFResNetModel",
+ "TFResNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.roberta"].extend(
+ [
+ "TFRobertaForCausalLM",
+ "TFRobertaForMaskedLM",
+ "TFRobertaForMultipleChoice",
+ "TFRobertaForQuestionAnswering",
+ "TFRobertaForSequenceClassification",
+ "TFRobertaForTokenClassification",
+ "TFRobertaMainLayer",
+ "TFRobertaModel",
+ "TFRobertaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.roberta_prelayernorm"].extend(
+ [
+ "TFRobertaPreLayerNormForCausalLM",
+ "TFRobertaPreLayerNormForMaskedLM",
+ "TFRobertaPreLayerNormForMultipleChoice",
+ "TFRobertaPreLayerNormForQuestionAnswering",
+ "TFRobertaPreLayerNormForSequenceClassification",
+ "TFRobertaPreLayerNormForTokenClassification",
+ "TFRobertaPreLayerNormMainLayer",
+ "TFRobertaPreLayerNormModel",
+ "TFRobertaPreLayerNormPreTrainedModel",
+ ]
+ )
+ _import_structure["models.roformer"].extend(
+ [
+ "TFRoFormerForCausalLM",
+ "TFRoFormerForMaskedLM",
+ "TFRoFormerForMultipleChoice",
+ "TFRoFormerForQuestionAnswering",
+ "TFRoFormerForSequenceClassification",
+ "TFRoFormerForTokenClassification",
+ "TFRoFormerModel",
+ "TFRoFormerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.sam"].extend(
+ [
+ "TFSamModel",
+ "TFSamPreTrainedModel",
+ ]
+ )
+ _import_structure["models.segformer"].extend(
+ [
+ "TFSegformerDecodeHead",
+ "TFSegformerForImageClassification",
+ "TFSegformerForSemanticSegmentation",
+ "TFSegformerModel",
+ "TFSegformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.speech_to_text"].extend(
+ [
+ "TFSpeech2TextForConditionalGeneration",
+ "TFSpeech2TextModel",
+ "TFSpeech2TextPreTrainedModel",
+ ]
+ )
+ _import_structure["models.swiftformer"].extend(
+ [
+ "TFSwiftFormerForImageClassification",
+ "TFSwiftFormerModel",
+ "TFSwiftFormerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.swin"].extend(
+ [
+ "TFSwinForImageClassification",
+ "TFSwinForMaskedImageModeling",
+ "TFSwinModel",
+ "TFSwinPreTrainedModel",
+ ]
+ )
+ _import_structure["models.t5"].extend(
+ [
+ "TFT5EncoderModel",
+ "TFT5ForConditionalGeneration",
+ "TFT5Model",
+ "TFT5PreTrainedModel",
+ ]
+ )
+ _import_structure["models.tapas"].extend(
+ [
+ "TFTapasForMaskedLM",
+ "TFTapasForQuestionAnswering",
+ "TFTapasForSequenceClassification",
+ "TFTapasModel",
+ "TFTapasPreTrainedModel",
+ ]
+ )
+ _import_structure["models.vision_encoder_decoder"].extend(["TFVisionEncoderDecoderModel"])
+ _import_structure["models.vision_text_dual_encoder"].extend(["TFVisionTextDualEncoderModel"])
+ _import_structure["models.vit"].extend(
+ [
+ "TFViTForImageClassification",
+ "TFViTModel",
+ "TFViTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.vit_mae"].extend(
+ [
+ "TFViTMAEForPreTraining",
+ "TFViTMAEModel",
+ "TFViTMAEPreTrainedModel",
+ ]
+ )
+ _import_structure["models.wav2vec2"].extend(
+ [
+ "TFWav2Vec2ForCTC",
+ "TFWav2Vec2ForSequenceClassification",
+ "TFWav2Vec2Model",
+ "TFWav2Vec2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.whisper"].extend(
+ [
+ "TFWhisperForConditionalGeneration",
+ "TFWhisperModel",
+ "TFWhisperPreTrainedModel",
+ ]
+ )
+ _import_structure["models.xglm"].extend(
+ [
+ "TFXGLMForCausalLM",
+ "TFXGLMModel",
+ "TFXGLMPreTrainedModel",
+ ]
+ )
+ _import_structure["models.xlm"].extend(
+ [
+ "TFXLMForMultipleChoice",
+ "TFXLMForQuestionAnsweringSimple",
+ "TFXLMForSequenceClassification",
+ "TFXLMForTokenClassification",
+ "TFXLMMainLayer",
+ "TFXLMModel",
+ "TFXLMPreTrainedModel",
+ "TFXLMWithLMHeadModel",
+ ]
+ )
+ _import_structure["models.xlm_roberta"].extend(
+ [
+ "TFXLMRobertaForCausalLM",
+ "TFXLMRobertaForMaskedLM",
+ "TFXLMRobertaForMultipleChoice",
+ "TFXLMRobertaForQuestionAnswering",
+ "TFXLMRobertaForSequenceClassification",
+ "TFXLMRobertaForTokenClassification",
+ "TFXLMRobertaModel",
+ "TFXLMRobertaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.xlnet"].extend(
+ [
+ "TFXLNetForMultipleChoice",
+ "TFXLNetForQuestionAnsweringSimple",
+ "TFXLNetForSequenceClassification",
+ "TFXLNetForTokenClassification",
+ "TFXLNetLMHeadModel",
+ "TFXLNetMainLayer",
+ "TFXLNetModel",
+ "TFXLNetPreTrainedModel",
+ ]
+ )
+ _import_structure["optimization_tf"] = [
+ "AdamWeightDecay",
+ "GradientAccumulator",
+ "WarmUp",
+ "create_optimizer",
+ ]
+ _import_structure["tf_utils"] = []
+
+
+try:
+ if not (
+ is_librosa_available()
+ and is_essentia_available()
+ and is_scipy_available()
+ and is_torch_available()
+ and is_pretty_midi_available()
+ ):
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import (
+ dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects,
+ )
+
+ _import_structure["utils.dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects"] = [
+ name
+ for name in dir(dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects)
+ if not name.startswith("_")
+ ]
+else:
+ _import_structure["models.pop2piano"].append("Pop2PianoFeatureExtractor")
+ _import_structure["models.pop2piano"].append("Pop2PianoTokenizer")
+ _import_structure["models.pop2piano"].append("Pop2PianoProcessor")
+
+try:
+ if not is_torchaudio_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import (
+ dummy_torchaudio_objects,
+ )
+
+ _import_structure["utils.dummy_torchaudio_objects"] = [
+ name for name in dir(dummy_torchaudio_objects) if not name.startswith("_")
+ ]
+else:
+ _import_structure["models.musicgen_melody"].append("MusicgenMelodyFeatureExtractor")
+ _import_structure["models.musicgen_melody"].append("MusicgenMelodyProcessor")
+
+
+# FLAX-backed objects
+try:
+ if not is_flax_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ from .utils import dummy_flax_objects
+
+ _import_structure["utils.dummy_flax_objects"] = [
+ name for name in dir(dummy_flax_objects) if not name.startswith("_")
+ ]
+else:
+ _import_structure["generation"].extend(
+ [
+ "FlaxForcedBOSTokenLogitsProcessor",
+ "FlaxForcedEOSTokenLogitsProcessor",
+ "FlaxForceTokensLogitsProcessor",
+ "FlaxGenerationMixin",
+ "FlaxLogitsProcessor",
+ "FlaxLogitsProcessorList",
+ "FlaxLogitsWarper",
+ "FlaxMinLengthLogitsProcessor",
+ "FlaxTemperatureLogitsWarper",
+ "FlaxSuppressTokensAtBeginLogitsProcessor",
+ "FlaxSuppressTokensLogitsProcessor",
+ "FlaxTopKLogitsWarper",
+ "FlaxTopPLogitsWarper",
+ "FlaxWhisperTimeStampLogitsProcessor",
+ ]
+ )
+ _import_structure["modeling_flax_outputs"] = []
+ _import_structure["modeling_flax_utils"] = ["FlaxPreTrainedModel"]
+ _import_structure["models.albert"].extend(
+ [
+ "FlaxAlbertForMaskedLM",
+ "FlaxAlbertForMultipleChoice",
+ "FlaxAlbertForPreTraining",
+ "FlaxAlbertForQuestionAnswering",
+ "FlaxAlbertForSequenceClassification",
+ "FlaxAlbertForTokenClassification",
+ "FlaxAlbertModel",
+ "FlaxAlbertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.auto"].extend(
+ [
+ "FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING",
+ "FLAX_MODEL_FOR_CAUSAL_LM_MAPPING",
+ "FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
+ "FLAX_MODEL_FOR_MASKED_LM_MAPPING",
+ "FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING",
+ "FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING",
+ "FLAX_MODEL_FOR_PRETRAINING_MAPPING",
+ "FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING",
+ "FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING",
+ "FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
+ "FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
+ "FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
+ "FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING",
+ "FLAX_MODEL_MAPPING",
+ "FlaxAutoModel",
+ "FlaxAutoModelForCausalLM",
+ "FlaxAutoModelForImageClassification",
+ "FlaxAutoModelForMaskedLM",
+ "FlaxAutoModelForMultipleChoice",
+ "FlaxAutoModelForNextSentencePrediction",
+ "FlaxAutoModelForPreTraining",
+ "FlaxAutoModelForQuestionAnswering",
+ "FlaxAutoModelForSeq2SeqLM",
+ "FlaxAutoModelForSequenceClassification",
+ "FlaxAutoModelForSpeechSeq2Seq",
+ "FlaxAutoModelForTokenClassification",
+ "FlaxAutoModelForVision2Seq",
+ ]
+ )
+
+ # Flax models structure
+
+ _import_structure["models.bart"].extend(
+ [
+ "FlaxBartDecoderPreTrainedModel",
+ "FlaxBartForCausalLM",
+ "FlaxBartForConditionalGeneration",
+ "FlaxBartForQuestionAnswering",
+ "FlaxBartForSequenceClassification",
+ "FlaxBartModel",
+ "FlaxBartPreTrainedModel",
+ ]
+ )
+ _import_structure["models.beit"].extend(
+ [
+ "FlaxBeitForImageClassification",
+ "FlaxBeitForMaskedImageModeling",
+ "FlaxBeitModel",
+ "FlaxBeitPreTrainedModel",
+ ]
+ )
+
+ _import_structure["models.bert"].extend(
+ [
+ "FlaxBertForCausalLM",
+ "FlaxBertForMaskedLM",
+ "FlaxBertForMultipleChoice",
+ "FlaxBertForNextSentencePrediction",
+ "FlaxBertForPreTraining",
+ "FlaxBertForQuestionAnswering",
+ "FlaxBertForSequenceClassification",
+ "FlaxBertForTokenClassification",
+ "FlaxBertModel",
+ "FlaxBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.big_bird"].extend(
+ [
+ "FlaxBigBirdForCausalLM",
+ "FlaxBigBirdForMaskedLM",
+ "FlaxBigBirdForMultipleChoice",
+ "FlaxBigBirdForPreTraining",
+ "FlaxBigBirdForQuestionAnswering",
+ "FlaxBigBirdForSequenceClassification",
+ "FlaxBigBirdForTokenClassification",
+ "FlaxBigBirdModel",
+ "FlaxBigBirdPreTrainedModel",
+ ]
+ )
+ _import_structure["models.blenderbot"].extend(
+ [
+ "FlaxBlenderbotForConditionalGeneration",
+ "FlaxBlenderbotModel",
+ "FlaxBlenderbotPreTrainedModel",
+ ]
+ )
+ _import_structure["models.blenderbot_small"].extend(
+ [
+ "FlaxBlenderbotSmallForConditionalGeneration",
+ "FlaxBlenderbotSmallModel",
+ "FlaxBlenderbotSmallPreTrainedModel",
+ ]
+ )
+ _import_structure["models.bloom"].extend(
+ [
+ "FlaxBloomForCausalLM",
+ "FlaxBloomModel",
+ "FlaxBloomPreTrainedModel",
+ ]
+ )
+ _import_structure["models.clip"].extend(
+ [
+ "FlaxCLIPModel",
+ "FlaxCLIPPreTrainedModel",
+ "FlaxCLIPTextModel",
+ "FlaxCLIPTextPreTrainedModel",
+ "FlaxCLIPTextModelWithProjection",
+ "FlaxCLIPVisionModel",
+ "FlaxCLIPVisionPreTrainedModel",
+ ]
+ )
+ _import_structure["models.dinov2"].extend(
+ [
+ "FlaxDinov2Model",
+ "FlaxDinov2ForImageClassification",
+ "FlaxDinov2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.distilbert"].extend(
+ [
+ "FlaxDistilBertForMaskedLM",
+ "FlaxDistilBertForMultipleChoice",
+ "FlaxDistilBertForQuestionAnswering",
+ "FlaxDistilBertForSequenceClassification",
+ "FlaxDistilBertForTokenClassification",
+ "FlaxDistilBertModel",
+ "FlaxDistilBertPreTrainedModel",
+ ]
+ )
+ _import_structure["models.electra"].extend(
+ [
+ "FlaxElectraForCausalLM",
+ "FlaxElectraForMaskedLM",
+ "FlaxElectraForMultipleChoice",
+ "FlaxElectraForPreTraining",
+ "FlaxElectraForQuestionAnswering",
+ "FlaxElectraForSequenceClassification",
+ "FlaxElectraForTokenClassification",
+ "FlaxElectraModel",
+ "FlaxElectraPreTrainedModel",
+ ]
+ )
+ _import_structure["models.encoder_decoder"].append("FlaxEncoderDecoderModel")
+ _import_structure["models.gpt2"].extend(["FlaxGPT2LMHeadModel", "FlaxGPT2Model", "FlaxGPT2PreTrainedModel"])
+ _import_structure["models.gpt_neo"].extend(
+ ["FlaxGPTNeoForCausalLM", "FlaxGPTNeoModel", "FlaxGPTNeoPreTrainedModel"]
+ )
+ _import_structure["models.gptj"].extend(["FlaxGPTJForCausalLM", "FlaxGPTJModel", "FlaxGPTJPreTrainedModel"])
+ _import_structure["models.llama"].extend(["FlaxLlamaForCausalLM", "FlaxLlamaModel", "FlaxLlamaPreTrainedModel"])
+ _import_structure["models.gemma"].extend(["FlaxGemmaForCausalLM", "FlaxGemmaModel", "FlaxGemmaPreTrainedModel"])
+ _import_structure["models.longt5"].extend(
+ [
+ "FlaxLongT5ForConditionalGeneration",
+ "FlaxLongT5Model",
+ "FlaxLongT5PreTrainedModel",
+ ]
+ )
+ _import_structure["models.marian"].extend(
+ [
+ "FlaxMarianModel",
+ "FlaxMarianMTModel",
+ "FlaxMarianPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mbart"].extend(
+ [
+ "FlaxMBartForConditionalGeneration",
+ "FlaxMBartForQuestionAnswering",
+ "FlaxMBartForSequenceClassification",
+ "FlaxMBartModel",
+ "FlaxMBartPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mistral"].extend(
+ [
+ "FlaxMistralForCausalLM",
+ "FlaxMistralModel",
+ "FlaxMistralPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mt5"].extend(["FlaxMT5EncoderModel", "FlaxMT5ForConditionalGeneration", "FlaxMT5Model"])
+ _import_structure["models.opt"].extend(
+ [
+ "FlaxOPTForCausalLM",
+ "FlaxOPTModel",
+ "FlaxOPTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.pegasus"].extend(
+ [
+ "FlaxPegasusForConditionalGeneration",
+ "FlaxPegasusModel",
+ "FlaxPegasusPreTrainedModel",
+ ]
+ )
+ _import_structure["models.regnet"].extend(
+ [
+ "FlaxRegNetForImageClassification",
+ "FlaxRegNetModel",
+ "FlaxRegNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.resnet"].extend(
+ [
+ "FlaxResNetForImageClassification",
+ "FlaxResNetModel",
+ "FlaxResNetPreTrainedModel",
+ ]
+ )
+ _import_structure["models.roberta"].extend(
+ [
+ "FlaxRobertaForCausalLM",
+ "FlaxRobertaForMaskedLM",
+ "FlaxRobertaForMultipleChoice",
+ "FlaxRobertaForQuestionAnswering",
+ "FlaxRobertaForSequenceClassification",
+ "FlaxRobertaForTokenClassification",
+ "FlaxRobertaModel",
+ "FlaxRobertaPreTrainedModel",
+ ]
+ )
+ _import_structure["models.roberta_prelayernorm"].extend(
+ [
+ "FlaxRobertaPreLayerNormForCausalLM",
+ "FlaxRobertaPreLayerNormForMaskedLM",
+ "FlaxRobertaPreLayerNormForMultipleChoice",
+ "FlaxRobertaPreLayerNormForQuestionAnswering",
+ "FlaxRobertaPreLayerNormForSequenceClassification",
+ "FlaxRobertaPreLayerNormForTokenClassification",
+ "FlaxRobertaPreLayerNormModel",
+ "FlaxRobertaPreLayerNormPreTrainedModel",
+ ]
+ )
+ _import_structure["models.roformer"].extend(
+ [
+ "FlaxRoFormerForMaskedLM",
+ "FlaxRoFormerForMultipleChoice",
+ "FlaxRoFormerForQuestionAnswering",
+ "FlaxRoFormerForSequenceClassification",
+ "FlaxRoFormerForTokenClassification",
+ "FlaxRoFormerModel",
+ "FlaxRoFormerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.speech_encoder_decoder"].append("FlaxSpeechEncoderDecoderModel")
+ _import_structure["models.t5"].extend(
+ [
+ "FlaxT5EncoderModel",
+ "FlaxT5ForConditionalGeneration",
+ "FlaxT5Model",
+ "FlaxT5PreTrainedModel",
+ ]
+ )
+ _import_structure["models.vision_encoder_decoder"].append("FlaxVisionEncoderDecoderModel")
+ _import_structure["models.vision_text_dual_encoder"].extend(["FlaxVisionTextDualEncoderModel"])
+ _import_structure["models.vit"].extend(["FlaxViTForImageClassification", "FlaxViTModel", "FlaxViTPreTrainedModel"])
+ _import_structure["models.wav2vec2"].extend(
+ [
+ "FlaxWav2Vec2ForCTC",
+ "FlaxWav2Vec2ForPreTraining",
+ "FlaxWav2Vec2Model",
+ "FlaxWav2Vec2PreTrainedModel",
+ ]
+ )
+ _import_structure["models.whisper"].extend(
+ [
+ "FlaxWhisperForConditionalGeneration",
+ "FlaxWhisperModel",
+ "FlaxWhisperPreTrainedModel",
+ "FlaxWhisperForAudioClassification",
+ ]
+ )
+ _import_structure["models.xglm"].extend(
+ [
+ "FlaxXGLMForCausalLM",
+ "FlaxXGLMModel",
+ "FlaxXGLMPreTrainedModel",
+ ]
+ )
+ _import_structure["models.xlm_roberta"].extend(
+ [
+ "FlaxXLMRobertaForMaskedLM",
+ "FlaxXLMRobertaForMultipleChoice",
+ "FlaxXLMRobertaForQuestionAnswering",
+ "FlaxXLMRobertaForSequenceClassification",
+ "FlaxXLMRobertaForTokenClassification",
+ "FlaxXLMRobertaModel",
+ "FlaxXLMRobertaForCausalLM",
+ "FlaxXLMRobertaPreTrainedModel",
+ ]
+ )
+
+
+# Direct imports for type-checking
+if TYPE_CHECKING:
+ # Configuration
+ # Agents
+ from .agents import (
+ Agent,
+ CodeAgent,
+ HfApiEngine,
+ ManagedAgent,
+ PipelineTool,
+ ReactAgent,
+ ReactCodeAgent,
+ ReactJsonAgent,
+ Tool,
+ Toolbox,
+ ToolCollection,
+ TransformersEngine,
+ launch_gradio_demo,
+ load_tool,
+ stream_to_gradio,
+ tool,
+ )
+ from .configuration_utils import PretrainedConfig
+
+ # Data
+ from .data import (
+ DataProcessor,
+ InputExample,
+ InputFeatures,
+ SingleSentenceClassificationProcessor,
+ SquadExample,
+ SquadFeatures,
+ SquadV1Processor,
+ SquadV2Processor,
+ glue_compute_metrics,
+ glue_convert_examples_to_features,
+ glue_output_modes,
+ glue_processors,
+ glue_tasks_num_labels,
+ squad_convert_examples_to_features,
+ xnli_compute_metrics,
+ xnli_output_modes,
+ xnli_processors,
+ xnli_tasks_num_labels,
+ )
+ from .data.data_collator import (
+ DataCollator,
+ DataCollatorForLanguageModeling,
+ DataCollatorForPermutationLanguageModeling,
+ DataCollatorForSeq2Seq,
+ DataCollatorForSOP,
+ DataCollatorForTokenClassification,
+ DataCollatorForWholeWordMask,
+ DataCollatorWithFlattening,
+ DataCollatorWithPadding,
+ DefaultDataCollator,
+ default_data_collator,
+ )
+ from .feature_extraction_sequence_utils import SequenceFeatureExtractor
+
+ # Feature Extractor
+ from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
+
+ # Generation
+ from .generation import (
+ AsyncTextIteratorStreamer,
+ CompileConfig,
+ GenerationConfig,
+ TextIteratorStreamer,
+ TextStreamer,
+ WatermarkingConfig,
+ )
+ from .hf_argparser import HfArgumentParser
+
+ # Integrations
+ from .integrations import (
+ is_clearml_available,
+ is_comet_available,
+ is_dvclive_available,
+ is_neptune_available,
+ is_optuna_available,
+ is_ray_available,
+ is_ray_tune_available,
+ is_sigopt_available,
+ is_tensorboard_available,
+ is_wandb_available,
+ )
+
+ # Model Cards
+ from .modelcard import ModelCard
+
+ # TF 2.0 <=> PyTorch conversion utilities
+ from .modeling_tf_pytorch_utils import (
+ convert_tf_weight_name_to_pt_weight_name,
+ load_pytorch_checkpoint_in_tf2_model,
+ load_pytorch_model_in_tf2_model,
+ load_pytorch_weights_in_tf2_model,
+ load_tf2_checkpoint_in_pytorch_model,
+ load_tf2_model_in_pytorch_model,
+ load_tf2_weights_in_pytorch_model,
+ )
+ from .models.albert import AlbertConfig
+ from .models.align import (
+ AlignConfig,
+ AlignProcessor,
+ AlignTextConfig,
+ AlignVisionConfig,
+ )
+ from .models.altclip import (
+ AltCLIPConfig,
+ AltCLIPProcessor,
+ AltCLIPTextConfig,
+ AltCLIPVisionConfig,
+ )
+ from .models.aria import (
+ AriaConfig,
+ AriaProcessor,
+ AriaTextConfig,
+ )
+ from .models.audio_spectrogram_transformer import (
+ ASTConfig,
+ ASTFeatureExtractor,
+ )
+ from .models.auto import (
+ CONFIG_MAPPING,
+ FEATURE_EXTRACTOR_MAPPING,
+ IMAGE_PROCESSOR_MAPPING,
+ MODEL_NAMES_MAPPING,
+ PROCESSOR_MAPPING,
+ TOKENIZER_MAPPING,
+ AutoConfig,
+ AutoFeatureExtractor,
+ AutoImageProcessor,
+ AutoProcessor,
+ AutoTokenizer,
+ )
+ from .models.autoformer import (
+ AutoformerConfig,
+ )
+ from .models.bamba import BambaConfig
+ from .models.bark import (
+ BarkCoarseConfig,
+ BarkConfig,
+ BarkFineConfig,
+ BarkProcessor,
+ BarkSemanticConfig,
+ )
+ from .models.bart import BartConfig, BartTokenizer
+ from .models.beit import BeitConfig
+ from .models.bert import (
+ BasicTokenizer,
+ BertConfig,
+ BertTokenizer,
+ WordpieceTokenizer,
+ )
+ from .models.bert_generation import BertGenerationConfig
+ from .models.bert_japanese import (
+ BertJapaneseTokenizer,
+ CharacterTokenizer,
+ MecabTokenizer,
+ )
+ from .models.bertweet import BertweetTokenizer
+ from .models.big_bird import BigBirdConfig
+ from .models.bigbird_pegasus import (
+ BigBirdPegasusConfig,
+ )
+ from .models.biogpt import (
+ BioGptConfig,
+ BioGptTokenizer,
+ )
+ from .models.bit import BitConfig
+ from .models.blenderbot import (
+ BlenderbotConfig,
+ BlenderbotTokenizer,
+ )
+ from .models.blenderbot_small import (
+ BlenderbotSmallConfig,
+ BlenderbotSmallTokenizer,
+ )
+ from .models.blip import (
+ BlipConfig,
+ BlipProcessor,
+ BlipTextConfig,
+ BlipVisionConfig,
+ )
+ from .models.blip_2 import (
+ Blip2Config,
+ Blip2Processor,
+ Blip2QFormerConfig,
+ Blip2VisionConfig,
+ )
+ from .models.bloom import BloomConfig
+ from .models.bridgetower import (
+ BridgeTowerConfig,
+ BridgeTowerProcessor,
+ BridgeTowerTextConfig,
+ BridgeTowerVisionConfig,
+ )
+ from .models.bros import (
+ BrosConfig,
+ BrosProcessor,
+ )
+ from .models.byt5 import ByT5Tokenizer
+ from .models.camembert import (
+ CamembertConfig,
+ )
+ from .models.canine import (
+ CanineConfig,
+ CanineTokenizer,
+ )
+ from .models.chameleon import (
+ ChameleonConfig,
+ ChameleonProcessor,
+ ChameleonVQVAEConfig,
+ )
+ from .models.chinese_clip import (
+ ChineseCLIPConfig,
+ ChineseCLIPProcessor,
+ ChineseCLIPTextConfig,
+ ChineseCLIPVisionConfig,
+ )
+ from .models.clap import (
+ ClapAudioConfig,
+ ClapConfig,
+ ClapProcessor,
+ ClapTextConfig,
+ )
+ from .models.clip import (
+ CLIPConfig,
+ CLIPProcessor,
+ CLIPTextConfig,
+ CLIPTokenizer,
+ CLIPVisionConfig,
+ )
+ from .models.clipseg import (
+ CLIPSegConfig,
+ CLIPSegProcessor,
+ CLIPSegTextConfig,
+ CLIPSegVisionConfig,
+ )
+ from .models.clvp import (
+ ClvpConfig,
+ ClvpDecoderConfig,
+ ClvpEncoderConfig,
+ ClvpFeatureExtractor,
+ ClvpProcessor,
+ ClvpTokenizer,
+ )
+ from .models.codegen import (
+ CodeGenConfig,
+ CodeGenTokenizer,
+ )
+ from .models.cohere import CohereConfig
+ from .models.cohere2 import Cohere2Config
+ from .models.colpali import (
+ ColPaliConfig,
+ ColPaliProcessor,
+ )
+ from .models.conditional_detr import (
+ ConditionalDetrConfig,
+ )
+ from .models.convbert import (
+ ConvBertConfig,
+ ConvBertTokenizer,
+ )
+ from .models.convnext import ConvNextConfig
+ from .models.convnextv2 import (
+ ConvNextV2Config,
+ )
+ from .models.cpmant import (
+ CpmAntConfig,
+ CpmAntTokenizer,
+ )
+ from .models.ctrl import (
+ CTRLConfig,
+ CTRLTokenizer,
+ )
+ from .models.cvt import CvtConfig
+ from .models.dac import (
+ DacConfig,
+ DacFeatureExtractor,
+ )
+ from .models.data2vec import (
+ Data2VecAudioConfig,
+ Data2VecTextConfig,
+ Data2VecVisionConfig,
+ )
+ from .models.dbrx import DbrxConfig
+ from .models.deberta import (
+ DebertaConfig,
+ DebertaTokenizer,
+ )
+ from .models.deberta_v2 import (
+ DebertaV2Config,
+ )
+ from .models.decision_transformer import (
+ DecisionTransformerConfig,
+ )
+ from .models.deformable_detr import (
+ DeformableDetrConfig,
+ )
+ from .models.deit import DeiTConfig
+ from .models.deprecated.deta import DetaConfig
+ from .models.deprecated.efficientformer import (
+ EfficientFormerConfig,
+ )
+ from .models.deprecated.ernie_m import ErnieMConfig
+ from .models.deprecated.gptsan_japanese import (
+ GPTSanJapaneseConfig,
+ GPTSanJapaneseTokenizer,
+ )
+ from .models.deprecated.graphormer import GraphormerConfig
+ from .models.deprecated.jukebox import (
+ JukeboxConfig,
+ JukeboxPriorConfig,
+ JukeboxTokenizer,
+ JukeboxVQVAEConfig,
+ )
+ from .models.deprecated.mctct import (
+ MCTCTConfig,
+ MCTCTFeatureExtractor,
+ MCTCTProcessor,
+ )
+ from .models.deprecated.mega import MegaConfig
+ from .models.deprecated.mmbt import MMBTConfig
+ from .models.deprecated.nat import NatConfig
+ from .models.deprecated.nezha import NezhaConfig
+ from .models.deprecated.open_llama import (
+ OpenLlamaConfig,
+ )
+ from .models.deprecated.qdqbert import QDQBertConfig
+ from .models.deprecated.realm import (
+ RealmConfig,
+ RealmTokenizer,
+ )
+ from .models.deprecated.retribert import (
+ RetriBertConfig,
+ RetriBertTokenizer,
+ )
+ from .models.deprecated.speech_to_text_2 import (
+ Speech2Text2Config,
+ Speech2Text2Processor,
+ Speech2Text2Tokenizer,
+ )
+ from .models.deprecated.tapex import TapexTokenizer
+ from .models.deprecated.trajectory_transformer import (
+ TrajectoryTransformerConfig,
+ )
+ from .models.deprecated.transfo_xl import (
+ TransfoXLConfig,
+ TransfoXLCorpus,
+ TransfoXLTokenizer,
+ )
+ from .models.deprecated.tvlt import (
+ TvltConfig,
+ TvltFeatureExtractor,
+ TvltProcessor,
+ )
+ from .models.deprecated.van import VanConfig
+ from .models.deprecated.vit_hybrid import (
+ ViTHybridConfig,
+ )
+ from .models.deprecated.xlm_prophetnet import (
+ XLMProphetNetConfig,
+ )
+ from .models.depth_anything import DepthAnythingConfig
+ from .models.detr import DetrConfig
+ from .models.dinat import DinatConfig
+ from .models.dinov2 import Dinov2Config
+ from .models.distilbert import (
+ DistilBertConfig,
+ DistilBertTokenizer,
+ )
+ from .models.donut import (
+ DonutProcessor,
+ DonutSwinConfig,
+ )
+ from .models.dpr import (
+ DPRConfig,
+ DPRContextEncoderTokenizer,
+ DPRQuestionEncoderTokenizer,
+ DPRReaderOutput,
+ DPRReaderTokenizer,
+ )
+ from .models.dpt import DPTConfig
+ from .models.efficientnet import (
+ EfficientNetConfig,
+ )
+ from .models.electra import (
+ ElectraConfig,
+ ElectraTokenizer,
+ )
+ from .models.encodec import (
+ EncodecConfig,
+ EncodecFeatureExtractor,
+ )
+ from .models.encoder_decoder import EncoderDecoderConfig
+ from .models.ernie import ErnieConfig
+ from .models.esm import EsmConfig, EsmTokenizer
+ from .models.falcon import FalconConfig
+ from .models.falcon_mamba import FalconMambaConfig
+ from .models.fastspeech2_conformer import (
+ FastSpeech2ConformerConfig,
+ FastSpeech2ConformerHifiGanConfig,
+ FastSpeech2ConformerTokenizer,
+ FastSpeech2ConformerWithHifiGanConfig,
+ )
+ from .models.flaubert import FlaubertConfig, FlaubertTokenizer
+ from .models.flava import (
+ FlavaConfig,
+ FlavaImageCodebookConfig,
+ FlavaImageConfig,
+ FlavaMultimodalConfig,
+ FlavaTextConfig,
+ )
+ from .models.fnet import FNetConfig
+ from .models.focalnet import FocalNetConfig
+ from .models.fsmt import (
+ FSMTConfig,
+ FSMTTokenizer,
+ )
+ from .models.funnel import (
+ FunnelConfig,
+ FunnelTokenizer,
+ )
+ from .models.fuyu import FuyuConfig
+ from .models.gemma import GemmaConfig
+ from .models.gemma2 import Gemma2Config
+ from .models.git import (
+ GitConfig,
+ GitProcessor,
+ GitVisionConfig,
+ )
+ from .models.glm import GlmConfig
+ from .models.glpn import GLPNConfig
+ from .models.gpt2 import (
+ GPT2Config,
+ GPT2Tokenizer,
+ )
+ from .models.gpt_bigcode import (
+ GPTBigCodeConfig,
+ )
+ from .models.gpt_neo import GPTNeoConfig
+ from .models.gpt_neox import GPTNeoXConfig
+ from .models.gpt_neox_japanese import (
+ GPTNeoXJapaneseConfig,
+ )
+ from .models.gptj import GPTJConfig
+ from .models.granite import GraniteConfig
+ from .models.granitemoe import GraniteMoeConfig
+ from .models.grounding_dino import (
+ GroundingDinoConfig,
+ GroundingDinoProcessor,
+ )
+ from .models.groupvit import (
+ GroupViTConfig,
+ GroupViTTextConfig,
+ GroupViTVisionConfig,
+ )
+ from .models.herbert import HerbertTokenizer
+ from .models.hiera import HieraConfig
+ from .models.hubert import HubertConfig
+ from .models.ibert import IBertConfig
+ from .models.idefics import (
+ IdeficsConfig,
+ )
+ from .models.idefics2 import Idefics2Config
+ from .models.idefics3 import Idefics3Config
+ from .models.ijepa import IJepaConfig
+ from .models.imagegpt import ImageGPTConfig
+ from .models.informer import InformerConfig
+ from .models.instructblip import (
+ InstructBlipConfig,
+ InstructBlipProcessor,
+ InstructBlipQFormerConfig,
+ InstructBlipVisionConfig,
+ )
+ from .models.instructblipvideo import (
+ InstructBlipVideoConfig,
+ InstructBlipVideoProcessor,
+ InstructBlipVideoQFormerConfig,
+ InstructBlipVideoVisionConfig,
+ )
+ from .models.jamba import JambaConfig
+ from .models.jetmoe import JetMoeConfig
+ from .models.kosmos2 import (
+ Kosmos2Config,
+ Kosmos2Processor,
+ )
+ from .models.layoutlm import (
+ LayoutLMConfig,
+ LayoutLMTokenizer,
+ )
+ from .models.layoutlmv2 import (
+ LayoutLMv2Config,
+ LayoutLMv2FeatureExtractor,
+ LayoutLMv2ImageProcessor,
+ LayoutLMv2Processor,
+ LayoutLMv2Tokenizer,
+ )
+ from .models.layoutlmv3 import (
+ LayoutLMv3Config,
+ LayoutLMv3FeatureExtractor,
+ LayoutLMv3ImageProcessor,
+ LayoutLMv3Processor,
+ LayoutLMv3Tokenizer,
+ )
+ from .models.layoutxlm import LayoutXLMProcessor
+ from .models.led import LEDConfig, LEDTokenizer
+ from .models.levit import LevitConfig
+ from .models.lilt import LiltConfig
+ from .models.llama import LlamaConfig
+ from .models.llava import (
+ LlavaConfig,
+ LlavaProcessor,
+ )
+ from .models.llava_next import (
+ LlavaNextConfig,
+ LlavaNextProcessor,
+ )
+ from .models.llava_next_video import (
+ LlavaNextVideoConfig,
+ LlavaNextVideoProcessor,
+ )
+ from .models.llava_onevision import (
+ LlavaOnevisionConfig,
+ LlavaOnevisionProcessor,
+ )
+ from .models.longformer import (
+ LongformerConfig,
+ LongformerTokenizer,
+ )
+ from .models.longt5 import LongT5Config
+ from .models.luke import (
+ LukeConfig,
+ LukeTokenizer,
+ )
+ from .models.lxmert import (
+ LxmertConfig,
+ LxmertTokenizer,
+ )
+ from .models.m2m_100 import M2M100Config
+ from .models.mamba import MambaConfig
+ from .models.mamba2 import Mamba2Config
+ from .models.marian import MarianConfig
+ from .models.markuplm import (
+ MarkupLMConfig,
+ MarkupLMFeatureExtractor,
+ MarkupLMProcessor,
+ MarkupLMTokenizer,
+ )
+ from .models.mask2former import (
+ Mask2FormerConfig,
+ )
+ from .models.maskformer import (
+ MaskFormerConfig,
+ MaskFormerSwinConfig,
+ )
+ from .models.mbart import MBartConfig
+ from .models.megatron_bert import (
+ MegatronBertConfig,
+ )
+ from .models.mgp_str import (
+ MgpstrConfig,
+ MgpstrProcessor,
+ MgpstrTokenizer,
+ )
+ from .models.mimi import (
+ MimiConfig,
+ )
+ from .models.mistral import MistralConfig
+ from .models.mixtral import MixtralConfig
+ from .models.mllama import (
+ MllamaConfig,
+ MllamaProcessor,
+ )
+ from .models.mobilebert import (
+ MobileBertConfig,
+ MobileBertTokenizer,
+ )
+ from .models.mobilenet_v1 import (
+ MobileNetV1Config,
+ )
+ from .models.mobilenet_v2 import (
+ MobileNetV2Config,
+ )
+ from .models.mobilevit import (
+ MobileViTConfig,
+ )
+ from .models.mobilevitv2 import (
+ MobileViTV2Config,
+ )
+ from .models.modernbert import ModernBertConfig
+ from .models.moshi import (
+ MoshiConfig,
+ MoshiDepthConfig,
+ )
+ from .models.mpnet import (
+ MPNetConfig,
+ MPNetTokenizer,
+ )
+ from .models.mpt import MptConfig
+ from .models.mra import MraConfig
+ from .models.mt5 import MT5Config
+ from .models.musicgen import (
+ MusicgenConfig,
+ MusicgenDecoderConfig,
+ )
+ from .models.musicgen_melody import (
+ MusicgenMelodyConfig,
+ MusicgenMelodyDecoderConfig,
+ )
+ from .models.mvp import MvpConfig, MvpTokenizer
+ from .models.myt5 import MyT5Tokenizer
+ from .models.nemotron import NemotronConfig
+ from .models.nllb_moe import NllbMoeConfig
+ from .models.nougat import NougatProcessor
+ from .models.nystromformer import (
+ NystromformerConfig,
+ )
+ from .models.olmo import OlmoConfig
+ from .models.olmo2 import Olmo2Config
+ from .models.olmoe import OlmoeConfig
+ from .models.omdet_turbo import (
+ OmDetTurboConfig,
+ OmDetTurboProcessor,
+ )
+ from .models.oneformer import (
+ OneFormerConfig,
+ OneFormerProcessor,
+ )
+ from .models.openai import (
+ OpenAIGPTConfig,
+ OpenAIGPTTokenizer,
+ )
+ from .models.opt import OPTConfig
+ from .models.owlv2 import (
+ Owlv2Config,
+ Owlv2Processor,
+ Owlv2TextConfig,
+ Owlv2VisionConfig,
+ )
+ from .models.owlvit import (
+ OwlViTConfig,
+ OwlViTProcessor,
+ OwlViTTextConfig,
+ OwlViTVisionConfig,
+ )
+ from .models.paligemma import (
+ PaliGemmaConfig,
+ )
+ from .models.patchtsmixer import (
+ PatchTSMixerConfig,
+ )
+ from .models.patchtst import PatchTSTConfig
+ from .models.pegasus import (
+ PegasusConfig,
+ PegasusTokenizer,
+ )
+ from .models.pegasus_x import (
+ PegasusXConfig,
+ )
+ from .models.perceiver import (
+ PerceiverConfig,
+ PerceiverTokenizer,
+ )
+ from .models.persimmon import (
+ PersimmonConfig,
+ )
+ from .models.phi import PhiConfig
+ from .models.phi3 import Phi3Config
+ from .models.phimoe import PhimoeConfig
+ from .models.phobert import PhobertTokenizer
+ from .models.pix2struct import (
+ Pix2StructConfig,
+ Pix2StructProcessor,
+ Pix2StructTextConfig,
+ Pix2StructVisionConfig,
+ )
+ from .models.pixtral import (
+ PixtralProcessor,
+ PixtralVisionConfig,
+ )
+ from .models.plbart import PLBartConfig
+ from .models.poolformer import (
+ PoolFormerConfig,
+ )
+ from .models.pop2piano import (
+ Pop2PianoConfig,
+ )
+ from .models.prophetnet import (
+ ProphetNetConfig,
+ ProphetNetTokenizer,
+ )
+ from .models.pvt import PvtConfig
+ from .models.pvt_v2 import PvtV2Config
+ from .models.qwen2 import Qwen2Config, Qwen2Tokenizer
+ from .models.qwen2_audio import (
+ Qwen2AudioConfig,
+ Qwen2AudioEncoderConfig,
+ Qwen2AudioProcessor,
+ )
+ from .models.qwen2_moe import Qwen2MoeConfig
+ from .models.qwen2_vl import (
+ Qwen2VLConfig,
+ Qwen2VLProcessor,
+ )
+ from .models.rag import RagConfig, RagRetriever, RagTokenizer
+ from .models.recurrent_gemma import RecurrentGemmaConfig
+ from .models.reformer import ReformerConfig
+ from .models.regnet import RegNetConfig
+ from .models.rembert import RemBertConfig
+ from .models.resnet import ResNetConfig
+ from .models.roberta import (
+ RobertaConfig,
+ RobertaTokenizer,
+ )
+ from .models.roberta_prelayernorm import (
+ RobertaPreLayerNormConfig,
+ )
+ from .models.roc_bert import (
+ RoCBertConfig,
+ RoCBertTokenizer,
+ )
+ from .models.roformer import (
+ RoFormerConfig,
+ RoFormerTokenizer,
+ )
+ from .models.rt_detr import (
+ RTDetrConfig,
+ RTDetrResNetConfig,
+ )
+ from .models.rwkv import RwkvConfig
+ from .models.sam import (
+ SamConfig,
+ SamMaskDecoderConfig,
+ SamProcessor,
+ SamPromptEncoderConfig,
+ SamVisionConfig,
+ )
+ from .models.seamless_m4t import (
+ SeamlessM4TConfig,
+ SeamlessM4TFeatureExtractor,
+ SeamlessM4TProcessor,
+ )
+ from .models.seamless_m4t_v2 import (
+ SeamlessM4Tv2Config,
+ )
+ from .models.segformer import SegformerConfig
+ from .models.seggpt import SegGptConfig
+ from .models.sew import SEWConfig
+ from .models.sew_d import SEWDConfig
+ from .models.siglip import (
+ SiglipConfig,
+ SiglipProcessor,
+ SiglipTextConfig,
+ SiglipVisionConfig,
+ )
+ from .models.speech_encoder_decoder import SpeechEncoderDecoderConfig
+ from .models.speech_to_text import (
+ Speech2TextConfig,
+ Speech2TextFeatureExtractor,
+ Speech2TextProcessor,
+ )
+ from .models.speecht5 import (
+ SpeechT5Config,
+ SpeechT5FeatureExtractor,
+ SpeechT5HifiGanConfig,
+ SpeechT5Processor,
+ )
+ from .models.splinter import (
+ SplinterConfig,
+ SplinterTokenizer,
+ )
+ from .models.squeezebert import (
+ SqueezeBertConfig,
+ SqueezeBertTokenizer,
+ )
+ from .models.stablelm import StableLmConfig
+ from .models.starcoder2 import Starcoder2Config
+ from .models.superpoint import SuperPointConfig
+ from .models.swiftformer import (
+ SwiftFormerConfig,
+ )
+ from .models.swin import SwinConfig
+ from .models.swin2sr import Swin2SRConfig
+ from .models.swinv2 import Swinv2Config
+ from .models.switch_transformers import (
+ SwitchTransformersConfig,
+ )
+ from .models.t5 import T5Config
+ from .models.table_transformer import (
+ TableTransformerConfig,
+ )
+ from .models.tapas import (
+ TapasConfig,
+ TapasTokenizer,
+ )
+ from .models.time_series_transformer import (
+ TimeSeriesTransformerConfig,
+ )
+ from .models.timesformer import (
+ TimesformerConfig,
+ )
+ from .models.timm_backbone import TimmBackboneConfig
+ from .models.timm_wrapper import TimmWrapperConfig
+ from .models.trocr import (
+ TrOCRConfig,
+ TrOCRProcessor,
+ )
+ from .models.tvp import (
+ TvpConfig,
+ TvpProcessor,
+ )
+ from .models.udop import UdopConfig, UdopProcessor
+ from .models.umt5 import UMT5Config
+ from .models.unispeech import (
+ UniSpeechConfig,
+ )
+ from .models.unispeech_sat import (
+ UniSpeechSatConfig,
+ )
+ from .models.univnet import (
+ UnivNetConfig,
+ UnivNetFeatureExtractor,
+ )
+ from .models.upernet import UperNetConfig
+ from .models.video_llava import VideoLlavaConfig
+ from .models.videomae import VideoMAEConfig
+ from .models.vilt import (
+ ViltConfig,
+ ViltFeatureExtractor,
+ ViltImageProcessor,
+ ViltProcessor,
+ )
+ from .models.vipllava import (
+ VipLlavaConfig,
+ )
+ from .models.vision_encoder_decoder import VisionEncoderDecoderConfig
+ from .models.vision_text_dual_encoder import (
+ VisionTextDualEncoderConfig,
+ VisionTextDualEncoderProcessor,
+ )
+ from .models.visual_bert import (
+ VisualBertConfig,
+ )
+ from .models.vit import ViTConfig
+ from .models.vit_mae import ViTMAEConfig
+ from .models.vit_msn import ViTMSNConfig
+ from .models.vitdet import VitDetConfig
+ from .models.vitmatte import VitMatteConfig
+ from .models.vits import (
+ VitsConfig,
+ VitsTokenizer,
+ )
+ from .models.vivit import VivitConfig
+ from .models.wav2vec2 import (
+ Wav2Vec2Config,
+ Wav2Vec2CTCTokenizer,
+ Wav2Vec2FeatureExtractor,
+ Wav2Vec2Processor,
+ Wav2Vec2Tokenizer,
+ )
+ from .models.wav2vec2_bert import (
+ Wav2Vec2BertConfig,
+ Wav2Vec2BertProcessor,
+ )
+ from .models.wav2vec2_conformer import (
+ Wav2Vec2ConformerConfig,
+ )
+ from .models.wav2vec2_phoneme import Wav2Vec2PhonemeCTCTokenizer
+ from .models.wav2vec2_with_lm import Wav2Vec2ProcessorWithLM
+ from .models.wavlm import WavLMConfig
+ from .models.whisper import (
+ WhisperConfig,
+ WhisperFeatureExtractor,
+ WhisperProcessor,
+ WhisperTokenizer,
+ )
+ from .models.x_clip import (
+ XCLIPConfig,
+ XCLIPProcessor,
+ XCLIPTextConfig,
+ XCLIPVisionConfig,
+ )
+ from .models.xglm import XGLMConfig
+ from .models.xlm import XLMConfig, XLMTokenizer
+ from .models.xlm_roberta import (
+ XLMRobertaConfig,
+ )
+ from .models.xlm_roberta_xl import (
+ XLMRobertaXLConfig,
+ )
+ from .models.xlnet import XLNetConfig
+ from .models.xmod import XmodConfig
+ from .models.yolos import YolosConfig
+ from .models.yoso import YosoConfig
+ from .models.zamba import ZambaConfig
+ from .models.zoedepth import ZoeDepthConfig
+
+ # Pipelines
+ from .pipelines import (
+ AudioClassificationPipeline,
+ AutomaticSpeechRecognitionPipeline,
+ CsvPipelineDataFormat,
+ DepthEstimationPipeline,
+ DocumentQuestionAnsweringPipeline,
+ FeatureExtractionPipeline,
+ FillMaskPipeline,
+ ImageClassificationPipeline,
+ ImageFeatureExtractionPipeline,
+ ImageSegmentationPipeline,
+ ImageTextToTextPipeline,
+ ImageToImagePipeline,
+ ImageToTextPipeline,
+ JsonPipelineDataFormat,
+ MaskGenerationPipeline,
+ NerPipeline,
+ ObjectDetectionPipeline,
+ PipedPipelineDataFormat,
+ Pipeline,
+ PipelineDataFormat,
+ QuestionAnsweringPipeline,
+ SummarizationPipeline,
+ TableQuestionAnsweringPipeline,
+ Text2TextGenerationPipeline,
+ TextClassificationPipeline,
+ TextGenerationPipeline,
+ TextToAudioPipeline,
+ TokenClassificationPipeline,
+ TranslationPipeline,
+ VideoClassificationPipeline,
+ VisualQuestionAnsweringPipeline,
+ ZeroShotAudioClassificationPipeline,
+ ZeroShotClassificationPipeline,
+ ZeroShotImageClassificationPipeline,
+ ZeroShotObjectDetectionPipeline,
+ pipeline,
+ )
+ from .processing_utils import ProcessorMixin
+
+ # Tokenization
+ from .tokenization_utils import PreTrainedTokenizer
+ from .tokenization_utils_base import (
+ AddedToken,
+ BatchEncoding,
+ CharSpan,
+ PreTrainedTokenizerBase,
+ SpecialTokensMixin,
+ TokenSpan,
+ )
+
+ # Trainer
+ from .trainer_callback import (
+ DefaultFlowCallback,
+ EarlyStoppingCallback,
+ PrinterCallback,
+ ProgressCallback,
+ TrainerCallback,
+ TrainerControl,
+ TrainerState,
+ )
+ from .trainer_utils import (
+ EvalPrediction,
+ IntervalStrategy,
+ SchedulerType,
+ enable_full_determinism,
+ set_seed,
+ )
+ from .training_args import TrainingArguments
+ from .training_args_seq2seq import Seq2SeqTrainingArguments
+ from .training_args_tf import TFTrainingArguments
+
+ # Files and general utilities
+ from .utils import (
+ CONFIG_NAME,
+ MODEL_CARD_NAME,
+ PYTORCH_PRETRAINED_BERT_CACHE,
+ PYTORCH_TRANSFORMERS_CACHE,
+ SPIECE_UNDERLINE,
+ TF2_WEIGHTS_NAME,
+ TF_WEIGHTS_NAME,
+ TRANSFORMERS_CACHE,
+ WEIGHTS_NAME,
+ TensorType,
+ add_end_docstrings,
+ add_start_docstrings,
+ is_apex_available,
+ is_av_available,
+ is_bitsandbytes_available,
+ is_datasets_available,
+ is_faiss_available,
+ is_flax_available,
+ is_keras_nlp_available,
+ is_phonemizer_available,
+ is_psutil_available,
+ is_py3nvml_available,
+ is_pyctcdecode_available,
+ is_sacremoses_available,
+ is_safetensors_available,
+ is_scipy_available,
+ is_sentencepiece_available,
+ is_sklearn_available,
+ is_speech_available,
+ is_tensorflow_text_available,
+ is_tf_available,
+ is_timm_available,
+ is_tokenizers_available,
+ is_torch_available,
+ is_torch_mlu_available,
+ is_torch_musa_available,
+ is_torch_neuroncore_available,
+ is_torch_npu_available,
+ is_torch_tpu_available,
+ is_torch_xla_available,
+ is_torch_xpu_available,
+ is_torchvision_available,
+ is_vision_available,
+ logging,
+ )
+
+ # bitsandbytes config
+ from .utils.quantization_config import (
+ AqlmConfig,
+ AwqConfig,
+ BitNetConfig,
+ BitsAndBytesConfig,
+ CompressedTensorsConfig,
+ EetqConfig,
+ FbgemmFp8Config,
+ GPTQConfig,
+ HiggsConfig,
+ HqqConfig,
+ QuantoConfig,
+ TorchAoConfig,
+ VptqConfig,
+ )
+
+ try:
+ if not is_sentencepiece_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ from .utils.dummy_sentencepiece_objects import *
+ else:
+ from .models.albert import AlbertTokenizer
+ from .models.barthez import BarthezTokenizer
+ from .models.bartpho import BartphoTokenizer
+ from .models.bert_generation import BertGenerationTokenizer
+ from .models.big_bird import BigBirdTokenizer
+ from .models.camembert import CamembertTokenizer
+ from .models.code_llama import CodeLlamaTokenizer
+ from .models.cpm import CpmTokenizer
+ from .models.deberta_v2 import DebertaV2Tokenizer
+ from .models.deprecated.ernie_m import ErnieMTokenizer
+ from .models.deprecated.xlm_prophetnet import XLMProphetNetTokenizer
+ from .models.fnet import FNetTokenizer
+ from .models.gemma import GemmaTokenizer
+ from .models.gpt_sw3 import GPTSw3Tokenizer
+ from .models.layoutxlm import LayoutXLMTokenizer
+ from .models.llama import LlamaTokenizer
+ from .models.m2m_100 import M2M100Tokenizer
+ from .models.marian import MarianTokenizer
+ from .models.mbart import MBartTokenizer
+ from .models.mbart50 import MBart50Tokenizer
+ from .models.mluke import MLukeTokenizer
+ from .models.mt5 import MT5Tokenizer
+ from .models.nllb import NllbTokenizer
+ from .models.pegasus import PegasusTokenizer
+ from .models.plbart import PLBartTokenizer
+ from .models.reformer import ReformerTokenizer
+ from .models.rembert import RemBertTokenizer
+ from .models.seamless_m4t import SeamlessM4TTokenizer
+ from .models.siglip import SiglipTokenizer
+ from .models.speech_to_text import Speech2TextTokenizer
+ from .models.speecht5 import SpeechT5Tokenizer
+ from .models.t5 import T5Tokenizer
+ from .models.udop import UdopTokenizer
+ from .models.xglm import XGLMTokenizer
+ from .models.xlm_roberta import XLMRobertaTokenizer
+ from .models.xlnet import XLNetTokenizer
+
+ try:
+ if not is_tokenizers_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ from .utils.dummy_tokenizers_objects import *
+ else:
+ # Fast tokenizers imports
+ from .models.albert import AlbertTokenizerFast
+ from .models.bart import BartTokenizerFast
+ from .models.barthez import BarthezTokenizerFast
+ from .models.bert import BertTokenizerFast
+ from .models.big_bird import BigBirdTokenizerFast
+ from .models.blenderbot import BlenderbotTokenizerFast
+ from .models.blenderbot_small import BlenderbotSmallTokenizerFast
+ from .models.bloom import BloomTokenizerFast
+ from .models.camembert import CamembertTokenizerFast
+ from .models.clip import CLIPTokenizerFast
+ from .models.code_llama import CodeLlamaTokenizerFast
+ from .models.codegen import CodeGenTokenizerFast
+ from .models.cohere import CohereTokenizerFast
+ from .models.convbert import ConvBertTokenizerFast
+ from .models.cpm import CpmTokenizerFast
+ from .models.deberta import DebertaTokenizerFast
+ from .models.deberta_v2 import DebertaV2TokenizerFast
+ from .models.deprecated.realm import RealmTokenizerFast
+ from .models.deprecated.retribert import RetriBertTokenizerFast
+ from .models.distilbert import DistilBertTokenizerFast
+ from .models.dpr import (
+ DPRContextEncoderTokenizerFast,
+ DPRQuestionEncoderTokenizerFast,
+ DPRReaderTokenizerFast,
+ )
+ from .models.electra import ElectraTokenizerFast
+ from .models.fnet import FNetTokenizerFast
+ from .models.funnel import FunnelTokenizerFast
+ from .models.gemma import GemmaTokenizerFast
+ from .models.gpt2 import GPT2TokenizerFast
+ from .models.gpt_neox import GPTNeoXTokenizerFast
+ from .models.gpt_neox_japanese import GPTNeoXJapaneseTokenizer
+ from .models.herbert import HerbertTokenizerFast
+ from .models.layoutlm import LayoutLMTokenizerFast
+ from .models.layoutlmv2 import LayoutLMv2TokenizerFast
+ from .models.layoutlmv3 import LayoutLMv3TokenizerFast
+ from .models.layoutxlm import LayoutXLMTokenizerFast
+ from .models.led import LEDTokenizerFast
+ from .models.llama import LlamaTokenizerFast
+ from .models.longformer import LongformerTokenizerFast
+ from .models.lxmert import LxmertTokenizerFast
+ from .models.markuplm import MarkupLMTokenizerFast
+ from .models.mbart import MBartTokenizerFast
+ from .models.mbart50 import MBart50TokenizerFast
+ from .models.mobilebert import MobileBertTokenizerFast
+ from .models.mpnet import MPNetTokenizerFast
+ from .models.mt5 import MT5TokenizerFast
+ from .models.mvp import MvpTokenizerFast
+ from .models.nllb import NllbTokenizerFast
+ from .models.nougat import NougatTokenizerFast
+ from .models.openai import OpenAIGPTTokenizerFast
+ from .models.pegasus import PegasusTokenizerFast
+ from .models.qwen2 import Qwen2TokenizerFast
+ from .models.reformer import ReformerTokenizerFast
+ from .models.rembert import RemBertTokenizerFast
+ from .models.roberta import RobertaTokenizerFast
+ from .models.roformer import RoFormerTokenizerFast
+ from .models.seamless_m4t import SeamlessM4TTokenizerFast
+ from .models.splinter import SplinterTokenizerFast
+ from .models.squeezebert import SqueezeBertTokenizerFast
+ from .models.t5 import T5TokenizerFast
+ from .models.udop import UdopTokenizerFast
+ from .models.whisper import WhisperTokenizerFast
+ from .models.xglm import XGLMTokenizerFast
+ from .models.xlm_roberta import XLMRobertaTokenizerFast
+ from .models.xlnet import XLNetTokenizerFast
+ from .tokenization_utils_fast import PreTrainedTokenizerFast
+
+ try:
+ if not (is_sentencepiece_available() and is_tokenizers_available()):
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ from .utils.dummies_sentencepiece_and_tokenizers_objects import *
+ else:
+ from .convert_slow_tokenizer import (
+ SLOW_TO_FAST_CONVERTERS,
+ convert_slow_tokenizer,
+ )
+
+ try:
+ if not is_tensorflow_text_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ from .utils.dummy_tensorflow_text_objects import *
+ else:
+ from .models.bert import TFBertTokenizer
+
+ try:
+ if not is_keras_nlp_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ from .utils.dummy_keras_nlp_objects import *
+ else:
+ from .models.gpt2 import TFGPT2Tokenizer
+
+ try:
+ if not is_vision_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ from .utils.dummy_vision_objects import *
+ else:
+ from .image_processing_base import ImageProcessingMixin
+ from .image_processing_utils import BaseImageProcessor
+ from .image_utils import ImageFeatureExtractionMixin
+ from .models.aria import AriaImageProcessor
+ from .models.beit import BeitFeatureExtractor, BeitImageProcessor
+ from .models.bit import BitImageProcessor
+ from .models.blip import BlipImageProcessor
+ from .models.bridgetower import BridgeTowerImageProcessor
+ from .models.chameleon import ChameleonImageProcessor
+ from .models.chinese_clip import (
+ ChineseCLIPFeatureExtractor,
+ ChineseCLIPImageProcessor,
+ )
+ from .models.clip import CLIPFeatureExtractor, CLIPImageProcessor
+ from .models.conditional_detr import (
+ ConditionalDetrFeatureExtractor,
+ ConditionalDetrImageProcessor,
+ )
+ from .models.convnext import ConvNextFeatureExtractor, ConvNextImageProcessor
+ from .models.deformable_detr import DeformableDetrFeatureExtractor, DeformableDetrImageProcessor
+ from .models.deit import DeiTFeatureExtractor, DeiTImageProcessor
+ from .models.deprecated.deta import DetaImageProcessor
+ from .models.deprecated.efficientformer import EfficientFormerImageProcessor
+ from .models.deprecated.tvlt import TvltImageProcessor
+ from .models.deprecated.vit_hybrid import ViTHybridImageProcessor
+ from .models.detr import DetrFeatureExtractor, DetrImageProcessor
+ from .models.donut import DonutFeatureExtractor, DonutImageProcessor
+ from .models.dpt import DPTFeatureExtractor, DPTImageProcessor
+ from .models.efficientnet import EfficientNetImageProcessor
+ from .models.flava import (
+ FlavaFeatureExtractor,
+ FlavaImageProcessor,
+ FlavaProcessor,
+ )
+ from .models.fuyu import FuyuImageProcessor, FuyuProcessor
+ from .models.glpn import GLPNFeatureExtractor, GLPNImageProcessor
+ from .models.grounding_dino import GroundingDinoImageProcessor
+ from .models.idefics import IdeficsImageProcessor
+ from .models.idefics2 import Idefics2ImageProcessor
+ from .models.idefics3 import Idefics3ImageProcessor
+ from .models.imagegpt import ImageGPTFeatureExtractor, ImageGPTImageProcessor
+ from .models.instructblipvideo import InstructBlipVideoImageProcessor
+ from .models.layoutlmv2 import (
+ LayoutLMv2FeatureExtractor,
+ LayoutLMv2ImageProcessor,
+ )
+ from .models.layoutlmv3 import (
+ LayoutLMv3FeatureExtractor,
+ LayoutLMv3ImageProcessor,
+ )
+ from .models.levit import LevitFeatureExtractor, LevitImageProcessor
+ from .models.llava_next import LlavaNextImageProcessor
+ from .models.llava_next_video import LlavaNextVideoImageProcessor
+ from .models.llava_onevision import LlavaOnevisionImageProcessor, LlavaOnevisionVideoProcessor
+ from .models.mask2former import Mask2FormerImageProcessor
+ from .models.maskformer import (
+ MaskFormerFeatureExtractor,
+ MaskFormerImageProcessor,
+ )
+ from .models.mllama import MllamaImageProcessor
+ from .models.mobilenet_v1 import (
+ MobileNetV1FeatureExtractor,
+ MobileNetV1ImageProcessor,
+ )
+ from .models.mobilenet_v2 import (
+ MobileNetV2FeatureExtractor,
+ MobileNetV2ImageProcessor,
+ )
+ from .models.mobilevit import MobileViTFeatureExtractor, MobileViTImageProcessor
+ from .models.nougat import NougatImageProcessor
+ from .models.oneformer import OneFormerImageProcessor
+ from .models.owlv2 import Owlv2ImageProcessor
+ from .models.owlvit import OwlViTFeatureExtractor, OwlViTImageProcessor
+ from .models.perceiver import PerceiverFeatureExtractor, PerceiverImageProcessor
+ from .models.pix2struct import Pix2StructImageProcessor
+ from .models.pixtral import PixtralImageProcessor
+ from .models.poolformer import (
+ PoolFormerFeatureExtractor,
+ PoolFormerImageProcessor,
+ )
+ from .models.pvt import PvtImageProcessor
+ from .models.qwen2_vl import Qwen2VLImageProcessor
+ from .models.rt_detr import RTDetrImageProcessor
+ from .models.sam import SamImageProcessor
+ from .models.segformer import SegformerFeatureExtractor, SegformerImageProcessor
+ from .models.seggpt import SegGptImageProcessor
+ from .models.siglip import SiglipImageProcessor
+ from .models.superpoint import SuperPointImageProcessor
+ from .models.swin2sr import Swin2SRImageProcessor
+ from .models.tvp import TvpImageProcessor
+ from .models.video_llava import VideoLlavaImageProcessor
+ from .models.videomae import VideoMAEFeatureExtractor, VideoMAEImageProcessor
+ from .models.vilt import ViltFeatureExtractor, ViltImageProcessor, ViltProcessor
+ from .models.vit import ViTFeatureExtractor, ViTImageProcessor
+ from .models.vitmatte import VitMatteImageProcessor
+ from .models.vivit import VivitImageProcessor
+ from .models.yolos import YolosFeatureExtractor, YolosImageProcessor
+ from .models.zoedepth import ZoeDepthImageProcessor
+
+ try:
+ if not is_torchvision_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ from .utils.dummy_torchvision_objects import *
+ else:
+ from .image_processing_utils_fast import BaseImageProcessorFast
+ from .models.deformable_detr import DeformableDetrImageProcessorFast
+ from .models.detr import DetrImageProcessorFast
+ from .models.pixtral import PixtralImageProcessorFast
+ from .models.rt_detr import RTDetrImageProcessorFast
+ from .models.vit import ViTImageProcessorFast
+
+ try:
+ if not is_torchvision_available() and not is_timm_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ from .utils.dummy_timm_and_torchvision_objects import *
+ else:
+ from .models.timm_wrapper import TimmWrapperImageProcessor
+
+ # Modeling
+ try:
+ if not is_torch_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ from .utils.dummy_pt_objects import *
+ else:
+ # Benchmarks
+ from .benchmark.benchmark import PyTorchBenchmark
+ from .benchmark.benchmark_args import PyTorchBenchmarkArguments
+ from .cache_utils import (
+ Cache,
+ CacheConfig,
+ DynamicCache,
+ EncoderDecoderCache,
+ HQQQuantizedCache,
+ HybridCache,
+ MambaCache,
+ OffloadedCache,
+ OffloadedStaticCache,
+ QuantizedCache,
+ QuantizedCacheConfig,
+ QuantoQuantizedCache,
+ SinkCache,
+ SlidingWindowCache,
+ StaticCache,
+ )
+ from .data.datasets import (
+ GlueDataset,
+ GlueDataTrainingArguments,
+ LineByLineTextDataset,
+ LineByLineWithRefDataset,
+ LineByLineWithSOPTextDataset,
+ SquadDataset,
+ SquadDataTrainingArguments,
+ TextDataset,
+ TextDatasetForNextSentencePrediction,
+ )
+ from .generation import (
+ AlternatingCodebooksLogitsProcessor,
+ BayesianDetectorConfig,
+ BayesianDetectorModel,
+ BeamScorer,
+ BeamSearchScorer,
+ ClassifierFreeGuidanceLogitsProcessor,
+ ConstrainedBeamSearchScorer,
+ Constraint,
+ ConstraintListState,
+ DisjunctiveConstraint,
+ EncoderNoRepeatNGramLogitsProcessor,
+ EncoderRepetitionPenaltyLogitsProcessor,
+ EosTokenCriteria,
+ EpsilonLogitsWarper,
+ EtaLogitsWarper,
+ ExponentialDecayLengthPenalty,
+ ForcedBOSTokenLogitsProcessor,
+ ForcedEOSTokenLogitsProcessor,
+ GenerationMixin,
+ HammingDiversityLogitsProcessor,
+ InfNanRemoveLogitsProcessor,
+ LogitNormalization,
+ LogitsProcessor,
+ LogitsProcessorList,
+ LogitsWarper,
+ MaxLengthCriteria,
+ MaxTimeCriteria,
+ MinLengthLogitsProcessor,
+ MinNewTokensLengthLogitsProcessor,
+ MinPLogitsWarper,
+ NoBadWordsLogitsProcessor,
+ NoRepeatNGramLogitsProcessor,
+ PhrasalConstraint,
+ PrefixConstrainedLogitsProcessor,
+ RepetitionPenaltyLogitsProcessor,
+ SequenceBiasLogitsProcessor,
+ StoppingCriteria,
+ StoppingCriteriaList,
+ StopStringCriteria,
+ SuppressTokensAtBeginLogitsProcessor,
+ SuppressTokensLogitsProcessor,
+ SynthIDTextWatermarkDetector,
+ SynthIDTextWatermarkingConfig,
+ SynthIDTextWatermarkLogitsProcessor,
+ TemperatureLogitsWarper,
+ TopKLogitsWarper,
+ TopPLogitsWarper,
+ TypicalLogitsWarper,
+ UnbatchedClassifierFreeGuidanceLogitsProcessor,
+ WatermarkDetector,
+ WatermarkLogitsProcessor,
+ WhisperTimeStampLogitsProcessor,
+ )
+ from .integrations.executorch import (
+ TorchExportableModuleWithStaticCache,
+ convert_and_export_with_cache,
+ )
+ from .modeling_rope_utils import ROPE_INIT_FUNCTIONS
+ from .modeling_utils import PreTrainedModel
+ from .models.albert import (
+ AlbertForMaskedLM,
+ AlbertForMultipleChoice,
+ AlbertForPreTraining,
+ AlbertForQuestionAnswering,
+ AlbertForSequenceClassification,
+ AlbertForTokenClassification,
+ AlbertModel,
+ AlbertPreTrainedModel,
+ load_tf_weights_in_albert,
+ )
+ from .models.align import (
+ AlignModel,
+ AlignPreTrainedModel,
+ AlignTextModel,
+ AlignVisionModel,
+ )
+ from .models.altclip import (
+ AltCLIPModel,
+ AltCLIPPreTrainedModel,
+ AltCLIPTextModel,
+ AltCLIPVisionModel,
+ )
+ from .models.aria import (
+ AriaForConditionalGeneration,
+ AriaPreTrainedModel,
+ AriaTextForCausalLM,
+ AriaTextModel,
+ AriaTextPreTrainedModel,
+ )
+ from .models.audio_spectrogram_transformer import (
+ ASTForAudioClassification,
+ ASTModel,
+ ASTPreTrainedModel,
+ )
+ from .models.auto import (
+ MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING,
+ MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING,
+ MODEL_FOR_AUDIO_XVECTOR_MAPPING,
+ MODEL_FOR_BACKBONE_MAPPING,
+ MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING,
+ MODEL_FOR_CAUSAL_LM_MAPPING,
+ MODEL_FOR_CTC_MAPPING,
+ MODEL_FOR_DEPTH_ESTIMATION_MAPPING,
+ MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING,
+ MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
+ MODEL_FOR_IMAGE_MAPPING,
+ MODEL_FOR_IMAGE_SEGMENTATION_MAPPING,
+ MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING,
+ MODEL_FOR_IMAGE_TO_IMAGE_MAPPING,
+ MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING,
+ MODEL_FOR_KEYPOINT_DETECTION_MAPPING,
+ MODEL_FOR_MASK_GENERATION_MAPPING,
+ MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
+ MODEL_FOR_MASKED_LM_MAPPING,
+ MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
+ MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
+ MODEL_FOR_OBJECT_DETECTION_MAPPING,
+ MODEL_FOR_PRETRAINING_MAPPING,
+ MODEL_FOR_QUESTION_ANSWERING_MAPPING,
+ MODEL_FOR_RETRIEVAL_MAPPING,
+ MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING,
+ MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
+ MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
+ MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
+ MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
+ MODEL_FOR_TEXT_ENCODING_MAPPING,
+ MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING,
+ MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING,
+ MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING,
+ MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING,
+ MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
+ MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING,
+ MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
+ MODEL_FOR_VISION_2_SEQ_MAPPING,
+ MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING,
+ MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING,
+ MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING,
+ MODEL_MAPPING,
+ MODEL_WITH_LM_HEAD_MAPPING,
+ AutoBackbone,
+ AutoModel,
+ AutoModelForAudioClassification,
+ AutoModelForAudioFrameClassification,
+ AutoModelForAudioXVector,
+ AutoModelForCausalLM,
+ AutoModelForCTC,
+ AutoModelForDepthEstimation,
+ AutoModelForDocumentQuestionAnswering,
+ AutoModelForImageClassification,
+ AutoModelForImageSegmentation,
+ AutoModelForImageTextToText,
+ AutoModelForImageToImage,
+ AutoModelForInstanceSegmentation,
+ AutoModelForKeypointDetection,
+ AutoModelForMaskedImageModeling,
+ AutoModelForMaskedLM,
+ AutoModelForMaskGeneration,
+ AutoModelForMultipleChoice,
+ AutoModelForNextSentencePrediction,
+ AutoModelForObjectDetection,
+ AutoModelForPreTraining,
+ AutoModelForQuestionAnswering,
+ AutoModelForSemanticSegmentation,
+ AutoModelForSeq2SeqLM,
+ AutoModelForSequenceClassification,
+ AutoModelForSpeechSeq2Seq,
+ AutoModelForTableQuestionAnswering,
+ AutoModelForTextEncoding,
+ AutoModelForTextToSpectrogram,
+ AutoModelForTextToWaveform,
+ AutoModelForTokenClassification,
+ AutoModelForUniversalSegmentation,
+ AutoModelForVideoClassification,
+ AutoModelForVision2Seq,
+ AutoModelForVisualQuestionAnswering,
+ AutoModelForZeroShotImageClassification,
+ AutoModelForZeroShotObjectDetection,
+ AutoModelWithLMHead,
+ )
+ from .models.autoformer import (
+ AutoformerForPrediction,
+ AutoformerModel,
+ AutoformerPreTrainedModel,
+ )
+ from .models.bamba import BambaForCausalLM, BambaModel, BambaPreTrainedModel
+ from .models.bark import (
+ BarkCausalModel,
+ BarkCoarseModel,
+ BarkFineModel,
+ BarkModel,
+ BarkPreTrainedModel,
+ BarkSemanticModel,
+ )
+ from .models.bart import (
+ BartForCausalLM,
+ BartForConditionalGeneration,
+ BartForQuestionAnswering,
+ BartForSequenceClassification,
+ BartModel,
+ BartPreTrainedModel,
+ BartPretrainedModel,
+ PretrainedBartModel,
+ )
+ from .models.beit import (
+ BeitBackbone,
+ BeitForImageClassification,
+ BeitForMaskedImageModeling,
+ BeitForSemanticSegmentation,
+ BeitModel,
+ BeitPreTrainedModel,
+ )
+ from .models.bert import (
+ BertForMaskedLM,
+ BertForMultipleChoice,
+ BertForNextSentencePrediction,
+ BertForPreTraining,
+ BertForQuestionAnswering,
+ BertForSequenceClassification,
+ BertForTokenClassification,
+ BertLMHeadModel,
+ BertModel,
+ BertPreTrainedModel,
+ load_tf_weights_in_bert,
+ )
+ from .models.bert_generation import (
+ BertGenerationDecoder,
+ BertGenerationEncoder,
+ BertGenerationPreTrainedModel,
+ load_tf_weights_in_bert_generation,
+ )
+ from .models.big_bird import (
+ BigBirdForCausalLM,
+ BigBirdForMaskedLM,
+ BigBirdForMultipleChoice,
+ BigBirdForPreTraining,
+ BigBirdForQuestionAnswering,
+ BigBirdForSequenceClassification,
+ BigBirdForTokenClassification,
+ BigBirdModel,
+ BigBirdPreTrainedModel,
+ load_tf_weights_in_big_bird,
+ )
+ from .models.bigbird_pegasus import (
+ BigBirdPegasusForCausalLM,
+ BigBirdPegasusForConditionalGeneration,
+ BigBirdPegasusForQuestionAnswering,
+ BigBirdPegasusForSequenceClassification,
+ BigBirdPegasusModel,
+ BigBirdPegasusPreTrainedModel,
+ )
+ from .models.biogpt import (
+ BioGptForCausalLM,
+ BioGptForSequenceClassification,
+ BioGptForTokenClassification,
+ BioGptModel,
+ BioGptPreTrainedModel,
+ )
+ from .models.bit import (
+ BitBackbone,
+ BitForImageClassification,
+ BitModel,
+ BitPreTrainedModel,
+ )
+ from .models.blenderbot import (
+ BlenderbotForCausalLM,
+ BlenderbotForConditionalGeneration,
+ BlenderbotModel,
+ BlenderbotPreTrainedModel,
+ )
+ from .models.blenderbot_small import (
+ BlenderbotSmallForCausalLM,
+ BlenderbotSmallForConditionalGeneration,
+ BlenderbotSmallModel,
+ BlenderbotSmallPreTrainedModel,
+ )
+ from .models.blip import (
+ BlipForConditionalGeneration,
+ BlipForImageTextRetrieval,
+ BlipForQuestionAnswering,
+ BlipModel,
+ BlipPreTrainedModel,
+ BlipTextModel,
+ BlipVisionModel,
+ )
+ from .models.blip_2 import (
+ Blip2ForConditionalGeneration,
+ Blip2ForImageTextRetrieval,
+ Blip2Model,
+ Blip2PreTrainedModel,
+ Blip2QFormerModel,
+ Blip2TextModelWithProjection,
+ Blip2VisionModel,
+ Blip2VisionModelWithProjection,
+ )
+ from .models.bloom import (
+ BloomForCausalLM,
+ BloomForQuestionAnswering,
+ BloomForSequenceClassification,
+ BloomForTokenClassification,
+ BloomModel,
+ BloomPreTrainedModel,
+ )
+ from .models.bridgetower import (
+ BridgeTowerForContrastiveLearning,
+ BridgeTowerForImageAndTextRetrieval,
+ BridgeTowerForMaskedLM,
+ BridgeTowerModel,
+ BridgeTowerPreTrainedModel,
+ )
+ from .models.bros import (
+ BrosForTokenClassification,
+ BrosModel,
+ BrosPreTrainedModel,
+ BrosProcessor,
+ BrosSpadeEEForTokenClassification,
+ BrosSpadeELForTokenClassification,
+ )
+ from .models.camembert import (
+ CamembertForCausalLM,
+ CamembertForMaskedLM,
+ CamembertForMultipleChoice,
+ CamembertForQuestionAnswering,
+ CamembertForSequenceClassification,
+ CamembertForTokenClassification,
+ CamembertModel,
+ CamembertPreTrainedModel,
+ )
+ from .models.canine import (
+ CanineForMultipleChoice,
+ CanineForQuestionAnswering,
+ CanineForSequenceClassification,
+ CanineForTokenClassification,
+ CanineModel,
+ CaninePreTrainedModel,
+ load_tf_weights_in_canine,
+ )
+ from .models.chameleon import (
+ ChameleonForConditionalGeneration,
+ ChameleonModel,
+ ChameleonPreTrainedModel,
+ ChameleonProcessor,
+ ChameleonVQVAE,
+ )
+ from .models.chinese_clip import (
+ ChineseCLIPModel,
+ ChineseCLIPPreTrainedModel,
+ ChineseCLIPTextModel,
+ ChineseCLIPVisionModel,
+ )
+ from .models.clap import (
+ ClapAudioModel,
+ ClapAudioModelWithProjection,
+ ClapFeatureExtractor,
+ ClapModel,
+ ClapPreTrainedModel,
+ ClapTextModel,
+ ClapTextModelWithProjection,
+ )
+ from .models.clip import (
+ CLIPForImageClassification,
+ CLIPModel,
+ CLIPPreTrainedModel,
+ CLIPTextModel,
+ CLIPTextModelWithProjection,
+ CLIPVisionModel,
+ CLIPVisionModelWithProjection,
+ )
+ from .models.clipseg import (
+ CLIPSegForImageSegmentation,
+ CLIPSegModel,
+ CLIPSegPreTrainedModel,
+ CLIPSegTextModel,
+ CLIPSegVisionModel,
+ )
+ from .models.clvp import (
+ ClvpDecoder,
+ ClvpEncoder,
+ ClvpForCausalLM,
+ ClvpModel,
+ ClvpModelForConditionalGeneration,
+ ClvpPreTrainedModel,
+ )
+ from .models.codegen import (
+ CodeGenForCausalLM,
+ CodeGenModel,
+ CodeGenPreTrainedModel,
+ )
+ from .models.cohere import (
+ CohereForCausalLM,
+ CohereModel,
+ CoherePreTrainedModel,
+ )
+ from .models.cohere2 import (
+ Cohere2ForCausalLM,
+ Cohere2Model,
+ Cohere2PreTrainedModel,
+ )
+ from .models.colpali import (
+ ColPaliForRetrieval,
+ ColPaliPreTrainedModel,
+ )
+ from .models.conditional_detr import (
+ ConditionalDetrForObjectDetection,
+ ConditionalDetrForSegmentation,
+ ConditionalDetrModel,
+ ConditionalDetrPreTrainedModel,
+ )
+ from .models.convbert import (
+ ConvBertForMaskedLM,
+ ConvBertForMultipleChoice,
+ ConvBertForQuestionAnswering,
+ ConvBertForSequenceClassification,
+ ConvBertForTokenClassification,
+ ConvBertModel,
+ ConvBertPreTrainedModel,
+ load_tf_weights_in_convbert,
+ )
+ from .models.convnext import (
+ ConvNextBackbone,
+ ConvNextForImageClassification,
+ ConvNextModel,
+ ConvNextPreTrainedModel,
+ )
+ from .models.convnextv2 import (
+ ConvNextV2Backbone,
+ ConvNextV2ForImageClassification,
+ ConvNextV2Model,
+ ConvNextV2PreTrainedModel,
+ )
+ from .models.cpmant import (
+ CpmAntForCausalLM,
+ CpmAntModel,
+ CpmAntPreTrainedModel,
+ )
+ from .models.ctrl import (
+ CTRLForSequenceClassification,
+ CTRLLMHeadModel,
+ CTRLModel,
+ CTRLPreTrainedModel,
+ )
+ from .models.cvt import (
+ CvtForImageClassification,
+ CvtModel,
+ CvtPreTrainedModel,
+ )
+ from .models.dac import (
+ DacModel,
+ DacPreTrainedModel,
+ )
+ from .models.data2vec import (
+ Data2VecAudioForAudioFrameClassification,
+ Data2VecAudioForCTC,
+ Data2VecAudioForSequenceClassification,
+ Data2VecAudioForXVector,
+ Data2VecAudioModel,
+ Data2VecAudioPreTrainedModel,
+ Data2VecTextForCausalLM,
+ Data2VecTextForMaskedLM,
+ Data2VecTextForMultipleChoice,
+ Data2VecTextForQuestionAnswering,
+ Data2VecTextForSequenceClassification,
+ Data2VecTextForTokenClassification,
+ Data2VecTextModel,
+ Data2VecTextPreTrainedModel,
+ Data2VecVisionForImageClassification,
+ Data2VecVisionForSemanticSegmentation,
+ Data2VecVisionModel,
+ Data2VecVisionPreTrainedModel,
+ )
+
+ # PyTorch model imports
+ from .models.dbrx import (
+ DbrxForCausalLM,
+ DbrxModel,
+ DbrxPreTrainedModel,
+ )
+ from .models.deberta import (
+ DebertaForMaskedLM,
+ DebertaForQuestionAnswering,
+ DebertaForSequenceClassification,
+ DebertaForTokenClassification,
+ DebertaModel,
+ DebertaPreTrainedModel,
+ )
+ from .models.deberta_v2 import (
+ DebertaV2ForMaskedLM,
+ DebertaV2ForMultipleChoice,
+ DebertaV2ForQuestionAnswering,
+ DebertaV2ForSequenceClassification,
+ DebertaV2ForTokenClassification,
+ DebertaV2Model,
+ DebertaV2PreTrainedModel,
+ )
+ from .models.decision_transformer import (
+ DecisionTransformerGPT2Model,
+ DecisionTransformerGPT2PreTrainedModel,
+ DecisionTransformerModel,
+ DecisionTransformerPreTrainedModel,
+ )
+ from .models.deformable_detr import (
+ DeformableDetrForObjectDetection,
+ DeformableDetrModel,
+ DeformableDetrPreTrainedModel,
+ )
+ from .models.deit import (
+ DeiTForImageClassification,
+ DeiTForImageClassificationWithTeacher,
+ DeiTForMaskedImageModeling,
+ DeiTModel,
+ DeiTPreTrainedModel,
+ )
+ from .models.deprecated.deta import (
+ DetaForObjectDetection,
+ DetaModel,
+ DetaPreTrainedModel,
+ )
+ from .models.deprecated.efficientformer import (
+ EfficientFormerForImageClassification,
+ EfficientFormerForImageClassificationWithTeacher,
+ EfficientFormerModel,
+ EfficientFormerPreTrainedModel,
+ )
+ from .models.deprecated.ernie_m import (
+ ErnieMForInformationExtraction,
+ ErnieMForMultipleChoice,
+ ErnieMForQuestionAnswering,
+ ErnieMForSequenceClassification,
+ ErnieMForTokenClassification,
+ ErnieMModel,
+ ErnieMPreTrainedModel,
+ )
+ from .models.deprecated.gptsan_japanese import (
+ GPTSanJapaneseForConditionalGeneration,
+ GPTSanJapaneseModel,
+ GPTSanJapanesePreTrainedModel,
+ )
+ from .models.deprecated.graphormer import (
+ GraphormerForGraphClassification,
+ GraphormerModel,
+ GraphormerPreTrainedModel,
+ )
+ from .models.deprecated.jukebox import (
+ JukeboxModel,
+ JukeboxPreTrainedModel,
+ JukeboxPrior,
+ JukeboxVQVAE,
+ )
+ from .models.deprecated.mctct import (
+ MCTCTForCTC,
+ MCTCTModel,
+ MCTCTPreTrainedModel,
+ )
+ from .models.deprecated.mega import (
+ MegaForCausalLM,
+ MegaForMaskedLM,
+ MegaForMultipleChoice,
+ MegaForQuestionAnswering,
+ MegaForSequenceClassification,
+ MegaForTokenClassification,
+ MegaModel,
+ MegaPreTrainedModel,
+ )
+ from .models.deprecated.mmbt import (
+ MMBTForClassification,
+ MMBTModel,
+ ModalEmbeddings,
+ )
+ from .models.deprecated.nat import (
+ NatBackbone,
+ NatForImageClassification,
+ NatModel,
+ NatPreTrainedModel,
+ )
+ from .models.deprecated.nezha import (
+ NezhaForMaskedLM,
+ NezhaForMultipleChoice,
+ NezhaForNextSentencePrediction,
+ NezhaForPreTraining,
+ NezhaForQuestionAnswering,
+ NezhaForSequenceClassification,
+ NezhaForTokenClassification,
+ NezhaModel,
+ NezhaPreTrainedModel,
+ )
+ from .models.deprecated.open_llama import (
+ OpenLlamaForCausalLM,
+ OpenLlamaForSequenceClassification,
+ OpenLlamaModel,
+ OpenLlamaPreTrainedModel,
+ )
+ from .models.deprecated.qdqbert import (
+ QDQBertForMaskedLM,
+ QDQBertForMultipleChoice,
+ QDQBertForNextSentencePrediction,
+ QDQBertForQuestionAnswering,
+ QDQBertForSequenceClassification,
+ QDQBertForTokenClassification,
+ QDQBertLMHeadModel,
+ QDQBertModel,
+ QDQBertPreTrainedModel,
+ load_tf_weights_in_qdqbert,
+ )
+ from .models.deprecated.realm import (
+ RealmEmbedder,
+ RealmForOpenQA,
+ RealmKnowledgeAugEncoder,
+ RealmPreTrainedModel,
+ RealmReader,
+ RealmRetriever,
+ RealmScorer,
+ load_tf_weights_in_realm,
+ )
+ from .models.deprecated.retribert import (
+ RetriBertModel,
+ RetriBertPreTrainedModel,
+ )
+ from .models.deprecated.speech_to_text_2 import (
+ Speech2Text2ForCausalLM,
+ Speech2Text2PreTrainedModel,
+ )
+ from .models.deprecated.trajectory_transformer import (
+ TrajectoryTransformerModel,
+ TrajectoryTransformerPreTrainedModel,
+ )
+ from .models.deprecated.transfo_xl import (
+ AdaptiveEmbedding,
+ TransfoXLForSequenceClassification,
+ TransfoXLLMHeadModel,
+ TransfoXLModel,
+ TransfoXLPreTrainedModel,
+ load_tf_weights_in_transfo_xl,
+ )
+ from .models.deprecated.tvlt import (
+ TvltForAudioVisualClassification,
+ TvltForPreTraining,
+ TvltModel,
+ TvltPreTrainedModel,
+ )
+ from .models.deprecated.van import (
+ VanForImageClassification,
+ VanModel,
+ VanPreTrainedModel,
+ )
+ from .models.deprecated.vit_hybrid import (
+ ViTHybridForImageClassification,
+ ViTHybridModel,
+ ViTHybridPreTrainedModel,
+ )
+ from .models.deprecated.xlm_prophetnet import (
+ XLMProphetNetDecoder,
+ XLMProphetNetEncoder,
+ XLMProphetNetForCausalLM,
+ XLMProphetNetForConditionalGeneration,
+ XLMProphetNetModel,
+ XLMProphetNetPreTrainedModel,
+ )
+ from .models.depth_anything import (
+ DepthAnythingForDepthEstimation,
+ DepthAnythingPreTrainedModel,
+ )
+ from .models.detr import (
+ DetrForObjectDetection,
+ DetrForSegmentation,
+ DetrModel,
+ DetrPreTrainedModel,
+ )
+ from .models.dinat import (
+ DinatBackbone,
+ DinatForImageClassification,
+ DinatModel,
+ DinatPreTrainedModel,
+ )
+ from .models.dinov2 import (
+ Dinov2Backbone,
+ Dinov2ForImageClassification,
+ Dinov2Model,
+ Dinov2PreTrainedModel,
+ )
+ from .models.distilbert import (
+ DistilBertForMaskedLM,
+ DistilBertForMultipleChoice,
+ DistilBertForQuestionAnswering,
+ DistilBertForSequenceClassification,
+ DistilBertForTokenClassification,
+ DistilBertModel,
+ DistilBertPreTrainedModel,
+ )
+ from .models.donut import (
+ DonutSwinModel,
+ DonutSwinPreTrainedModel,
+ )
+ from .models.dpr import (
+ DPRContextEncoder,
+ DPRPretrainedContextEncoder,
+ DPRPreTrainedModel,
+ DPRPretrainedQuestionEncoder,
+ DPRPretrainedReader,
+ DPRQuestionEncoder,
+ DPRReader,
+ )
+ from .models.dpt import (
+ DPTForDepthEstimation,
+ DPTForSemanticSegmentation,
+ DPTModel,
+ DPTPreTrainedModel,
+ )
+ from .models.efficientnet import (
+ EfficientNetForImageClassification,
+ EfficientNetModel,
+ EfficientNetPreTrainedModel,
+ )
+ from .models.electra import (
+ ElectraForCausalLM,
+ ElectraForMaskedLM,
+ ElectraForMultipleChoice,
+ ElectraForPreTraining,
+ ElectraForQuestionAnswering,
+ ElectraForSequenceClassification,
+ ElectraForTokenClassification,
+ ElectraModel,
+ ElectraPreTrainedModel,
+ load_tf_weights_in_electra,
+ )
+ from .models.encodec import (
+ EncodecModel,
+ EncodecPreTrainedModel,
+ )
+ from .models.encoder_decoder import EncoderDecoderModel
+ from .models.ernie import (
+ ErnieForCausalLM,
+ ErnieForMaskedLM,
+ ErnieForMultipleChoice,
+ ErnieForNextSentencePrediction,
+ ErnieForPreTraining,
+ ErnieForQuestionAnswering,
+ ErnieForSequenceClassification,
+ ErnieForTokenClassification,
+ ErnieModel,
+ ErniePreTrainedModel,
+ )
+ from .models.esm import (
+ EsmFoldPreTrainedModel,
+ EsmForMaskedLM,
+ EsmForProteinFolding,
+ EsmForSequenceClassification,
+ EsmForTokenClassification,
+ EsmModel,
+ EsmPreTrainedModel,
+ )
+ from .models.falcon import (
+ FalconForCausalLM,
+ FalconForQuestionAnswering,
+ FalconForSequenceClassification,
+ FalconForTokenClassification,
+ FalconModel,
+ FalconPreTrainedModel,
+ )
+ from .models.falcon_mamba import (
+ FalconMambaForCausalLM,
+ FalconMambaModel,
+ FalconMambaPreTrainedModel,
+ )
+ from .models.fastspeech2_conformer import (
+ FastSpeech2ConformerHifiGan,
+ FastSpeech2ConformerModel,
+ FastSpeech2ConformerPreTrainedModel,
+ FastSpeech2ConformerWithHifiGan,
+ )
+ from .models.flaubert import (
+ FlaubertForMultipleChoice,
+ FlaubertForQuestionAnswering,
+ FlaubertForQuestionAnsweringSimple,
+ FlaubertForSequenceClassification,
+ FlaubertForTokenClassification,
+ FlaubertModel,
+ FlaubertPreTrainedModel,
+ FlaubertWithLMHeadModel,
+ )
+ from .models.flava import (
+ FlavaForPreTraining,
+ FlavaImageCodebook,
+ FlavaImageModel,
+ FlavaModel,
+ FlavaMultimodalModel,
+ FlavaPreTrainedModel,
+ FlavaTextModel,
+ )
+ from .models.fnet import (
+ FNetForMaskedLM,
+ FNetForMultipleChoice,
+ FNetForNextSentencePrediction,
+ FNetForPreTraining,
+ FNetForQuestionAnswering,
+ FNetForSequenceClassification,
+ FNetForTokenClassification,
+ FNetModel,
+ FNetPreTrainedModel,
+ )
+ from .models.focalnet import (
+ FocalNetBackbone,
+ FocalNetForImageClassification,
+ FocalNetForMaskedImageModeling,
+ FocalNetModel,
+ FocalNetPreTrainedModel,
+ )
+ from .models.fsmt import (
+ FSMTForConditionalGeneration,
+ FSMTModel,
+ PretrainedFSMTModel,
+ )
+ from .models.funnel import (
+ FunnelBaseModel,
+ FunnelForMaskedLM,
+ FunnelForMultipleChoice,
+ FunnelForPreTraining,
+ FunnelForQuestionAnswering,
+ FunnelForSequenceClassification,
+ FunnelForTokenClassification,
+ FunnelModel,
+ FunnelPreTrainedModel,
+ load_tf_weights_in_funnel,
+ )
+ from .models.fuyu import (
+ FuyuForCausalLM,
+ FuyuPreTrainedModel,
+ )
+ from .models.gemma import (
+ GemmaForCausalLM,
+ GemmaForSequenceClassification,
+ GemmaForTokenClassification,
+ GemmaModel,
+ GemmaPreTrainedModel,
+ )
+ from .models.gemma2 import (
+ Gemma2ForCausalLM,
+ Gemma2ForSequenceClassification,
+ Gemma2ForTokenClassification,
+ Gemma2Model,
+ Gemma2PreTrainedModel,
+ )
+ from .models.git import (
+ GitForCausalLM,
+ GitModel,
+ GitPreTrainedModel,
+ GitVisionModel,
+ )
+ from .models.glm import (
+ GlmForCausalLM,
+ GlmForSequenceClassification,
+ GlmForTokenClassification,
+ GlmModel,
+ GlmPreTrainedModel,
+ )
+ from .models.glpn import (
+ GLPNForDepthEstimation,
+ GLPNModel,
+ GLPNPreTrainedModel,
+ )
+ from .models.gpt2 import (
+ GPT2DoubleHeadsModel,
+ GPT2ForQuestionAnswering,
+ GPT2ForSequenceClassification,
+ GPT2ForTokenClassification,
+ GPT2LMHeadModel,
+ GPT2Model,
+ GPT2PreTrainedModel,
+ load_tf_weights_in_gpt2,
+ )
+ from .models.gpt_bigcode import (
+ GPTBigCodeForCausalLM,
+ GPTBigCodeForSequenceClassification,
+ GPTBigCodeForTokenClassification,
+ GPTBigCodeModel,
+ GPTBigCodePreTrainedModel,
+ )
+ from .models.gpt_neo import (
+ GPTNeoForCausalLM,
+ GPTNeoForQuestionAnswering,
+ GPTNeoForSequenceClassification,
+ GPTNeoForTokenClassification,
+ GPTNeoModel,
+ GPTNeoPreTrainedModel,
+ load_tf_weights_in_gpt_neo,
+ )
+ from .models.gpt_neox import (
+ GPTNeoXForCausalLM,
+ GPTNeoXForQuestionAnswering,
+ GPTNeoXForSequenceClassification,
+ GPTNeoXForTokenClassification,
+ GPTNeoXModel,
+ GPTNeoXPreTrainedModel,
+ )
+ from .models.gpt_neox_japanese import (
+ GPTNeoXJapaneseForCausalLM,
+ GPTNeoXJapaneseModel,
+ GPTNeoXJapanesePreTrainedModel,
+ )
+ from .models.gptj import (
+ GPTJForCausalLM,
+ GPTJForQuestionAnswering,
+ GPTJForSequenceClassification,
+ GPTJModel,
+ GPTJPreTrainedModel,
+ )
+ from .models.granite import (
+ GraniteForCausalLM,
+ GraniteModel,
+ GranitePreTrainedModel,
+ )
+ from .models.granitemoe import (
+ GraniteMoeForCausalLM,
+ GraniteMoeModel,
+ GraniteMoePreTrainedModel,
+ )
+ from .models.grounding_dino import (
+ GroundingDinoForObjectDetection,
+ GroundingDinoModel,
+ GroundingDinoPreTrainedModel,
+ )
+ from .models.groupvit import (
+ GroupViTModel,
+ GroupViTPreTrainedModel,
+ GroupViTTextModel,
+ GroupViTVisionModel,
+ )
+ from .models.hiera import (
+ HieraBackbone,
+ HieraForImageClassification,
+ HieraForPreTraining,
+ HieraModel,
+ HieraPreTrainedModel,
+ )
+ from .models.hubert import (
+ HubertForCTC,
+ HubertForSequenceClassification,
+ HubertModel,
+ HubertPreTrainedModel,
+ )
+ from .models.ibert import (
+ IBertForMaskedLM,
+ IBertForMultipleChoice,
+ IBertForQuestionAnswering,
+ IBertForSequenceClassification,
+ IBertForTokenClassification,
+ IBertModel,
+ IBertPreTrainedModel,
+ )
+ from .models.idefics import (
+ IdeficsForVisionText2Text,
+ IdeficsModel,
+ IdeficsPreTrainedModel,
+ IdeficsProcessor,
+ )
+ from .models.idefics2 import (
+ Idefics2ForConditionalGeneration,
+ Idefics2Model,
+ Idefics2PreTrainedModel,
+ Idefics2Processor,
+ )
+ from .models.idefics3 import (
+ Idefics3ForConditionalGeneration,
+ Idefics3Model,
+ Idefics3PreTrainedModel,
+ Idefics3Processor,
+ Idefics3VisionConfig,
+ Idefics3VisionTransformer,
+ )
+ from .models.ijepa import (
+ IJepaForImageClassification,
+ IJepaModel,
+ IJepaPreTrainedModel,
+ )
+ from .models.imagegpt import (
+ ImageGPTForCausalImageModeling,
+ ImageGPTForImageClassification,
+ ImageGPTModel,
+ ImageGPTPreTrainedModel,
+ load_tf_weights_in_imagegpt,
+ )
+ from .models.informer import (
+ InformerForPrediction,
+ InformerModel,
+ InformerPreTrainedModel,
+ )
+ from .models.instructblip import (
+ InstructBlipForConditionalGeneration,
+ InstructBlipPreTrainedModel,
+ InstructBlipQFormerModel,
+ InstructBlipVisionModel,
+ )
+ from .models.instructblipvideo import (
+ InstructBlipVideoForConditionalGeneration,
+ InstructBlipVideoPreTrainedModel,
+ InstructBlipVideoQFormerModel,
+ InstructBlipVideoVisionModel,
+ )
+ from .models.jamba import (
+ JambaForCausalLM,
+ JambaForSequenceClassification,
+ JambaModel,
+ JambaPreTrainedModel,
+ )
+ from .models.jetmoe import (
+ JetMoeForCausalLM,
+ JetMoeForSequenceClassification,
+ JetMoeModel,
+ JetMoePreTrainedModel,
+ )
+ from .models.kosmos2 import (
+ Kosmos2ForConditionalGeneration,
+ Kosmos2Model,
+ Kosmos2PreTrainedModel,
+ )
+ from .models.layoutlm import (
+ LayoutLMForMaskedLM,
+ LayoutLMForQuestionAnswering,
+ LayoutLMForSequenceClassification,
+ LayoutLMForTokenClassification,
+ LayoutLMModel,
+ LayoutLMPreTrainedModel,
+ )
+ from .models.layoutlmv2 import (
+ LayoutLMv2ForQuestionAnswering,
+ LayoutLMv2ForSequenceClassification,
+ LayoutLMv2ForTokenClassification,
+ LayoutLMv2Model,
+ LayoutLMv2PreTrainedModel,
+ )
+ from .models.layoutlmv3 import (
+ LayoutLMv3ForQuestionAnswering,
+ LayoutLMv3ForSequenceClassification,
+ LayoutLMv3ForTokenClassification,
+ LayoutLMv3Model,
+ LayoutLMv3PreTrainedModel,
+ )
+ from .models.led import (
+ LEDForConditionalGeneration,
+ LEDForQuestionAnswering,
+ LEDForSequenceClassification,
+ LEDModel,
+ LEDPreTrainedModel,
+ )
+ from .models.levit import (
+ LevitForImageClassification,
+ LevitForImageClassificationWithTeacher,
+ LevitModel,
+ LevitPreTrainedModel,
+ )
+ from .models.lilt import (
+ LiltForQuestionAnswering,
+ LiltForSequenceClassification,
+ LiltForTokenClassification,
+ LiltModel,
+ LiltPreTrainedModel,
+ )
+ from .models.llama import (
+ LlamaForCausalLM,
+ LlamaForQuestionAnswering,
+ LlamaForSequenceClassification,
+ LlamaForTokenClassification,
+ LlamaModel,
+ LlamaPreTrainedModel,
+ )
+ from .models.llava import (
+ LlavaForConditionalGeneration,
+ LlavaPreTrainedModel,
+ )
+ from .models.llava_next import (
+ LlavaNextForConditionalGeneration,
+ LlavaNextPreTrainedModel,
+ )
+ from .models.llava_next_video import (
+ LlavaNextVideoForConditionalGeneration,
+ LlavaNextVideoPreTrainedModel,
+ )
+ from .models.llava_onevision import (
+ LlavaOnevisionForConditionalGeneration,
+ LlavaOnevisionPreTrainedModel,
+ )
+ from .models.longformer import (
+ LongformerForMaskedLM,
+ LongformerForMultipleChoice,
+ LongformerForQuestionAnswering,
+ LongformerForSequenceClassification,
+ LongformerForTokenClassification,
+ LongformerModel,
+ LongformerPreTrainedModel,
+ )
+ from .models.longt5 import (
+ LongT5EncoderModel,
+ LongT5ForConditionalGeneration,
+ LongT5Model,
+ LongT5PreTrainedModel,
+ )
+ from .models.luke import (
+ LukeForEntityClassification,
+ LukeForEntityPairClassification,
+ LukeForEntitySpanClassification,
+ LukeForMaskedLM,
+ LukeForMultipleChoice,
+ LukeForQuestionAnswering,
+ LukeForSequenceClassification,
+ LukeForTokenClassification,
+ LukeModel,
+ LukePreTrainedModel,
+ )
+ from .models.lxmert import (
+ LxmertEncoder,
+ LxmertForPreTraining,
+ LxmertForQuestionAnswering,
+ LxmertModel,
+ LxmertPreTrainedModel,
+ LxmertVisualFeatureEncoder,
+ )
+ from .models.m2m_100 import (
+ M2M100ForConditionalGeneration,
+ M2M100Model,
+ M2M100PreTrainedModel,
+ )
+ from .models.mamba import (
+ MambaForCausalLM,
+ MambaModel,
+ MambaPreTrainedModel,
+ )
+ from .models.mamba2 import (
+ Mamba2ForCausalLM,
+ Mamba2Model,
+ Mamba2PreTrainedModel,
+ )
+ from .models.marian import MarianForCausalLM, MarianModel, MarianMTModel, MarianPreTrainedModel
+ from .models.markuplm import (
+ MarkupLMForQuestionAnswering,
+ MarkupLMForSequenceClassification,
+ MarkupLMForTokenClassification,
+ MarkupLMModel,
+ MarkupLMPreTrainedModel,
+ )
+ from .models.mask2former import (
+ Mask2FormerForUniversalSegmentation,
+ Mask2FormerModel,
+ Mask2FormerPreTrainedModel,
+ )
+ from .models.maskformer import (
+ MaskFormerForInstanceSegmentation,
+ MaskFormerModel,
+ MaskFormerPreTrainedModel,
+ MaskFormerSwinBackbone,
+ )
+ from .models.mbart import (
+ MBartForCausalLM,
+ MBartForConditionalGeneration,
+ MBartForQuestionAnswering,
+ MBartForSequenceClassification,
+ MBartModel,
+ MBartPreTrainedModel,
+ )
+ from .models.megatron_bert import (
+ MegatronBertForCausalLM,
+ MegatronBertForMaskedLM,
+ MegatronBertForMultipleChoice,
+ MegatronBertForNextSentencePrediction,
+ MegatronBertForPreTraining,
+ MegatronBertForQuestionAnswering,
+ MegatronBertForSequenceClassification,
+ MegatronBertForTokenClassification,
+ MegatronBertModel,
+ MegatronBertPreTrainedModel,
+ )
+ from .models.mgp_str import (
+ MgpstrForSceneTextRecognition,
+ MgpstrModel,
+ MgpstrPreTrainedModel,
+ )
+ from .models.mimi import (
+ MimiModel,
+ MimiPreTrainedModel,
+ )
+ from .models.mistral import (
+ MistralForCausalLM,
+ MistralForQuestionAnswering,
+ MistralForSequenceClassification,
+ MistralForTokenClassification,
+ MistralModel,
+ MistralPreTrainedModel,
+ )
+ from .models.mixtral import (
+ MixtralForCausalLM,
+ MixtralForQuestionAnswering,
+ MixtralForSequenceClassification,
+ MixtralForTokenClassification,
+ MixtralModel,
+ MixtralPreTrainedModel,
+ )
+ from .models.mllama import (
+ MllamaForCausalLM,
+ MllamaForConditionalGeneration,
+ MllamaPreTrainedModel,
+ MllamaProcessor,
+ MllamaTextModel,
+ MllamaVisionModel,
+ )
+ from .models.mobilebert import (
+ MobileBertForMaskedLM,
+ MobileBertForMultipleChoice,
+ MobileBertForNextSentencePrediction,
+ MobileBertForPreTraining,
+ MobileBertForQuestionAnswering,
+ MobileBertForSequenceClassification,
+ MobileBertForTokenClassification,
+ MobileBertModel,
+ MobileBertPreTrainedModel,
+ load_tf_weights_in_mobilebert,
+ )
+ from .models.mobilenet_v1 import (
+ MobileNetV1ForImageClassification,
+ MobileNetV1Model,
+ MobileNetV1PreTrainedModel,
+ load_tf_weights_in_mobilenet_v1,
+ )
+ from .models.mobilenet_v2 import (
+ MobileNetV2ForImageClassification,
+ MobileNetV2ForSemanticSegmentation,
+ MobileNetV2Model,
+ MobileNetV2PreTrainedModel,
+ load_tf_weights_in_mobilenet_v2,
+ )
+ from .models.mobilevit import (
+ MobileViTForImageClassification,
+ MobileViTForSemanticSegmentation,
+ MobileViTModel,
+ MobileViTPreTrainedModel,
+ )
+ from .models.mobilevitv2 import (
+ MobileViTV2ForImageClassification,
+ MobileViTV2ForSemanticSegmentation,
+ MobileViTV2Model,
+ MobileViTV2PreTrainedModel,
+ )
+ from .models.modernbert import (
+ ModernBertForMaskedLM,
+ ModernBertForSequenceClassification,
+ ModernBertForTokenClassification,
+ ModernBertModel,
+ ModernBertPreTrainedModel,
+ )
+ from .models.moshi import (
+ MoshiForCausalLM,
+ MoshiForConditionalGeneration,
+ MoshiModel,
+ MoshiPreTrainedModel,
+ )
+ from .models.mpnet import (
+ MPNetForMaskedLM,
+ MPNetForMultipleChoice,
+ MPNetForQuestionAnswering,
+ MPNetForSequenceClassification,
+ MPNetForTokenClassification,
+ MPNetModel,
+ MPNetPreTrainedModel,
+ )
+ from .models.mpt import (
+ MptForCausalLM,
+ MptForQuestionAnswering,
+ MptForSequenceClassification,
+ MptForTokenClassification,
+ MptModel,
+ MptPreTrainedModel,
+ )
+ from .models.mra import (
+ MraForMaskedLM,
+ MraForMultipleChoice,
+ MraForQuestionAnswering,
+ MraForSequenceClassification,
+ MraForTokenClassification,
+ MraModel,
+ MraPreTrainedModel,
+ )
+ from .models.mt5 import (
+ MT5EncoderModel,
+ MT5ForConditionalGeneration,
+ MT5ForQuestionAnswering,
+ MT5ForSequenceClassification,
+ MT5ForTokenClassification,
+ MT5Model,
+ MT5PreTrainedModel,
+ )
+ from .models.musicgen import (
+ MusicgenForCausalLM,
+ MusicgenForConditionalGeneration,
+ MusicgenModel,
+ MusicgenPreTrainedModel,
+ MusicgenProcessor,
+ )
+ from .models.musicgen_melody import (
+ MusicgenMelodyForCausalLM,
+ MusicgenMelodyForConditionalGeneration,
+ MusicgenMelodyModel,
+ MusicgenMelodyPreTrainedModel,
+ )
+ from .models.mvp import (
+ MvpForCausalLM,
+ MvpForConditionalGeneration,
+ MvpForQuestionAnswering,
+ MvpForSequenceClassification,
+ MvpModel,
+ MvpPreTrainedModel,
+ )
+ from .models.nemotron import (
+ NemotronForCausalLM,
+ NemotronForQuestionAnswering,
+ NemotronForSequenceClassification,
+ NemotronForTokenClassification,
+ NemotronModel,
+ NemotronPreTrainedModel,
+ )
+ from .models.nllb_moe import (
+ NllbMoeForConditionalGeneration,
+ NllbMoeModel,
+ NllbMoePreTrainedModel,
+ NllbMoeSparseMLP,
+ NllbMoeTop2Router,
+ )
+ from .models.nystromformer import (
+ NystromformerForMaskedLM,
+ NystromformerForMultipleChoice,
+ NystromformerForQuestionAnswering,
+ NystromformerForSequenceClassification,
+ NystromformerForTokenClassification,
+ NystromformerModel,
+ NystromformerPreTrainedModel,
+ )
+ from .models.olmo import (
+ OlmoForCausalLM,
+ OlmoModel,
+ OlmoPreTrainedModel,
+ )
+ from .models.olmo2 import (
+ Olmo2ForCausalLM,
+ Olmo2Model,
+ Olmo2PreTrainedModel,
+ )
+ from .models.olmoe import (
+ OlmoeForCausalLM,
+ OlmoeModel,
+ OlmoePreTrainedModel,
+ )
+ from .models.omdet_turbo import (
+ OmDetTurboForObjectDetection,
+ OmDetTurboPreTrainedModel,
+ )
+ from .models.oneformer import (
+ OneFormerForUniversalSegmentation,
+ OneFormerModel,
+ OneFormerPreTrainedModel,
+ )
+ from .models.openai import (
+ OpenAIGPTDoubleHeadsModel,
+ OpenAIGPTForSequenceClassification,
+ OpenAIGPTLMHeadModel,
+ OpenAIGPTModel,
+ OpenAIGPTPreTrainedModel,
+ load_tf_weights_in_openai_gpt,
+ )
+ from .models.opt import (
+ OPTForCausalLM,
+ OPTForQuestionAnswering,
+ OPTForSequenceClassification,
+ OPTModel,
+ OPTPreTrainedModel,
+ )
+ from .models.owlv2 import (
+ Owlv2ForObjectDetection,
+ Owlv2Model,
+ Owlv2PreTrainedModel,
+ Owlv2TextModel,
+ Owlv2VisionModel,
+ )
+ from .models.owlvit import (
+ OwlViTForObjectDetection,
+ OwlViTModel,
+ OwlViTPreTrainedModel,
+ OwlViTTextModel,
+ OwlViTVisionModel,
+ )
+ from .models.paligemma import (
+ PaliGemmaForConditionalGeneration,
+ PaliGemmaPreTrainedModel,
+ PaliGemmaProcessor,
+ )
+ from .models.patchtsmixer import (
+ PatchTSMixerForPrediction,
+ PatchTSMixerForPretraining,
+ PatchTSMixerForRegression,
+ PatchTSMixerForTimeSeriesClassification,
+ PatchTSMixerModel,
+ PatchTSMixerPreTrainedModel,
+ )
+ from .models.patchtst import (
+ PatchTSTForClassification,
+ PatchTSTForPrediction,
+ PatchTSTForPretraining,
+ PatchTSTForRegression,
+ PatchTSTModel,
+ PatchTSTPreTrainedModel,
+ )
+ from .models.pegasus import (
+ PegasusForCausalLM,
+ PegasusForConditionalGeneration,
+ PegasusModel,
+ PegasusPreTrainedModel,
+ )
+ from .models.pegasus_x import (
+ PegasusXForConditionalGeneration,
+ PegasusXModel,
+ PegasusXPreTrainedModel,
+ )
+ from .models.perceiver import (
+ PerceiverForImageClassificationConvProcessing,
+ PerceiverForImageClassificationFourier,
+ PerceiverForImageClassificationLearned,
+ PerceiverForMaskedLM,
+ PerceiverForMultimodalAutoencoding,
+ PerceiverForOpticalFlow,
+ PerceiverForSequenceClassification,
+ PerceiverModel,
+ PerceiverPreTrainedModel,
+ )
+ from .models.persimmon import (
+ PersimmonForCausalLM,
+ PersimmonForSequenceClassification,
+ PersimmonForTokenClassification,
+ PersimmonModel,
+ PersimmonPreTrainedModel,
+ )
+ from .models.phi import (
+ PhiForCausalLM,
+ PhiForSequenceClassification,
+ PhiForTokenClassification,
+ PhiModel,
+ PhiPreTrainedModel,
+ )
+ from .models.phi3 import (
+ Phi3ForCausalLM,
+ Phi3ForSequenceClassification,
+ Phi3ForTokenClassification,
+ Phi3Model,
+ Phi3PreTrainedModel,
+ )
+ from .models.phimoe import (
+ PhimoeForCausalLM,
+ PhimoeForSequenceClassification,
+ PhimoeModel,
+ PhimoePreTrainedModel,
+ )
+ from .models.pix2struct import (
+ Pix2StructForConditionalGeneration,
+ Pix2StructPreTrainedModel,
+ Pix2StructTextModel,
+ Pix2StructVisionModel,
+ )
+ from .models.pixtral import (
+ PixtralPreTrainedModel,
+ PixtralVisionModel,
+ )
+ from .models.plbart import (
+ PLBartForCausalLM,
+ PLBartForConditionalGeneration,
+ PLBartForSequenceClassification,
+ PLBartModel,
+ PLBartPreTrainedModel,
+ )
+ from .models.poolformer import (
+ PoolFormerForImageClassification,
+ PoolFormerModel,
+ PoolFormerPreTrainedModel,
+ )
+ from .models.pop2piano import (
+ Pop2PianoForConditionalGeneration,
+ Pop2PianoPreTrainedModel,
+ )
+ from .models.prophetnet import (
+ ProphetNetDecoder,
+ ProphetNetEncoder,
+ ProphetNetForCausalLM,
+ ProphetNetForConditionalGeneration,
+ ProphetNetModel,
+ ProphetNetPreTrainedModel,
+ )
+ from .models.pvt import (
+ PvtForImageClassification,
+ PvtModel,
+ PvtPreTrainedModel,
+ )
+ from .models.pvt_v2 import (
+ PvtV2Backbone,
+ PvtV2ForImageClassification,
+ PvtV2Model,
+ PvtV2PreTrainedModel,
+ )
+ from .models.qwen2 import (
+ Qwen2ForCausalLM,
+ Qwen2ForQuestionAnswering,
+ Qwen2ForSequenceClassification,
+ Qwen2ForTokenClassification,
+ Qwen2Model,
+ Qwen2PreTrainedModel,
+ )
+ from .models.qwen2_audio import (
+ Qwen2AudioEncoder,
+ Qwen2AudioForConditionalGeneration,
+ Qwen2AudioPreTrainedModel,
+ )
+ from .models.qwen2_moe import (
+ Qwen2MoeForCausalLM,
+ Qwen2MoeForQuestionAnswering,
+ Qwen2MoeForSequenceClassification,
+ Qwen2MoeForTokenClassification,
+ Qwen2MoeModel,
+ Qwen2MoePreTrainedModel,
+ )
+ from .models.qwen2_vl import (
+ Qwen2VLForConditionalGeneration,
+ Qwen2VLModel,
+ Qwen2VLPreTrainedModel,
+ )
+ from .models.rag import (
+ RagModel,
+ RagPreTrainedModel,
+ RagSequenceForGeneration,
+ RagTokenForGeneration,
+ )
+ from .models.recurrent_gemma import (
+ RecurrentGemmaForCausalLM,
+ RecurrentGemmaModel,
+ RecurrentGemmaPreTrainedModel,
+ )
+ from .models.reformer import (
+ ReformerForMaskedLM,
+ ReformerForQuestionAnswering,
+ ReformerForSequenceClassification,
+ ReformerModel,
+ ReformerModelWithLMHead,
+ ReformerPreTrainedModel,
+ )
+ from .models.regnet import (
+ RegNetForImageClassification,
+ RegNetModel,
+ RegNetPreTrainedModel,
+ )
+ from .models.rembert import (
+ RemBertForCausalLM,
+ RemBertForMaskedLM,
+ RemBertForMultipleChoice,
+ RemBertForQuestionAnswering,
+ RemBertForSequenceClassification,
+ RemBertForTokenClassification,
+ RemBertModel,
+ RemBertPreTrainedModel,
+ load_tf_weights_in_rembert,
+ )
+ from .models.resnet import (
+ ResNetBackbone,
+ ResNetForImageClassification,
+ ResNetModel,
+ ResNetPreTrainedModel,
+ )
+ from .models.roberta import (
+ RobertaForCausalLM,
+ RobertaForMaskedLM,
+ RobertaForMultipleChoice,
+ RobertaForQuestionAnswering,
+ RobertaForSequenceClassification,
+ RobertaForTokenClassification,
+ RobertaModel,
+ RobertaPreTrainedModel,
+ )
+ from .models.roberta_prelayernorm import (
+ RobertaPreLayerNormForCausalLM,
+ RobertaPreLayerNormForMaskedLM,
+ RobertaPreLayerNormForMultipleChoice,
+ RobertaPreLayerNormForQuestionAnswering,
+ RobertaPreLayerNormForSequenceClassification,
+ RobertaPreLayerNormForTokenClassification,
+ RobertaPreLayerNormModel,
+ RobertaPreLayerNormPreTrainedModel,
+ )
+ from .models.roc_bert import (
+ RoCBertForCausalLM,
+ RoCBertForMaskedLM,
+ RoCBertForMultipleChoice,
+ RoCBertForPreTraining,
+ RoCBertForQuestionAnswering,
+ RoCBertForSequenceClassification,
+ RoCBertForTokenClassification,
+ RoCBertModel,
+ RoCBertPreTrainedModel,
+ load_tf_weights_in_roc_bert,
+ )
+ from .models.roformer import (
+ RoFormerForCausalLM,
+ RoFormerForMaskedLM,
+ RoFormerForMultipleChoice,
+ RoFormerForQuestionAnswering,
+ RoFormerForSequenceClassification,
+ RoFormerForTokenClassification,
+ RoFormerModel,
+ RoFormerPreTrainedModel,
+ load_tf_weights_in_roformer,
+ )
+ from .models.rt_detr import (
+ RTDetrForObjectDetection,
+ RTDetrModel,
+ RTDetrPreTrainedModel,
+ RTDetrResNetBackbone,
+ RTDetrResNetPreTrainedModel,
+ )
+ from .models.rwkv import (
+ RwkvForCausalLM,
+ RwkvModel,
+ RwkvPreTrainedModel,
+ )
+ from .models.sam import (
+ SamModel,
+ SamPreTrainedModel,
+ )
+ from .models.seamless_m4t import (
+ SeamlessM4TCodeHifiGan,
+ SeamlessM4TForSpeechToSpeech,
+ SeamlessM4TForSpeechToText,
+ SeamlessM4TForTextToSpeech,
+ SeamlessM4TForTextToText,
+ SeamlessM4THifiGan,
+ SeamlessM4TModel,
+ SeamlessM4TPreTrainedModel,
+ SeamlessM4TTextToUnitForConditionalGeneration,
+ SeamlessM4TTextToUnitModel,
+ )
+ from .models.seamless_m4t_v2 import (
+ SeamlessM4Tv2ForSpeechToSpeech,
+ SeamlessM4Tv2ForSpeechToText,
+ SeamlessM4Tv2ForTextToSpeech,
+ SeamlessM4Tv2ForTextToText,
+ SeamlessM4Tv2Model,
+ SeamlessM4Tv2PreTrainedModel,
+ )
+ from .models.segformer import (
+ SegformerDecodeHead,
+ SegformerForImageClassification,
+ SegformerForSemanticSegmentation,
+ SegformerModel,
+ SegformerPreTrainedModel,
+ )
+ from .models.seggpt import (
+ SegGptForImageSegmentation,
+ SegGptModel,
+ SegGptPreTrainedModel,
+ )
+ from .models.sew import (
+ SEWForCTC,
+ SEWForSequenceClassification,
+ SEWModel,
+ SEWPreTrainedModel,
+ )
+ from .models.sew_d import (
+ SEWDForCTC,
+ SEWDForSequenceClassification,
+ SEWDModel,
+ SEWDPreTrainedModel,
+ )
+ from .models.siglip import (
+ SiglipForImageClassification,
+ SiglipModel,
+ SiglipPreTrainedModel,
+ SiglipTextModel,
+ SiglipVisionModel,
+ )
+ from .models.speech_encoder_decoder import SpeechEncoderDecoderModel
+ from .models.speech_to_text import (
+ Speech2TextForConditionalGeneration,
+ Speech2TextModel,
+ Speech2TextPreTrainedModel,
+ )
+ from .models.speecht5 import (
+ SpeechT5ForSpeechToSpeech,
+ SpeechT5ForSpeechToText,
+ SpeechT5ForTextToSpeech,
+ SpeechT5HifiGan,
+ SpeechT5Model,
+ SpeechT5PreTrainedModel,
+ )
+ from .models.splinter import (
+ SplinterForPreTraining,
+ SplinterForQuestionAnswering,
+ SplinterModel,
+ SplinterPreTrainedModel,
+ )
+ from .models.squeezebert import (
+ SqueezeBertForMaskedLM,
+ SqueezeBertForMultipleChoice,
+ SqueezeBertForQuestionAnswering,
+ SqueezeBertForSequenceClassification,
+ SqueezeBertForTokenClassification,
+ SqueezeBertModel,
+ SqueezeBertPreTrainedModel,
+ )
+ from .models.stablelm import (
+ StableLmForCausalLM,
+ StableLmForSequenceClassification,
+ StableLmForTokenClassification,
+ StableLmModel,
+ StableLmPreTrainedModel,
+ )
+ from .models.starcoder2 import (
+ Starcoder2ForCausalLM,
+ Starcoder2ForSequenceClassification,
+ Starcoder2ForTokenClassification,
+ Starcoder2Model,
+ Starcoder2PreTrainedModel,
+ )
+ from .models.superpoint import (
+ SuperPointForKeypointDetection,
+ SuperPointPreTrainedModel,
+ )
+ from .models.swiftformer import (
+ SwiftFormerForImageClassification,
+ SwiftFormerModel,
+ SwiftFormerPreTrainedModel,
+ )
+ from .models.swin import (
+ SwinBackbone,
+ SwinForImageClassification,
+ SwinForMaskedImageModeling,
+ SwinModel,
+ SwinPreTrainedModel,
+ )
+ from .models.swin2sr import (
+ Swin2SRForImageSuperResolution,
+ Swin2SRModel,
+ Swin2SRPreTrainedModel,
+ )
+ from .models.swinv2 import (
+ Swinv2Backbone,
+ Swinv2ForImageClassification,
+ Swinv2ForMaskedImageModeling,
+ Swinv2Model,
+ Swinv2PreTrainedModel,
+ )
+ from .models.switch_transformers import (
+ SwitchTransformersEncoderModel,
+ SwitchTransformersForConditionalGeneration,
+ SwitchTransformersModel,
+ SwitchTransformersPreTrainedModel,
+ SwitchTransformersSparseMLP,
+ SwitchTransformersTop1Router,
+ )
+ from .models.t5 import (
+ T5EncoderModel,
+ T5ForConditionalGeneration,
+ T5ForQuestionAnswering,
+ T5ForSequenceClassification,
+ T5ForTokenClassification,
+ T5Model,
+ T5PreTrainedModel,
+ load_tf_weights_in_t5,
+ )
+ from .models.table_transformer import (
+ TableTransformerForObjectDetection,
+ TableTransformerModel,
+ TableTransformerPreTrainedModel,
+ )
+ from .models.tapas import (
+ TapasForMaskedLM,
+ TapasForQuestionAnswering,
+ TapasForSequenceClassification,
+ TapasModel,
+ TapasPreTrainedModel,
+ load_tf_weights_in_tapas,
+ )
+ from .models.time_series_transformer import (
+ TimeSeriesTransformerForPrediction,
+ TimeSeriesTransformerModel,
+ TimeSeriesTransformerPreTrainedModel,
+ )
+ from .models.timesformer import (
+ TimesformerForVideoClassification,
+ TimesformerModel,
+ TimesformerPreTrainedModel,
+ )
+ from .models.timm_backbone import TimmBackbone
+ from .models.timm_wrapper import (
+ TimmWrapperForImageClassification,
+ TimmWrapperModel,
+ TimmWrapperPreTrainedModel,
+ )
+ from .models.trocr import (
+ TrOCRForCausalLM,
+ TrOCRPreTrainedModel,
+ )
+ from .models.tvp import (
+ TvpForVideoGrounding,
+ TvpModel,
+ TvpPreTrainedModel,
+ )
+ from .models.udop import (
+ UdopEncoderModel,
+ UdopForConditionalGeneration,
+ UdopModel,
+ UdopPreTrainedModel,
+ )
+ from .models.umt5 import (
+ UMT5EncoderModel,
+ UMT5ForConditionalGeneration,
+ UMT5ForQuestionAnswering,
+ UMT5ForSequenceClassification,
+ UMT5ForTokenClassification,
+ UMT5Model,
+ UMT5PreTrainedModel,
+ )
+ from .models.unispeech import (
+ UniSpeechForCTC,
+ UniSpeechForPreTraining,
+ UniSpeechForSequenceClassification,
+ UniSpeechModel,
+ UniSpeechPreTrainedModel,
+ )
+ from .models.unispeech_sat import (
+ UniSpeechSatForAudioFrameClassification,
+ UniSpeechSatForCTC,
+ UniSpeechSatForPreTraining,
+ UniSpeechSatForSequenceClassification,
+ UniSpeechSatForXVector,
+ UniSpeechSatModel,
+ UniSpeechSatPreTrainedModel,
+ )
+ from .models.univnet import UnivNetModel
+ from .models.upernet import (
+ UperNetForSemanticSegmentation,
+ UperNetPreTrainedModel,
+ )
+ from .models.video_llava import (
+ VideoLlavaForConditionalGeneration,
+ VideoLlavaPreTrainedModel,
+ VideoLlavaProcessor,
+ )
+ from .models.videomae import (
+ VideoMAEForPreTraining,
+ VideoMAEForVideoClassification,
+ VideoMAEModel,
+ VideoMAEPreTrainedModel,
+ )
+ from .models.vilt import (
+ ViltForImageAndTextRetrieval,
+ ViltForImagesAndTextClassification,
+ ViltForMaskedLM,
+ ViltForQuestionAnswering,
+ ViltForTokenClassification,
+ ViltModel,
+ ViltPreTrainedModel,
+ )
+ from .models.vipllava import (
+ VipLlavaForConditionalGeneration,
+ VipLlavaPreTrainedModel,
+ )
+ from .models.vision_encoder_decoder import VisionEncoderDecoderModel
+ from .models.vision_text_dual_encoder import VisionTextDualEncoderModel
+ from .models.visual_bert import (
+ VisualBertForMultipleChoice,
+ VisualBertForPreTraining,
+ VisualBertForQuestionAnswering,
+ VisualBertForRegionToPhraseAlignment,
+ VisualBertForVisualReasoning,
+ VisualBertModel,
+ VisualBertPreTrainedModel,
+ )
+ from .models.vit import (
+ ViTForImageClassification,
+ ViTForMaskedImageModeling,
+ ViTModel,
+ ViTPreTrainedModel,
+ )
+ from .models.vit_mae import (
+ ViTMAEForPreTraining,
+ ViTMAEModel,
+ ViTMAEPreTrainedModel,
+ )
+ from .models.vit_msn import (
+ ViTMSNForImageClassification,
+ ViTMSNModel,
+ ViTMSNPreTrainedModel,
+ )
+ from .models.vitdet import (
+ VitDetBackbone,
+ VitDetModel,
+ VitDetPreTrainedModel,
+ )
+ from .models.vitmatte import (
+ VitMatteForImageMatting,
+ VitMattePreTrainedModel,
+ )
+ from .models.vits import (
+ VitsModel,
+ VitsPreTrainedModel,
+ )
+ from .models.vivit import (
+ VivitForVideoClassification,
+ VivitModel,
+ VivitPreTrainedModel,
+ )
+ from .models.wav2vec2 import (
+ Wav2Vec2ForAudioFrameClassification,
+ Wav2Vec2ForCTC,
+ Wav2Vec2ForMaskedLM,
+ Wav2Vec2ForPreTraining,
+ Wav2Vec2ForSequenceClassification,
+ Wav2Vec2ForXVector,
+ Wav2Vec2Model,
+ Wav2Vec2PreTrainedModel,
+ )
+ from .models.wav2vec2_bert import (
+ Wav2Vec2BertForAudioFrameClassification,
+ Wav2Vec2BertForCTC,
+ Wav2Vec2BertForSequenceClassification,
+ Wav2Vec2BertForXVector,
+ Wav2Vec2BertModel,
+ Wav2Vec2BertPreTrainedModel,
+ )
+ from .models.wav2vec2_conformer import (
+ Wav2Vec2ConformerForAudioFrameClassification,
+ Wav2Vec2ConformerForCTC,
+ Wav2Vec2ConformerForPreTraining,
+ Wav2Vec2ConformerForSequenceClassification,
+ Wav2Vec2ConformerForXVector,
+ Wav2Vec2ConformerModel,
+ Wav2Vec2ConformerPreTrainedModel,
+ )
+ from .models.wavlm import (
+ WavLMForAudioFrameClassification,
+ WavLMForCTC,
+ WavLMForSequenceClassification,
+ WavLMForXVector,
+ WavLMModel,
+ WavLMPreTrainedModel,
+ )
+ from .models.whisper import (
+ WhisperForAudioClassification,
+ WhisperForCausalLM,
+ WhisperForConditionalGeneration,
+ WhisperModel,
+ WhisperPreTrainedModel,
+ )
+ from .models.x_clip import (
+ XCLIPModel,
+ XCLIPPreTrainedModel,
+ XCLIPTextModel,
+ XCLIPVisionModel,
+ )
+ from .models.xglm import (
+ XGLMForCausalLM,
+ XGLMModel,
+ XGLMPreTrainedModel,
+ )
+ from .models.xlm import (
+ XLMForMultipleChoice,
+ XLMForQuestionAnswering,
+ XLMForQuestionAnsweringSimple,
+ XLMForSequenceClassification,
+ XLMForTokenClassification,
+ XLMModel,
+ XLMPreTrainedModel,
+ XLMWithLMHeadModel,
+ )
+ from .models.xlm_roberta import (
+ XLMRobertaForCausalLM,
+ XLMRobertaForMaskedLM,
+ XLMRobertaForMultipleChoice,
+ XLMRobertaForQuestionAnswering,
+ XLMRobertaForSequenceClassification,
+ XLMRobertaForTokenClassification,
+ XLMRobertaModel,
+ XLMRobertaPreTrainedModel,
+ )
+ from .models.xlm_roberta_xl import (
+ XLMRobertaXLForCausalLM,
+ XLMRobertaXLForMaskedLM,
+ XLMRobertaXLForMultipleChoice,
+ XLMRobertaXLForQuestionAnswering,
+ XLMRobertaXLForSequenceClassification,
+ XLMRobertaXLForTokenClassification,
+ XLMRobertaXLModel,
+ XLMRobertaXLPreTrainedModel,
+ )
+ from .models.xlnet import (
+ XLNetForMultipleChoice,
+ XLNetForQuestionAnswering,
+ XLNetForQuestionAnsweringSimple,
+ XLNetForSequenceClassification,
+ XLNetForTokenClassification,
+ XLNetLMHeadModel,
+ XLNetModel,
+ XLNetPreTrainedModel,
+ load_tf_weights_in_xlnet,
+ )
+ from .models.xmod import (
+ XmodForCausalLM,
+ XmodForMaskedLM,
+ XmodForMultipleChoice,
+ XmodForQuestionAnswering,
+ XmodForSequenceClassification,
+ XmodForTokenClassification,
+ XmodModel,
+ XmodPreTrainedModel,
+ )
+ from .models.yolos import (
+ YolosForObjectDetection,
+ YolosModel,
+ YolosPreTrainedModel,
+ )
+ from .models.yoso import (
+ YosoForMaskedLM,
+ YosoForMultipleChoice,
+ YosoForQuestionAnswering,
+ YosoForSequenceClassification,
+ YosoForTokenClassification,
+ YosoModel,
+ YosoPreTrainedModel,
+ )
+ from .models.zamba import (
+ ZambaForCausalLM,
+ ZambaForSequenceClassification,
+ ZambaModel,
+ ZambaPreTrainedModel,
+ )
+ from .models.zoedepth import (
+ ZoeDepthForDepthEstimation,
+ ZoeDepthPreTrainedModel,
+ )
+
+ # Optimization
+ from .optimization import (
+ Adafactor,
+ AdamW,
+ get_constant_schedule,
+ get_constant_schedule_with_warmup,
+ get_cosine_schedule_with_warmup,
+ get_cosine_with_hard_restarts_schedule_with_warmup,
+ get_inverse_sqrt_schedule,
+ get_linear_schedule_with_warmup,
+ get_polynomial_decay_schedule_with_warmup,
+ get_scheduler,
+ get_wsd_schedule,
+ )
+ from .pytorch_utils import Conv1D, apply_chunking_to_forward, prune_layer
+
+ # Trainer
+ from .trainer import Trainer
+ from .trainer_pt_utils import torch_distributed_zero_first
+ from .trainer_seq2seq import Seq2SeqTrainer
+
+ # TensorFlow
+ try:
+ if not is_tf_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ # Import the same objects as dummies to get them in the namespace.
+ # They will raise an import error if the user tries to instantiate / use them.
+ from .utils.dummy_tf_objects import *
+ else:
+ from .benchmark.benchmark_args_tf import TensorFlowBenchmarkArguments
+
+ # Benchmarks
+ from .benchmark.benchmark_tf import TensorFlowBenchmark
+ from .generation import (
+ TFForcedBOSTokenLogitsProcessor,
+ TFForcedEOSTokenLogitsProcessor,
+ TFForceTokensLogitsProcessor,
+ TFGenerationMixin,
+ TFLogitsProcessor,
+ TFLogitsProcessorList,
+ TFLogitsWarper,
+ TFMinLengthLogitsProcessor,
+ TFNoBadWordsLogitsProcessor,
+ TFNoRepeatNGramLogitsProcessor,
+ TFRepetitionPenaltyLogitsProcessor,
+ TFSuppressTokensAtBeginLogitsProcessor,
+ TFSuppressTokensLogitsProcessor,
+ TFTemperatureLogitsWarper,
+ TFTopKLogitsWarper,
+ TFTopPLogitsWarper,
+ )
+ from .keras_callbacks import KerasMetricCallback, PushToHubCallback
+ from .modeling_tf_utils import (
+ TFPreTrainedModel,
+ TFSequenceSummary,
+ TFSharedEmbeddings,
+ shape_list,
+ )
+
+ # TensorFlow model imports
+ from .models.albert import (
+ TFAlbertForMaskedLM,
+ TFAlbertForMultipleChoice,
+ TFAlbertForPreTraining,
+ TFAlbertForQuestionAnswering,
+ TFAlbertForSequenceClassification,
+ TFAlbertForTokenClassification,
+ TFAlbertMainLayer,
+ TFAlbertModel,
+ TFAlbertPreTrainedModel,
+ )
+ from .models.auto import (
+ TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING,
+ TF_MODEL_FOR_CAUSAL_LM_MAPPING,
+ TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING,
+ TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
+ TF_MODEL_FOR_MASK_GENERATION_MAPPING,
+ TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
+ TF_MODEL_FOR_MASKED_LM_MAPPING,
+ TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
+ TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
+ TF_MODEL_FOR_PRETRAINING_MAPPING,
+ TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
+ TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING,
+ TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
+ TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
+ TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
+ TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
+ TF_MODEL_FOR_TEXT_ENCODING_MAPPING,
+ TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
+ TF_MODEL_FOR_VISION_2_SEQ_MAPPING,
+ TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING,
+ TF_MODEL_MAPPING,
+ TF_MODEL_WITH_LM_HEAD_MAPPING,
+ TFAutoModel,
+ TFAutoModelForAudioClassification,
+ TFAutoModelForCausalLM,
+ TFAutoModelForDocumentQuestionAnswering,
+ TFAutoModelForImageClassification,
+ TFAutoModelForMaskedImageModeling,
+ TFAutoModelForMaskedLM,
+ TFAutoModelForMaskGeneration,
+ TFAutoModelForMultipleChoice,
+ TFAutoModelForNextSentencePrediction,
+ TFAutoModelForPreTraining,
+ TFAutoModelForQuestionAnswering,
+ TFAutoModelForSemanticSegmentation,
+ TFAutoModelForSeq2SeqLM,
+ TFAutoModelForSequenceClassification,
+ TFAutoModelForSpeechSeq2Seq,
+ TFAutoModelForTableQuestionAnswering,
+ TFAutoModelForTextEncoding,
+ TFAutoModelForTokenClassification,
+ TFAutoModelForVision2Seq,
+ TFAutoModelForZeroShotImageClassification,
+ TFAutoModelWithLMHead,
+ )
+ from .models.bart import (
+ TFBartForConditionalGeneration,
+ TFBartForSequenceClassification,
+ TFBartModel,
+ TFBartPretrainedModel,
+ )
+ from .models.bert import (
+ TFBertForMaskedLM,
+ TFBertForMultipleChoice,
+ TFBertForNextSentencePrediction,
+ TFBertForPreTraining,
+ TFBertForQuestionAnswering,
+ TFBertForSequenceClassification,
+ TFBertForTokenClassification,
+ TFBertLMHeadModel,
+ TFBertMainLayer,
+ TFBertModel,
+ TFBertPreTrainedModel,
+ )
+ from .models.blenderbot import (
+ TFBlenderbotForConditionalGeneration,
+ TFBlenderbotModel,
+ TFBlenderbotPreTrainedModel,
+ )
+ from .models.blenderbot_small import (
+ TFBlenderbotSmallForConditionalGeneration,
+ TFBlenderbotSmallModel,
+ TFBlenderbotSmallPreTrainedModel,
+ )
+ from .models.blip import (
+ TFBlipForConditionalGeneration,
+ TFBlipForImageTextRetrieval,
+ TFBlipForQuestionAnswering,
+ TFBlipModel,
+ TFBlipPreTrainedModel,
+ TFBlipTextModel,
+ TFBlipVisionModel,
+ )
+ from .models.camembert import (
+ TFCamembertForCausalLM,
+ TFCamembertForMaskedLM,
+ TFCamembertForMultipleChoice,
+ TFCamembertForQuestionAnswering,
+ TFCamembertForSequenceClassification,
+ TFCamembertForTokenClassification,
+ TFCamembertModel,
+ TFCamembertPreTrainedModel,
+ )
+ from .models.clip import (
+ TFCLIPModel,
+ TFCLIPPreTrainedModel,
+ TFCLIPTextModel,
+ TFCLIPVisionModel,
+ )
+ from .models.convbert import (
+ TFConvBertForMaskedLM,
+ TFConvBertForMultipleChoice,
+ TFConvBertForQuestionAnswering,
+ TFConvBertForSequenceClassification,
+ TFConvBertForTokenClassification,
+ TFConvBertModel,
+ TFConvBertPreTrainedModel,
+ )
+ from .models.convnext import (
+ TFConvNextForImageClassification,
+ TFConvNextModel,
+ TFConvNextPreTrainedModel,
+ )
+ from .models.convnextv2 import (
+ TFConvNextV2ForImageClassification,
+ TFConvNextV2Model,
+ TFConvNextV2PreTrainedModel,
+ )
+ from .models.ctrl import (
+ TFCTRLForSequenceClassification,
+ TFCTRLLMHeadModel,
+ TFCTRLModel,
+ TFCTRLPreTrainedModel,
+ )
+ from .models.cvt import (
+ TFCvtForImageClassification,
+ TFCvtModel,
+ TFCvtPreTrainedModel,
+ )
+ from .models.data2vec import (
+ TFData2VecVisionForImageClassification,
+ TFData2VecVisionForSemanticSegmentation,
+ TFData2VecVisionModel,
+ TFData2VecVisionPreTrainedModel,
+ )
+ from .models.deberta import (
+ TFDebertaForMaskedLM,
+ TFDebertaForQuestionAnswering,
+ TFDebertaForSequenceClassification,
+ TFDebertaForTokenClassification,
+ TFDebertaModel,
+ TFDebertaPreTrainedModel,
+ )
+ from .models.deberta_v2 import (
+ TFDebertaV2ForMaskedLM,
+ TFDebertaV2ForMultipleChoice,
+ TFDebertaV2ForQuestionAnswering,
+ TFDebertaV2ForSequenceClassification,
+ TFDebertaV2ForTokenClassification,
+ TFDebertaV2Model,
+ TFDebertaV2PreTrainedModel,
+ )
+ from .models.deit import (
+ TFDeiTForImageClassification,
+ TFDeiTForImageClassificationWithTeacher,
+ TFDeiTForMaskedImageModeling,
+ TFDeiTModel,
+ TFDeiTPreTrainedModel,
+ )
+ from .models.deprecated.efficientformer import (
+ TFEfficientFormerForImageClassification,
+ TFEfficientFormerForImageClassificationWithTeacher,
+ TFEfficientFormerModel,
+ TFEfficientFormerPreTrainedModel,
+ )
+ from .models.deprecated.transfo_xl import (
+ TFAdaptiveEmbedding,
+ TFTransfoXLForSequenceClassification,
+ TFTransfoXLLMHeadModel,
+ TFTransfoXLMainLayer,
+ TFTransfoXLModel,
+ TFTransfoXLPreTrainedModel,
+ )
+ from .models.distilbert import (
+ TFDistilBertForMaskedLM,
+ TFDistilBertForMultipleChoice,
+ TFDistilBertForQuestionAnswering,
+ TFDistilBertForSequenceClassification,
+ TFDistilBertForTokenClassification,
+ TFDistilBertMainLayer,
+ TFDistilBertModel,
+ TFDistilBertPreTrainedModel,
+ )
+ from .models.dpr import (
+ TFDPRContextEncoder,
+ TFDPRPretrainedContextEncoder,
+ TFDPRPretrainedQuestionEncoder,
+ TFDPRPretrainedReader,
+ TFDPRQuestionEncoder,
+ TFDPRReader,
+ )
+ from .models.electra import (
+ TFElectraForMaskedLM,
+ TFElectraForMultipleChoice,
+ TFElectraForPreTraining,
+ TFElectraForQuestionAnswering,
+ TFElectraForSequenceClassification,
+ TFElectraForTokenClassification,
+ TFElectraModel,
+ TFElectraPreTrainedModel,
+ )
+ from .models.encoder_decoder import TFEncoderDecoderModel
+ from .models.esm import (
+ TFEsmForMaskedLM,
+ TFEsmForSequenceClassification,
+ TFEsmForTokenClassification,
+ TFEsmModel,
+ TFEsmPreTrainedModel,
+ )
+ from .models.flaubert import (
+ TFFlaubertForMultipleChoice,
+ TFFlaubertForQuestionAnsweringSimple,
+ TFFlaubertForSequenceClassification,
+ TFFlaubertForTokenClassification,
+ TFFlaubertModel,
+ TFFlaubertPreTrainedModel,
+ TFFlaubertWithLMHeadModel,
+ )
+ from .models.funnel import (
+ TFFunnelBaseModel,
+ TFFunnelForMaskedLM,
+ TFFunnelForMultipleChoice,
+ TFFunnelForPreTraining,
+ TFFunnelForQuestionAnswering,
+ TFFunnelForSequenceClassification,
+ TFFunnelForTokenClassification,
+ TFFunnelModel,
+ TFFunnelPreTrainedModel,
+ )
+ from .models.gpt2 import (
+ TFGPT2DoubleHeadsModel,
+ TFGPT2ForSequenceClassification,
+ TFGPT2LMHeadModel,
+ TFGPT2MainLayer,
+ TFGPT2Model,
+ TFGPT2PreTrainedModel,
+ )
+ from .models.gptj import (
+ TFGPTJForCausalLM,
+ TFGPTJForQuestionAnswering,
+ TFGPTJForSequenceClassification,
+ TFGPTJModel,
+ TFGPTJPreTrainedModel,
+ )
+ from .models.groupvit import (
+ TFGroupViTModel,
+ TFGroupViTPreTrainedModel,
+ TFGroupViTTextModel,
+ TFGroupViTVisionModel,
+ )
+ from .models.hubert import (
+ TFHubertForCTC,
+ TFHubertModel,
+ TFHubertPreTrainedModel,
+ )
+ from .models.idefics import (
+ TFIdeficsForVisionText2Text,
+ TFIdeficsModel,
+ TFIdeficsPreTrainedModel,
+ )
+ from .models.layoutlm import (
+ TFLayoutLMForMaskedLM,
+ TFLayoutLMForQuestionAnswering,
+ TFLayoutLMForSequenceClassification,
+ TFLayoutLMForTokenClassification,
+ TFLayoutLMMainLayer,
+ TFLayoutLMModel,
+ TFLayoutLMPreTrainedModel,
+ )
+ from .models.layoutlmv3 import (
+ TFLayoutLMv3ForQuestionAnswering,
+ TFLayoutLMv3ForSequenceClassification,
+ TFLayoutLMv3ForTokenClassification,
+ TFLayoutLMv3Model,
+ TFLayoutLMv3PreTrainedModel,
+ )
+ from .models.led import (
+ TFLEDForConditionalGeneration,
+ TFLEDModel,
+ TFLEDPreTrainedModel,
+ )
+ from .models.longformer import (
+ TFLongformerForMaskedLM,
+ TFLongformerForMultipleChoice,
+ TFLongformerForQuestionAnswering,
+ TFLongformerForSequenceClassification,
+ TFLongformerForTokenClassification,
+ TFLongformerModel,
+ TFLongformerPreTrainedModel,
+ )
+ from .models.lxmert import (
+ TFLxmertForPreTraining,
+ TFLxmertMainLayer,
+ TFLxmertModel,
+ TFLxmertPreTrainedModel,
+ TFLxmertVisualFeatureEncoder,
+ )
+ from .models.marian import (
+ TFMarianModel,
+ TFMarianMTModel,
+ TFMarianPreTrainedModel,
+ )
+ from .models.mbart import (
+ TFMBartForConditionalGeneration,
+ TFMBartModel,
+ TFMBartPreTrainedModel,
+ )
+ from .models.mistral import (
+ TFMistralForCausalLM,
+ TFMistralForSequenceClassification,
+ TFMistralModel,
+ TFMistralPreTrainedModel,
+ )
+ from .models.mobilebert import (
+ TFMobileBertForMaskedLM,
+ TFMobileBertForMultipleChoice,
+ TFMobileBertForNextSentencePrediction,
+ TFMobileBertForPreTraining,
+ TFMobileBertForQuestionAnswering,
+ TFMobileBertForSequenceClassification,
+ TFMobileBertForTokenClassification,
+ TFMobileBertMainLayer,
+ TFMobileBertModel,
+ TFMobileBertPreTrainedModel,
+ )
+ from .models.mobilevit import (
+ TFMobileViTForImageClassification,
+ TFMobileViTForSemanticSegmentation,
+ TFMobileViTModel,
+ TFMobileViTPreTrainedModel,
+ )
+ from .models.mpnet import (
+ TFMPNetForMaskedLM,
+ TFMPNetForMultipleChoice,
+ TFMPNetForQuestionAnswering,
+ TFMPNetForSequenceClassification,
+ TFMPNetForTokenClassification,
+ TFMPNetMainLayer,
+ TFMPNetModel,
+ TFMPNetPreTrainedModel,
+ )
+ from .models.mt5 import (
+ TFMT5EncoderModel,
+ TFMT5ForConditionalGeneration,
+ TFMT5Model,
+ )
+ from .models.openai import (
+ TFOpenAIGPTDoubleHeadsModel,
+ TFOpenAIGPTForSequenceClassification,
+ TFOpenAIGPTLMHeadModel,
+ TFOpenAIGPTMainLayer,
+ TFOpenAIGPTModel,
+ TFOpenAIGPTPreTrainedModel,
+ )
+ from .models.opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel
+ from .models.pegasus import (
+ TFPegasusForConditionalGeneration,
+ TFPegasusModel,
+ TFPegasusPreTrainedModel,
+ )
+ from .models.rag import (
+ TFRagModel,
+ TFRagPreTrainedModel,
+ TFRagSequenceForGeneration,
+ TFRagTokenForGeneration,
+ )
+ from .models.regnet import (
+ TFRegNetForImageClassification,
+ TFRegNetModel,
+ TFRegNetPreTrainedModel,
+ )
+ from .models.rembert import (
+ TFRemBertForCausalLM,
+ TFRemBertForMaskedLM,
+ TFRemBertForMultipleChoice,
+ TFRemBertForQuestionAnswering,
+ TFRemBertForSequenceClassification,
+ TFRemBertForTokenClassification,
+ TFRemBertModel,
+ TFRemBertPreTrainedModel,
+ )
+ from .models.resnet import (
+ TFResNetForImageClassification,
+ TFResNetModel,
+ TFResNetPreTrainedModel,
+ )
+ from .models.roberta import (
+ TFRobertaForCausalLM,
+ TFRobertaForMaskedLM,
+ TFRobertaForMultipleChoice,
+ TFRobertaForQuestionAnswering,
+ TFRobertaForSequenceClassification,
+ TFRobertaForTokenClassification,
+ TFRobertaMainLayer,
+ TFRobertaModel,
+ TFRobertaPreTrainedModel,
+ )
+ from .models.roberta_prelayernorm import (
+ TFRobertaPreLayerNormForCausalLM,
+ TFRobertaPreLayerNormForMaskedLM,
+ TFRobertaPreLayerNormForMultipleChoice,
+ TFRobertaPreLayerNormForQuestionAnswering,
+ TFRobertaPreLayerNormForSequenceClassification,
+ TFRobertaPreLayerNormForTokenClassification,
+ TFRobertaPreLayerNormMainLayer,
+ TFRobertaPreLayerNormModel,
+ TFRobertaPreLayerNormPreTrainedModel,
+ )
+ from .models.roformer import (
+ TFRoFormerForCausalLM,
+ TFRoFormerForMaskedLM,
+ TFRoFormerForMultipleChoice,
+ TFRoFormerForQuestionAnswering,
+ TFRoFormerForSequenceClassification,
+ TFRoFormerForTokenClassification,
+ TFRoFormerModel,
+ TFRoFormerPreTrainedModel,
+ )
+ from .models.sam import (
+ TFSamModel,
+ TFSamPreTrainedModel,
+ )
+ from .models.segformer import (
+ TFSegformerDecodeHead,
+ TFSegformerForImageClassification,
+ TFSegformerForSemanticSegmentation,
+ TFSegformerModel,
+ TFSegformerPreTrainedModel,
+ )
+ from .models.speech_to_text import (
+ TFSpeech2TextForConditionalGeneration,
+ TFSpeech2TextModel,
+ TFSpeech2TextPreTrainedModel,
+ )
+ from .models.swiftformer import (
+ TFSwiftFormerForImageClassification,
+ TFSwiftFormerModel,
+ TFSwiftFormerPreTrainedModel,
+ )
+ from .models.swin import (
+ TFSwinForImageClassification,
+ TFSwinForMaskedImageModeling,
+ TFSwinModel,
+ TFSwinPreTrainedModel,
+ )
+ from .models.t5 import (
+ TFT5EncoderModel,
+ TFT5ForConditionalGeneration,
+ TFT5Model,
+ TFT5PreTrainedModel,
+ )
+ from .models.tapas import (
+ TFTapasForMaskedLM,
+ TFTapasForQuestionAnswering,
+ TFTapasForSequenceClassification,
+ TFTapasModel,
+ TFTapasPreTrainedModel,
+ )
+ from .models.vision_encoder_decoder import TFVisionEncoderDecoderModel
+ from .models.vision_text_dual_encoder import TFVisionTextDualEncoderModel
+ from .models.vit import (
+ TFViTForImageClassification,
+ TFViTModel,
+ TFViTPreTrainedModel,
+ )
+ from .models.vit_mae import (
+ TFViTMAEForPreTraining,
+ TFViTMAEModel,
+ TFViTMAEPreTrainedModel,
+ )
+ from .models.wav2vec2 import (
+ TFWav2Vec2ForCTC,
+ TFWav2Vec2ForSequenceClassification,
+ TFWav2Vec2Model,
+ TFWav2Vec2PreTrainedModel,
+ )
+ from .models.whisper import (
+ TFWhisperForConditionalGeneration,
+ TFWhisperModel,
+ TFWhisperPreTrainedModel,
+ )
+ from .models.xglm import (
+ TFXGLMForCausalLM,
+ TFXGLMModel,
+ TFXGLMPreTrainedModel,
+ )
+ from .models.xlm import (
+ TFXLMForMultipleChoice,
+ TFXLMForQuestionAnsweringSimple,
+ TFXLMForSequenceClassification,
+ TFXLMForTokenClassification,
+ TFXLMMainLayer,
+ TFXLMModel,
+ TFXLMPreTrainedModel,
+ TFXLMWithLMHeadModel,
+ )
+ from .models.xlm_roberta import (
+ TFXLMRobertaForCausalLM,
+ TFXLMRobertaForMaskedLM,
+ TFXLMRobertaForMultipleChoice,
+ TFXLMRobertaForQuestionAnswering,
+ TFXLMRobertaForSequenceClassification,
+ TFXLMRobertaForTokenClassification,
+ TFXLMRobertaModel,
+ TFXLMRobertaPreTrainedModel,
+ )
+ from .models.xlnet import (
+ TFXLNetForMultipleChoice,
+ TFXLNetForQuestionAnsweringSimple,
+ TFXLNetForSequenceClassification,
+ TFXLNetForTokenClassification,
+ TFXLNetLMHeadModel,
+ TFXLNetMainLayer,
+ TFXLNetModel,
+ TFXLNetPreTrainedModel,
+ )
+
+ # Optimization
+ from .optimization_tf import (
+ AdamWeightDecay,
+ GradientAccumulator,
+ WarmUp,
+ create_optimizer,
+ )
+
+ try:
+ if not (
+ is_librosa_available()
+ and is_essentia_available()
+ and is_scipy_available()
+ and is_torch_available()
+ and is_pretty_midi_available()
+ ):
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ from .utils.dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects import *
+ else:
+ from .models.pop2piano import (
+ Pop2PianoFeatureExtractor,
+ Pop2PianoProcessor,
+ Pop2PianoTokenizer,
+ )
+
+ try:
+ if not is_torchaudio_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ from .utils.dummy_torchaudio_objects import *
+ else:
+ from .models.musicgen_melody import MusicgenMelodyFeatureExtractor, MusicgenMelodyProcessor
+ try:
+ if not is_flax_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ # Import the same objects as dummies to get them in the namespace.
+ # They will raise an import error if the user tries to instantiate / use them.
+ from .utils.dummy_flax_objects import *
+ else:
+ from .generation import (
+ FlaxForcedBOSTokenLogitsProcessor,
+ FlaxForcedEOSTokenLogitsProcessor,
+ FlaxForceTokensLogitsProcessor,
+ FlaxGenerationMixin,
+ FlaxLogitsProcessor,
+ FlaxLogitsProcessorList,
+ FlaxLogitsWarper,
+ FlaxMinLengthLogitsProcessor,
+ FlaxSuppressTokensAtBeginLogitsProcessor,
+ FlaxSuppressTokensLogitsProcessor,
+ FlaxTemperatureLogitsWarper,
+ FlaxTopKLogitsWarper,
+ FlaxTopPLogitsWarper,
+ FlaxWhisperTimeStampLogitsProcessor,
+ )
+ from .modeling_flax_utils import FlaxPreTrainedModel
+
+ # Flax model imports
+ from .models.albert import (
+ FlaxAlbertForMaskedLM,
+ FlaxAlbertForMultipleChoice,
+ FlaxAlbertForPreTraining,
+ FlaxAlbertForQuestionAnswering,
+ FlaxAlbertForSequenceClassification,
+ FlaxAlbertForTokenClassification,
+ FlaxAlbertModel,
+ FlaxAlbertPreTrainedModel,
+ )
+ from .models.auto import (
+ FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING,
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
+ FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING,
+ FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
+ FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
+ FLAX_MODEL_FOR_PRETRAINING_MAPPING,
+ FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
+ FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
+ FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
+ FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
+ FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
+ FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING,
+ FLAX_MODEL_MAPPING,
+ FlaxAutoModel,
+ FlaxAutoModelForCausalLM,
+ FlaxAutoModelForImageClassification,
+ FlaxAutoModelForMaskedLM,
+ FlaxAutoModelForMultipleChoice,
+ FlaxAutoModelForNextSentencePrediction,
+ FlaxAutoModelForPreTraining,
+ FlaxAutoModelForQuestionAnswering,
+ FlaxAutoModelForSeq2SeqLM,
+ FlaxAutoModelForSequenceClassification,
+ FlaxAutoModelForSpeechSeq2Seq,
+ FlaxAutoModelForTokenClassification,
+ FlaxAutoModelForVision2Seq,
+ )
+ from .models.bart import (
+ FlaxBartDecoderPreTrainedModel,
+ FlaxBartForCausalLM,
+ FlaxBartForConditionalGeneration,
+ FlaxBartForQuestionAnswering,
+ FlaxBartForSequenceClassification,
+ FlaxBartModel,
+ FlaxBartPreTrainedModel,
+ )
+ from .models.beit import (
+ FlaxBeitForImageClassification,
+ FlaxBeitForMaskedImageModeling,
+ FlaxBeitModel,
+ FlaxBeitPreTrainedModel,
+ )
+ from .models.bert import (
+ FlaxBertForCausalLM,
+ FlaxBertForMaskedLM,
+ FlaxBertForMultipleChoice,
+ FlaxBertForNextSentencePrediction,
+ FlaxBertForPreTraining,
+ FlaxBertForQuestionAnswering,
+ FlaxBertForSequenceClassification,
+ FlaxBertForTokenClassification,
+ FlaxBertModel,
+ FlaxBertPreTrainedModel,
+ )
+ from .models.big_bird import (
+ FlaxBigBirdForCausalLM,
+ FlaxBigBirdForMaskedLM,
+ FlaxBigBirdForMultipleChoice,
+ FlaxBigBirdForPreTraining,
+ FlaxBigBirdForQuestionAnswering,
+ FlaxBigBirdForSequenceClassification,
+ FlaxBigBirdForTokenClassification,
+ FlaxBigBirdModel,
+ FlaxBigBirdPreTrainedModel,
+ )
+ from .models.blenderbot import (
+ FlaxBlenderbotForConditionalGeneration,
+ FlaxBlenderbotModel,
+ FlaxBlenderbotPreTrainedModel,
+ )
+ from .models.blenderbot_small import (
+ FlaxBlenderbotSmallForConditionalGeneration,
+ FlaxBlenderbotSmallModel,
+ FlaxBlenderbotSmallPreTrainedModel,
+ )
+ from .models.bloom import (
+ FlaxBloomForCausalLM,
+ FlaxBloomModel,
+ FlaxBloomPreTrainedModel,
+ )
+ from .models.clip import (
+ FlaxCLIPModel,
+ FlaxCLIPPreTrainedModel,
+ FlaxCLIPTextModel,
+ FlaxCLIPTextModelWithProjection,
+ FlaxCLIPTextPreTrainedModel,
+ FlaxCLIPVisionModel,
+ FlaxCLIPVisionPreTrainedModel,
+ )
+ from .models.dinov2 import (
+ FlaxDinov2ForImageClassification,
+ FlaxDinov2Model,
+ FlaxDinov2PreTrainedModel,
+ )
+ from .models.distilbert import (
+ FlaxDistilBertForMaskedLM,
+ FlaxDistilBertForMultipleChoice,
+ FlaxDistilBertForQuestionAnswering,
+ FlaxDistilBertForSequenceClassification,
+ FlaxDistilBertForTokenClassification,
+ FlaxDistilBertModel,
+ FlaxDistilBertPreTrainedModel,
+ )
+ from .models.electra import (
+ FlaxElectraForCausalLM,
+ FlaxElectraForMaskedLM,
+ FlaxElectraForMultipleChoice,
+ FlaxElectraForPreTraining,
+ FlaxElectraForQuestionAnswering,
+ FlaxElectraForSequenceClassification,
+ FlaxElectraForTokenClassification,
+ FlaxElectraModel,
+ FlaxElectraPreTrainedModel,
+ )
+ from .models.encoder_decoder import FlaxEncoderDecoderModel
+ from .models.gemma import (
+ FlaxGemmaForCausalLM,
+ FlaxGemmaModel,
+ FlaxGemmaPreTrainedModel,
+ )
+ from .models.gpt2 import (
+ FlaxGPT2LMHeadModel,
+ FlaxGPT2Model,
+ FlaxGPT2PreTrainedModel,
+ )
+ from .models.gpt_neo import (
+ FlaxGPTNeoForCausalLM,
+ FlaxGPTNeoModel,
+ FlaxGPTNeoPreTrainedModel,
+ )
+ from .models.gptj import (
+ FlaxGPTJForCausalLM,
+ FlaxGPTJModel,
+ FlaxGPTJPreTrainedModel,
+ )
+ from .models.llama import (
+ FlaxLlamaForCausalLM,
+ FlaxLlamaModel,
+ FlaxLlamaPreTrainedModel,
+ )
+ from .models.longt5 import (
+ FlaxLongT5ForConditionalGeneration,
+ FlaxLongT5Model,
+ FlaxLongT5PreTrainedModel,
+ )
+ from .models.marian import (
+ FlaxMarianModel,
+ FlaxMarianMTModel,
+ FlaxMarianPreTrainedModel,
+ )
+ from .models.mbart import (
+ FlaxMBartForConditionalGeneration,
+ FlaxMBartForQuestionAnswering,
+ FlaxMBartForSequenceClassification,
+ FlaxMBartModel,
+ FlaxMBartPreTrainedModel,
+ )
+ from .models.mistral import (
+ FlaxMistralForCausalLM,
+ FlaxMistralModel,
+ FlaxMistralPreTrainedModel,
+ )
+ from .models.mt5 import (
+ FlaxMT5EncoderModel,
+ FlaxMT5ForConditionalGeneration,
+ FlaxMT5Model,
+ )
+ from .models.opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel
+ from .models.pegasus import (
+ FlaxPegasusForConditionalGeneration,
+ FlaxPegasusModel,
+ FlaxPegasusPreTrainedModel,
+ )
+ from .models.regnet import (
+ FlaxRegNetForImageClassification,
+ FlaxRegNetModel,
+ FlaxRegNetPreTrainedModel,
+ )
+ from .models.resnet import (
+ FlaxResNetForImageClassification,
+ FlaxResNetModel,
+ FlaxResNetPreTrainedModel,
+ )
+ from .models.roberta import (
+ FlaxRobertaForCausalLM,
+ FlaxRobertaForMaskedLM,
+ FlaxRobertaForMultipleChoice,
+ FlaxRobertaForQuestionAnswering,
+ FlaxRobertaForSequenceClassification,
+ FlaxRobertaForTokenClassification,
+ FlaxRobertaModel,
+ FlaxRobertaPreTrainedModel,
+ )
+ from .models.roberta_prelayernorm import (
+ FlaxRobertaPreLayerNormForCausalLM,
+ FlaxRobertaPreLayerNormForMaskedLM,
+ FlaxRobertaPreLayerNormForMultipleChoice,
+ FlaxRobertaPreLayerNormForQuestionAnswering,
+ FlaxRobertaPreLayerNormForSequenceClassification,
+ FlaxRobertaPreLayerNormForTokenClassification,
+ FlaxRobertaPreLayerNormModel,
+ FlaxRobertaPreLayerNormPreTrainedModel,
+ )
+ from .models.roformer import (
+ FlaxRoFormerForMaskedLM,
+ FlaxRoFormerForMultipleChoice,
+ FlaxRoFormerForQuestionAnswering,
+ FlaxRoFormerForSequenceClassification,
+ FlaxRoFormerForTokenClassification,
+ FlaxRoFormerModel,
+ FlaxRoFormerPreTrainedModel,
+ )
+ from .models.speech_encoder_decoder import FlaxSpeechEncoderDecoderModel
+ from .models.t5 import (
+ FlaxT5EncoderModel,
+ FlaxT5ForConditionalGeneration,
+ FlaxT5Model,
+ FlaxT5PreTrainedModel,
+ )
+ from .models.vision_encoder_decoder import FlaxVisionEncoderDecoderModel
+ from .models.vision_text_dual_encoder import FlaxVisionTextDualEncoderModel
+ from .models.vit import (
+ FlaxViTForImageClassification,
+ FlaxViTModel,
+ FlaxViTPreTrainedModel,
+ )
+ from .models.wav2vec2 import (
+ FlaxWav2Vec2ForCTC,
+ FlaxWav2Vec2ForPreTraining,
+ FlaxWav2Vec2Model,
+ FlaxWav2Vec2PreTrainedModel,
+ )
+ from .models.whisper import (
+ FlaxWhisperForAudioClassification,
+ FlaxWhisperForConditionalGeneration,
+ FlaxWhisperModel,
+ FlaxWhisperPreTrainedModel,
+ )
+ from .models.xglm import (
+ FlaxXGLMForCausalLM,
+ FlaxXGLMModel,
+ FlaxXGLMPreTrainedModel,
+ )
+ from .models.xlm_roberta import (
+ FlaxXLMRobertaForCausalLM,
+ FlaxXLMRobertaForMaskedLM,
+ FlaxXLMRobertaForMultipleChoice,
+ FlaxXLMRobertaForQuestionAnswering,
+ FlaxXLMRobertaForSequenceClassification,
+ FlaxXLMRobertaForTokenClassification,
+ FlaxXLMRobertaModel,
+ FlaxXLMRobertaPreTrainedModel,
+ )
+
+
+else:
+ import sys
+
+ sys.modules[__name__] = _LazyModule(
+ __name__,
+ globals()["__file__"],
+ _import_structure,
+ module_spec=__spec__,
+ extra_objects={"__version__": __version__},
+ )
+
+
+if not is_tf_available() and not is_torch_available() and not is_flax_available():
+ logger.warning_advice(
+ "None of PyTorch, TensorFlow >= 2.0, or Flax have been found. "
+ "Models won't be available and only tokenizers, configuration "
+ "and file/data utilities can be used."
+ )
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/activations.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/activations.py
new file mode 100644
index 0000000000000000000000000000000000000000..2355fb5fed678d0de6e2c53f52644a35a691a34e
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/activations.py
@@ -0,0 +1,239 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from collections import OrderedDict
+
+import torch
+from packaging import version
+from torch import Tensor, nn
+
+from .utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class PytorchGELUTanh(nn.Module):
+ """
+ A fast C implementation of the tanh approximation of the GeLU activation function. See
+ https://arxiv.org/abs/1606.08415.
+
+ This implementation is equivalent to NewGELU and FastGELU but much faster. However, it is not an exact numerical
+ match due to rounding errors.
+ """
+
+ def __init__(self):
+ super().__init__()
+ if version.parse(torch.__version__) < version.parse("1.12.0"):
+ raise ImportError(
+ f"You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use "
+ "PytorchGELUTanh. Please upgrade torch."
+ )
+
+ def forward(self, input: Tensor) -> Tensor:
+ return nn.functional.gelu(input, approximate="tanh")
+
+
+class NewGELUActivation(nn.Module):
+ """
+ Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see
+ the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
+ """
+
+ def forward(self, input: Tensor) -> Tensor:
+ return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(input, 3.0))))
+
+
+class GELUActivation(nn.Module):
+ """
+ Original Implementation of the GELU activation function in Google BERT repo when initially created. For
+ information: OpenAI GPT's GELU is slightly different (and gives slightly different results): 0.5 * x * (1 +
+ torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) This is now written in C in nn.functional
+ Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
+ """
+
+ def __init__(self, use_gelu_python: bool = False):
+ super().__init__()
+ if use_gelu_python:
+ self.act = self._gelu_python
+ else:
+ self.act = nn.functional.gelu
+
+ def _gelu_python(self, input: Tensor) -> Tensor:
+ return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0)))
+
+ def forward(self, input: Tensor) -> Tensor:
+ return self.act(input)
+
+
+class FastGELUActivation(nn.Module):
+ """
+ Applies GELU approximation that is slower than QuickGELU but more accurate. See: https://github.com/hendrycks/GELUs
+ """
+
+ def forward(self, input: Tensor) -> Tensor:
+ return 0.5 * input * (1.0 + torch.tanh(input * 0.7978845608 * (1.0 + 0.044715 * input * input)))
+
+
+class QuickGELUActivation(nn.Module):
+ """
+ Applies GELU approximation that is fast but somewhat inaccurate. See: https://github.com/hendrycks/GELUs
+ """
+
+ def forward(self, input: Tensor) -> Tensor:
+ return input * torch.sigmoid(1.702 * input)
+
+
+class ClippedGELUActivation(nn.Module):
+ """
+ Clip the range of possible GeLU outputs between [min, max]. This is especially useful for quantization purpose, as
+ it allows mapping negatives values in the GeLU spectrum. For more information on this trick, please refer to
+ https://arxiv.org/abs/2004.09602.
+
+ Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when
+ initially created.
+
+ For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 +
+ torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))). See https://arxiv.org/abs/1606.08415
+ """
+
+ def __init__(self, min: float, max: float):
+ if min > max:
+ raise ValueError(f"min should be < max (got min: {min}, max: {max})")
+
+ super().__init__()
+ self.min = min
+ self.max = max
+
+ def forward(self, x: Tensor) -> Tensor:
+ return torch.clip(gelu(x), self.min, self.max)
+
+
+class AccurateGELUActivation(nn.Module):
+ """
+ Applies GELU approximation that is faster than default and more accurate than QuickGELU. See:
+ https://github.com/hendrycks/GELUs
+
+ Implemented along with MEGA (Moving Average Equipped Gated Attention)
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.precomputed_constant = math.sqrt(2 / math.pi)
+
+ def forward(self, input: Tensor) -> Tensor:
+ return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044715 * torch.pow(input, 3))))
+
+
+class MishActivation(nn.Module):
+ """
+ See Mish: A Self-Regularized Non-Monotonic Activation Function (Misra., https://arxiv.org/abs/1908.08681). Also
+ visit the official repository for the paper: https://github.com/digantamisra98/Mish
+ """
+
+ def __init__(self):
+ super().__init__()
+ if version.parse(torch.__version__) < version.parse("1.9.0"):
+ self.act = self._mish_python
+ else:
+ self.act = nn.functional.mish
+
+ def _mish_python(self, input: Tensor) -> Tensor:
+ return input * torch.tanh(nn.functional.softplus(input))
+
+ def forward(self, input: Tensor) -> Tensor:
+ return self.act(input)
+
+
+class LinearActivation(nn.Module):
+ """
+ Applies the linear activation function, i.e. forwarding input directly to output.
+ """
+
+ def forward(self, input: Tensor) -> Tensor:
+ return input
+
+
+class LaplaceActivation(nn.Module):
+ """
+ Applies elementwise activation based on Laplace function, introduced in MEGA as an attention activation. See
+ https://arxiv.org/abs/2209.10655
+
+ Inspired by squared relu, but with bounded range and gradient for better stability
+ """
+
+ def forward(self, input, mu=0.707107, sigma=0.282095):
+ input = (input - mu).div(sigma * math.sqrt(2.0))
+ return 0.5 * (1.0 + torch.erf(input))
+
+
+class ReLUSquaredActivation(nn.Module):
+ """
+ Applies the relu^2 activation introduced in https://arxiv.org/abs/2109.08668v2
+ """
+
+ def forward(self, input):
+ relu_applied = nn.functional.relu(input)
+ squared = torch.square(relu_applied)
+ return squared
+
+
+class ClassInstantier(OrderedDict):
+ def __getitem__(self, key):
+ content = super().__getitem__(key)
+ cls, kwargs = content if isinstance(content, tuple) else (content, {})
+ return cls(**kwargs)
+
+
+ACT2CLS = {
+ "gelu": GELUActivation,
+ "gelu_10": (ClippedGELUActivation, {"min": -10, "max": 10}),
+ "gelu_fast": FastGELUActivation,
+ "gelu_new": NewGELUActivation,
+ "gelu_python": (GELUActivation, {"use_gelu_python": True}),
+ "gelu_pytorch_tanh": PytorchGELUTanh,
+ "gelu_accurate": AccurateGELUActivation,
+ "laplace": LaplaceActivation,
+ "leaky_relu": nn.LeakyReLU,
+ "linear": LinearActivation,
+ "mish": MishActivation,
+ "quick_gelu": QuickGELUActivation,
+ "relu": nn.ReLU,
+ "relu2": ReLUSquaredActivation,
+ "relu6": nn.ReLU6,
+ "sigmoid": nn.Sigmoid,
+ "silu": nn.SiLU,
+ "swish": nn.SiLU,
+ "tanh": nn.Tanh,
+}
+ACT2FN = ClassInstantier(ACT2CLS)
+
+
+def get_activation(activation_string):
+ if activation_string in ACT2FN:
+ return ACT2FN[activation_string]
+ else:
+ raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACT2FN.keys())}")
+
+
+# For backwards compatibility with: from activations import gelu_python
+gelu_python = get_activation("gelu_python")
+gelu_new = get_activation("gelu_new")
+gelu = get_activation("gelu")
+gelu_fast = get_activation("gelu_fast")
+quick_gelu = get_activation("quick_gelu")
+silu = get_activation("silu")
+mish = get_activation("mish")
+linear_act = get_activation("linear")
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/activations_tf.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/activations_tf.py
new file mode 100644
index 0000000000000000000000000000000000000000..d12b73ea45176f3a4bc42cdabe8b73078a3b90f2
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/activations_tf.py
@@ -0,0 +1,147 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+
+import tensorflow as tf
+from packaging.version import parse
+
+
+try:
+ import tf_keras as keras
+except (ModuleNotFoundError, ImportError):
+ import keras
+
+ if parse(keras.__version__).major > 2:
+ raise ValueError(
+ "Your currently installed version of Keras is Keras 3, but this is not yet supported in "
+ "Transformers. Please install the backwards-compatible tf-keras package with "
+ "`pip install tf-keras`."
+ )
+
+
+def _gelu(x):
+ """
+ Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when
+ initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
+ 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see
+ https://arxiv.org/abs/1606.08415
+ """
+ x = tf.convert_to_tensor(x)
+ cdf = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0), x.dtype)))
+
+ return x * cdf
+
+
+def _gelu_new(x):
+ """
+ Gaussian Error Linear Unit. This is a smoother version of the GELU. Original paper: https://arxiv.org/abs/1606.0841
+
+ Args:
+ x: float Tensor to perform activation
+
+ Returns:
+ `x` with the GELU activation applied.
+ """
+ x = tf.convert_to_tensor(x)
+ pi = tf.cast(math.pi, x.dtype)
+ coeff = tf.cast(0.044715, x.dtype)
+ cdf = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi) * (x + coeff * tf.pow(x, 3))))
+
+ return x * cdf
+
+
+def mish(x):
+ x = tf.convert_to_tensor(x)
+
+ return x * tf.tanh(tf.math.softplus(x))
+
+
+def gelu_fast(x):
+ x = tf.convert_to_tensor(x)
+ coeff1 = tf.cast(0.044715, x.dtype)
+ coeff2 = tf.cast(0.7978845608, x.dtype)
+
+ return 0.5 * x * (1.0 + tf.tanh(x * coeff2 * (1.0 + coeff1 * x * x)))
+
+
+def quick_gelu(x):
+ x = tf.convert_to_tensor(x)
+ coeff = tf.cast(1.702, x.dtype)
+ return x * tf.math.sigmoid(coeff * x)
+
+
+def gelu_10(x):
+ """
+ Clip the range of possible GeLU outputs between [-10, 10]. This is especially useful for quantization purpose, as
+ it allows mapping 2 negatives values in the GeLU spectrum. For more information on this trick, please refer to
+ https://arxiv.org/abs/2004.09602
+
+ Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when
+ initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
+ 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see
+ https://arxiv.org/abs/1606.08415 :param x: :return:
+ """
+ return tf.clip_by_value(_gelu(x), -10, 10)
+
+
+def glu(x, axis=-1):
+ """
+ Gated Linear Unit. Implementation as defined in the original paper (see https://arxiv.org/abs/1612.08083), where
+ the input `x` is split in two halves across a dimension (`axis`), A and B, returning A * sigmoid(B).
+
+ Args:
+ `x`: float Tensor to perform activation
+ `axis`: dimension across which `x` be split in half
+
+ Returns:
+ `x` with the GLU activation applied (with its size halved across the dimension `axis`).
+ """
+ a, b = tf.split(x, 2, axis=axis)
+ return a * tf.math.sigmoid(b)
+
+
+if parse(tf.version.VERSION) >= parse("2.4"):
+
+ def approximate_gelu_wrap(x):
+ return keras.activations.gelu(x, approximate=True)
+
+ gelu = keras.activations.gelu
+ gelu_new = approximate_gelu_wrap
+else:
+ gelu = _gelu
+ gelu_new = _gelu_new
+
+
+ACT2FN = {
+ "gelu": gelu,
+ "gelu_10": gelu_10,
+ "gelu_fast": gelu_fast,
+ "gelu_new": gelu_new,
+ "glu": glu,
+ "mish": mish,
+ "quick_gelu": quick_gelu,
+ "relu": keras.activations.relu,
+ "sigmoid": keras.activations.sigmoid,
+ "silu": keras.activations.swish,
+ "swish": keras.activations.swish,
+ "tanh": keras.activations.tanh,
+}
+
+
+def get_tf_activation(activation_string):
+ if activation_string in ACT2FN:
+ return ACT2FN[activation_string]
+ else:
+ raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACT2FN.keys())}")
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/__init__.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..70762c252a832882a53c1baf515c58356dffe1a1
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/__init__.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+# coding=utf-8
+
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ..utils import (
+ OptionalDependencyNotAvailable,
+ _LazyModule,
+ is_torch_available,
+)
+
+
+_import_structure = {
+ "agents": ["Agent", "CodeAgent", "ManagedAgent", "ReactAgent", "ReactCodeAgent", "ReactJsonAgent", "Toolbox"],
+ "llm_engine": ["HfApiEngine", "TransformersEngine"],
+ "monitoring": ["stream_to_gradio"],
+ "tools": ["PipelineTool", "Tool", "ToolCollection", "launch_gradio_demo", "load_tool", "tool"],
+}
+
+try:
+ if not is_torch_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ pass
+else:
+ _import_structure["default_tools"] = ["FinalAnswerTool", "PythonInterpreterTool"]
+ _import_structure["document_question_answering"] = ["DocumentQuestionAnsweringTool"]
+ _import_structure["image_question_answering"] = ["ImageQuestionAnsweringTool"]
+ _import_structure["search"] = ["DuckDuckGoSearchTool", "VisitWebpageTool"]
+ _import_structure["speech_to_text"] = ["SpeechToTextTool"]
+ _import_structure["text_to_speech"] = ["TextToSpeechTool"]
+ _import_structure["translation"] = ["TranslationTool"]
+
+if TYPE_CHECKING:
+ from .agents import Agent, CodeAgent, ManagedAgent, ReactAgent, ReactCodeAgent, ReactJsonAgent, Toolbox
+ from .llm_engine import HfApiEngine, TransformersEngine
+ from .monitoring import stream_to_gradio
+ from .tools import PipelineTool, Tool, ToolCollection, launch_gradio_demo, load_tool, tool
+
+ try:
+ if not is_torch_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ pass
+ else:
+ from .default_tools import FinalAnswerTool, PythonInterpreterTool
+ from .document_question_answering import DocumentQuestionAnsweringTool
+ from .image_question_answering import ImageQuestionAnsweringTool
+ from .search import DuckDuckGoSearchTool, VisitWebpageTool
+ from .speech_to_text import SpeechToTextTool
+ from .text_to_speech import TextToSpeechTool
+ from .translation import TranslationTool
+else:
+ import sys
+
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/agent_types.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/agent_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5be7462657c78ea9ddced08f0acff95fd63902a
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/agent_types.py
@@ -0,0 +1,260 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import os
+import pathlib
+import tempfile
+import uuid
+
+import numpy as np
+
+from ..utils import is_soundfile_availble, is_torch_available, is_vision_available, logging
+
+
+logger = logging.get_logger(__name__)
+
+if is_vision_available():
+ from PIL import Image
+ from PIL.Image import Image as ImageType
+else:
+ ImageType = object
+
+if is_torch_available():
+ import torch
+ from torch import Tensor
+else:
+ Tensor = object
+
+if is_soundfile_availble():
+ import soundfile as sf
+
+
+class AgentType:
+ """
+ Abstract class to be reimplemented to define types that can be returned by agents.
+
+ These objects serve three purposes:
+
+ - They behave as they were the type they're meant to be, e.g., a string for text, a PIL.Image for images
+ - They can be stringified: str(object) in order to return a string defining the object
+ - They should be displayed correctly in ipython notebooks/colab/jupyter
+ """
+
+ def __init__(self, value):
+ self._value = value
+
+ def __str__(self):
+ return self.to_string()
+
+ def to_raw(self):
+ logger.error(
+ "This is a raw AgentType of unknown type. Display in notebooks and string conversion will be unreliable"
+ )
+ return self._value
+
+ def to_string(self) -> str:
+ logger.error(
+ "This is a raw AgentType of unknown type. Display in notebooks and string conversion will be unreliable"
+ )
+ return str(self._value)
+
+
+class AgentText(AgentType, str):
+ """
+ Text type returned by the agent. Behaves as a string.
+ """
+
+ def to_raw(self):
+ return self._value
+
+ def to_string(self):
+ return str(self._value)
+
+
+class AgentImage(AgentType, ImageType):
+ """
+ Image type returned by the agent. Behaves as a PIL.Image.
+ """
+
+ def __init__(self, value):
+ AgentType.__init__(self, value)
+ ImageType.__init__(self)
+
+ if not is_vision_available():
+ raise ImportError("PIL must be installed in order to handle images.")
+
+ self._path = None
+ self._raw = None
+ self._tensor = None
+
+ if isinstance(value, ImageType):
+ self._raw = value
+ elif isinstance(value, (str, pathlib.Path)):
+ self._path = value
+ elif isinstance(value, torch.Tensor):
+ self._tensor = value
+ elif isinstance(value, np.ndarray):
+ self._tensor = torch.from_numpy(value)
+ else:
+ raise TypeError(f"Unsupported type for {self.__class__.__name__}: {type(value)}")
+
+ def _ipython_display_(self, include=None, exclude=None):
+ """
+ Displays correctly this type in an ipython notebook (ipython, colab, jupyter, ...)
+ """
+ from IPython.display import Image, display
+
+ display(Image(self.to_string()))
+
+ def to_raw(self):
+ """
+ Returns the "raw" version of that object. In the case of an AgentImage, it is a PIL.Image.
+ """
+ if self._raw is not None:
+ return self._raw
+
+ if self._path is not None:
+ self._raw = Image.open(self._path)
+ return self._raw
+
+ if self._tensor is not None:
+ array = self._tensor.cpu().detach().numpy()
+ return Image.fromarray((255 - array * 255).astype(np.uint8))
+
+ def to_string(self):
+ """
+ Returns the stringified version of that object. In the case of an AgentImage, it is a path to the serialized
+ version of the image.
+ """
+ if self._path is not None:
+ return self._path
+
+ if self._raw is not None:
+ directory = tempfile.mkdtemp()
+ self._path = os.path.join(directory, str(uuid.uuid4()) + ".png")
+ self._raw.save(self._path)
+ return self._path
+
+ if self._tensor is not None:
+ array = self._tensor.cpu().detach().numpy()
+
+ # There is likely simpler than load into image into save
+ img = Image.fromarray((255 - array * 255).astype(np.uint8))
+
+ directory = tempfile.mkdtemp()
+ self._path = os.path.join(directory, str(uuid.uuid4()) + ".png")
+
+ img.save(self._path)
+
+ return self._path
+
+ def save(self, output_bytes, format, **params):
+ """
+ Saves the image to a file.
+ Args:
+ output_bytes (bytes): The output bytes to save the image to.
+ format (str): The format to use for the output image. The format is the same as in PIL.Image.save.
+ **params: Additional parameters to pass to PIL.Image.save.
+ """
+ img = self.to_raw()
+ img.save(output_bytes, format, **params)
+
+
+class AgentAudio(AgentType, str):
+ """
+ Audio type returned by the agent.
+ """
+
+ def __init__(self, value, samplerate=16_000):
+ super().__init__(value)
+
+ if not is_soundfile_availble():
+ raise ImportError("soundfile must be installed in order to handle audio.")
+
+ self._path = None
+ self._tensor = None
+
+ self.samplerate = samplerate
+ if isinstance(value, (str, pathlib.Path)):
+ self._path = value
+ elif is_torch_available() and isinstance(value, torch.Tensor):
+ self._tensor = value
+ elif isinstance(value, tuple):
+ self.samplerate = value[0]
+ if isinstance(value[1], np.ndarray):
+ self._tensor = torch.from_numpy(value[1])
+ else:
+ self._tensor = torch.tensor(value[1])
+ else:
+ raise ValueError(f"Unsupported audio type: {type(value)}")
+
+ def _ipython_display_(self, include=None, exclude=None):
+ """
+ Displays correctly this type in an ipython notebook (ipython, colab, jupyter, ...)
+ """
+ from IPython.display import Audio, display
+
+ display(Audio(self.to_string(), rate=self.samplerate))
+
+ def to_raw(self):
+ """
+ Returns the "raw" version of that object. It is a `torch.Tensor` object.
+ """
+ if self._tensor is not None:
+ return self._tensor
+
+ if self._path is not None:
+ tensor, self.samplerate = sf.read(self._path)
+ self._tensor = torch.tensor(tensor)
+ return self._tensor
+
+ def to_string(self):
+ """
+ Returns the stringified version of that object. In the case of an AgentAudio, it is a path to the serialized
+ version of the audio.
+ """
+ if self._path is not None:
+ return self._path
+
+ if self._tensor is not None:
+ directory = tempfile.mkdtemp()
+ self._path = os.path.join(directory, str(uuid.uuid4()) + ".wav")
+ sf.write(self._path, self._tensor, samplerate=self.samplerate)
+ return self._path
+
+
+AGENT_TYPE_MAPPING = {"string": AgentText, "image": AgentImage, "audio": AgentAudio}
+INSTANCE_TYPE_MAPPING = {str: AgentText, ImageType: AgentImage}
+
+if is_torch_available():
+ INSTANCE_TYPE_MAPPING[Tensor] = AgentAudio
+
+
+def handle_agent_inputs(*args, **kwargs):
+ args = [(arg.to_raw() if isinstance(arg, AgentType) else arg) for arg in args]
+ kwargs = {k: (v.to_raw() if isinstance(v, AgentType) else v) for k, v in kwargs.items()}
+ return args, kwargs
+
+
+def handle_agent_outputs(output, output_type=None):
+ if output_type in AGENT_TYPE_MAPPING:
+ # If the class has defined outputs, we can map directly according to the class definition
+ decoded_outputs = AGENT_TYPE_MAPPING[output_type](output)
+ return decoded_outputs
+ else:
+ # If the class does not have defined output, then we map according to the type
+ for _k, _v in INSTANCE_TYPE_MAPPING.items():
+ if isinstance(output, _k):
+ return _v(output)
+ return output
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/agents.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/agents.py
new file mode 100644
index 0000000000000000000000000000000000000000..08c30d54fd43d5c9ffe142e90a41f5d09f26e969
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/agents.py
@@ -0,0 +1,1278 @@
+#!/usr/bin/env python
+# coding=utf-8
+
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import json
+import logging
+import re
+import time
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+
+from .. import is_torch_available
+from ..utils import logging as transformers_logging
+from ..utils.import_utils import is_pygments_available
+from .agent_types import AgentAudio, AgentImage
+from .default_tools import BASE_PYTHON_TOOLS, FinalAnswerTool, setup_default_tools
+from .llm_engine import HfApiEngine, MessageRole
+from .monitoring import Monitor
+from .prompts import (
+ DEFAULT_CODE_SYSTEM_PROMPT,
+ DEFAULT_REACT_CODE_SYSTEM_PROMPT,
+ DEFAULT_REACT_JSON_SYSTEM_PROMPT,
+ PLAN_UPDATE_FINAL_PLAN_REDACTION,
+ PROMPTS_FOR_INITIAL_PLAN,
+ PROMPTS_FOR_PLAN_UPDATE,
+ SUPPORTED_PLAN_TYPES,
+ SYSTEM_PROMPT_FACTS,
+ SYSTEM_PROMPT_FACTS_UPDATE,
+ USER_PROMPT_FACTS_UPDATE,
+)
+from .python_interpreter import LIST_SAFE_MODULES, evaluate_python_code
+from .tools import (
+ DEFAULT_TOOL_DESCRIPTION_TEMPLATE,
+ Tool,
+ get_tool_description_with_args,
+ load_tool,
+)
+
+
+if is_pygments_available():
+ from pygments import highlight
+ from pygments.formatters import Terminal256Formatter
+ from pygments.lexers import PythonLexer
+
+
+class CustomFormatter(logging.Formatter):
+ grey = "\x1b[38;20m"
+ bold_yellow = "\x1b[33;1m"
+ red = "\x1b[31;20m"
+ green = "\x1b[32;20m"
+ bold_green = "\x1b[32;20;1m"
+ bold_red = "\x1b[31;1m"
+ bold_white = "\x1b[37;1m"
+ orange = "\x1b[38;5;214m"
+ bold_orange = "\x1b[38;5;214;1m"
+ reset = "\x1b[0m"
+ format = "%(message)s"
+
+ FORMATS = {
+ logging.DEBUG: grey + format + reset,
+ logging.INFO: format,
+ logging.WARNING: bold_yellow + format + reset,
+ logging.ERROR: red + format + reset,
+ logging.CRITICAL: bold_red + format + reset,
+ 31: reset + format + reset,
+ 32: green + format + reset,
+ 33: bold_green + format + reset,
+ 34: bold_white + format + reset,
+ 35: orange + format + reset,
+ 36: bold_orange + format + reset,
+ }
+
+ def format(self, record):
+ log_fmt = self.FORMATS.get(record.levelno)
+ formatter = logging.Formatter(log_fmt)
+ return formatter.format(record)
+
+
+logger = transformers_logging.get_logger(__name__)
+logger.propagate = False
+ch = logging.StreamHandler()
+ch.setFormatter(CustomFormatter())
+logger.addHandler(ch)
+
+
+def parse_json_blob(json_blob: str) -> Dict[str, str]:
+ try:
+ first_accolade_index = json_blob.find("{")
+ last_accolade_index = [a.start() for a in list(re.finditer("}", json_blob))][-1]
+ json_blob = json_blob[first_accolade_index : last_accolade_index + 1].replace('\\"', "'")
+ json_data = json.loads(json_blob, strict=False)
+ return json_data
+ except json.JSONDecodeError as e:
+ place = e.pos
+ if json_blob[place - 1 : place + 2] == "},\n":
+ raise ValueError(
+ "JSON is invalid: you probably tried to provide multiple tool calls in one action. PROVIDE ONLY ONE TOOL CALL."
+ )
+ raise ValueError(
+ f"The JSON blob you used is invalid due to the following error: {e}.\n"
+ f"JSON blob was: {json_blob}, decoding failed on that specific part of the blob:\n"
+ f"'{json_blob[place-4:place+5]}'."
+ )
+ except Exception as e:
+ raise ValueError(f"Error in parsing the JSON blob: {e}")
+
+
+def parse_code_blob(code_blob: str) -> str:
+ try:
+ pattern = r"```(?:py|python)?\n(.*?)\n```"
+ match = re.search(pattern, code_blob, re.DOTALL)
+ return match.group(1).strip()
+ except Exception as e:
+ raise ValueError(
+ f"""
+The code blob you used is invalid: due to the following error: {e}
+This means that the regex pattern {pattern} was not respected: make sure to include code with the correct pattern, for instance:
+Thoughts: Your thoughts
+Code:
+```py
+# Your python code here
+```"""
+ )
+
+
+def parse_json_tool_call(json_blob: str) -> Tuple[str, Dict[str, str]]:
+ json_blob = json_blob.replace("```json", "").replace("```", "")
+ tool_call = parse_json_blob(json_blob)
+ if "action" in tool_call and "action_input" in tool_call:
+ return tool_call["action"], tool_call["action_input"]
+ elif "action" in tool_call:
+ return tool_call["action"], None
+ else:
+ raise ValueError(
+ f"Missing keys: {[key for key in ['action', 'action_input'] if key not in tool_call]} in blob {tool_call}"
+ )
+
+
+def parse_text_tool_call(text: str) -> Tuple[str, Union[str, Dict[str, str]]]:
+ """
+ Expects a text in the format: 'Action:', 'Action input:', 'Observation:'. 'Action input:' contains a json string with input arguments.
+ """
+ try:
+ if "Observation:" in text:
+ text = text.split("Observation:")[0]
+ if "Action:" in text:
+ text = text.split("Action:")[1]
+ tool_name, tool_input = text.split("Action input:")
+ if "{" in tool_input:
+ tool_input = parse_json_blob(tool_input)
+ else:
+ tool_input = tool_input.strip().replace('"', "")
+ return tool_name.strip().replace('"', "").replace("\\", ""), tool_input
+ except Exception as e:
+ raise ValueError(
+ f"Error in parsing the text tool call: {e}. Be sure to provide the correct format. DO NOT repeat your previous incorrect tool call."
+ )
+
+
+def to_text(input: Union[List[Dict[str, str]], Dict[str, str], str]) -> str:
+ if isinstance(input, list):
+ return "\n".join([m["content"] for m in input])
+ elif isinstance(input, dict):
+ return input["content"]
+ else:
+ return input
+
+
+HUGGINGFACE_DEFAULT_TOOLS = {}
+_tools_are_initialized = False
+
+
+class Toolbox:
+ """
+ The toolbox contains all tools that the agent can perform operations with, as well as a few methods to
+ manage them.
+
+ Args:
+ tools (`List[Tool]`):
+ The list of tools to instantiate the toolbox with
+ add_base_tools (`bool`, defaults to `False`, *optional*, defaults to `False`):
+ Whether to add the tools available within `transformers` to the toolbox.
+ """
+
+ def __init__(self, tools: List[Tool], add_base_tools: bool = False):
+ self._tools = {tool.name: tool for tool in tools}
+ if add_base_tools:
+ self.add_base_tools()
+ self._load_tools_if_needed()
+
+ def add_base_tools(self, add_python_interpreter: bool = False):
+ global _tools_are_initialized
+ global HUGGINGFACE_DEFAULT_TOOLS
+ if not _tools_are_initialized:
+ HUGGINGFACE_DEFAULT_TOOLS = setup_default_tools(logger)
+ _tools_are_initialized = True
+ for tool in HUGGINGFACE_DEFAULT_TOOLS.values():
+ if tool.name != "python_interpreter" or add_python_interpreter:
+ self.add_tool(tool)
+ self._load_tools_if_needed()
+
+ @property
+ def tools(self) -> Dict[str, Tool]:
+ """Get all tools currently in the toolbox"""
+ return self._tools
+
+ def show_tool_descriptions(self, tool_description_template: str = None) -> str:
+ """
+ Returns the description of all tools in the toolbox
+
+ Args:
+ tool_description_template (`str`, *optional*):
+ The template to use to describe the tools. If not provided, the default template will be used.
+ """
+ return "\n".join(
+ [get_tool_description_with_args(tool, tool_description_template) for tool in self._tools.values()]
+ )
+
+ def add_tool(self, tool: Tool):
+ """
+ Adds a tool to the toolbox
+
+ Args:
+ tool (`Tool`):
+ The tool to add to the toolbox.
+ """
+ if tool.name in self._tools:
+ raise KeyError(f"Error: tool '{tool.name}' already exists in the toolbox.")
+ self._tools[tool.name] = tool
+
+ def remove_tool(self, tool_name: str):
+ """
+ Removes a tool from the toolbox
+
+ Args:
+ tool_name (`str`):
+ The tool to remove from the toolbox.
+ """
+ if tool_name not in self._tools:
+ raise KeyError(
+ f"Error: tool {tool_name} not found in toolbox for removal, should be instead one of {list(self._tools.keys())}."
+ )
+ del self._tools[tool_name]
+
+ def update_tool(self, tool: Tool):
+ """
+ Updates a tool in the toolbox according to its name.
+
+ Args:
+ tool (`Tool`):
+ The tool to update to the toolbox.
+ """
+ if tool.name not in self._tools:
+ raise KeyError(
+ f"Error: tool {tool.name} not found in toolbox for update, should be instead one of {list(self._tools.keys())}."
+ )
+ self._tools[tool.name] = tool
+
+ def clear_toolbox(self):
+ """Clears the toolbox"""
+ self._tools = {}
+
+ def _load_tools_if_needed(self):
+ for name, tool in self._tools.items():
+ if not isinstance(tool, Tool):
+ task_or_repo_id = tool.task if tool.repo_id is None else tool.repo_id
+ self._tools[name] = load_tool(task_or_repo_id)
+
+ def __repr__(self):
+ toolbox_description = "Toolbox contents:\n"
+ for tool in self._tools.values():
+ toolbox_description += f"\t{tool.name}: {tool.description}\n"
+ return toolbox_description
+
+
+class AgentError(Exception):
+ """Base class for other agent-related exceptions"""
+
+ def __init__(self, message):
+ super().__init__(message)
+ self.message = message
+
+
+class AgentParsingError(AgentError):
+ """Exception raised for errors in parsing in the agent"""
+
+ pass
+
+
+class AgentExecutionError(AgentError):
+ """Exception raised for errors in execution in the agent"""
+
+ pass
+
+
+class AgentMaxIterationsError(AgentError):
+ """Exception raised for errors in execution in the agent"""
+
+ pass
+
+
+class AgentGenerationError(AgentError):
+ """Exception raised for errors in generation in the agent"""
+
+ pass
+
+
+def format_prompt_with_tools(toolbox: Toolbox, prompt_template: str, tool_description_template: str) -> str:
+ tool_descriptions = toolbox.show_tool_descriptions(tool_description_template)
+ prompt = prompt_template.replace("<>", tool_descriptions)
+
+ if "<>" in prompt:
+ tool_names = [f"'{tool_name}'" for tool_name in toolbox.tools.keys()]
+ prompt = prompt.replace("<>", ", ".join(tool_names))
+
+ return prompt
+
+
+def show_agents_descriptions(managed_agents: list):
+ managed_agents_descriptions = """
+You can also give requests to team members.
+Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaning your request.
+Given that this team member is a real human, you should be very verbose in your request.
+Here is a list of the team members that you can call:"""
+ for agent in managed_agents.values():
+ managed_agents_descriptions += f"\n- {agent.name}: {agent.description}"
+ return managed_agents_descriptions
+
+
+def format_prompt_with_managed_agents_descriptions(prompt_template, managed_agents=None) -> str:
+ if managed_agents is not None:
+ return prompt_template.replace("<>", show_agents_descriptions(managed_agents))
+ else:
+ return prompt_template.replace("<>", "")
+
+
+def format_prompt_with_imports(prompt_template: str, authorized_imports: List[str]) -> str:
+ if "<>" not in prompt_template:
+ raise AgentError("Tag '<>' should be provided in the prompt.")
+ return prompt_template.replace("<>", str(authorized_imports))
+
+
+class Agent:
+ def __init__(
+ self,
+ tools: Union[List[Tool], Toolbox],
+ llm_engine: Callable = None,
+ system_prompt: Optional[str] = None,
+ tool_description_template: Optional[str] = None,
+ additional_args: Dict = {},
+ max_iterations: int = 6,
+ tool_parser: Optional[Callable] = None,
+ add_base_tools: bool = False,
+ verbose: int = 0,
+ grammar: Optional[Dict[str, str]] = None,
+ managed_agents: Optional[List] = None,
+ step_callbacks: Optional[List[Callable]] = None,
+ monitor_metrics: bool = True,
+ ):
+ if system_prompt is None:
+ system_prompt = DEFAULT_REACT_CODE_SYSTEM_PROMPT
+ if tool_parser is None:
+ tool_parser = parse_json_tool_call
+ self.agent_name = self.__class__.__name__
+ self.llm_engine = llm_engine
+ self.system_prompt_template = system_prompt
+ self.tool_description_template = (
+ tool_description_template if tool_description_template else DEFAULT_TOOL_DESCRIPTION_TEMPLATE
+ )
+ self.additional_args = additional_args
+ self.max_iterations = max_iterations
+ self.logger = logger
+ self.tool_parser = tool_parser
+ self.grammar = grammar
+
+ self.managed_agents = None
+ if managed_agents is not None:
+ self.managed_agents = {agent.name: agent for agent in managed_agents}
+
+ if isinstance(tools, Toolbox):
+ self._toolbox = tools
+ if add_base_tools:
+ if not is_torch_available():
+ raise ImportError("Using the base tools requires torch to be installed.")
+
+ self._toolbox.add_base_tools(add_python_interpreter=(self.__class__ == ReactJsonAgent))
+ else:
+ self._toolbox = Toolbox(tools, add_base_tools=add_base_tools)
+ self._toolbox.add_tool(FinalAnswerTool())
+
+ self.system_prompt = format_prompt_with_tools(
+ self._toolbox, self.system_prompt_template, self.tool_description_template
+ )
+ self.system_prompt = format_prompt_with_managed_agents_descriptions(self.system_prompt, self.managed_agents)
+ self.prompt = None
+ self.logs = []
+ self.task = None
+
+ if verbose == 0:
+ logger.setLevel(logging.WARNING)
+ elif verbose == 1:
+ logger.setLevel(logging.INFO)
+ elif verbose == 2:
+ logger.setLevel(logging.DEBUG)
+
+ # Initialize step callbacks
+ self.step_callbacks = step_callbacks if step_callbacks is not None else []
+
+ # Initialize Monitor if monitor_metrics is True
+ self.monitor = None
+ if monitor_metrics:
+ self.monitor = Monitor(self.llm_engine)
+ self.step_callbacks.append(self.monitor.update_metrics)
+
+ @property
+ def toolbox(self) -> Toolbox:
+ """Get the toolbox currently available to the agent"""
+ return self._toolbox
+
+ def initialize_for_run(self):
+ self.token_count = 0
+ self.system_prompt = format_prompt_with_tools(
+ self._toolbox,
+ self.system_prompt_template,
+ self.tool_description_template,
+ )
+ self.system_prompt = format_prompt_with_managed_agents_descriptions(self.system_prompt, self.managed_agents)
+ if hasattr(self, "authorized_imports"):
+ self.system_prompt = format_prompt_with_imports(
+ self.system_prompt, list(set(LIST_SAFE_MODULES) | set(self.authorized_imports))
+ )
+ self.logs = [{"system_prompt": self.system_prompt, "task": self.task}]
+ self.logger.log(33, "======== New task ========")
+ self.logger.log(34, self.task)
+ self.logger.debug("System prompt is as follows:")
+ self.logger.debug(self.system_prompt)
+
+ def write_inner_memory_from_logs(self, summary_mode: Optional[bool] = False) -> List[Dict[str, str]]:
+ """
+ Reads past llm_outputs, actions, and observations or errors from the logs into a series of messages
+ that can be used as input to the LLM.
+ """
+ prompt_message = {"role": MessageRole.SYSTEM, "content": self.logs[0]["system_prompt"]}
+ task_message = {
+ "role": MessageRole.USER,
+ "content": "Task: " + self.logs[0]["task"],
+ }
+ if summary_mode:
+ memory = [task_message]
+ else:
+ memory = [prompt_message, task_message]
+ for i, step_log in enumerate(self.logs[1:]):
+ if "llm_output" in step_log and not summary_mode:
+ thought_message = {"role": MessageRole.ASSISTANT, "content": step_log["llm_output"].strip()}
+ memory.append(thought_message)
+ if "facts" in step_log:
+ thought_message = {
+ "role": MessageRole.ASSISTANT,
+ "content": "[FACTS LIST]:\n" + step_log["facts"].strip(),
+ }
+ memory.append(thought_message)
+
+ if "plan" in step_log and not summary_mode:
+ thought_message = {"role": MessageRole.ASSISTANT, "content": "[PLAN]:\n" + step_log["plan"].strip()}
+ memory.append(thought_message)
+
+ if "tool_call" in step_log and summary_mode:
+ tool_call_message = {
+ "role": MessageRole.ASSISTANT,
+ "content": f"[STEP {i} TOOL CALL]: " + str(step_log["tool_call"]).strip(),
+ }
+ memory.append(tool_call_message)
+
+ if "task" in step_log:
+ tool_call_message = {
+ "role": MessageRole.USER,
+ "content": "New task:\n" + step_log["task"],
+ }
+ memory.append(tool_call_message)
+
+ if "error" in step_log or "observation" in step_log:
+ if "error" in step_log:
+ message_content = (
+ f"[OUTPUT OF STEP {i}] -> Error:\n"
+ + str(step_log["error"])
+ + "\nNow let's retry: take care not to repeat previous errors! If you have retried several times, try a completely different approach.\n"
+ )
+ elif "observation" in step_log:
+ message_content = f"[OUTPUT OF STEP {i}] -> Observation:\n{step_log['observation']}"
+ tool_response_message = {"role": MessageRole.TOOL_RESPONSE, "content": message_content}
+ memory.append(tool_response_message)
+
+ return memory
+
+ def get_succinct_logs(self):
+ return [{key: value for key, value in log.items() if key != "agent_memory"} for log in self.logs]
+
+ def extract_action(self, llm_output: str, split_token: str) -> str:
+ """
+ Parse action from the LLM output
+
+ Args:
+ llm_output (`str`): Output of the LLM
+ split_token (`str`): Separator for the action. Should match the example in the system prompt.
+ """
+ try:
+ split = llm_output.split(split_token)
+ rationale, action = (
+ split[-2],
+ split[-1],
+ ) # NOTE: using indexes starting from the end solves for when you have more than one split_token in the output
+ except Exception as e:
+ self.logger.error(e, exc_info=1)
+ raise AgentParsingError(
+ f"Error: No '{split_token}' token provided in your output.\nYour output:\n{llm_output}\n. Be sure to include an action, prefaced with '{split_token}'!"
+ )
+ return rationale.strip(), action.strip()
+
+ def execute_tool_call(self, tool_name: str, arguments: Dict[str, str]) -> Any:
+ """
+ Execute tool with the provided input and returns the result.
+ This method replaces arguments with the actual values from the state if they refer to state variables.
+
+ Args:
+ tool_name (`str`): Name of the Tool to execute (should be one from self.toolbox).
+ arguments (Dict[str, str]): Arguments passed to the Tool.
+ """
+ available_tools = self.toolbox.tools
+ if self.managed_agents is not None:
+ available_tools = {**available_tools, **self.managed_agents}
+ if tool_name not in available_tools:
+ error_msg = f"Error: unknown tool {tool_name}, should be instead one of {list(available_tools.keys())}."
+ self.logger.error(error_msg, exc_info=1)
+ raise AgentExecutionError(error_msg)
+
+ try:
+ if isinstance(arguments, str):
+ observation = available_tools[tool_name](arguments)
+ elif isinstance(arguments, dict):
+ for key, value in arguments.items():
+ # if the value is the name of a state variable like "image.png", replace it with the actual value
+ if isinstance(value, str) and value in self.state:
+ arguments[key] = self.state[value]
+ observation = available_tools[tool_name](**arguments)
+ else:
+ raise AgentExecutionError(
+ f"Arguments passed to tool should be a dict or string: got a {type(arguments)}."
+ )
+ return observation
+ except Exception as e:
+ if tool_name in self.toolbox.tools:
+ raise AgentExecutionError(
+ f"Error in tool call execution: {e}\nYou should only use this tool with a correct input.\n"
+ f"As a reminder, this tool's description is the following:\n{get_tool_description_with_args(available_tools[tool_name])}"
+ )
+ elif tool_name in self.managed_agents:
+ raise AgentExecutionError(
+ f"Error in calling team member: {e}\nYou should only ask this team member with a correct request.\n"
+ f"As a reminder, this team member's description is the following:\n{available_tools[tool_name]}"
+ )
+
+ def log_rationale_code_action(self, rationale: str, code_action: str) -> None:
+ self.logger.warning("=== Agent thoughts:")
+ self.logger.log(31, rationale)
+ self.logger.warning(">>> Agent is executing the code below:")
+ if is_pygments_available():
+ self.logger.log(
+ 31, highlight(code_action, PythonLexer(ensurenl=False), Terminal256Formatter(style="nord"))
+ )
+ else:
+ self.logger.log(31, code_action)
+ self.logger.warning("====")
+
+ def run(self, **kwargs):
+ """To be implemented in the child class"""
+ raise NotImplementedError
+
+
+class CodeAgent(Agent):
+ """
+ A class for an agent that solves the given task using a single block of code. It plans all its actions, then executes all in one shot.
+ """
+
+ def __init__(
+ self,
+ tools: List[Tool],
+ llm_engine: Optional[Callable] = None,
+ system_prompt: Optional[str] = None,
+ tool_description_template: Optional[str] = None,
+ grammar: Optional[Dict[str, str]] = None,
+ additional_authorized_imports: Optional[List[str]] = None,
+ **kwargs,
+ ):
+ if llm_engine is None:
+ llm_engine = HfApiEngine()
+ if system_prompt is None:
+ system_prompt = DEFAULT_CODE_SYSTEM_PROMPT
+ if tool_description_template is None:
+ tool_description_template = DEFAULT_TOOL_DESCRIPTION_TEMPLATE
+ super().__init__(
+ tools=tools,
+ llm_engine=llm_engine,
+ system_prompt=system_prompt,
+ tool_description_template=tool_description_template,
+ grammar=grammar,
+ **kwargs,
+ )
+
+ if not is_pygments_available():
+ transformers_logging.warning_once(
+ logger,
+ "pygments isn't installed. Installing pygments will enable color syntax highlighting in the "
+ "CodeAgent.",
+ )
+
+ self.python_evaluator = evaluate_python_code
+ self.additional_authorized_imports = additional_authorized_imports if additional_authorized_imports else []
+ self.authorized_imports = list(set(LIST_SAFE_MODULES) | set(self.additional_authorized_imports))
+ self.system_prompt = self.system_prompt.replace("<>", str(self.authorized_imports))
+
+ def parse_code_blob(self, result: str) -> str:
+ """
+ Override this method if you want to change the way the code is
+ cleaned in the `run` method.
+ """
+ return parse_code_blob(result)
+
+ def run(self, task: str, return_generated_code: bool = False, **kwargs):
+ """
+ Runs the agent for the given task.
+
+ Args:
+ task (`str`): The task to perform
+ return_generated_code (`bool`, *optional*, defaults to `False`): Whether to return the generated code instead of running it
+ kwargs (additional keyword arguments, *optional*):
+ Any keyword argument to send to the agent when evaluating the code.
+
+ Example:
+
+ ```py
+ from transformers.agents import CodeAgent
+
+ agent = CodeAgent(tools=[])
+ agent.run("What is the result of 2 power 3.7384?")
+ ```
+ """
+ self.task = task
+ if len(kwargs) > 0:
+ self.task += f"\nYou have been provided with these initial arguments: {str(kwargs)}."
+ self.state = kwargs.copy()
+ self.initialize_for_run()
+
+ # Run LLM
+ prompt_message = {"role": MessageRole.SYSTEM, "content": self.system_prompt}
+ task_message = {
+ "role": MessageRole.USER,
+ "content": "Task: " + self.task,
+ }
+
+ self.prompt = [prompt_message, task_message]
+ self.logger.info("====Executing with this prompt====")
+ self.logger.info(self.prompt)
+
+ additional_args = {"grammar": self.grammar} if self.grammar is not None else {}
+ llm_output = self.llm_engine(self.prompt, stop_sequences=[""], **additional_args)
+
+ if return_generated_code:
+ return llm_output
+
+ # Parse
+ try:
+ rationale, code_action = self.extract_action(llm_output=llm_output, split_token="Code:")
+ except Exception as e:
+ self.logger.debug(
+ f"Error in extracting action, trying to parse the whole output as code. Error trace: {e}"
+ )
+ rationale, code_action = "", llm_output
+
+ try:
+ code_action = self.parse_code_blob(code_action)
+ except Exception as e:
+ error_msg = f"Error in code parsing: {e}. Be sure to provide correct code"
+ self.logger.error(error_msg, exc_info=1)
+ return error_msg
+
+ # Execute
+ self.log_rationale_code_action(rationale, code_action)
+ try:
+ available_tools = {**BASE_PYTHON_TOOLS.copy(), **self.toolbox.tools}
+ output = self.python_evaluator(
+ code_action,
+ static_tools=available_tools,
+ custom_tools={},
+ state=self.state,
+ authorized_imports=self.authorized_imports,
+ )
+ self.logger.info(self.state["print_outputs"])
+ return output
+ except Exception as e:
+ error_msg = f"Error in execution: {e}. Be sure to provide correct code."
+ self.logger.error(error_msg, exc_info=1)
+ return error_msg
+
+
+class ReactAgent(Agent):
+ """
+ This agent that solves the given task step by step, using the ReAct framework:
+ While the objective is not reached, the agent will perform a cycle of thinking and acting.
+ The action will be parsed from the LLM output: it consists in calls to tools from the toolbox, with arguments chosen by the LLM engine.
+ """
+
+ def __init__(
+ self,
+ tools: List[Tool],
+ llm_engine: Optional[Callable] = None,
+ system_prompt: Optional[str] = None,
+ tool_description_template: Optional[str] = None,
+ grammar: Optional[Dict[str, str]] = None,
+ plan_type: Optional[str] = None,
+ planning_interval: Optional[int] = None,
+ **kwargs,
+ ):
+ if llm_engine is None:
+ llm_engine = HfApiEngine()
+ if system_prompt is None:
+ system_prompt = DEFAULT_REACT_CODE_SYSTEM_PROMPT
+ if tool_description_template is None:
+ tool_description_template = DEFAULT_TOOL_DESCRIPTION_TEMPLATE
+ if plan_type is None:
+ plan_type = SUPPORTED_PLAN_TYPES[0]
+ else:
+ assert plan_type in SUPPORTED_PLAN_TYPES, f"plan type {plan_type} is not supported"
+ super().__init__(
+ tools=tools,
+ llm_engine=llm_engine,
+ system_prompt=system_prompt,
+ tool_description_template=tool_description_template,
+ grammar=grammar,
+ **kwargs,
+ )
+ self.planning_interval = planning_interval
+ self.plan_type = plan_type
+
+ def provide_final_answer(self, task) -> str:
+ """
+ This method provides a final answer to the task, based on the logs of the agent's interactions.
+ """
+ self.prompt = [
+ {
+ "role": MessageRole.SYSTEM,
+ "content": "An agent tried to answer an user query but it got stuck and failed to do so. You are tasked with providing an answer instead. Here is the agent's memory:",
+ }
+ ]
+ self.prompt += self.write_inner_memory_from_logs()[1:]
+ self.prompt += [
+ {
+ "role": MessageRole.USER,
+ "content": f"Based on the above, please provide an answer to the following user request:\n{task}",
+ }
+ ]
+ try:
+ return self.llm_engine(self.prompt)
+ except Exception as e:
+ return f"Error in generating final llm output: {e}."
+
+ def run(self, task: str, stream: bool = False, reset: bool = True, **kwargs):
+ """
+ Runs the agent for the given task.
+
+ Args:
+ task (`str`): The task to perform
+
+ Example:
+ ```py
+ from transformers.agents import ReactCodeAgent
+ agent = ReactCodeAgent(tools=[])
+ agent.run("What is the result of 2 power 3.7384?")
+ ```
+ """
+ self.task = task
+ if len(kwargs) > 0:
+ self.task += f"\nYou have been provided with these initial arguments: {str(kwargs)}."
+ self.state = kwargs.copy()
+ if reset:
+ self.initialize_for_run()
+ else:
+ self.logs.append({"task": task})
+ if stream:
+ return self.stream_run(task)
+ else:
+ return self.direct_run(task)
+
+ def stream_run(self, task: str):
+ """
+ Runs the agent in streaming mode, yielding steps as they are executed: should be launched only in the `run` method.
+ """
+ final_answer = None
+ iteration = 0
+ while final_answer is None and iteration < self.max_iterations:
+ step_start_time = time.time()
+ step_log_entry = {"iteration": iteration, "start_time": step_start_time}
+ try:
+ self.step(step_log_entry)
+ if "final_answer" in step_log_entry:
+ final_answer = step_log_entry["final_answer"]
+ except AgentError as e:
+ self.logger.error(e, exc_info=1)
+ step_log_entry["error"] = e
+ finally:
+ step_end_time = time.time()
+ step_log_entry["step_end_time"] = step_end_time
+ step_log_entry["step_duration"] = step_end_time - step_start_time
+ self.logs.append(step_log_entry)
+ for callback in self.step_callbacks:
+ callback(step_log_entry)
+ iteration += 1
+ yield step_log_entry
+
+ if final_answer is None and iteration == self.max_iterations:
+ error_message = "Reached max iterations."
+ final_step_log = {"error": AgentMaxIterationsError(error_message)}
+ self.logs.append(final_step_log)
+ self.logger.error(error_message, exc_info=1)
+ final_answer = self.provide_final_answer(task)
+ final_step_log["final_answer"] = final_answer
+ final_step_log["step_duration"] = 0
+ for callback in self.step_callbacks:
+ callback(final_step_log)
+ yield final_step_log
+
+ yield final_answer
+
+ def direct_run(self, task: str):
+ """
+ Runs the agent in direct mode, returning outputs only at the end: should be launched only in the `run` method.
+ """
+ final_answer = None
+ iteration = 0
+ while final_answer is None and iteration < self.max_iterations:
+ step_start_time = time.time()
+ step_log_entry = {"iteration": iteration, "start_time": step_start_time}
+ try:
+ if self.planning_interval is not None and iteration % self.planning_interval == 0:
+ self.planning_step(task, is_first_step=(iteration == 0), iteration=iteration)
+ self.step(step_log_entry)
+ if "final_answer" in step_log_entry:
+ final_answer = step_log_entry["final_answer"]
+ except AgentError as e:
+ self.logger.error(e, exc_info=1)
+ step_log_entry["error"] = e
+ finally:
+ step_end_time = time.time()
+ step_log_entry["step_end_time"] = step_end_time
+ step_log_entry["step_duration"] = step_end_time - step_start_time
+ self.logs.append(step_log_entry)
+ for callback in self.step_callbacks:
+ callback(step_log_entry)
+ iteration += 1
+
+ if final_answer is None and iteration == self.max_iterations:
+ error_message = "Reached max iterations."
+ final_step_log = {"error": AgentMaxIterationsError(error_message)}
+ self.logs.append(final_step_log)
+ self.logger.error(error_message, exc_info=1)
+ final_answer = self.provide_final_answer(task)
+ final_step_log["final_answer"] = final_answer
+ final_step_log["step_duration"] = 0
+ for callback in self.step_callbacks:
+ callback(final_step_log)
+
+ return final_answer
+
+ def planning_step(self, task, is_first_step: bool = False, iteration: int = None):
+ """
+ Used periodically by the agent to plan the next steps to reach the objective.
+
+ Args:
+ task (`str`): The task to perform
+ is_first_step (`bool`): If this step is not the first one, the plan should be an update over a previous plan.
+ iteration (`int`): The number of the current step, used as an indication for the LLM.
+ """
+ if is_first_step:
+ message_prompt_facts = {"role": MessageRole.SYSTEM, "content": SYSTEM_PROMPT_FACTS}
+ message_prompt_task = {
+ "role": MessageRole.USER,
+ "content": f"""Here is the task:
+```
+{task}
+```
+Now begin!""",
+ }
+
+ answer_facts = self.llm_engine([message_prompt_facts, message_prompt_task])
+
+ message_system_prompt_plan = {
+ "role": MessageRole.SYSTEM,
+ "content": PROMPTS_FOR_INITIAL_PLAN[self.plan_type]["system"],
+ }
+ message_user_prompt_plan = {
+ "role": MessageRole.USER,
+ "content": PROMPTS_FOR_INITIAL_PLAN[self.plan_type]["user"].format(
+ task=task,
+ tool_descriptions=self._toolbox.show_tool_descriptions(self.tool_description_template),
+ managed_agents_descriptions=(
+ show_agents_descriptions(self.managed_agents) if self.managed_agents is not None else ""
+ ),
+ answer_facts=answer_facts,
+ ),
+ }
+ answer_plan = self.llm_engine(
+ [message_system_prompt_plan, message_user_prompt_plan], stop_sequences=[""]
+ )
+
+ final_plan_redaction = f"""Here is the plan of action that I will follow to solve the task:
+```
+{answer_plan}
+```"""
+ final_facts_redaction = f"""Here are the facts that I know so far:
+```
+{answer_facts}
+```""".strip()
+ self.logs.append({"plan": final_plan_redaction, "facts": final_facts_redaction})
+ self.logger.log(36, "===== Initial plan =====")
+ self.logger.log(35, final_plan_redaction)
+ else: # update plan
+ agent_memory = self.write_inner_memory_from_logs(
+ summary_mode=False
+ ) # This will not log the plan but will log facts
+
+ # Redact updated facts
+ facts_update_system_prompt = {
+ "role": MessageRole.SYSTEM,
+ "content": SYSTEM_PROMPT_FACTS_UPDATE,
+ }
+ facts_update_message = {
+ "role": MessageRole.USER,
+ "content": USER_PROMPT_FACTS_UPDATE,
+ }
+ facts_update = self.llm_engine([facts_update_system_prompt] + agent_memory + [facts_update_message])
+
+ # Redact updated plan
+ plan_update_message = {
+ "role": MessageRole.SYSTEM,
+ "content": PROMPTS_FOR_PLAN_UPDATE[self.plan_type]["system"].format(task=task),
+ }
+ plan_update_message_user = {
+ "role": MessageRole.USER,
+ "content": PROMPTS_FOR_PLAN_UPDATE[self.plan_type]["user"].format(
+ task=task,
+ tool_descriptions=self._toolbox.show_tool_descriptions(self.tool_description_template),
+ managed_agents_descriptions=(
+ show_agents_descriptions(self.managed_agents) if self.managed_agents is not None else ""
+ ),
+ facts_update=facts_update,
+ remaining_steps=(self.max_iterations - iteration),
+ ),
+ }
+ plan_update = self.llm_engine(
+ [plan_update_message] + agent_memory + [plan_update_message_user], stop_sequences=[""]
+ )
+
+ # Log final facts and plan
+ final_plan_redaction = PLAN_UPDATE_FINAL_PLAN_REDACTION.format(task=task, plan_update=plan_update)
+ final_facts_redaction = f"""Here is the updated list of the facts that I know:
+```
+{facts_update}
+```"""
+ self.logs.append({"plan": final_plan_redaction, "facts": final_facts_redaction})
+ self.logger.log(36, "===== Updated plan =====")
+ self.logger.log(35, final_plan_redaction)
+
+
+class ReactJsonAgent(ReactAgent):
+ """
+ This agent that solves the given task step by step, using the ReAct framework:
+ While the objective is not reached, the agent will perform a cycle of thinking and acting.
+ The tool calls will be formulated by the LLM in JSON format, then parsed and executed.
+ """
+
+ def __init__(
+ self,
+ tools: List[Tool],
+ llm_engine: Optional[Callable] = None,
+ system_prompt: Optional[str] = None,
+ tool_description_template: Optional[str] = None,
+ grammar: Optional[Dict[str, str]] = None,
+ planning_interval: Optional[int] = None,
+ **kwargs,
+ ):
+ if llm_engine is None:
+ llm_engine = HfApiEngine()
+ if system_prompt is None:
+ system_prompt = DEFAULT_REACT_JSON_SYSTEM_PROMPT
+ if tool_description_template is None:
+ tool_description_template = DEFAULT_TOOL_DESCRIPTION_TEMPLATE
+ super().__init__(
+ tools=tools,
+ llm_engine=llm_engine,
+ system_prompt=system_prompt,
+ tool_description_template=tool_description_template,
+ grammar=grammar,
+ planning_interval=planning_interval,
+ **kwargs,
+ )
+
+ def step(self, log_entry: Dict[str, Any]):
+ """
+ Perform one step in the ReAct framework: the agent thinks, acts, and observes the result.
+ The errors are raised here, they are caught and logged in the run() method.
+ """
+ agent_memory = self.write_inner_memory_from_logs()
+
+ self.prompt = agent_memory
+ self.logger.debug("===== New step =====")
+
+ # Add new step in logs
+ log_entry["agent_memory"] = agent_memory.copy()
+
+ self.logger.info("===== Calling LLM with this last message: =====")
+ self.logger.info(self.prompt[-1])
+
+ try:
+ additional_args = {"grammar": self.grammar} if self.grammar is not None else {}
+ llm_output = self.llm_engine(
+ self.prompt, stop_sequences=["", "Observation:"], **additional_args
+ )
+ except Exception as e:
+ raise AgentGenerationError(f"Error in generating llm output: {e}.")
+ self.logger.debug("===== Output message of the LLM: =====")
+ self.logger.debug(llm_output)
+ log_entry["llm_output"] = llm_output
+
+ # Parse
+ self.logger.debug("===== Extracting action =====")
+ rationale, action = self.extract_action(llm_output=llm_output, split_token="Action:")
+
+ try:
+ tool_name, arguments = self.tool_parser(action)
+ except Exception as e:
+ raise AgentParsingError(f"Could not parse the given action: {e}.")
+
+ log_entry["rationale"] = rationale
+ log_entry["tool_call"] = {"tool_name": tool_name, "tool_arguments": arguments}
+
+ # Execute
+ self.logger.warning("=== Agent thoughts:")
+ self.logger.log(31, rationale)
+ self.logger.warning(f">>> Calling tool: '{tool_name}' with arguments: {arguments}")
+ if tool_name == "final_answer":
+ if isinstance(arguments, dict):
+ if "answer" in arguments:
+ answer = arguments["answer"]
+ if (
+ isinstance(answer, str) and answer in self.state.keys()
+ ): # if the answer is a state variable, return the value
+ answer = self.state[answer]
+ else:
+ answer = arguments
+ else:
+ answer = arguments
+ log_entry["final_answer"] = answer
+ return answer
+ else:
+ if arguments is None:
+ arguments = {}
+ observation = self.execute_tool_call(tool_name, arguments)
+ observation_type = type(observation)
+ if observation_type in [AgentImage, AgentAudio]:
+ if observation_type == AgentImage:
+ observation_name = "image.png"
+ elif observation_type == AgentAudio:
+ observation_name = "audio.mp3"
+ # TODO: observation naming could allow for different names of same type
+
+ self.state[observation_name] = observation
+ updated_information = f"Stored '{observation_name}' in memory."
+ else:
+ updated_information = str(observation).strip()
+ self.logger.info(updated_information)
+ log_entry["observation"] = updated_information
+ return log_entry
+
+
+class ReactCodeAgent(ReactAgent):
+ """
+ This agent that solves the given task step by step, using the ReAct framework:
+ While the objective is not reached, the agent will perform a cycle of thinking and acting.
+ The tool calls will be formulated by the LLM in code format, then parsed and executed.
+ """
+
+ def __init__(
+ self,
+ tools: List[Tool],
+ llm_engine: Optional[Callable] = None,
+ system_prompt: Optional[str] = None,
+ tool_description_template: Optional[str] = None,
+ grammar: Optional[Dict[str, str]] = None,
+ additional_authorized_imports: Optional[List[str]] = None,
+ planning_interval: Optional[int] = None,
+ **kwargs,
+ ):
+ if llm_engine is None:
+ llm_engine = HfApiEngine()
+ if system_prompt is None:
+ system_prompt = DEFAULT_REACT_CODE_SYSTEM_PROMPT
+ if tool_description_template is None:
+ tool_description_template = DEFAULT_TOOL_DESCRIPTION_TEMPLATE
+ super().__init__(
+ tools=tools,
+ llm_engine=llm_engine,
+ system_prompt=system_prompt,
+ tool_description_template=tool_description_template,
+ grammar=grammar,
+ planning_interval=planning_interval,
+ **kwargs,
+ )
+
+ if not is_pygments_available():
+ transformers_logging.warning_once(
+ logger,
+ "pygments isn't installed. Installing pygments will enable color syntax highlighting in the "
+ "ReactCodeAgent.",
+ )
+
+ self.python_evaluator = evaluate_python_code
+ self.additional_authorized_imports = additional_authorized_imports if additional_authorized_imports else []
+ self.authorized_imports = list(set(LIST_SAFE_MODULES) | set(self.additional_authorized_imports))
+ self.system_prompt = self.system_prompt.replace("<>", str(self.authorized_imports))
+ self.custom_tools = {}
+
+ def step(self, log_entry: Dict[str, Any]):
+ """
+ Perform one step in the ReAct framework: the agent thinks, acts, and observes the result.
+ The errors are raised here, they are caught and logged in the run() method.
+ """
+ agent_memory = self.write_inner_memory_from_logs()
+
+ self.prompt = agent_memory.copy()
+ self.logger.debug("===== New step =====")
+
+ # Add new step in logs
+ log_entry["agent_memory"] = agent_memory.copy()
+
+ self.logger.info("===== Calling LLM with these last messages: =====")
+ self.logger.info(self.prompt[-2:])
+
+ try:
+ additional_args = {"grammar": self.grammar} if self.grammar is not None else {}
+ llm_output = self.llm_engine(
+ self.prompt, stop_sequences=["", "Observation:"], **additional_args
+ )
+ except Exception as e:
+ raise AgentGenerationError(f"Error in generating llm output: {e}.")
+
+ self.logger.debug("=== Output message of the LLM:")
+ self.logger.debug(llm_output)
+ log_entry["llm_output"] = llm_output
+
+ # Parse
+ self.logger.debug("=== Extracting action ===")
+ try:
+ rationale, raw_code_action = self.extract_action(llm_output=llm_output, split_token="Code:")
+ except Exception as e:
+ self.logger.debug(f"Error in extracting action, trying to parse the whole output. Error trace: {e}")
+ rationale, raw_code_action = llm_output, llm_output
+
+ try:
+ code_action = parse_code_blob(raw_code_action)
+ except Exception as e:
+ error_msg = f"Error in code parsing: {e}. Make sure to provide correct code"
+ raise AgentParsingError(error_msg)
+
+ log_entry["rationale"] = rationale
+ log_entry["tool_call"] = {"tool_name": "code interpreter", "tool_arguments": code_action}
+
+ # Execute
+ self.log_rationale_code_action(rationale, code_action)
+ try:
+ static_tools = {
+ **BASE_PYTHON_TOOLS.copy(),
+ **self.toolbox.tools,
+ }
+ if self.managed_agents is not None:
+ static_tools = {**static_tools, **self.managed_agents}
+ result = self.python_evaluator(
+ code_action,
+ static_tools=static_tools,
+ custom_tools=self.custom_tools,
+ state=self.state,
+ authorized_imports=self.authorized_imports,
+ )
+ self.logger.warning("Print outputs:")
+ self.logger.log(32, self.state["print_outputs"])
+ observation = "Print outputs:\n" + self.state["print_outputs"]
+ if result is not None:
+ self.logger.warning("Last output from code snippet:")
+ self.logger.log(32, str(result))
+ observation += "Last output from code snippet:\n" + str(result)[:100000]
+ log_entry["observation"] = observation
+ except Exception as e:
+ error_msg = f"Code execution failed due to the following error:\n{str(e)}"
+ if "'dict' object has no attribute 'read'" in str(e):
+ error_msg += "\nYou get this error because you passed a dict as input for one of the arguments instead of a string."
+ raise AgentExecutionError(error_msg)
+ for line in code_action.split("\n"):
+ if line[: len("final_answer")] == "final_answer":
+ self.logger.log(33, "Final answer:")
+ self.logger.log(32, result)
+ log_entry["final_answer"] = result
+ return result
+
+
+LENGTH_TRUNCATE_REPORTS = 1000
+
+
+class ManagedAgent:
+ def __init__(self, agent, name, description, additional_prompting=None, provide_run_summary=False):
+ self.agent = agent
+ self.name = name
+ self.description = description
+ self.additional_prompting = additional_prompting
+ self.provide_run_summary = provide_run_summary
+
+ def write_full_task(self, task):
+ full_task = f"""You're a helpful agent named '{self.name}'.
+You have been submitted this task by your manager.
+---
+Task:
+{task}
+---
+You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible so that they have a clear understanding of the answer.
+
+Your final_answer WILL HAVE to contain these parts:
+### 1. Task outcome (short version):
+### 2. Task outcome (extremely detailed version):
+### 3. Additional context (if relevant):
+
+Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
+And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
+<>"""
+ if self.additional_prompting:
+ full_task = full_task.replace("\n<>", self.additional_prompting).strip()
+ else:
+ full_task = full_task.replace("\n<>", "").strip()
+ return full_task
+
+ def __call__(self, request, **kwargs):
+ full_task = self.write_full_task(request)
+ output = self.agent.run(full_task, **kwargs)
+ if self.provide_run_summary:
+ answer = f"Here is the final answer from your managed agent '{self.name}':\n"
+ answer += str(output)
+ answer += f"\n\nFor more detail, find below a summary of this agent's work:\nSUMMARY OF WORK FROM AGENT '{self.name}':\n"
+ for message in self.agent.write_inner_memory_from_logs(summary_mode=True):
+ content = message["content"]
+ if len(str(content)) < LENGTH_TRUNCATE_REPORTS or "[FACTS LIST]" in str(content):
+ answer += "\n" + str(content) + "\n---"
+ else:
+ answer += (
+ "\n"
+ + str(content)[:LENGTH_TRUNCATE_REPORTS]
+ + "\n(...Step was truncated because too long)...\n---"
+ )
+ answer += f"\nEND OF SUMMARY OF WORK FROM AGENT '{self.name}'."
+ return answer
+ else:
+ return output
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/default_tools.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/default_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..3946aa9f873503c9a9564da2d5e0dbba7773db89
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/default_tools.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python
+# coding=utf-8
+
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import importlib.util
+import json
+import math
+from dataclasses import dataclass
+from math import sqrt
+from typing import Dict
+
+from huggingface_hub import hf_hub_download, list_spaces
+
+from ..utils import is_offline_mode
+from .python_interpreter import LIST_SAFE_MODULES, evaluate_python_code
+from .tools import TOOL_CONFIG_FILE, TOOL_MAPPING, Tool
+
+
+def custom_print(*args):
+ return None
+
+
+BASE_PYTHON_TOOLS = {
+ "print": custom_print,
+ "isinstance": isinstance,
+ "range": range,
+ "float": float,
+ "int": int,
+ "bool": bool,
+ "str": str,
+ "set": set,
+ "list": list,
+ "dict": dict,
+ "tuple": tuple,
+ "round": round,
+ "ceil": math.ceil,
+ "floor": math.floor,
+ "log": math.log,
+ "exp": math.exp,
+ "sin": math.sin,
+ "cos": math.cos,
+ "tan": math.tan,
+ "asin": math.asin,
+ "acos": math.acos,
+ "atan": math.atan,
+ "atan2": math.atan2,
+ "degrees": math.degrees,
+ "radians": math.radians,
+ "pow": math.pow,
+ "sqrt": sqrt,
+ "len": len,
+ "sum": sum,
+ "max": max,
+ "min": min,
+ "abs": abs,
+ "enumerate": enumerate,
+ "zip": zip,
+ "reversed": reversed,
+ "sorted": sorted,
+ "all": all,
+ "any": any,
+ "map": map,
+ "filter": filter,
+ "ord": ord,
+ "chr": chr,
+ "next": next,
+ "iter": iter,
+ "divmod": divmod,
+ "callable": callable,
+ "getattr": getattr,
+ "hasattr": hasattr,
+ "setattr": setattr,
+ "issubclass": issubclass,
+ "type": type,
+}
+
+
+@dataclass
+class PreTool:
+ name: str
+ inputs: Dict[str, str]
+ output_type: type
+ task: str
+ description: str
+ repo_id: str
+
+
+HUGGINGFACE_DEFAULT_TOOLS_FROM_HUB = [
+ "image-transformation",
+ "text-to-image",
+]
+
+
+def get_remote_tools(logger, organization="huggingface-tools"):
+ if is_offline_mode():
+ logger.info("You are in offline mode, so remote tools are not available.")
+ return {}
+
+ spaces = list_spaces(author=organization)
+ tools = {}
+ for space_info in spaces:
+ repo_id = space_info.id
+ resolved_config_file = hf_hub_download(repo_id, TOOL_CONFIG_FILE, repo_type="space")
+ with open(resolved_config_file, encoding="utf-8") as reader:
+ config = json.load(reader)
+ task = repo_id.split("/")[-1]
+ tools[config["name"]] = PreTool(
+ task=task,
+ description=config["description"],
+ repo_id=repo_id,
+ name=task,
+ inputs=config["inputs"],
+ output_type=config["output_type"],
+ )
+
+ return tools
+
+
+def setup_default_tools(logger):
+ default_tools = {}
+ main_module = importlib.import_module("transformers")
+ tools_module = main_module.agents
+
+ for task_name, tool_class_name in TOOL_MAPPING.items():
+ tool_class = getattr(tools_module, tool_class_name)
+ tool_instance = tool_class()
+ default_tools[tool_class.name] = PreTool(
+ name=tool_instance.name,
+ inputs=tool_instance.inputs,
+ output_type=tool_instance.output_type,
+ task=task_name,
+ description=tool_instance.description,
+ repo_id=None,
+ )
+
+ return default_tools
+
+
+class PythonInterpreterTool(Tool):
+ name = "python_interpreter"
+ description = "This is a tool that evaluates python code. It can be used to perform calculations."
+
+ output_type = "string"
+
+ def __init__(self, *args, authorized_imports=None, **kwargs):
+ if authorized_imports is None:
+ self.authorized_imports = list(set(LIST_SAFE_MODULES))
+ else:
+ self.authorized_imports = list(set(LIST_SAFE_MODULES) | set(authorized_imports))
+ self.inputs = {
+ "code": {
+ "type": "string",
+ "description": (
+ "The code snippet to evaluate. All variables used in this snippet must be defined in this same snippet, "
+ f"else you will get an error. This code can only import the following python libraries: {authorized_imports}."
+ ),
+ }
+ }
+ super().__init__(*args, **kwargs)
+
+ def forward(self, code):
+ output = str(
+ evaluate_python_code(code, static_tools=BASE_PYTHON_TOOLS, authorized_imports=self.authorized_imports)
+ )
+ return output
+
+
+class FinalAnswerTool(Tool):
+ name = "final_answer"
+ description = "Provides a final answer to the given problem."
+ inputs = {"answer": {"type": "any", "description": "The final answer to the problem"}}
+ output_type = "any"
+
+ def forward(self, answer):
+ return answer
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/document_question_answering.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/document_question_answering.py
new file mode 100644
index 0000000000000000000000000000000000000000..23ae5b0429120dd6dd9c2eb7f454959c92625012
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/document_question_answering.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python
+# coding=utf-8
+
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import re
+
+import numpy as np
+import torch
+
+from ..models.auto import AutoProcessor
+from ..models.vision_encoder_decoder import VisionEncoderDecoderModel
+from ..utils import is_vision_available
+from .tools import PipelineTool
+
+
+if is_vision_available():
+ from PIL import Image
+
+
+class DocumentQuestionAnsweringTool(PipelineTool):
+ default_checkpoint = "naver-clova-ix/donut-base-finetuned-docvqa"
+ description = "This is a tool that answers a question about an document (pdf). It returns a string that contains the answer to the question."
+ name = "document_qa"
+ pre_processor_class = AutoProcessor
+ model_class = VisionEncoderDecoderModel
+
+ inputs = {
+ "document": {
+ "type": "image",
+ "description": "The image containing the information. Can be a PIL Image or a string path to the image.",
+ },
+ "question": {"type": "string", "description": "The question in English"},
+ }
+ output_type = "string"
+
+ def __init__(self, *args, **kwargs):
+ if not is_vision_available():
+ raise ValueError("Pillow must be installed to use the DocumentQuestionAnsweringTool.")
+
+ super().__init__(*args, **kwargs)
+
+ def encode(self, document: "Image", question: str):
+ task_prompt = "{user_input}"
+ prompt = task_prompt.replace("{user_input}", question)
+ decoder_input_ids = self.pre_processor.tokenizer(
+ prompt, add_special_tokens=False, return_tensors="pt"
+ ).input_ids
+ if isinstance(document, str):
+ img = Image.open(document).convert("RGB")
+ img_array = np.array(img).transpose(2, 0, 1)
+ document = torch.from_numpy(img_array)
+ pixel_values = self.pre_processor(document, return_tensors="pt").pixel_values
+
+ return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values}
+
+ def forward(self, inputs):
+ return self.model.generate(
+ inputs["pixel_values"].to(self.device),
+ decoder_input_ids=inputs["decoder_input_ids"].to(self.device),
+ max_length=self.model.decoder.config.max_position_embeddings,
+ early_stopping=True,
+ pad_token_id=self.pre_processor.tokenizer.pad_token_id,
+ eos_token_id=self.pre_processor.tokenizer.eos_token_id,
+ use_cache=True,
+ num_beams=1,
+ bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]],
+ return_dict_in_generate=True,
+ ).sequences
+
+ def decode(self, outputs):
+ sequence = self.pre_processor.batch_decode(outputs)[0]
+ sequence = sequence.replace(self.pre_processor.tokenizer.eos_token, "")
+ sequence = sequence.replace(self.pre_processor.tokenizer.pad_token, "")
+ sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token
+ sequence = self.pre_processor.token2json(sequence)
+
+ return sequence["answer"]
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/evaluate_agent.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/evaluate_agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..90dfd4ff0322b81e36e3d10733555488b3c94f5e
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/evaluate_agent.py
@@ -0,0 +1,414 @@
+#!/usr/bin/env python
+# coding=utf-8
+
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from .agents import BASE_PYTHON_TOOLS
+from .python_interpreter import InterpreterError, evaluate
+
+
+### Fake tools for test
+def classifier(text, labels):
+ return f"This is the classification of {text} along {labels}."
+
+
+def translator(text, src_lang, tgt_lang):
+ return f"This is the translation of {text} from {src_lang} to {tgt_lang}."
+
+
+def speaker(text):
+ return f"This is actually a sound reading {text}."
+
+
+def transcriber(audio):
+ if "sound" not in audio:
+ raise ValueError(f"`audio` ({audio}) is not a sound.")
+ return f"This is the transcribed text from {audio}."
+
+
+def image_generator(prompt):
+ return f"This is actually an image representing {prompt}."
+
+
+def image_captioner(image):
+ if "image" not in image:
+ raise ValueError(f"`image` ({image}) is not an image.")
+ return f"This is a description of {image}."
+
+
+def image_transformer(image, prompt):
+ if "image" not in image:
+ raise ValueError(f"`image` ({image}) is not an image.")
+ return f"This is a transformation of {image} according to {prompt}."
+
+
+def question_answerer(text, question):
+ return f"This is the answer to {question} from {text}."
+
+
+def image_qa(image, question):
+ if "image" not in image:
+ raise ValueError(f"`image` ({image}) is not an image.")
+ return f"This is the answer to {question} from {image}."
+
+
+def text_downloader(url):
+ return f"This is the content of {url}."
+
+
+def summarizer(text):
+ return f"This is a summary of {text}."
+
+
+def video_generator(prompt, seconds=2):
+ return f"A video of {prompt}"
+
+
+def document_qa(image, question):
+ return f"This is the answer to {question} from the document {image}."
+
+
+def image_segmenter(image, prompt):
+ return f"This is the mask of {prompt} in {image}"
+
+
+TEST_TOOLS = {
+ "text_classifier": classifier,
+ "translator": translator,
+ "text_reader": speaker,
+ "summarizer": summarizer,
+ "transcriber": transcriber,
+ "image_generator": image_generator,
+ "image_captioner": image_captioner,
+ "image_transformer": image_transformer,
+ "text_qa": question_answerer,
+ "text_downloader": text_downloader,
+ "image_qa": image_qa,
+ "video_generator": video_generator,
+ "document_qa": document_qa,
+ "image_segmenter": image_segmenter,
+}
+
+
+class Problem:
+ """
+ A class regrouping all the information to solve a problem on which we will evaluate agents.
+
+ Args:
+ task (`str` ou `list[str]`):
+ One or several descriptions of the task to perform. If a list, it should contain variations on the
+ phrasing, but for the same task.
+ inputs (`list[str]` or `dict[str, str]`):
+ The inputs that will be fed to the tools. For this testing environment, only strings are accepted as
+ values. Pass along a dictionary when you want to specify the values of each inputs, or just the list of
+ inputs expected (the value used will be `<>` in this case).
+ answer (`str` or `list[str]`):
+ The theoretical answer (or list of possible valid answers) to the problem, as code.
+ """
+
+ def __init__(self, task, inputs, answer):
+ self.task = task
+ self.inputs = inputs
+ self.answer = answer
+
+
+### The list of problems the agent will be evaluated on.
+EVALUATION_TASKS = [
+ Problem(
+ task=[
+ "Is the following `text` (in Spanish) positive or negative?",
+ "Is the text in the variable `text` (in Spanish) positive or negative?",
+ "Translate the following `text` from Spanish to English then tell me if its positive or negative.",
+ ],
+ inputs=["text"],
+ answer="""text_classifier(translator(text, src_lang="Spanish", tgt_lang="English"), labels=["positive", "negative"])""",
+ ),
+ Problem(
+ task=[
+ "Tell me out loud what the `image` contains.",
+ "Describe the following `image` out loud.",
+ "Find what is in the picture stored in `image` then read it out loud.",
+ ],
+ inputs=["image"],
+ answer=[
+ "text_reader(image_captioner(image))",
+ "text_reader(image_qa(image, question='What is in the image?'))",
+ ],
+ ),
+ Problem(
+ task=[
+ "Generate an image from the text given in `text_input`. Then transform it according to the text in `prompt`.",
+ "Use the following `text_input` to generate an image, then transform it by using the text in `prompt`.",
+ ],
+ inputs=["text_input", "prompt"],
+ answer="image_transformer(image_generator(text_input), prompt)",
+ ),
+ Problem(
+ task=[
+ "Download the content of `url`, summarize it then generate an image from its content.",
+ "Use a summary of the web page at `url` to generate an image.",
+ "Summarize the content of the web page at `url`, and use the result to generate an image.",
+ ],
+ inputs=["url"],
+ answer="image_generator(summarizer(text_downloader(url)))",
+ ),
+ Problem(
+ task=[
+ "Transform the following `image` using the prompt in `text`. The prompt is in Spanish.",
+ "Use the text prompt in `text` (in Spanish) to transform the following `image`.",
+ "Translate the `text` from Spanish to English then use it to transform the picture in `image`.",
+ ],
+ inputs=["text", "image"],
+ answer="image_transformer(image, translator(text, src_lang='Spanish', tgt_lang='English'))",
+ ),
+ Problem(
+ task=[
+ "Download the content of `url`, summarize it then read it out loud to me.",
+ "Read me a summary of the web page at `url`.",
+ ],
+ inputs=["url"],
+ answer="text_reader(summarizer(text_downloader(url)))",
+ ),
+ Problem(
+ task=[
+ "Generate an image from the text given in `text_input`.",
+ ],
+ inputs=["text_input"],
+ answer="image_generator(text_input)",
+ ),
+ Problem(
+ task=[
+ "Replace the beaver in the `image` by the `prompt`.",
+ "Transform the `image` so that it contains the `prompt`.",
+ "Use `prompt` to transform this `image`.",
+ ],
+ inputs=["image", "prompt"],
+ answer="image_transformer(image, prompt)",
+ ),
+ Problem(
+ task=[
+ "Provide me the summary of the `text`, then read it to me before transcribing it and translating it in French.",
+ "Summarize `text`, read it out loud then transcribe the audio and translate it in French.",
+ "Read me a summary of the `text` out loud. Transcribe this and translate it in French.",
+ ],
+ inputs=["text"],
+ answer="translator(transcriber(text_reader(summarizer(text))), src_lang='English', tgt_lang='French')",
+ ),
+ Problem(
+ task=["Generate a video of the `prompt`", "Animate a `prompt`", "Make me a short video using `prompt`."],
+ inputs={"prompt": "A lobster swimming"},
+ answer="video_generator('A lobster swimming')",
+ ),
+ Problem(
+ task=[
+ "Download the following file `url`, summarize it in a few words and generate a video from it."
+ "Fetch the file at this `url`, summarize it, and create an animation out of it."
+ ],
+ inputs=["url"],
+ answer="video_generator(summarizer(text_downloader(url)))",
+ ),
+]
+
+
+def get_theoretical_tools(agent_answer, theoretical_answer, code_answer):
+ if not isinstance(theoretical_answer, list):
+ return {name for name in TEST_TOOLS if name in code_answer}
+
+ if isinstance(agent_answer, dict):
+ for one_answer, one_code in zip(theoretical_answer, code_answer):
+ if one_answer in agent_answer.values():
+ return {name for name in TEST_TOOLS if name in one_code}
+
+ for one_answer, one_code in zip(theoretical_answer, code_answer):
+ if agent_answer == one_answer:
+ return {name for name in TEST_TOOLS if name in one_code}
+
+ return {name for name in TEST_TOOLS if name in code_answer[0]}
+
+
+def evaluate_code(code, inputs=None, state=None, verbose=False, return_interpretor_error=False):
+ tools = BASE_PYTHON_TOOLS.copy()
+ for name, tool in TEST_TOOLS.items():
+ if name not in code:
+ continue
+ tools[name] = tool
+
+ if isinstance(inputs, dict):
+ inputs = inputs.copy()
+ elif inputs is not None:
+ inputs = {inp: f"<<{inp}>>" for inp in inputs}
+
+ if state is not None:
+ state.update(inputs)
+ else:
+ state = inputs
+
+ try:
+ return evaluate(code, tools, state)
+ except InterpreterError as e:
+ return str(e)
+ except Exception as e:
+ if verbose:
+ print(e)
+ return None
+
+
+def score_code(agent_answer, theoretical_answer, verbose: bool = False):
+ if verbose:
+ print(agent_answer, theoretical_answer)
+ theoretical_answer = theoretical_answer if isinstance(theoretical_answer, list) else [theoretical_answer]
+
+ if agent_answer in theoretical_answer:
+ if verbose:
+ print("Perfect!")
+ return 1
+ elif isinstance(agent_answer, dict) and any(v in theoretical_answer for v in agent_answer.values()):
+ if verbose:
+ print("Almsot perfect, result in state!")
+ return 0.75
+ else:
+ if verbose:
+ print("Result is not the right one but code executed.")
+ return 0.3
+
+
+def evaluate_one_result(code, agent_answer, theoretical_answer, answer, verbose=False):
+ tools_in_code = {name for name in TEST_TOOLS if f"`{name}`" in code}
+ theoretical_tools = get_theoretical_tools(agent_answer, theoretical_answer, answer)
+ if tools_in_code == theoretical_tools:
+ tool_selection_score = 1.0
+ tool_selection_errors = None
+ else:
+ missing_tools = len(theoretical_tools - tools_in_code)
+ unexpected_tools = len(tools_in_code - theoretical_tools)
+ tool_selection_score = max(0, 1.0 - 0.25 * missing_tools - 0.25 * unexpected_tools)
+
+ tool_selection_errors = {
+ "selected_tools": tools_in_code,
+ "theoretical_tools": theoretical_tools,
+ }
+
+ tools_in_code = {name for name in TEST_TOOLS if name in code}
+ if tools_in_code == theoretical_tools:
+ tool_used_score = 1.0
+ tool_used_errors = None
+ else:
+ missing_tools = len(theoretical_tools - tools_in_code)
+ unexpected_tools = len(tools_in_code - theoretical_tools)
+ tool_used_score = max(0, 1.0 - 0.25 * missing_tools - 0.25 * unexpected_tools)
+
+ tool_used_errors = {
+ "selected_tools": tools_in_code,
+ "theoretical_tools": theoretical_tools,
+ }
+
+ score = score_code(agent_answer, theoretical_answer, verbose=verbose)
+ if score < 1.0:
+ code_errors = {
+ "code_produced": code,
+ "evaluation": agent_answer,
+ "theoretical_answer": theoretical_answer,
+ }
+ else:
+ code_errors = None
+
+ return (tool_selection_score, tool_used_score, score), (tool_selection_errors, tool_used_errors, code_errors)
+
+
+def evaluate_agent(agent, batch_size=8, verbose=False, return_errors=False):
+ """
+ Evaluates a new agent on all `EVALUATION_TASKS`.
+
+ Example:
+
+ ```py
+ agent = NewOpenAiAgent(model="text-davinci-003", api_key=your_api_key)
+ bads = new_evaluate_agent(agent)
+ for bad in bads:
+ print(bad)
+ ```
+ """
+ # Sanity check
+ agent_tools = set(agent.toolbox.keys())
+ if agent_tools != set(TEST_TOOLS):
+ missing_tools = set(TEST_TOOLS) - agent_tools
+ unexpected_tools = set(agent_tools) - TEST_TOOLS
+ raise ValueError(
+ f"Fix the test tools in the evaluate_agent module. Tools mising: {missing_tools}. Extra tools: {unexpected_tools}."
+ )
+
+ eval_tasks = []
+ eval_idx = []
+ for idx, pb in enumerate(EVALUATION_TASKS):
+ if isinstance(pb.task, list):
+ eval_tasks.extend(pb.task)
+ eval_idx.extend([idx] * len(pb.task))
+ else:
+ eval_tasks.append(pb.task)
+ eval_idx.append(idx)
+
+ tool_selection_score = 0
+ tool_used_score = 0
+ code_score = 0
+
+ if return_errors:
+ tool_selection_errors = {}
+ tool_used_errors = {}
+ code_errors = {}
+
+ for start_idx in range(0, len(eval_tasks), batch_size):
+ end_idx = min(start_idx + batch_size, len(eval_tasks))
+ batch_tasks = eval_tasks[start_idx:end_idx]
+
+ results = [agent.run(task, return_generated_code=True) for task in batch_tasks]
+
+ for idx, result in enumerate(results):
+ problem = EVALUATION_TASKS[eval_idx[start_idx + idx]]
+ if verbose:
+ print(f"====Task {start_idx + idx}====\n{batch_tasks[idx]}\n")
+ code = agent.extract_action(result, split_token="Answer:")
+
+ # Evaluate agent answer and code answer
+ agent_answer = evaluate_code(code, problem.inputs, verbose=verbose)
+ if isinstance(problem.answer, list):
+ theoretical_answer = [evaluate_code(answer, problem.inputs) for answer in problem.answer]
+ else:
+ theoretical_answer = evaluate_code(problem.answer, problem.inputs)
+
+ scores, errors = evaluate_one_result(
+ code, agent_answer, theoretical_answer, problem.answer, verbose=verbose
+ )
+
+ tool_selection_score += scores[0]
+ tool_used_score += scores[1]
+ code_score += scores[2]
+
+ if return_errors:
+ if errors[0] is not None:
+ tool_selection_errors[batch_tasks[idx]] = errors[0]
+ if errors[1] is not None:
+ tool_used_errors[batch_tasks[idx]] = errors[1]
+ if errors[2] is not None:
+ code_errors[batch_tasks[idx]] = errors[2]
+
+ scores = {
+ "tool selection score": 100 * (tool_selection_score / len(eval_tasks)),
+ "tool used score": 100 * (tool_used_score / len(eval_tasks)),
+ "code score": 100 * (code_score / len(eval_tasks)),
+ }
+
+ if return_errors:
+ return scores, tool_selection_errors, tool_used_errors, code_errors
+ else:
+ return scores
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/image_question_answering.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/image_question_answering.py
new file mode 100644
index 0000000000000000000000000000000000000000..de0efb7b6f380b899c396bc16e101c306b77f11f
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/image_question_answering.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+# coding=utf-8
+
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import torch
+from PIL import Image
+
+from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor
+from ..utils import requires_backends
+from .tools import PipelineTool
+
+
+class ImageQuestionAnsweringTool(PipelineTool):
+ default_checkpoint = "dandelin/vilt-b32-finetuned-vqa"
+ description = (
+ "This is a tool that answers a question about an image. It "
+ "returns a text that is the answer to the question."
+ )
+ name = "image_qa"
+ pre_processor_class = AutoProcessor
+ model_class = AutoModelForVisualQuestionAnswering
+
+ inputs = {
+ "image": {
+ "type": "image",
+ "description": "The image containing the information. Can be a PIL Image or a string path to the image.",
+ },
+ "question": {"type": "string", "description": "The question in English"},
+ }
+ output_type = "string"
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["vision"])
+ super().__init__(*args, **kwargs)
+
+ def encode(self, image: "Image", question: str):
+ return self.pre_processor(image, question, return_tensors="pt")
+
+ def forward(self, inputs):
+ with torch.no_grad():
+ return self.model(**inputs).logits
+
+ def decode(self, outputs):
+ idx = outputs.argmax(-1).item()
+ return self.model.config.id2label[idx]
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/llm_engine.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/llm_engine.py
new file mode 100644
index 0000000000000000000000000000000000000000..afa4d62d059e5b47863bcc84d8c5f542a70f2e2e
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/llm_engine.py
@@ -0,0 +1,238 @@
+#!/usr/bin/env python
+# coding=utf-8
+
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from copy import deepcopy
+from enum import Enum
+from typing import Dict, List, Optional
+
+from huggingface_hub import InferenceClient
+
+from .. import AutoTokenizer
+from ..pipelines.base import Pipeline
+from ..utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class MessageRole(str, Enum):
+ USER = "user"
+ ASSISTANT = "assistant"
+ SYSTEM = "system"
+ TOOL_CALL = "tool-call"
+ TOOL_RESPONSE = "tool-response"
+
+ @classmethod
+ def roles(cls):
+ return [r.value for r in cls]
+
+
+def get_clean_message_list(message_list: List[Dict[str, str]], role_conversions: Dict[str, str] = {}):
+ """
+ Subsequent messages with the same role will be concatenated to a single message.
+
+ Args:
+ message_list (`List[Dict[str, str]]`): List of chat messages.
+ """
+ final_message_list = []
+ message_list = deepcopy(message_list) # Avoid modifying the original list
+ for message in message_list:
+ if not set(message.keys()) == {"role", "content"}:
+ raise ValueError("Message should contain only 'role' and 'content' keys!")
+
+ role = message["role"]
+ if role not in MessageRole.roles():
+ raise ValueError(f"Incorrect role {role}, only {MessageRole.roles()} are supported for now.")
+
+ if role in role_conversions:
+ message["role"] = role_conversions[role]
+
+ if len(final_message_list) > 0 and message["role"] == final_message_list[-1]["role"]:
+ final_message_list[-1]["content"] += "\n=======\n" + message["content"]
+ else:
+ final_message_list.append(message)
+ return final_message_list
+
+
+llama_role_conversions = {
+ MessageRole.TOOL_RESPONSE: MessageRole.USER,
+}
+
+
+class HfEngine:
+ def __init__(self, model_id: Optional[str] = None):
+ self.last_input_token_count = None
+ self.last_output_token_count = None
+ if model_id is None:
+ model_id = "HuggingFaceTB/SmolLM2-1.7B-Instruct"
+ logger.warning(f"Using default model for token counting: '{model_id}'")
+ try:
+ self.tokenizer = AutoTokenizer.from_pretrained(model_id)
+ except Exception as e:
+ logger.warning(f"Failed to load tokenizer for model {model_id}: {e}. Loading default tokenizer instead.")
+ self.tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-1.7B-Instruct")
+
+ def get_token_counts(self):
+ return {
+ "input_token_count": self.last_input_token_count,
+ "output_token_count": self.last_output_token_count,
+ }
+
+ def generate(
+ self, messages: List[Dict[str, str]], stop_sequences: Optional[List[str]] = None, grammar: Optional[str] = None
+ ):
+ raise NotImplementedError
+
+ def __call__(
+ self, messages: List[Dict[str, str]], stop_sequences: Optional[List[str]] = None, grammar: Optional[str] = None
+ ) -> str:
+ """Process the input messages and return the model's response.
+
+ This method sends a list of messages to the Hugging Face Inference API, optionally with stop sequences and grammar customization.
+
+ Parameters:
+ messages (`List[Dict[str, str]]`):
+ A list of message dictionaries to be processed. Each dictionary should have the structure `{"role": "user/system", "content": "message content"}`.
+ stop_sequences (`List[str]`, *optional*):
+ A list of strings that will stop the generation if encountered in the model's output.
+ grammar (`str`, *optional*):
+ The grammar or formatting structure to use in the model's response.
+
+ Returns:
+ `str`: The text content of the model's response.
+
+ Example:
+ ```python
+ >>> engine = HfApiEngine(
+ ... model="meta-llama/Meta-Llama-3.1-8B-Instruct",
+ ... token="your_hf_token_here",
+ ... max_tokens=2000
+ ... )
+ >>> messages = [{"role": "user", "content": "Explain quantum mechanics in simple terms."}]
+ >>> response = engine(messages, stop_sequences=["END"])
+ >>> print(response)
+ "Quantum mechanics is the branch of physics that studies..."
+ ```
+ """
+ if not isinstance(messages, List):
+ raise ValueError("Messages should be a list of dictionaries with 'role' and 'content' keys.")
+ if stop_sequences is None:
+ stop_sequences = []
+ response = self.generate(messages, stop_sequences, grammar)
+ self.last_input_token_count = len(self.tokenizer.apply_chat_template(messages, tokenize=True))
+ self.last_output_token_count = len(self.tokenizer.encode(response))
+
+ # Remove stop sequences from LLM output
+ for stop_seq in stop_sequences:
+ if response[-len(stop_seq) :] == stop_seq:
+ response = response[: -len(stop_seq)]
+ return response
+
+
+class HfApiEngine(HfEngine):
+ """A class to interact with Hugging Face's Inference API for language model interaction.
+
+ This engine allows you to communicate with Hugging Face's models using the Inference API. It can be used in both serverless mode or with a dedicated endpoint, supporting features like stop sequences and grammar customization.
+
+ Parameters:
+ model (`str`, *optional*, defaults to `"meta-llama/Meta-Llama-3.1-8B-Instruct"`):
+ The Hugging Face model ID to be used for inference. This can be a path or model identifier from the Hugging Face model hub.
+ token (`str`, *optional*):
+ Token used by the Hugging Face API for authentication.
+ If not provided, the class will use the token stored in the Hugging Face CLI configuration.
+ max_tokens (`int`, *optional*, defaults to 1500):
+ The maximum number of tokens allowed in the output.
+ timeout (`int`, *optional*, defaults to 120):
+ Timeout for the API request, in seconds.
+
+ Raises:
+ ValueError:
+ If the model name is not provided.
+ """
+
+ def __init__(
+ self,
+ model: str = "meta-llama/Meta-Llama-3.1-8B-Instruct",
+ token: Optional[str] = None,
+ max_tokens: Optional[int] = 1500,
+ timeout: Optional[int] = 120,
+ ):
+ super().__init__(model_id=model)
+ self.model = model
+ self.client = InferenceClient(self.model, token=token, timeout=timeout)
+ self.max_tokens = max_tokens
+
+ def generate(
+ self, messages: List[Dict[str, str]], stop_sequences: Optional[List[str]] = None, grammar: Optional[str] = None
+ ) -> str:
+ # Get clean message list
+ messages = get_clean_message_list(messages, role_conversions=llama_role_conversions)
+
+ # Send messages to the Hugging Face Inference API
+ if grammar is not None:
+ response = self.client.chat_completion(
+ messages, stop=stop_sequences, max_tokens=self.max_tokens, response_format=grammar
+ )
+ else:
+ response = self.client.chat_completion(messages, stop=stop_sequences, max_tokens=self.max_tokens)
+
+ response = response.choices[0].message.content
+ return response
+
+
+class TransformersEngine(HfEngine):
+ """This engine uses a pre-initialized local text-generation pipeline."""
+
+ def __init__(self, pipeline: Pipeline, model_id: Optional[str] = None):
+ super().__init__(model_id)
+ self.pipeline = pipeline
+
+ def generate(
+ self,
+ messages: List[Dict[str, str]],
+ stop_sequences: Optional[List[str]] = None,
+ grammar: Optional[str] = None,
+ max_length: int = 1500,
+ ) -> str:
+ # Get clean message list
+ messages = get_clean_message_list(messages, role_conversions=llama_role_conversions)
+
+ # Get LLM output
+ if stop_sequences is not None and len(stop_sequences) > 0:
+ stop_strings = stop_sequences
+ else:
+ stop_strings = None
+
+ output = self.pipeline(
+ messages,
+ stop_strings=stop_strings,
+ max_length=max_length,
+ tokenizer=self.pipeline.tokenizer,
+ )
+
+ response = output[0]["generated_text"][-1]["content"]
+ return response
+
+
+DEFAULT_JSONAGENT_REGEX_GRAMMAR = {
+ "type": "regex",
+ "value": 'Thought: .+?\\nAction:\\n\\{\\n\\s{4}"action":\\s"[^"\\n]+",\\n\\s{4}"action_input":\\s"[^"\\n]+"\\n\\}\\n',
+}
+
+DEFAULT_CODEAGENT_REGEX_GRAMMAR = {
+ "type": "regex",
+ "value": "Thought: .+?\\nCode:\\n```(?:py|python)?\\n(?:.|\\s)+?\\n```",
+}
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/monitoring.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/monitoring.py
new file mode 100644
index 0000000000000000000000000000000000000000..7126e72b5fd0606fbb4bb6f7eff46e0ad0992abd
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/monitoring.py
@@ -0,0 +1,117 @@
+#!/usr/bin/env python
+# coding=utf-8
+
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from ..utils import logging
+from .agent_types import AgentAudio, AgentImage, AgentText
+
+
+logger = logging.get_logger(__name__)
+
+
+def pull_message(step_log: dict, test_mode: bool = True):
+ try:
+ from gradio import ChatMessage
+ except ImportError:
+ if test_mode:
+
+ class ChatMessage:
+ def __init__(self, role, content, metadata=None):
+ self.role = role
+ self.content = content
+ self.metadata = metadata
+ else:
+ raise ImportError("Gradio should be installed in order to launch a gradio demo.")
+
+ if step_log.get("rationale"):
+ yield ChatMessage(role="assistant", content=step_log["rationale"])
+ if step_log.get("tool_call"):
+ used_code = step_log["tool_call"]["tool_name"] == "code interpreter"
+ content = step_log["tool_call"]["tool_arguments"]
+ if used_code:
+ content = f"```py\n{content}\n```"
+ yield ChatMessage(
+ role="assistant",
+ metadata={"title": f"🛠️ Used tool {step_log['tool_call']['tool_name']}"},
+ content=str(content),
+ )
+ if step_log.get("observation"):
+ yield ChatMessage(role="assistant", content=f"```\n{step_log['observation']}\n```")
+ if step_log.get("error"):
+ yield ChatMessage(
+ role="assistant",
+ content=str(step_log["error"]),
+ metadata={"title": "💥 Error"},
+ )
+
+
+def stream_to_gradio(agent, task: str, test_mode: bool = False, **kwargs):
+ """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
+
+ try:
+ from gradio import ChatMessage
+ except ImportError:
+ if test_mode:
+
+ class ChatMessage:
+ def __init__(self, role, content, metadata=None):
+ self.role = role
+ self.content = content
+ self.metadata = metadata
+ else:
+ raise ImportError("Gradio should be installed in order to launch a gradio demo.")
+
+ for step_log in agent.run(task, stream=True, **kwargs):
+ if isinstance(step_log, dict):
+ for message in pull_message(step_log, test_mode=test_mode):
+ yield message
+
+ final_answer = step_log # Last log is the run's final_answer
+
+ if isinstance(final_answer, AgentText):
+ yield ChatMessage(role="assistant", content=f"**Final answer:**\n```\n{final_answer.to_string()}\n```")
+ elif isinstance(final_answer, AgentImage):
+ yield ChatMessage(
+ role="assistant",
+ content={"path": final_answer.to_string(), "mime_type": "image/png"},
+ )
+ elif isinstance(final_answer, AgentAudio):
+ yield ChatMessage(
+ role="assistant",
+ content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
+ )
+ else:
+ yield ChatMessage(role="assistant", content=str(final_answer))
+
+
+class Monitor:
+ def __init__(self, tracked_llm_engine):
+ self.step_durations = []
+ self.tracked_llm_engine = tracked_llm_engine
+ if getattr(self.tracked_llm_engine, "last_input_token_count", "Not found") != "Not found":
+ self.total_input_token_count = 0
+ self.total_output_token_count = 0
+
+ def update_metrics(self, step_log):
+ step_duration = step_log["step_duration"]
+ self.step_durations.append(step_duration)
+ logger.info(f"Step {len(self.step_durations)}:")
+ logger.info(f"- Time taken: {step_duration:.2f} seconds (valid only if step succeeded)")
+
+ if getattr(self.tracked_llm_engine, "last_input_token_count", None) is not None:
+ self.total_input_token_count += self.tracked_llm_engine.last_input_token_count
+ self.total_output_token_count += self.tracked_llm_engine.last_output_token_count
+ logger.info(f"- Input tokens: {self.total_input_token_count}")
+ logger.info(f"- Output tokens: {self.total_output_token_count}")
diff --git a/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/prompts.py b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/prompts.py
new file mode 100644
index 0000000000000000000000000000000000000000..0cf8beb144f8ba222125ee23ae1c206d1a84189b
--- /dev/null
+++ b/tasks/tasksmith-5dd11b34cce1/environment/source/src/transformers/agents/prompts.py
@@ -0,0 +1,789 @@
+#!/usr/bin/env python
+# coding=utf-8
+
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import re
+
+from ..utils import cached_file
+
+
+# docstyle-ignore
+CHAT_MESSAGE_PROMPT = """
+Human: <>
+
+Assistant: """
+
+
+DEFAULT_PROMPTS_REPO = "huggingface-tools/default-prompts"
+PROMPT_FILES = {"chat": "chat_prompt_template.txt", "run": "run_prompt_template.txt"}
+
+
+def download_prompt(prompt_or_repo_id, agent_name, mode="run"):
+ """
+ Downloads and caches the prompt from a repo and returns it contents (if necessary).
+ """
+ if prompt_or_repo_id is None:
+ prompt_or_repo_id = DEFAULT_PROMPTS_REPO
+
+ # prompt is considered a repo ID when it does not contain any kind of space
+ if re.search("\\s", prompt_or_repo_id) is not None:
+ return prompt_or_repo_id
+
+ prompt_file = cached_file(
+ prompt_or_repo_id, PROMPT_FILES[mode], repo_type="dataset", user_agent={"agent": agent_name}
+ )
+ with open(prompt_file, "r", encoding="utf-8") as f:
+ return f.read()
+
+
+DEFAULT_CODE_SYSTEM_PROMPT = """You will be given a task to solve, your job is to come up with a series of simple commands in Python that will perform the task.
+To help you, I will give you access to a set of tools that you can use. Each tool is a Python function and has a description explaining the task it performs, the inputs it expects and the outputs it returns.
+You should first explain which tool you will use to perform the task and for what reason, then write the code in Python.
+Each instruction in Python should be a simple assignment. You can print intermediate results if it makes sense to do so.
+In the end, use tool 'final_answer' to return your answer, its argument will be what gets returned.
+You can use imports in your code, but only from the following list of modules: <>
+Be sure to provide a 'Code:' token, else the run will fail.
+
+Tools:
+<>
+
+Examples:
+---
+Task: "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French."
+
+Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
+Code:
+```py
+translated_question = translator(question=question, src_lang="French", tgt_lang="English")
+print(f"The translated question is {translated_question}.")
+answer = image_qa(image=image, question=translated_question)
+final_answer(f"The answer is {answer}")
+```
+
+---
+Task: "Identify the oldest person in the `document` and create an image showcasing the result."
+
+Thought: I will use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
+Code:
+```py
+answer = document_qa(document, question="What is the oldest person?")
+print(f"The answer is {answer}.")
+image = image_generator(answer)
+final_answer(image)
+```
+
+---
+Task: "Generate an image using the text given in the variable `caption`."
+
+Thought: I will use the following tool: `image_generator` to generate an image.
+Code:
+```py
+image = image_generator(prompt=caption)
+final_answer(image)
+```
+
+---
+Task: "Summarize the text given in the variable `text` and read it out loud."
+
+Thought: I will use the following tools: `summarizer` to create a summary of the input text, then `text_reader` to read it out loud.
+Code:
+```py
+summarized_text = summarizer(text)
+print(f"Summary: {summarized_text}")
+audio_summary = text_reader(summarized_text)
+final_answer(audio_summary)
+```
+
+---
+Task: "Answer the question in the variable `question` about the text in the variable `text`. Use the answer to generate an image."
+
+Thought: I will use the following tools: `text_qa` to create the answer, then `image_generator` to generate an image according to the answer.
+Code:
+```py
+answer = text_qa(text=text, question=question)
+print(f"The answer is {answer}.")
+image = image_generator(answer)
+final_answer(image)
+```
+
+---
+Task: "Caption the following `image`."
+
+Thought: I will use the following tool: `image_captioner` to generate a caption for the image.
+Code:
+```py
+caption = image_captioner(image)
+final_answer(caption)
+```
+
+---
+Above example were using tools that might not exist for you. You only have access to these Tools:
+<>
+
+Remember to make sure that variables you use are all defined.
+Be sure to provide a 'Code:\n```' sequence before the code and '```' after, else you will get an error.
+DO NOT pass the arguments as a dict as in 'answer = ask_search_agent({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = ask_search_agent(query="What is the place where James Bond lives?")'.
+
+Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
+"""
+
+
+DEFAULT_REACT_JSON_SYSTEM_PROMPT = """You are an expert assistant who can solve any task using JSON tool calls. You will be given a task to solve as best you can.
+To do so, you have been given access to the following tools: <>
+The way you use the tools is by specifying a json blob, ending with ''.
+Specifically, this json should have an `action` key (name of the tool to use) and an `action_input` key (input to the tool).
+
+The $ACTION_JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. It should be formatted in json. Do not try to escape special characters. Here is the template of a valid $ACTION_JSON_BLOB:
+{
+ "action": $TOOL_NAME,
+ "action_input": $INPUT
+}
+
+Make sure to have the $INPUT as a dictionary in the right format for the tool you are using, and do not put variable names as input if you can find the right values.
+
+You should ALWAYS use the following format:
+
+Thought: you should always think about one action to take. Then use the action as follows:
+Action:
+$ACTION_JSON_BLOB
+Observation: the result of the action
+... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $ACTION_JSON_BLOB must only use a SINGLE action at a time.)
+
+You can use the result of the previous action as input for the next action.
+The observation will always be a string: it can represent a file, like "image_1.jpg".
+Then you can use it as input for the next action. You can do it for instance as follows:
+
+Observation: "image_1.jpg"
+
+Thought: I need to transform the image that I received in the previous observation to make it green.
+Action:
+{
+ "action": "image_transformer",
+ "action_input": {"image": "image_1.jpg"}
+}
+
+To provide the final answer to the task, use an action blob with "action": "final_answer" tool. It is the only way to complete the task, else you will be stuck on a loop. So your final output should look like this:
+Action:
+{
+ "action": "final_answer",
+ "action_input": {"answer": "insert your final answer here"}
+}
+
+
+Here are a few examples using notional tools:
+---
+Task: "Generate an image of the oldest person in this document."
+
+Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
+Action:
+{
+ "action": "document_qa",
+ "action_input": {"document": "document.pdf", "question": "Who is the oldest person mentioned?"}
+}
+Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
+
+
+Thought: I will now generate an image showcasing the oldest person.
+Action:
+{
+ "action": "image_generator",
+ "action_input": {"prompt": "A portrait of John Doe, a 55-year-old man living in Canada."}
+}
+Observation: "image.png"
+
+Thought: I will now return the generated image.
+Action:
+{
+ "action": "final_answer",
+ "action_input": "image.png"
+}
+
+---
+Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
+
+Thought: I will use python code evaluator to compute the result of the operation and then return the final answer using the `final_answer` tool
+Action:
+{
+ "action": "python_interpreter",
+ "action_input": {"code": "5 + 3 + 1294.678"}
+}
+Observation: 1302.678
+
+Thought: Now that I know the result, I will now return it.
+Action:
+{
+ "action": "final_answer",
+ "action_input": "1302.678"
+}
+
+---
+Task: "Which city has the highest population , Guangzhou or Shanghai?"
+
+Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.
+Action:
+{
+ "action": "search",
+ "action_input": "Population Guangzhou"
+}
+Observation: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
+
+
+Thought: Now let's get the population of Shanghai using the tool 'search'.
+Action:
+{
+ "action": "search",
+ "action_input": "Population Shanghai"
+}
+Observation: '26 million (2019)'
+
+Thought: Now I know that Shanghai has a larger population. Let's return the result.
+Action:
+{
+ "action": "final_answer",
+ "action_input": "Shanghai"
+}
+
+
+Above example were using notional tools that might not exist for you. You only have access to these tools:
+<>
+
+Here are the rules you should always follow to solve your task:
+1. ALWAYS provide a 'Thought:' sequence, and an 'Action:' sequence that ends with , else you will fail.
+2. Always use the right arguments for the tools. Never use variable names in the 'action_input' field, use the value instead.
+3. Call a tool only when needed: do not call the search agent if you do not need information, try to solve the task yourself.
+4. Never re-do a tool call that you previously did with the exact same parameters.
+
+Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
+"""
+
+
+DEFAULT_REACT_CODE_SYSTEM_PROMPT = """You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
+To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
+To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
+
+At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
+Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '' sequence.
+During each intermediate step, you can use 'print()' to save whatever important information you will then need.
+These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
+In the end you have to return a final answer using the `final_answer` tool.
+
+Here are a few examples using notional tools:
+---
+Task: "Generate an image of the oldest person in this document."
+
+Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
+Code:
+```py
+answer = document_qa(document=document, question="Who is the oldest person mentioned?")
+print(answer)
+```
+Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
+
+Thought: I will now generate an image showcasing the oldest person.
+Code:
+```py
+image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
+final_answer(image)
+```
+
+---
+Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
+
+Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
+Code:
+```py
+result = 5 + 3 + 1294.678
+final_answer(result)
+```
+
+---
+Task: "Which city has the highest population: Guangzhou or Shanghai?"
+
+Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.
+Code:
+```py
+population_guangzhou = search("Guangzhou population")
+print("Population Guangzhou:", population_guangzhou)
+population_shanghai = search("Shanghai population")
+print("Population Shanghai:", population_shanghai)
+```
+Observation:
+Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
+Population Shanghai: '26 million (2019)'
+
+Thought: Now I know that Shanghai has the highest population.
+Code:
+```py
+final_answer("Shanghai")
+```
+
+---
+Task: "What is the current age of the pope, raised to the power 0.36?"
+
+Thought: I will use the tool `wiki` to get the age of the pope, then raise it to the power 0.36.
+Code:
+```py
+pope_age = wiki(query="current pope age")
+print("Pope age:", pope_age)
+```
+Observation:
+Pope age: "The pope Francis is currently 85 years old."
+
+Thought: I know that the pope is 85 years old. Let's compute the result using python code.
+Code:
+```py
+pope_current_age = 85 ** 0.36
+final_answer(pope_current_age)
+```
+
+Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you have access to these tools (and no other tool):
+
+<>
+
+<>
+
+Here are the rules you should always follow to solve your task:
+1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```' sequence, else you will fail.
+2. Use only variables that you have defined!
+3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
+4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
+5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
+6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
+7. Never create any notional variables in our code, as having these in your logs might derail you from the true variables.
+8. You can use imports in your code, but only from the following list of modules: <>
+9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
+10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
+
+Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
+"""
+
+SYSTEM_PROMPT_FACTS = """Below I will present you a task.
+
+You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
+To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
+Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
+
+---
+### 1. Facts given in the task
+List here the specific facts given in the task that could help you (there might be nothing here).
+
+### 2. Facts to look up
+List here any facts that we may need to look up.
+Also list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.
+
+### 3. Facts to derive
+List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
+
+Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
+### 1. Facts given in the task
+### 2. Facts to look up
+### 3. Facts to derive
+Do not add anything else."""
+
+SYSTEM_PROMPT_PLAN = """You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
+
+Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
+This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
+Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
+After writing the final step of the plan, write the '\n' tag and stop there."""
+
+USER_PROMPT_PLAN = """
+Here is your task:
+
+Task:
+```
+{task}
+```
+
+Your plan can leverage any of these tools:
+{tool_descriptions}
+
+{managed_agents_descriptions}
+
+List of facts that you know:
+```
+{answer_facts}
+```
+
+Now begin! Write your plan below."""
+
+SYSTEM_PROMPT_FACTS_UPDATE = """
+You are a world expert at gathering known and unknown facts based on a conversation.
+Below you will find a task, and ahistory of attempts made to solve the task. You will have to produce a list of these:
+### 1. Facts given in the task
+### 2. Facts that we have learned
+### 3. Facts still to look up
+### 4. Facts still to derive
+Find the task and history below."""
+
+USER_PROMPT_FACTS_UPDATE = """Earlier we've built a list of facts.
+But since in your previous steps you may have learned useful new facts or invalidated some false ones.
+Please update your list of facts based on the previous history, and provide these headings:
+### 1. Facts given in the task
+### 2. Facts that we have learned
+### 3. Facts still to look up
+### 4. Facts still to derive
+
+Now write your new list of facts below."""
+
+SYSTEM_PROMPT_PLAN_UPDATE = """You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
+
+You have been given a task:
+```
+{task}
+```
+
+Find below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.
+If the previous tries so far have met some success, you can make an updated plan based on these actions.
+If you are stalled, you can make a completely new plan starting from scratch.
+"""
+
+USER_PROMPT_PLAN_UPDATE = """You're still working towards solving this task:
+```
+{task}
+```
+
+You have access to these tools and only these:
+{tool_descriptions}
+
+{managed_agents_descriptions}
+
+Here is the up to date list of facts that you know:
+```
+{facts_update}
+```
+
+Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
+This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
+Beware that you have {remaining_steps} steps remaining.
+Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
+After writing the final step of the plan, write the '\n' tag and stop there.
+
+Now write your new plan below."""
+
+SYSTEM_PROMPT_PLAN_STRUCTURED = """Output a step-by-step plan to solve the task using the given tools.
+This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer. Each step should be structured as follows:
+Step #n: {
+ "description":
+ "tool": ,
+ "params": {
+
+ }
+ "output_var":