AdithyaSK HF Staff commited on
Commit
67f382d
·
verified ·
1 Parent(s): baf061c

Stage Harbor release files 101001-101500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-f40a643a6ef9/environment/source/utils/extract_tests_from_mixin.py +61 -0
  2. tasks/tasksmith-f40a643a6ef9/environment/source/utils/fetch_latest_release_branch.py +73 -0
  3. tasks/tasksmith-f40a643a6ef9/environment/source/utils/fetch_torch_cuda_pipeline_test_matrix.py +99 -0
  4. tasks/tasksmith-f40a643a6ef9/environment/source/utils/get_modified_files.py +34 -0
  5. tasks/tasksmith-f40a643a6ef9/environment/source/utils/log_reports.py +139 -0
  6. tasks/tasksmith-f40a643a6ef9/environment/source/utils/notify_benchmarking_status.py +56 -0
  7. tasks/tasksmith-f40a643a6ef9/environment/source/utils/notify_community_pipelines_mirror.py +54 -0
  8. tasks/tasksmith-f40a643a6ef9/environment/source/utils/notify_slack_about_release.py +81 -0
  9. tasks/tasksmith-f40a643a6ef9/environment/source/utils/overwrite_expected_slice.py +90 -0
  10. tasks/tasksmith-f40a643a6ef9/environment/source/utils/print_env.py +52 -0
  11. tasks/tasksmith-f40a643a6ef9/environment/source/utils/release.py +162 -0
  12. tasks/tasksmith-f40a643a6ef9/environment/source/utils/stale.py +69 -0
  13. tasks/tasksmith-f40a643a6ef9/environment/source/utils/tests_fetcher.py +1128 -0
  14. tasks/tasksmith-f40a643a6ef9/environment/source/utils/update_metadata.py +125 -0
  15. tasks/tasksmith-f40a643a6ef9/instruction.md +30 -0
  16. tasks/tasksmith-f40a643a6ef9/solution/reference/examples/dreambooth/train_dreambooth_lora_hidream.py +1721 -0
  17. tasks/tasksmith-f40a643a6ef9/solution/reference/src/diffusers/loaders/__init__.py +131 -0
  18. tasks/tasksmith-f40a643a6ef9/solution/reference/src/diffusers/loaders/lora_pipeline.py +0 -0
  19. tasks/tasksmith-f40a643a6ef9/solution/reference/src/diffusers/loaders/peft.py +862 -0
  20. tasks/tasksmith-f40a643a6ef9/solution/reference/src/diffusers/models/transformers/transformer_hidream_image.py +942 -0
  21. tasks/tasksmith-f40a643a6ef9/solution/reference/src/diffusers/pipelines/hidream_image/pipeline_hidream_image.py +1012 -0
  22. tasks/tasksmith-f40a643a6ef9/solution/solve.sh +14 -0
  23. tasks/tasksmith-f40a643a6ef9/task.toml +128 -0
  24. tasks/tasksmith-f40a643a6ef9/tests/Dockerfile +12 -0
  25. tasks/tasksmith-f40a643a6ef9/tests/contract.json +647 -0
  26. tasks/tasksmith-f40a643a6ef9/tests/grade.py +188 -0
  27. tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml +110 -0
  28. tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/config.yml +4 -0
  29. tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/feature_request.md +20 -0
  30. tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/feedback.md +12 -0
  31. tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/new-model-addition.yml +31 -0
  32. tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/remote-vae-pilot-feedback.yml +38 -0
  33. tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/translate.md +29 -0
  34. tasks/tasksmith-f40a643a6ef9/tests/source/.github/PULL_REQUEST_TEMPLATE.md +61 -0
  35. tasks/tasksmith-f40a643a6ef9/tests/source/.github/actions/setup-miniconda/action.yml +146 -0
  36. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/benchmark.yml +68 -0
  37. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/build_docker_images.yml +104 -0
  38. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/build_documentation.yml +27 -0
  39. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/build_pr_documentation.yml +23 -0
  40. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/mirror_community_pipeline.yml +102 -0
  41. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/nightly_tests.yml +593 -0
  42. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/notify_slack_about_release.yml +23 -0
  43. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_dependency_test.yml +35 -0
  44. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_flax_dependency_test.yml +38 -0
  45. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_style_bot.yml +17 -0
  46. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_test_fetcher.yml +177 -0
  47. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_tests.yml +302 -0
  48. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_tests_gpu.yml +296 -0
  49. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_torch_dependency_test.yml +36 -0
  50. tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/push_tests.yml +390 -0
tasks/tasksmith-f40a643a6ef9/environment/source/utils/extract_tests_from_mixin.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import inspect
3
+ import sys
4
+ from pathlib import Path
5
+ from typing import List, Type
6
+
7
+
8
+ root_dir = Path(__file__).parent.parent.absolute()
9
+ sys.path.insert(0, str(root_dir))
10
+
11
+ parser = argparse.ArgumentParser()
12
+ parser.add_argument("--type", type=str, default=None)
13
+ args = parser.parse_args()
14
+
15
+
16
+ def get_test_methods_from_class(cls: Type) -> List[str]:
17
+ """
18
+ Get all test method names from a given class.
19
+ Only returns methods that start with 'test_'.
20
+ """
21
+ test_methods = []
22
+ for name, obj in inspect.getmembers(cls):
23
+ if name.startswith("test_") and inspect.isfunction(obj):
24
+ test_methods.append(name)
25
+ return sorted(test_methods)
26
+
27
+
28
+ def generate_pytest_pattern(test_methods: List[str]) -> str:
29
+ """Generate pytest pattern string for the -k flag."""
30
+ return " or ".join(test_methods)
31
+
32
+
33
+ def generate_pattern_for_mixin(mixin_class: Type) -> str:
34
+ """
35
+ Generate pytest pattern for a specific mixin class.
36
+ """
37
+ if mixin_cls is None:
38
+ return ""
39
+ test_methods = get_test_methods_from_class(mixin_class)
40
+ return generate_pytest_pattern(test_methods)
41
+
42
+
43
+ if __name__ == "__main__":
44
+ mixin_cls = None
45
+ if args.type == "pipeline":
46
+ from tests.pipelines.test_pipelines_common import PipelineTesterMixin
47
+
48
+ mixin_cls = PipelineTesterMixin
49
+
50
+ elif args.type == "models":
51
+ from tests.models.test_modeling_common import ModelTesterMixin
52
+
53
+ mixin_cls = ModelTesterMixin
54
+
55
+ elif args.type == "lora":
56
+ from tests.lora.utils import PeftLoraLoaderMixinTests
57
+
58
+ mixin_cls = PeftLoraLoaderMixinTests
59
+
60
+ pattern = generate_pattern_for_mixin(mixin_cls)
61
+ print(pattern)
tasks/tasksmith-f40a643a6ef9/environment/source/utils/fetch_latest_release_branch.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ import requests
18
+ from packaging.version import parse
19
+
20
+
21
+ # GitHub repository details
22
+ USER = "huggingface"
23
+ REPO = "diffusers"
24
+
25
+
26
+ def fetch_all_branches(user, repo):
27
+ branches = [] # List to store all branches
28
+ page = 1 # Start from first page
29
+ while True:
30
+ # Make a request to the GitHub API for the branches
31
+ response = requests.get(
32
+ f"https://api.github.com/repos/{user}/{repo}/branches",
33
+ params={"page": page},
34
+ timeout=60,
35
+ )
36
+
37
+ # Check if the request was successful
38
+ if response.status_code == 200:
39
+ # Add the branches from the current page to the list
40
+ branches.extend([branch["name"] for branch in response.json()])
41
+
42
+ # Check if there is a 'next' link for pagination
43
+ if "next" in response.links:
44
+ page += 1 # Move to the next page
45
+ else:
46
+ break # Exit loop if there is no next page
47
+ else:
48
+ print("Failed to retrieve branches:", response.status_code)
49
+ break
50
+
51
+ return branches
52
+
53
+
54
+ def main():
55
+ # Fetch all branches
56
+ branches = fetch_all_branches(USER, REPO)
57
+
58
+ # Filter branches.
59
+ # print(f"Total branches: {len(branches)}")
60
+ filtered_branches = []
61
+ for branch in branches:
62
+ if branch.startswith("v") and ("-release" in branch or "-patch" in branch):
63
+ filtered_branches.append(branch)
64
+ # print(f"Filtered: {branch}")
65
+
66
+ sorted_branches = sorted(filtered_branches, key=lambda x: parse(x.split("-")[0][1:]), reverse=True)
67
+ latest_branch = sorted_branches[0]
68
+ # print(f"Latest branch: {latest_branch}")
69
+ return latest_branch
70
+
71
+
72
+ if __name__ == "__main__":
73
+ print(main())
tasks/tasksmith-f40a643a6ef9/environment/source/utils/fetch_torch_cuda_pipeline_test_matrix.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ from collections import defaultdict
5
+ from pathlib import Path
6
+
7
+ from huggingface_hub import HfApi
8
+
9
+ import diffusers
10
+
11
+
12
+ PATH_TO_REPO = Path(__file__).parent.parent.resolve()
13
+ ALWAYS_TEST_PIPELINE_MODULES = [
14
+ "controlnet",
15
+ "controlnet_flux",
16
+ "controlnet_sd3",
17
+ "stable_diffusion",
18
+ "stable_diffusion_2",
19
+ "stable_diffusion_3",
20
+ "stable_diffusion_xl",
21
+ "ip_adapters",
22
+ "flux",
23
+ ]
24
+ PIPELINE_USAGE_CUTOFF = int(os.getenv("PIPELINE_USAGE_CUTOFF", 50000))
25
+
26
+ logger = logging.getLogger(__name__)
27
+ api = HfApi()
28
+
29
+
30
+ def filter_pipelines(usage_dict, usage_cutoff=10000):
31
+ output = []
32
+ for diffusers_object, usage in usage_dict.items():
33
+ if usage < usage_cutoff:
34
+ continue
35
+
36
+ is_diffusers_pipeline = hasattr(diffusers.pipelines, diffusers_object)
37
+ if not is_diffusers_pipeline:
38
+ continue
39
+
40
+ output.append(diffusers_object)
41
+
42
+ return output
43
+
44
+
45
+ def fetch_pipeline_objects():
46
+ models = api.list_models(library="diffusers")
47
+ downloads = defaultdict(int)
48
+
49
+ for model in models:
50
+ is_counted = False
51
+ for tag in model.tags:
52
+ if tag.startswith("diffusers:"):
53
+ is_counted = True
54
+ downloads[tag[len("diffusers:") :]] += model.downloads
55
+
56
+ if not is_counted:
57
+ downloads["other"] += model.downloads
58
+
59
+ # Remove 0 downloads
60
+ downloads = {k: v for k, v in downloads.items() if v > 0}
61
+ pipeline_objects = filter_pipelines(downloads, PIPELINE_USAGE_CUTOFF)
62
+
63
+ return pipeline_objects
64
+
65
+
66
+ def fetch_pipeline_modules_to_test():
67
+ try:
68
+ pipeline_objects = fetch_pipeline_objects()
69
+ except Exception as e:
70
+ logger.error(e)
71
+ raise RuntimeError("Unable to fetch model list from HuggingFace Hub.")
72
+
73
+ test_modules = []
74
+ for pipeline_name in pipeline_objects:
75
+ module = getattr(diffusers, pipeline_name)
76
+
77
+ test_module = module.__module__.split(".")[-2].strip()
78
+ test_modules.append(test_module)
79
+
80
+ return test_modules
81
+
82
+
83
+ def main():
84
+ test_modules = fetch_pipeline_modules_to_test()
85
+ test_modules.extend(ALWAYS_TEST_PIPELINE_MODULES)
86
+
87
+ # Get unique modules
88
+ test_modules = sorted(set(test_modules))
89
+ print(json.dumps(test_modules))
90
+
91
+ save_path = f"{PATH_TO_REPO}/reports"
92
+ os.makedirs(save_path, exist_ok=True)
93
+
94
+ with open(f"{save_path}/test-pipelines.json", "w") as f:
95
+ json.dump({"pipeline_test_modules": test_modules}, f)
96
+
97
+
98
+ if __name__ == "__main__":
99
+ main()
tasks/tasksmith-f40a643a6ef9/environment/source/utils/get_modified_files.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.:
17
+ # python ./utils/get_modified_files.py utils src tests examples
18
+ #
19
+ # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered
20
+ # since the output of this script is fed into Makefile commands it doesn't print a newline after the results
21
+
22
+ import re
23
+ import subprocess
24
+ import sys
25
+
26
+
27
+ fork_point_sha = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8")
28
+ modified_files = subprocess.check_output(f"git diff --name-only {fork_point_sha}".split()).decode("utf-8").split()
29
+
30
+ joined_dirs = "|".join(sys.argv[1:])
31
+ regex = re.compile(rf"^({joined_dirs}).*?\.py$")
32
+
33
+ relevant_modified_files = [x for x in modified_files if regex.match(x)]
34
+ print(" ".join(relevant_modified_files), end="")
tasks/tasksmith-f40a643a6ef9/environment/source/utils/log_reports.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ from datetime import date
5
+ from pathlib import Path
6
+
7
+ from slack_sdk import WebClient
8
+ from tabulate import tabulate
9
+
10
+
11
+ MAX_LEN_MESSAGE = 2900 # slack endpoint has a limit of 3001 characters
12
+
13
+ parser = argparse.ArgumentParser()
14
+ parser.add_argument("--slack_channel_name", default="diffusers-ci-nightly")
15
+
16
+
17
+ def main(slack_channel_name=None):
18
+ failed = []
19
+ passed = []
20
+
21
+ group_info = []
22
+
23
+ total_num_failed = 0
24
+ empty_file = False or len(list(Path().glob("*.log"))) == 0
25
+
26
+ total_empty_files = []
27
+
28
+ for log in Path().glob("*.log"):
29
+ section_num_failed = 0
30
+ i = 0
31
+ with open(log) as f:
32
+ for line in f:
33
+ line = json.loads(line)
34
+ i += 1
35
+ if line.get("nodeid", "") != "":
36
+ test = line["nodeid"]
37
+ if line.get("duration", None) is not None:
38
+ duration = f"{line['duration']:.4f}"
39
+ if line.get("outcome", "") == "failed":
40
+ section_num_failed += 1
41
+ failed.append([test, duration, log.name.split("_")[0]])
42
+ total_num_failed += 1
43
+ else:
44
+ passed.append([test, duration, log.name.split("_")[0]])
45
+ empty_file = i == 0
46
+ group_info.append([str(log), section_num_failed, failed])
47
+ total_empty_files.append(empty_file)
48
+ os.remove(log)
49
+ failed = []
50
+ text = (
51
+ "🌞 There were no failures!"
52
+ if not any(total_empty_files)
53
+ else "Something went wrong there is at least one empty file - please check GH action results."
54
+ )
55
+ no_error_payload = {
56
+ "type": "section",
57
+ "text": {
58
+ "type": "plain_text",
59
+ "text": text,
60
+ "emoji": True,
61
+ },
62
+ }
63
+
64
+ message = ""
65
+ payload = [
66
+ {
67
+ "type": "header",
68
+ "text": {
69
+ "type": "plain_text",
70
+ "text": "🤗 Results of the Diffusers scheduled nightly tests.",
71
+ },
72
+ },
73
+ ]
74
+ if total_num_failed > 0:
75
+ for i, (name, num_failed, failed_tests) in enumerate(group_info):
76
+ if num_failed > 0:
77
+ if num_failed == 1:
78
+ message += f"*{name}: {num_failed} failed test*\n"
79
+ else:
80
+ message += f"*{name}: {num_failed} failed tests*\n"
81
+ failed_table = []
82
+ for test in failed_tests:
83
+ failed_table.append(test[0].split("::"))
84
+ failed_table = tabulate(
85
+ failed_table,
86
+ headers=["Test Location", "Test Case", "Test Name"],
87
+ showindex="always",
88
+ tablefmt="grid",
89
+ maxcolwidths=[12, 12, 12],
90
+ )
91
+ message += "\n```\n" + failed_table + "\n```"
92
+
93
+ if total_empty_files[i]:
94
+ message += f"\n*{name}: Warning! Empty file - please check the GitHub action job *\n"
95
+ print(f"### {message}")
96
+ else:
97
+ payload.append(no_error_payload)
98
+
99
+ if len(message) > MAX_LEN_MESSAGE:
100
+ print(f"Truncating long message from {len(message)} to {MAX_LEN_MESSAGE}")
101
+ message = message[:MAX_LEN_MESSAGE] + "..."
102
+
103
+ if len(message) != 0:
104
+ md_report = {
105
+ "type": "section",
106
+ "text": {"type": "mrkdwn", "text": message},
107
+ }
108
+ payload.append(md_report)
109
+ action_button = {
110
+ "type": "section",
111
+ "text": {"type": "mrkdwn", "text": "*For more details:*"},
112
+ "accessory": {
113
+ "type": "button",
114
+ "text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
115
+ "url": f"https://github.com/huggingface/diffusers/actions/runs/{os.environ['GITHUB_RUN_ID']}",
116
+ },
117
+ }
118
+ payload.append(action_button)
119
+
120
+ date_report = {
121
+ "type": "context",
122
+ "elements": [
123
+ {
124
+ "type": "plain_text",
125
+ "text": f"Nightly test results for {date.today()}",
126
+ },
127
+ ],
128
+ }
129
+ payload.append(date_report)
130
+
131
+ print(payload)
132
+
133
+ client = WebClient(token=os.environ.get("SLACK_API_TOKEN"))
134
+ client.chat_postMessage(channel=f"#{slack_channel_name}", text=message, blocks=payload)
135
+
136
+
137
+ if __name__ == "__main__":
138
+ args = parser.parse_args()
139
+ main(args.slack_channel_name)
tasks/tasksmith-f40a643a6ef9/environment/source/utils/notify_benchmarking_status.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import argparse
17
+ import os
18
+
19
+ import requests
20
+
21
+
22
+ # Configuration
23
+ GITHUB_REPO = "huggingface/diffusers"
24
+ GITHUB_RUN_ID = os.getenv("GITHUB_RUN_ID")
25
+ SLACK_WEBHOOK_URL = os.getenv("SLACK_WEBHOOK_URL")
26
+
27
+
28
+ def main(args):
29
+ action_url = f"https://github.com/{GITHUB_REPO}/actions/runs/{GITHUB_RUN_ID}"
30
+ if args.status == "success":
31
+ hub_path = "https://huggingface.co/datasets/diffusers/benchmarks/blob/main/collated_results.csv"
32
+ message = (
33
+ "✅ New benchmark workflow successfully run.\n"
34
+ f"🕸️ GitHub Action URL: {action_url}.\n"
35
+ f"🤗 Check out the benchmarks here: {hub_path}."
36
+ )
37
+ else:
38
+ message = (
39
+ "❌ Something wrong happened in the benchmarking workflow.\n"
40
+ f"Check out the GitHub Action to know more: {action_url}."
41
+ )
42
+
43
+ payload = {"text": message}
44
+ response = requests.post(SLACK_WEBHOOK_URL, json=payload)
45
+
46
+ if response.status_code == 200:
47
+ print("Notification sent to Slack successfully.")
48
+ else:
49
+ print("Failed to send notification to Slack.")
50
+
51
+
52
+ if __name__ == "__main__":
53
+ parser = argparse.ArgumentParser()
54
+ parser.add_argument("--status", type=str, default="success", choices=["success", "failure"])
55
+ args = parser.parse_args()
56
+ main(args)
tasks/tasksmith-f40a643a6ef9/environment/source/utils/notify_community_pipelines_mirror.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import argparse
17
+ import os
18
+
19
+ import requests
20
+
21
+
22
+ # Configuration
23
+ GITHUB_REPO = "huggingface/diffusers"
24
+ GITHUB_RUN_ID = os.getenv("GITHUB_RUN_ID")
25
+ SLACK_WEBHOOK_URL = os.getenv("SLACK_WEBHOOK_URL")
26
+ PATH_IN_REPO = os.getenv("PATH_IN_REPO")
27
+
28
+
29
+ def main(args):
30
+ action_url = f"https://github.com/{GITHUB_REPO}/actions/runs/{GITHUB_RUN_ID}"
31
+ if args.status == "success":
32
+ hub_path = f"https://huggingface.co/datasets/diffusers/community-pipelines-mirror/tree/main/{PATH_IN_REPO}"
33
+ message = (
34
+ "✅ Community pipelines successfully mirrored.\n"
35
+ f"🕸️ GitHub Action URL: {action_url}.\n"
36
+ f"🤗 Hub location: {hub_path}."
37
+ )
38
+ else:
39
+ message = f"❌ Something wrong happened. Check out the GitHub Action to know more: {action_url}."
40
+
41
+ payload = {"text": message}
42
+ response = requests.post(SLACK_WEBHOOK_URL, json=payload)
43
+
44
+ if response.status_code == 200:
45
+ print("Notification sent to Slack successfully.")
46
+ else:
47
+ print("Failed to send notification to Slack.")
48
+
49
+
50
+ if __name__ == "__main__":
51
+ parser = argparse.ArgumentParser()
52
+ parser.add_argument("--status", type=str, default="success", choices=["success", "failure"])
53
+ args = parser.parse_args()
54
+ main(args)
tasks/tasksmith-f40a643a6ef9/environment/source/utils/notify_slack_about_release.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+
18
+ import requests
19
+
20
+
21
+ # Configuration
22
+ LIBRARY_NAME = "diffusers"
23
+ GITHUB_REPO = "huggingface/diffusers"
24
+ SLACK_WEBHOOK_URL = os.getenv("SLACK_WEBHOOK_URL")
25
+
26
+
27
+ def check_pypi_for_latest_release(library_name):
28
+ """Check PyPI for the latest release of the library."""
29
+ response = requests.get(f"https://pypi.org/pypi/{library_name}/json", timeout=60)
30
+ if response.status_code == 200:
31
+ data = response.json()
32
+ return data["info"]["version"]
33
+ else:
34
+ print("Failed to fetch library details from PyPI.")
35
+ return None
36
+
37
+
38
+ def get_github_release_info(github_repo):
39
+ """Fetch the latest release info from GitHub."""
40
+ url = f"https://api.github.com/repos/{github_repo}/releases/latest"
41
+ response = requests.get(url, timeout=60)
42
+
43
+ if response.status_code == 200:
44
+ data = response.json()
45
+ return {"tag_name": data["tag_name"], "url": data["html_url"], "release_time": data["published_at"]}
46
+
47
+ else:
48
+ print("Failed to fetch release info from GitHub.")
49
+ return None
50
+
51
+
52
+ def notify_slack(webhook_url, library_name, version, release_info):
53
+ """Send a notification to a Slack channel."""
54
+ message = (
55
+ f"🚀 New release for {library_name} available: version **{version}** 🎉\n"
56
+ f"📜 Release Notes: {release_info['url']}\n"
57
+ f"⏱️ Release time: {release_info['release_time']}"
58
+ )
59
+ payload = {"text": message}
60
+ response = requests.post(webhook_url, json=payload)
61
+
62
+ if response.status_code == 200:
63
+ print("Notification sent to Slack successfully.")
64
+ else:
65
+ print("Failed to send notification to Slack.")
66
+
67
+
68
+ def main():
69
+ latest_version = check_pypi_for_latest_release(LIBRARY_NAME)
70
+ release_info = get_github_release_info(GITHUB_REPO)
71
+ parsed_version = release_info["tag_name"].replace("v", "")
72
+
73
+ if latest_version and release_info and latest_version == parsed_version:
74
+ notify_slack(SLACK_WEBHOOK_URL, LIBRARY_NAME, latest_version, release_info)
75
+ else:
76
+ print(f"{latest_version=}, {release_info=}, {parsed_version=}")
77
+ raise ValueError("There were some problems.")
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()
tasks/tasksmith-f40a643a6ef9/environment/source/utils/overwrite_expected_slice.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import argparse
16
+ from collections import defaultdict
17
+
18
+
19
+ def overwrite_file(file, class_name, test_name, correct_line, done_test):
20
+ _id = f"{file}_{class_name}_{test_name}"
21
+ done_test[_id] += 1
22
+
23
+ with open(file, "r") as f:
24
+ lines = f.readlines()
25
+
26
+ class_regex = f"class {class_name}("
27
+ test_regex = f"{4 * ' '}def {test_name}("
28
+ line_begin_regex = f"{8 * ' '}{correct_line.split()[0]}"
29
+ another_line_begin_regex = f"{16 * ' '}{correct_line.split()[0]}"
30
+ in_class = False
31
+ in_func = False
32
+ in_line = False
33
+ insert_line = False
34
+ count = 0
35
+ spaces = 0
36
+
37
+ new_lines = []
38
+ for line in lines:
39
+ if line.startswith(class_regex):
40
+ in_class = True
41
+ elif in_class and line.startswith(test_regex):
42
+ in_func = True
43
+ elif in_class and in_func and (line.startswith(line_begin_regex) or line.startswith(another_line_begin_regex)):
44
+ spaces = len(line.split(correct_line.split()[0])[0])
45
+ count += 1
46
+
47
+ if count == done_test[_id]:
48
+ in_line = True
49
+
50
+ if in_class and in_func and in_line:
51
+ if ")" not in line:
52
+ continue
53
+ else:
54
+ insert_line = True
55
+
56
+ if in_class and in_func and in_line and insert_line:
57
+ new_lines.append(f"{spaces * ' '}{correct_line}")
58
+ in_class = in_func = in_line = insert_line = False
59
+ else:
60
+ new_lines.append(line)
61
+
62
+ with open(file, "w") as f:
63
+ for line in new_lines:
64
+ f.write(line)
65
+
66
+
67
+ def main(correct, fail=None):
68
+ if fail is not None:
69
+ with open(fail, "r") as f:
70
+ test_failures = {l.strip() for l in f.readlines()}
71
+ else:
72
+ test_failures = None
73
+
74
+ with open(correct, "r") as f:
75
+ correct_lines = f.readlines()
76
+
77
+ done_tests = defaultdict(int)
78
+ for line in correct_lines:
79
+ file, class_name, test_name, correct_line = line.split("::")
80
+ if test_failures is None or "::".join([file, class_name, test_name]) in test_failures:
81
+ overwrite_file(file, class_name, test_name, correct_line, done_tests)
82
+
83
+
84
+ if __name__ == "__main__":
85
+ parser = argparse.ArgumentParser()
86
+ parser.add_argument("--correct_filename", help="filename of tests with expected result")
87
+ parser.add_argument("--fail_filename", help="filename of test failures", type=str, default=None)
88
+ args = parser.parse_args()
89
+
90
+ main(args.correct_filename, args.fail_filename)
tasks/tasksmith-f40a643a6ef9/environment/source/utils/print_env.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # coding=utf-8
4
+ # Copyright 2025 The HuggingFace Inc. team.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ # this script dumps information about the environment
19
+
20
+ import os
21
+ import platform
22
+ import sys
23
+
24
+
25
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
26
+
27
+ print("Python version:", sys.version)
28
+
29
+ print("OS platform:", platform.platform())
30
+ print("OS architecture:", platform.machine())
31
+
32
+ try:
33
+ import torch
34
+
35
+ print("Torch version:", torch.__version__)
36
+ print("Cuda available:", torch.cuda.is_available())
37
+ print("Cuda version:", torch.version.cuda)
38
+ print("CuDNN version:", torch.backends.cudnn.version())
39
+ print("Number of GPUs available:", torch.cuda.device_count())
40
+ if torch.cuda.is_available():
41
+ device_properties = torch.cuda.get_device_properties(0)
42
+ total_memory = device_properties.total_memory / (1024**3)
43
+ print(f"CUDA memory: {total_memory} GB")
44
+ except ImportError:
45
+ print("Torch version:", None)
46
+
47
+ try:
48
+ import transformers
49
+
50
+ print("transformers version:", transformers.__version__)
51
+ except ImportError:
52
+ print("transformers version:", None)
tasks/tasksmith-f40a643a6ef9/environment/source/utils/release.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import argparse
17
+ import os
18
+ import re
19
+
20
+ import packaging.version
21
+
22
+
23
+ PATH_TO_EXAMPLES = "examples/"
24
+ REPLACE_PATTERNS = {
25
+ "examples": (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'),
26
+ "init": (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'),
27
+ "setup": (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'),
28
+ "doc": (re.compile(r'^(\s*)release\s*=\s*"[^"]+"$', re.MULTILINE), 'release = "VERSION"\n'),
29
+ }
30
+ REPLACE_FILES = {
31
+ "init": "src/diffusers/__init__.py",
32
+ "setup": "setup.py",
33
+ }
34
+ README_FILE = "README.md"
35
+
36
+
37
+ def update_version_in_file(fname, version, pattern):
38
+ """Update the version in one file using a specific pattern."""
39
+ with open(fname, "r", encoding="utf-8", newline="\n") as f:
40
+ code = f.read()
41
+ re_pattern, replace = REPLACE_PATTERNS[pattern]
42
+ replace = replace.replace("VERSION", version)
43
+ code = re_pattern.sub(replace, code)
44
+ with open(fname, "w", encoding="utf-8", newline="\n") as f:
45
+ f.write(code)
46
+
47
+
48
+ def update_version_in_examples(version):
49
+ """Update the version in all examples files."""
50
+ for folder, directories, fnames in os.walk(PATH_TO_EXAMPLES):
51
+ # Removing some of the folders with non-actively maintained examples from the walk
52
+ if "research_projects" in directories:
53
+ directories.remove("research_projects")
54
+ if "legacy" in directories:
55
+ directories.remove("legacy")
56
+ for fname in fnames:
57
+ if fname.endswith(".py"):
58
+ update_version_in_file(os.path.join(folder, fname), version, pattern="examples")
59
+
60
+
61
+ def global_version_update(version, patch=False):
62
+ """Update the version in all needed files."""
63
+ for pattern, fname in REPLACE_FILES.items():
64
+ update_version_in_file(fname, version, pattern)
65
+ if not patch:
66
+ update_version_in_examples(version)
67
+
68
+
69
+ def clean_main_ref_in_model_list():
70
+ """Replace the links from main doc tp stable doc in the model list of the README."""
71
+ # If the introduction or the conclusion of the list change, the prompts may need to be updated.
72
+ _start_prompt = "🤗 Transformers currently provides the following architectures"
73
+ _end_prompt = "1. Want to contribute a new model?"
74
+ with open(README_FILE, "r", encoding="utf-8", newline="\n") as f:
75
+ lines = f.readlines()
76
+
77
+ # Find the start of the list.
78
+ start_index = 0
79
+ while not lines[start_index].startswith(_start_prompt):
80
+ start_index += 1
81
+ start_index += 1
82
+
83
+ index = start_index
84
+ # Update the lines in the model list.
85
+ while not lines[index].startswith(_end_prompt):
86
+ if lines[index].startswith("1."):
87
+ lines[index] = lines[index].replace(
88
+ "https://huggingface.co/docs/diffusers/main/model_doc",
89
+ "https://huggingface.co/docs/diffusers/model_doc",
90
+ )
91
+ index += 1
92
+
93
+ with open(README_FILE, "w", encoding="utf-8", newline="\n") as f:
94
+ f.writelines(lines)
95
+
96
+
97
+ def get_version():
98
+ """Reads the current version in the __init__."""
99
+ with open(REPLACE_FILES["init"], "r") as f:
100
+ code = f.read()
101
+ default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0]
102
+ return packaging.version.parse(default_version)
103
+
104
+
105
+ def pre_release_work(patch=False):
106
+ """Do all the necessary pre-release steps."""
107
+ # First let's get the default version: base version if we are in dev, bump minor otherwise.
108
+ default_version = get_version()
109
+ if patch and default_version.is_devrelease:
110
+ raise ValueError("Can't create a patch version from the dev branch, checkout a released version!")
111
+ if default_version.is_devrelease:
112
+ default_version = default_version.base_version
113
+ elif patch:
114
+ default_version = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
115
+ else:
116
+ default_version = f"{default_version.major}.{default_version.minor + 1}.0"
117
+
118
+ # Now let's ask nicely if that's the right one.
119
+ version = input(f"Which version are you releasing? [{default_version}]")
120
+ if len(version) == 0:
121
+ version = default_version
122
+
123
+ print(f"Updating version to {version}.")
124
+ global_version_update(version, patch=patch)
125
+
126
+
127
+ # if not patch:
128
+ # print("Cleaning main README, don't forget to run `make fix-copies`.")
129
+ # clean_main_ref_in_model_list()
130
+
131
+
132
+ def post_release_work():
133
+ """Do all the necessary post-release steps."""
134
+ # First let's get the current version
135
+ current_version = get_version()
136
+ dev_version = f"{current_version.major}.{current_version.minor + 1}.0.dev0"
137
+ current_version = current_version.base_version
138
+
139
+ # Check with the user we got that right.
140
+ version = input(f"Which version are we developing now? [{dev_version}]")
141
+ if len(version) == 0:
142
+ version = dev_version
143
+
144
+ print(f"Updating version to {version}.")
145
+ global_version_update(version)
146
+
147
+
148
+ # print("Cleaning main README, don't forget to run `make fix-copies`.")
149
+ # clean_main_ref_in_model_list()
150
+
151
+
152
+ if __name__ == "__main__":
153
+ parser = argparse.ArgumentParser()
154
+ parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
155
+ parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
156
+ args = parser.parse_args()
157
+ if not args.post_release:
158
+ pre_release_work(patch=args.patch)
159
+ elif args.patch:
160
+ print("Nothing to do after a patch :-)")
161
+ else:
162
+ post_release_work()
tasks/tasksmith-f40a643a6ef9/environment/source/utils/stale.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team, the AllenNLP library authors. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Script to close stale issue. Taken in part from the AllenNLP repository.
16
+ https://github.com/allenai/allennlp.
17
+ """
18
+
19
+ import os
20
+ from datetime import datetime as dt
21
+ from datetime import timezone
22
+
23
+ from github import Github
24
+
25
+
26
+ LABELS_TO_EXEMPT = [
27
+ "close-to-merge",
28
+ "good first issue",
29
+ "good second issue",
30
+ "good difficult issue",
31
+ "enhancement",
32
+ "new pipeline/model",
33
+ "new scheduler",
34
+ "wip",
35
+ ]
36
+
37
+
38
+ def main():
39
+ g = Github(os.environ["GITHUB_TOKEN"])
40
+ repo = g.get_repo("huggingface/diffusers")
41
+ open_issues = repo.get_issues(state="open")
42
+
43
+ for issue in open_issues:
44
+ labels = [label.name.lower() for label in issue.get_labels()]
45
+ if "stale" in labels:
46
+ comments = sorted(issue.get_comments(), key=lambda i: i.created_at, reverse=True)
47
+ last_comment = comments[0] if len(comments) > 0 else None
48
+ if last_comment is not None and last_comment.user.login != "github-actions[bot]":
49
+ # Opens the issue if someone other than Stalebot commented.
50
+ issue.edit(state="open")
51
+ issue.remove_from_labels("stale")
52
+ elif (
53
+ (dt.now(timezone.utc) - issue.updated_at).days > 23
54
+ and (dt.now(timezone.utc) - issue.created_at).days >= 30
55
+ and not any(label in LABELS_TO_EXEMPT for label in labels)
56
+ ):
57
+ # Post a Stalebot notification after 23 days of inactivity.
58
+ issue.create_comment(
59
+ "This issue has been automatically marked as stale because it has not had "
60
+ "recent activity. If you think this still needs to be addressed "
61
+ "please comment on this thread.\n\nPlease note that issues that do not follow the "
62
+ "[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) "
63
+ "are likely to be ignored."
64
+ )
65
+ issue.add_to_labels("stale")
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
tasks/tasksmith-f40a643a6ef9/environment/source/utils/tests_fetcher.py ADDED
@@ -0,0 +1,1128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Welcome to tests_fetcher V2.
18
+
19
+ This util is designed to fetch tests to run on a PR so that only the tests impacted by the modifications are run, and
20
+ when too many models are being impacted, only run the tests of a subset of core models. It works like this.
21
+
22
+ Stage 1: Identify the modified files. For jobs that run on the main branch, it's just the diff with the last commit.
23
+ On a PR, this takes all the files from the branching point to the current commit (so all modifications in a PR, not
24
+ just the last commit) but excludes modifications that are on docstrings or comments only.
25
+
26
+ Stage 2: Extract the tests to run. This is done by looking at the imports in each module and test file: if module A
27
+ imports module B, then changing module B impacts module A, so the tests using module A should be run. We thus get the
28
+ dependencies of each model and then recursively builds the 'reverse' map of dependencies to get all modules and tests
29
+ impacted by a given file. We then only keep the tests (and only the core models tests if there are too many modules).
30
+
31
+ Caveats:
32
+ - This module only filters tests by files (not individual tests) so it's better to have tests for different things
33
+ in different files.
34
+ - This module assumes inits are just importing things, not really building objects, so it's better to structure
35
+ them this way and move objects building in separate submodules.
36
+
37
+ Usage:
38
+
39
+ Base use to fetch the tests in a pull request
40
+
41
+ ```bash
42
+ python utils/tests_fetcher.py
43
+ ```
44
+
45
+ Base use to fetch the tests on a the main branch (with diff from the last commit):
46
+
47
+ ```bash
48
+ python utils/tests_fetcher.py --diff_with_last_commit
49
+ ```
50
+ """
51
+
52
+ import argparse
53
+ import collections
54
+ import json
55
+ import os
56
+ import re
57
+ from contextlib import contextmanager
58
+ from pathlib import Path
59
+ from typing import Dict, List, Optional, Tuple, Union
60
+
61
+ from git import Repo
62
+
63
+
64
+ PATH_TO_REPO = Path(__file__).parent.parent.resolve()
65
+ PATH_TO_EXAMPLES = PATH_TO_REPO / "examples"
66
+ PATH_TO_DIFFUSERS = PATH_TO_REPO / "src/diffusers"
67
+ PATH_TO_TESTS = PATH_TO_REPO / "tests"
68
+
69
+ # Ignore fixtures in tests folder
70
+ # Ignore lora since they are always tested
71
+ MODULES_TO_IGNORE = ["fixtures", "lora"]
72
+
73
+ IMPORTANT_PIPELINES = [
74
+ "controlnet",
75
+ "stable_diffusion",
76
+ "stable_diffusion_2",
77
+ "stable_diffusion_xl",
78
+ "stable_video_diffusion",
79
+ "deepfloyd_if",
80
+ "kandinsky",
81
+ "kandinsky2_2",
82
+ "text_to_video_synthesis",
83
+ "wuerstchen",
84
+ ]
85
+
86
+
87
+ @contextmanager
88
+ def checkout_commit(repo: Repo, commit_id: str):
89
+ """
90
+ Context manager that checks out a given commit when entered, but gets back to the reference it was at on exit.
91
+
92
+ Args:
93
+ repo (`git.Repo`): A git repository (for instance the Transformers repo).
94
+ commit_id (`str`): The commit reference to checkout inside the context manager.
95
+ """
96
+ current_head = repo.head.commit if repo.head.is_detached else repo.head.ref
97
+
98
+ try:
99
+ repo.git.checkout(commit_id)
100
+ yield
101
+
102
+ finally:
103
+ repo.git.checkout(current_head)
104
+
105
+
106
+ def clean_code(content: str) -> str:
107
+ """
108
+ Remove docstrings, empty line or comments from some code (used to detect if a diff is real or only concern
109
+ comments or docstrings).
110
+
111
+ Args:
112
+ content (`str`): The code to clean
113
+
114
+ Returns:
115
+ `str`: The cleaned code.
116
+ """
117
+ # We need to deactivate autoformatting here to write escaped triple quotes (we cannot use real triple quotes or
118
+ # this would mess up the result if this function applied to this particular file).
119
+ # fmt: off
120
+ # Remove docstrings by splitting on triple " then triple ':
121
+ splits = content.split('\"\"\"')
122
+ content = "".join(splits[::2])
123
+ splits = content.split("\'\'\'")
124
+ # fmt: on
125
+ content = "".join(splits[::2])
126
+
127
+ # Remove empty lines and comments
128
+ lines_to_keep = []
129
+ for line in content.split("\n"):
130
+ # remove anything that is after a # sign.
131
+ line = re.sub("#.*$", "", line)
132
+ # remove white lines
133
+ if len(line) != 0 and not line.isspace():
134
+ lines_to_keep.append(line)
135
+ return "\n".join(lines_to_keep)
136
+
137
+
138
+ def keep_doc_examples_only(content: str) -> str:
139
+ """
140
+ Remove everything from the code content except the doc examples (used to determined if a diff should trigger doc
141
+ tests or not).
142
+
143
+ Args:
144
+ content (`str`): The code to clean
145
+
146
+ Returns:
147
+ `str`: The cleaned code.
148
+ """
149
+ # Keep doc examples only by splitting on triple "`"
150
+ splits = content.split("```")
151
+ # Add leading and trailing "```" so the navigation is easier when compared to the original input `content`
152
+ content = "```" + "```".join(splits[1::2]) + "```"
153
+
154
+ # Remove empty lines and comments
155
+ lines_to_keep = []
156
+ for line in content.split("\n"):
157
+ # remove anything that is after a # sign.
158
+ line = re.sub("#.*$", "", line)
159
+ # remove white lines
160
+ if len(line) != 0 and not line.isspace():
161
+ lines_to_keep.append(line)
162
+ return "\n".join(lines_to_keep)
163
+
164
+
165
+ def get_all_tests() -> List[str]:
166
+ """
167
+ Walks the `tests` folder to return a list of files/subfolders. This is used to split the tests to run when using
168
+ parallelism. The split is:
169
+
170
+ - folders under `tests`: (`tokenization`, `pipelines`, etc) except the subfolder `models` is excluded.
171
+ - folders under `tests/models`: `bert`, `gpt2`, etc.
172
+ - test files under `tests`: `test_modeling_common.py`, `test_tokenization_common.py`, etc.
173
+ """
174
+
175
+ # test folders/files directly under `tests` folder
176
+ tests = os.listdir(PATH_TO_TESTS)
177
+ tests = [f"tests/{f}" for f in tests if "__pycache__" not in f]
178
+ tests = sorted([f for f in tests if (PATH_TO_REPO / f).is_dir() or f.startswith("tests/test_")])
179
+
180
+ return tests
181
+
182
+
183
+ def diff_is_docstring_only(repo: Repo, branching_point: str, filename: str) -> bool:
184
+ """
185
+ Check if the diff is only in docstrings (or comments and whitespace) in a filename.
186
+
187
+ Args:
188
+ repo (`git.Repo`): A git repository (for instance the Transformers repo).
189
+ branching_point (`str`): The commit reference of where to compare for the diff.
190
+ filename (`str`): The filename where we want to know if the diff isonly in docstrings/comments.
191
+
192
+ Returns:
193
+ `bool`: Whether the diff is docstring/comments only or not.
194
+ """
195
+ folder = Path(repo.working_dir)
196
+ with checkout_commit(repo, branching_point):
197
+ with open(folder / filename, "r", encoding="utf-8") as f:
198
+ old_content = f.read()
199
+
200
+ with open(folder / filename, "r", encoding="utf-8") as f:
201
+ new_content = f.read()
202
+
203
+ old_content_clean = clean_code(old_content)
204
+ new_content_clean = clean_code(new_content)
205
+
206
+ return old_content_clean == new_content_clean
207
+
208
+
209
+ def diff_contains_doc_examples(repo: Repo, branching_point: str, filename: str) -> bool:
210
+ """
211
+ Check if the diff is only in code examples of the doc in a filename.
212
+
213
+ Args:
214
+ repo (`git.Repo`): A git repository (for instance the Transformers repo).
215
+ branching_point (`str`): The commit reference of where to compare for the diff.
216
+ filename (`str`): The filename where we want to know if the diff is only in codes examples.
217
+
218
+ Returns:
219
+ `bool`: Whether the diff is only in code examples of the doc or not.
220
+ """
221
+ folder = Path(repo.working_dir)
222
+ with checkout_commit(repo, branching_point):
223
+ with open(folder / filename, "r", encoding="utf-8") as f:
224
+ old_content = f.read()
225
+
226
+ with open(folder / filename, "r", encoding="utf-8") as f:
227
+ new_content = f.read()
228
+
229
+ old_content_clean = keep_doc_examples_only(old_content)
230
+ new_content_clean = keep_doc_examples_only(new_content)
231
+
232
+ return old_content_clean != new_content_clean
233
+
234
+
235
+ def get_diff(repo: Repo, base_commit: str, commits: List[str]) -> List[str]:
236
+ """
237
+ Get the diff between a base commit and one or several commits.
238
+
239
+ Args:
240
+ repo (`git.Repo`):
241
+ A git repository (for instance the Transformers repo).
242
+ base_commit (`str`):
243
+ The commit reference of where to compare for the diff. This is the current commit, not the branching point!
244
+ commits (`List[str]`):
245
+ The list of commits with which to compare the repo at `base_commit` (so the branching point).
246
+
247
+ Returns:
248
+ `List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files
249
+ modified are returned if the diff in the file is not only in docstrings or comments, see
250
+ `diff_is_docstring_only`).
251
+ """
252
+ print("\n### DIFF ###\n")
253
+ code_diff = []
254
+ for commit in commits:
255
+ for diff_obj in commit.diff(base_commit):
256
+ # We always add new python files
257
+ if diff_obj.change_type == "A" and diff_obj.b_path.endswith(".py"):
258
+ code_diff.append(diff_obj.b_path)
259
+ # We check that deleted python files won't break corresponding tests.
260
+ elif diff_obj.change_type == "D" and diff_obj.a_path.endswith(".py"):
261
+ code_diff.append(diff_obj.a_path)
262
+ # Now for modified files
263
+ elif diff_obj.change_type in ["M", "R"] and diff_obj.b_path.endswith(".py"):
264
+ # In case of renames, we'll look at the tests using both the old and new name.
265
+ if diff_obj.a_path != diff_obj.b_path:
266
+ code_diff.extend([diff_obj.a_path, diff_obj.b_path])
267
+ else:
268
+ # Otherwise, we check modifications are in code and not docstrings.
269
+ if diff_is_docstring_only(repo, commit, diff_obj.b_path):
270
+ print(f"Ignoring diff in {diff_obj.b_path} as it only concerns docstrings or comments.")
271
+ else:
272
+ code_diff.append(diff_obj.a_path)
273
+
274
+ return code_diff
275
+
276
+
277
+ def get_modified_python_files(diff_with_last_commit: bool = False) -> List[str]:
278
+ """
279
+ Return a list of python files that have been modified between:
280
+
281
+ - the current head and the main branch if `diff_with_last_commit=False` (default)
282
+ - the current head and its parent commit otherwise.
283
+
284
+ Returns:
285
+ `List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files
286
+ modified are returned if the diff in the file is not only in docstrings or comments, see
287
+ `diff_is_docstring_only`).
288
+ """
289
+ repo = Repo(PATH_TO_REPO)
290
+
291
+ if not diff_with_last_commit:
292
+ # Need to fetch refs for main using remotes when running with github actions.
293
+ upstream_main = repo.remotes.origin.refs.main
294
+
295
+ print(f"main is at {upstream_main.commit}")
296
+ print(f"Current head is at {repo.head.commit}")
297
+
298
+ branching_commits = repo.merge_base(upstream_main, repo.head)
299
+ for commit in branching_commits:
300
+ print(f"Branching commit: {commit}")
301
+ return get_diff(repo, repo.head.commit, branching_commits)
302
+ else:
303
+ print(f"main is at {repo.head.commit}")
304
+ parent_commits = repo.head.commit.parents
305
+ for commit in parent_commits:
306
+ print(f"Parent commit: {commit}")
307
+ return get_diff(repo, repo.head.commit, parent_commits)
308
+
309
+
310
+ def get_diff_for_doctesting(repo: Repo, base_commit: str, commits: List[str]) -> List[str]:
311
+ """
312
+ Get the diff in doc examples between a base commit and one or several commits.
313
+
314
+ Args:
315
+ repo (`git.Repo`):
316
+ A git repository (for instance the Transformers repo).
317
+ base_commit (`str`):
318
+ The commit reference of where to compare for the diff. This is the current commit, not the branching point!
319
+ commits (`List[str]`):
320
+ The list of commits with which to compare the repo at `base_commit` (so the branching point).
321
+
322
+ Returns:
323
+ `List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files
324
+ modified are returned if the diff in the file is only in doctest examples).
325
+ """
326
+ print("\n### DIFF ###\n")
327
+ code_diff = []
328
+ for commit in commits:
329
+ for diff_obj in commit.diff(base_commit):
330
+ # We only consider Python files and doc files.
331
+ if not diff_obj.b_path.endswith(".py") and not diff_obj.b_path.endswith(".md"):
332
+ continue
333
+ # We always add new python/md files
334
+ if diff_obj.change_type in ["A"]:
335
+ code_diff.append(diff_obj.b_path)
336
+ # Now for modified files
337
+ elif diff_obj.change_type in ["M", "R"]:
338
+ # In case of renames, we'll look at the tests using both the old and new name.
339
+ if diff_obj.a_path != diff_obj.b_path:
340
+ code_diff.extend([diff_obj.a_path, diff_obj.b_path])
341
+ else:
342
+ # Otherwise, we check modifications contain some doc example(s).
343
+ if diff_contains_doc_examples(repo, commit, diff_obj.b_path):
344
+ code_diff.append(diff_obj.a_path)
345
+ else:
346
+ print(f"Ignoring diff in {diff_obj.b_path} as it doesn't contain any doc example.")
347
+
348
+ return code_diff
349
+
350
+
351
+ def get_all_doctest_files() -> List[str]:
352
+ """
353
+ Return the complete list of python and Markdown files on which we run doctest.
354
+
355
+ At this moment, we restrict this to only take files from `src/` or `docs/source/en/` that are not in `utils/not_doctested.txt`.
356
+
357
+ Returns:
358
+ `List[str]`: The complete list of Python and Markdown files on which we run doctest.
359
+ """
360
+ py_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.py")]
361
+ md_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.md")]
362
+ test_files_to_run = py_files + md_files
363
+
364
+ # only include files in `src` or `docs/source/en/`
365
+ test_files_to_run = [x for x in test_files_to_run if x.startswith(("src/", "docs/source/en/"))]
366
+ # not include init files
367
+ test_files_to_run = [x for x in test_files_to_run if not x.endswith(("__init__.py",))]
368
+
369
+ # These are files not doctested yet.
370
+ with open("utils/not_doctested.txt") as fp:
371
+ not_doctested = {x.split(" ")[0] for x in fp.read().strip().split("\n")}
372
+
373
+ # So far we don't have 100% coverage for doctest. This line will be removed once we achieve 100%.
374
+ test_files_to_run = [x for x in test_files_to_run if x not in not_doctested]
375
+
376
+ return sorted(test_files_to_run)
377
+
378
+
379
+ def get_new_doctest_files(repo, base_commit, branching_commit) -> List[str]:
380
+ """
381
+ Get the list of files that were removed from "utils/not_doctested.txt", between `base_commit` and
382
+ `branching_commit`.
383
+
384
+ Returns:
385
+ `List[str]`: List of files that were removed from "utils/not_doctested.txt".
386
+ """
387
+ for diff_obj in branching_commit.diff(base_commit):
388
+ # Ignores all but the "utils/not_doctested.txt" file.
389
+ if diff_obj.a_path != "utils/not_doctested.txt":
390
+ continue
391
+ # Loads the two versions
392
+ folder = Path(repo.working_dir)
393
+ with checkout_commit(repo, branching_commit):
394
+ with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f:
395
+ old_content = f.read()
396
+ with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f:
397
+ new_content = f.read()
398
+ # Compute the removed lines and return them
399
+ removed_content = {x.split(" ")[0] for x in old_content.split("\n")} - {
400
+ x.split(" ")[0] for x in new_content.split("\n")
401
+ }
402
+ return sorted(removed_content)
403
+ return []
404
+
405
+
406
+ def get_doctest_files(diff_with_last_commit: bool = False) -> List[str]:
407
+ """
408
+ Return a list of python and Markdown files where doc example have been modified between:
409
+
410
+ - the current head and the main branch if `diff_with_last_commit=False` (default)
411
+ - the current head and its parent commit otherwise.
412
+
413
+ Returns:
414
+ `List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files
415
+ modified are returned if the diff in the file is only in doctest examples).
416
+ """
417
+ repo = Repo(PATH_TO_REPO)
418
+
419
+ test_files_to_run = [] # noqa
420
+ if not diff_with_last_commit:
421
+ upstream_main = repo.remotes.origin.refs.main
422
+ print(f"main is at {upstream_main.commit}")
423
+ print(f"Current head is at {repo.head.commit}")
424
+
425
+ branching_commits = repo.merge_base(upstream_main, repo.head)
426
+ for commit in branching_commits:
427
+ print(f"Branching commit: {commit}")
428
+ test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, branching_commits)
429
+ else:
430
+ print(f"main is at {repo.head.commit}")
431
+ parent_commits = repo.head.commit.parents
432
+ for commit in parent_commits:
433
+ print(f"Parent commit: {commit}")
434
+ test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, parent_commits)
435
+
436
+ all_test_files_to_run = get_all_doctest_files()
437
+
438
+ # Add to the test files to run any removed entry from "utils/not_doctested.txt".
439
+ new_test_files = get_new_doctest_files(repo, repo.head.commit, upstream_main.commit)
440
+ test_files_to_run = list(set(test_files_to_run + new_test_files))
441
+
442
+ # Do not run slow doctest tests on CircleCI
443
+ with open("utils/slow_documentation_tests.txt") as fp:
444
+ slow_documentation_tests = set(fp.read().strip().split("\n"))
445
+ test_files_to_run = [
446
+ x for x in test_files_to_run if x in all_test_files_to_run and x not in slow_documentation_tests
447
+ ]
448
+
449
+ # Make sure we did not end up with a test file that was removed
450
+ test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()]
451
+
452
+ return sorted(test_files_to_run)
453
+
454
+
455
+ # (:?^|\n) -> Non-catching group for the beginning of the doc or a new line.
456
+ # \s*from\s+(\.+\S+)\s+import\s+([^\n]+) -> Line only contains from .xxx import yyy and we catch .xxx and yyy
457
+ # (?=\n) -> Look-ahead to a new line. We can't just put \n here or using find_all on this re will only catch every
458
+ # other import.
459
+ _re_single_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+([^\n]+)(?=\n)")
460
+ # (:?^|\n) -> Non-catching group for the beginning of the doc or a new line.
461
+ # \s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\) -> Line continues with from .xxx import (yyy) and we catch .xxx and yyy
462
+ # yyy will take multiple lines otherwise there wouldn't be parenthesis.
463
+ _re_multi_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\)")
464
+ # (:?^|\n) -> Non-catching group for the beginning of the doc or a new line.
465
+ # \s*from\s+transformers(\S*)\s+import\s+([^\n]+) -> Line only contains from transformers.xxx import yyy and we catch
466
+ # .xxx and yyy
467
+ # (?=\n) -> Look-ahead to a new line. We can't just put \n here or using find_all on this re will only catch every
468
+ # other import.
469
+ _re_single_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+diffusers(\S*)\s+import\s+([^\n]+)(?=\n)")
470
+ # (:?^|\n) -> Non-catching group for the beginning of the doc or a new line.
471
+ # \s*from\s+transformers(\S*)\s+import\s+\(([^\)]+)\) -> Line continues with from transformers.xxx import (yyy) and we
472
+ # catch .xxx and yyy. yyy will take multiple lines otherwise there wouldn't be parenthesis.
473
+ _re_multi_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+diffusers(\S*)\s+import\s+\(([^\)]+)\)")
474
+
475
+
476
+ def extract_imports(module_fname: str, cache: Dict[str, List[str]] = None) -> List[str]:
477
+ """
478
+ Get the imports a given module makes.
479
+
480
+ Args:
481
+ module_fname (`str`):
482
+ The name of the file of the module where we want to look at the imports (given relative to the root of
483
+ the repo).
484
+ cache (Dictionary `str` to `List[str]`, *optional*):
485
+ To speed up this function if it was previously called on `module_fname`, the cache of all previously
486
+ computed results.
487
+
488
+ Returns:
489
+ `List[str]`: The list of module filenames imported in the input `module_fname` (a submodule we import from that
490
+ is a subfolder will give its init file).
491
+ """
492
+ if cache is not None and module_fname in cache:
493
+ return cache[module_fname]
494
+
495
+ with open(PATH_TO_REPO / module_fname, "r", encoding="utf-8") as f:
496
+ content = f.read()
497
+
498
+ # Filter out all docstrings to not get imports in code examples. As before we need to deactivate formatting to
499
+ # keep this as escaped quotes and avoid this function failing on this file.
500
+ # fmt: off
501
+ splits = content.split('\"\"\"')
502
+ # fmt: on
503
+ content = "".join(splits[::2])
504
+
505
+ module_parts = str(module_fname).split(os.path.sep)
506
+ imported_modules = []
507
+
508
+ # Let's start with relative imports
509
+ relative_imports = _re_single_line_relative_imports.findall(content)
510
+ relative_imports = [
511
+ (mod, imp) for mod, imp in relative_imports if "# tests_ignore" not in imp and imp.strip() != "("
512
+ ]
513
+ multiline_relative_imports = _re_multi_line_relative_imports.findall(content)
514
+ relative_imports += [(mod, imp) for mod, imp in multiline_relative_imports if "# tests_ignore" not in imp]
515
+
516
+ # We need to remove parts of the module name depending on the depth of the relative imports.
517
+ for module, imports in relative_imports:
518
+ level = 0
519
+ while module.startswith("."):
520
+ module = module[1:]
521
+ level += 1
522
+
523
+ if len(module) > 0:
524
+ dep_parts = module_parts[: len(module_parts) - level] + module.split(".")
525
+ else:
526
+ dep_parts = module_parts[: len(module_parts) - level]
527
+ imported_module = os.path.sep.join(dep_parts)
528
+ imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")]))
529
+
530
+ # Let's continue with direct imports
531
+ direct_imports = _re_single_line_direct_imports.findall(content)
532
+ direct_imports = [(mod, imp) for mod, imp in direct_imports if "# tests_ignore" not in imp and imp.strip() != "("]
533
+ multiline_direct_imports = _re_multi_line_direct_imports.findall(content)
534
+ direct_imports += [(mod, imp) for mod, imp in multiline_direct_imports if "# tests_ignore" not in imp]
535
+
536
+ # We need to find the relative path of those imports.
537
+ for module, imports in direct_imports:
538
+ import_parts = module.split(".")[1:] # ignore the name of the repo since we add it below.
539
+ dep_parts = ["src", "diffusers"] + import_parts
540
+ imported_module = os.path.sep.join(dep_parts)
541
+ imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")]))
542
+
543
+ result = []
544
+ # Double check we get proper modules (either a python file or a folder with an init).
545
+ for module_file, imports in imported_modules:
546
+ if (PATH_TO_REPO / f"{module_file}.py").is_file():
547
+ module_file = f"{module_file}.py"
548
+ elif (PATH_TO_REPO / module_file).is_dir() and (PATH_TO_REPO / module_file / "__init__.py").is_file():
549
+ module_file = os.path.sep.join([module_file, "__init__.py"])
550
+ imports = [imp for imp in imports if len(imp) > 0 and re.match("^[A-Za-z0-9_]*$", imp)]
551
+ if len(imports) > 0:
552
+ result.append((module_file, imports))
553
+
554
+ if cache is not None:
555
+ cache[module_fname] = result
556
+
557
+ return result
558
+
559
+
560
+ def get_module_dependencies(module_fname: str, cache: Dict[str, List[str]] = None) -> List[str]:
561
+ """
562
+ Refines the result of `extract_imports` to remove subfolders and get a proper list of module filenames: if a file
563
+ as an import `from utils import Foo, Bar`, with `utils` being a subfolder containing many files, this will traverse
564
+ the `utils` init file to check where those dependencies come from: for instance the files utils/foo.py and utils/bar.py.
565
+
566
+ Warning: This presupposes that all intermediate inits are properly built (with imports from the respective
567
+ submodules) and work better if objects are defined in submodules and not the intermediate init (otherwise the
568
+ intermediate init is added, and inits usually have a lot of dependencies).
569
+
570
+ Args:
571
+ module_fname (`str`):
572
+ The name of the file of the module where we want to look at the imports (given relative to the root of
573
+ the repo).
574
+ cache (Dictionary `str` to `List[str]`, *optional*):
575
+ To speed up this function if it was previously called on `module_fname`, the cache of all previously
576
+ computed results.
577
+
578
+ Returns:
579
+ `List[str]`: The list of module filenames imported in the input `module_fname` (with submodule imports refined).
580
+ """
581
+ dependencies = []
582
+ imported_modules = extract_imports(module_fname, cache=cache)
583
+ # The while loop is to recursively traverse all inits we may encounter: we will add things as we go.
584
+ while len(imported_modules) > 0:
585
+ new_modules = []
586
+ for module, imports in imported_modules:
587
+ # If we end up in an __init__ we are often not actually importing from this init (except in the case where
588
+ # the object is fully defined in the __init__)
589
+ if module.endswith("__init__.py"):
590
+ # So we get the imports from that init then try to find where our objects come from.
591
+ new_imported_modules = extract_imports(module, cache=cache)
592
+ for new_module, new_imports in new_imported_modules:
593
+ if any(i in new_imports for i in imports):
594
+ if new_module not in dependencies:
595
+ new_modules.append((new_module, [i for i in new_imports if i in imports]))
596
+ imports = [i for i in imports if i not in new_imports]
597
+ if len(imports) > 0:
598
+ # If there are any objects lefts, they may be a submodule
599
+ path_to_module = PATH_TO_REPO / module.replace("__init__.py", "")
600
+ dependencies.extend(
601
+ [
602
+ os.path.join(module.replace("__init__.py", ""), f"{i}.py")
603
+ for i in imports
604
+ if (path_to_module / f"{i}.py").is_file()
605
+ ]
606
+ )
607
+ imports = [i for i in imports if not (path_to_module / f"{i}.py").is_file()]
608
+ if len(imports) > 0:
609
+ # Then if there are still objects left, they are fully defined in the init, so we keep it as a
610
+ # dependency.
611
+ dependencies.append(module)
612
+ else:
613
+ dependencies.append(module)
614
+
615
+ imported_modules = new_modules
616
+
617
+ return dependencies
618
+
619
+
620
+ def create_reverse_dependency_tree() -> List[Tuple[str, str]]:
621
+ """
622
+ Create a list of all edges (a, b) which mean that modifying a impacts b with a going over all module and test files.
623
+ """
624
+ cache = {}
625
+ all_modules = list(PATH_TO_DIFFUSERS.glob("**/*.py")) + list(PATH_TO_TESTS.glob("**/*.py"))
626
+ all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules]
627
+ edges = [(dep, mod) for mod in all_modules for dep in get_module_dependencies(mod, cache=cache)]
628
+
629
+ return list(set(edges))
630
+
631
+
632
+ def get_tree_starting_at(module: str, edges: List[Tuple[str, str]]) -> List[Union[str, List[str]]]:
633
+ """
634
+ Returns the tree starting at a given module following all edges.
635
+
636
+ Args:
637
+ module (`str`): The module that will be the root of the subtree we want.
638
+ edges (`List[Tuple[str, str]]`): The list of all edges of the tree.
639
+
640
+ Returns:
641
+ `List[Union[str, List[str]]]`: The tree to print in the following format: [module, [list of edges
642
+ starting at module], [list of edges starting at the preceding level], ...]
643
+ """
644
+ vertices_seen = [module]
645
+ new_edges = [edge for edge in edges if edge[0] == module and edge[1] != module and "__init__.py" not in edge[1]]
646
+ tree = [module]
647
+ while len(new_edges) > 0:
648
+ tree.append(new_edges)
649
+ final_vertices = list({edge[1] for edge in new_edges})
650
+ vertices_seen.extend(final_vertices)
651
+ new_edges = [
652
+ edge
653
+ for edge in edges
654
+ if edge[0] in final_vertices and edge[1] not in vertices_seen and "__init__.py" not in edge[1]
655
+ ]
656
+
657
+ return tree
658
+
659
+
660
+ def print_tree_deps_of(module, all_edges=None):
661
+ """
662
+ Prints the tree of modules depending on a given module.
663
+
664
+ Args:
665
+ module (`str`): The module that will be the root of the subtree we want.
666
+ all_edges (`List[Tuple[str, str]]`, *optional*):
667
+ The list of all edges of the tree. Will be set to `create_reverse_dependency_tree()` if not passed.
668
+ """
669
+ if all_edges is None:
670
+ all_edges = create_reverse_dependency_tree()
671
+ tree = get_tree_starting_at(module, all_edges)
672
+
673
+ # The list of lines is a list of tuples (line_to_be_printed, module)
674
+ # Keeping the modules lets us know where to insert each new lines in the list.
675
+ lines = [(tree[0], tree[0])]
676
+ for index in range(1, len(tree)):
677
+ edges = tree[index]
678
+ start_edges = {edge[0] for edge in edges}
679
+
680
+ for start in start_edges:
681
+ end_edges = {edge[1] for edge in edges if edge[0] == start}
682
+ # We will insert all those edges just after the line showing start.
683
+ pos = 0
684
+ while lines[pos][1] != start:
685
+ pos += 1
686
+ lines = lines[: pos + 1] + [(" " * (2 * index) + end, end) for end in end_edges] + lines[pos + 1 :]
687
+
688
+ for line in lines:
689
+ # We don't print the refs that where just here to help build lines.
690
+ print(line[0])
691
+
692
+
693
+ def init_test_examples_dependencies() -> Tuple[Dict[str, List[str]], List[str]]:
694
+ """
695
+ The test examples do not import from the examples (which are just scripts, not modules) so we need some extra
696
+ care initializing the dependency map, which is the goal of this function. It initializes the dependency map for
697
+ example files by linking each example to the example test file for the example framework.
698
+
699
+ Returns:
700
+ `Tuple[Dict[str, List[str]], List[str]]`: A tuple with two elements: the initialized dependency map which is a
701
+ dict test example file to list of example files potentially tested by that test file, and the list of all
702
+ example files (to avoid recomputing it later).
703
+ """
704
+ test_example_deps = {}
705
+ all_examples = []
706
+ for framework in ["flax", "pytorch", "tensorflow"]:
707
+ test_files = list((PATH_TO_EXAMPLES / framework).glob("test_*.py"))
708
+ all_examples.extend(test_files)
709
+ # Remove the files at the root of examples/framework since they are not proper examples (they are either utils
710
+ # or example test files).
711
+ examples = [
712
+ f for f in (PATH_TO_EXAMPLES / framework).glob("**/*.py") if f.parent != PATH_TO_EXAMPLES / framework
713
+ ]
714
+ all_examples.extend(examples)
715
+ for test_file in test_files:
716
+ with open(test_file, "r", encoding="utf-8") as f:
717
+ content = f.read()
718
+ # Map all examples to the test files found in examples/framework.
719
+ test_example_deps[str(test_file.relative_to(PATH_TO_REPO))] = [
720
+ str(e.relative_to(PATH_TO_REPO)) for e in examples if e.name in content
721
+ ]
722
+ # Also map the test files to themselves.
723
+ test_example_deps[str(test_file.relative_to(PATH_TO_REPO))].append(
724
+ str(test_file.relative_to(PATH_TO_REPO))
725
+ )
726
+ return test_example_deps, all_examples
727
+
728
+
729
+ def create_reverse_dependency_map() -> Dict[str, List[str]]:
730
+ """
731
+ Create the dependency map from module/test filename to the list of modules/tests that depend on it recursively.
732
+
733
+ Returns:
734
+ `Dict[str, List[str]]`: The reverse dependency map as a dictionary mapping filenames to all the filenames
735
+ depending on it recursively. This way the tests impacted by a change in file A are the test files in the list
736
+ corresponding to key A in this result.
737
+ """
738
+ cache = {}
739
+ # Start from the example deps init.
740
+ example_deps, examples = init_test_examples_dependencies()
741
+ # Add all modules and all tests to all examples
742
+ all_modules = list(PATH_TO_DIFFUSERS.glob("**/*.py")) + list(PATH_TO_TESTS.glob("**/*.py")) + examples
743
+ all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules]
744
+ # Compute the direct dependencies of all modules.
745
+ direct_deps = {m: get_module_dependencies(m, cache=cache) for m in all_modules}
746
+ direct_deps.update(example_deps)
747
+
748
+ # This recurses the dependencies
749
+ something_changed = True
750
+ while something_changed:
751
+ something_changed = False
752
+ for m in all_modules:
753
+ for d in direct_deps[m]:
754
+ # We stop recursing at an init (cause we always end up in the main init and we don't want to add all
755
+ # files which the main init imports)
756
+ if d.endswith("__init__.py"):
757
+ continue
758
+ if d not in direct_deps:
759
+ raise ValueError(f"KeyError:{d}. From {m}")
760
+ new_deps = set(direct_deps[d]) - set(direct_deps[m])
761
+ if len(new_deps) > 0:
762
+ direct_deps[m].extend(list(new_deps))
763
+ something_changed = True
764
+
765
+ # Finally we can build the reverse map.
766
+ reverse_map = collections.defaultdict(list)
767
+ for m in all_modules:
768
+ for d in direct_deps[m]:
769
+ reverse_map[d].append(m)
770
+
771
+ # For inits, we don't do the reverse deps but the direct deps: if modifying an init, we want to make sure we test
772
+ # all the modules impacted by that init.
773
+ for m in [f for f in all_modules if f.endswith("__init__.py")]:
774
+ direct_deps = get_module_dependencies(m, cache=cache)
775
+ deps = sum([reverse_map[d] for d in direct_deps if not d.endswith("__init__.py")], direct_deps)
776
+ reverse_map[m] = list(set(deps) - {m})
777
+
778
+ return reverse_map
779
+
780
+
781
+ def create_module_to_test_map(reverse_map: Dict[str, List[str]] = None) -> Dict[str, List[str]]:
782
+ """
783
+ Extract the tests from the reverse_dependency_map and potentially filters the model tests.
784
+
785
+ Args:
786
+ reverse_map (`Dict[str, List[str]]`, *optional*):
787
+ The reverse dependency map as created by `create_reverse_dependency_map`. Will default to the result of
788
+ that function if not provided.
789
+ filter_pipelines (`bool`, *optional*, defaults to `False`):
790
+ Whether or not to filter pipeline tests to only include core pipelines if a file impacts a lot of models.
791
+
792
+ Returns:
793
+ `Dict[str, List[str]]`: A dictionary that maps each file to the tests to execute if that file was modified.
794
+ """
795
+ if reverse_map is None:
796
+ reverse_map = create_reverse_dependency_map()
797
+
798
+ # Utility that tells us if a given file is a test (taking test examples into account)
799
+ def is_test(fname):
800
+ if fname.startswith("tests"):
801
+ return True
802
+ if fname.startswith("examples") and fname.split(os.path.sep)[-1].startswith("test"):
803
+ return True
804
+ return False
805
+
806
+ # Build the test map
807
+ test_map = {module: [f for f in deps if is_test(f)] for module, deps in reverse_map.items()}
808
+
809
+ return test_map
810
+
811
+
812
+ def check_imports_all_exist():
813
+ """
814
+ Isn't used per se by the test fetcher but might be used later as a quality check. Putting this here for now so the
815
+ code is not lost. This checks all imports in a given file do exist.
816
+ """
817
+ cache = {}
818
+ all_modules = list(PATH_TO_DIFFUSERS.glob("**/*.py")) + list(PATH_TO_TESTS.glob("**/*.py"))
819
+ all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules]
820
+ direct_deps = {m: get_module_dependencies(m, cache=cache) for m in all_modules}
821
+
822
+ for module, deps in direct_deps.items():
823
+ for dep in deps:
824
+ if not (PATH_TO_REPO / dep).is_file():
825
+ print(f"{module} has dependency on {dep} which does not exist.")
826
+
827
+
828
+ def _print_list(l) -> str:
829
+ """
830
+ Pretty print a list of elements with one line per element and a - starting each line.
831
+ """
832
+ return "\n".join([f"- {f}" for f in l])
833
+
834
+
835
+ def update_test_map_with_core_pipelines(json_output_file: str):
836
+ print(f"\n### ADD CORE PIPELINE TESTS ###\n{_print_list(IMPORTANT_PIPELINES)}")
837
+ with open(json_output_file, "rb") as fp:
838
+ test_map = json.load(fp)
839
+
840
+ # Add core pipelines as their own test group
841
+ test_map["core_pipelines"] = " ".join(
842
+ sorted([str(PATH_TO_TESTS / f"pipelines/{pipe}") for pipe in IMPORTANT_PIPELINES])
843
+ )
844
+
845
+ # If there are no existing pipeline tests save the map
846
+ if "pipelines" not in test_map:
847
+ with open(json_output_file, "w", encoding="UTF-8") as fp:
848
+ json.dump(test_map, fp, ensure_ascii=False)
849
+
850
+ pipeline_tests = test_map.pop("pipelines")
851
+ pipeline_tests = pipeline_tests.split(" ")
852
+
853
+ # Remove core pipeline tests from the fetched pipeline tests
854
+ updated_pipeline_tests = []
855
+ for pipe in pipeline_tests:
856
+ if pipe == "tests/pipelines" or Path(pipe).parts[2] in IMPORTANT_PIPELINES:
857
+ continue
858
+ updated_pipeline_tests.append(pipe)
859
+
860
+ if len(updated_pipeline_tests) > 0:
861
+ test_map["pipelines"] = " ".join(sorted(updated_pipeline_tests))
862
+
863
+ with open(json_output_file, "w", encoding="UTF-8") as fp:
864
+ json.dump(test_map, fp, ensure_ascii=False)
865
+
866
+
867
+ def create_json_map(test_files_to_run: List[str], json_output_file: Optional[str] = None):
868
+ """
869
+ Creates a map from a list of tests to run to easily split them by category, when running parallelism of slow tests.
870
+
871
+ Args:
872
+ test_files_to_run (`List[str]`): The list of tests to run.
873
+ json_output_file (`str`): The path where to store the built json map.
874
+ """
875
+ if json_output_file is None:
876
+ return
877
+
878
+ test_map = {}
879
+ for test_file in test_files_to_run:
880
+ # `test_file` is a path to a test folder/file, starting with `tests/`. For example,
881
+ # - `tests/models/bert/test_modeling_bert.py` or `tests/models/bert`
882
+ # - `tests/trainer/test_trainer.py` or `tests/trainer`
883
+ # - `tests/test_modeling_common.py`
884
+ names = test_file.split(os.path.sep)
885
+ module = names[1]
886
+ if module in MODULES_TO_IGNORE:
887
+ continue
888
+
889
+ if len(names) > 2 or not test_file.endswith(".py"):
890
+ # test folders under `tests` or python files under them
891
+ # take the part like tokenization, `pipeline`, etc. for other test categories
892
+ key = os.path.sep.join(names[1:2])
893
+ else:
894
+ # common test files directly under `tests/`
895
+ key = "common"
896
+
897
+ if key not in test_map:
898
+ test_map[key] = []
899
+ test_map[key].append(test_file)
900
+
901
+ # sort the keys & values
902
+ keys = sorted(test_map.keys())
903
+ test_map = {k: " ".join(sorted(test_map[k])) for k in keys}
904
+
905
+ with open(json_output_file, "w", encoding="UTF-8") as fp:
906
+ json.dump(test_map, fp, ensure_ascii=False)
907
+
908
+
909
+ def infer_tests_to_run(
910
+ output_file: str,
911
+ diff_with_last_commit: bool = False,
912
+ json_output_file: Optional[str] = None,
913
+ ):
914
+ """
915
+ The main function called by the test fetcher. Determines the tests to run from the diff.
916
+
917
+ Args:
918
+ output_file (`str`):
919
+ The path where to store the summary of the test fetcher analysis. Other files will be stored in the same
920
+ folder:
921
+
922
+ - examples_test_list.txt: The list of examples tests to run.
923
+ - test_repo_utils.txt: Will indicate if the repo utils tests should be run or not.
924
+ - doctest_list.txt: The list of doctests to run.
925
+
926
+ diff_with_last_commit (`bool`, *optional*, defaults to `False`):
927
+ Whether to analyze the diff with the last commit (for use on the main branch after a PR is merged) or with
928
+ the branching point from main (for use on each PR).
929
+ filter_models (`bool`, *optional*, defaults to `True`):
930
+ Whether or not to filter the tests to core models only, when a file modified results in a lot of model
931
+ tests.
932
+ json_output_file (`str`, *optional*):
933
+ The path where to store the json file mapping categories of tests to tests to run (used for parallelism or
934
+ the slow tests).
935
+ """
936
+ modified_files = get_modified_python_files(diff_with_last_commit=diff_with_last_commit)
937
+ print(f"\n### MODIFIED FILES ###\n{_print_list(modified_files)}")
938
+ # Create the map that will give us all impacted modules.
939
+ reverse_map = create_reverse_dependency_map()
940
+ impacted_files = modified_files.copy()
941
+ for f in modified_files:
942
+ if f in reverse_map:
943
+ impacted_files.extend(reverse_map[f])
944
+
945
+ # Remove duplicates
946
+ impacted_files = sorted(set(impacted_files))
947
+ print(f"\n### IMPACTED FILES ###\n{_print_list(impacted_files)}")
948
+
949
+ # Grab the corresponding test files:
950
+ if any(x in modified_files for x in ["setup.py"]):
951
+ test_files_to_run = ["tests", "examples"]
952
+
953
+ # in order to trigger pipeline tests even if no code change at all
954
+ if "tests/utils/tiny_model_summary.json" in modified_files:
955
+ test_files_to_run = ["tests"]
956
+ any(f.split(os.path.sep)[0] == "utils" for f in modified_files)
957
+ else:
958
+ # All modified tests need to be run.
959
+ test_files_to_run = [
960
+ f for f in modified_files if f.startswith("tests") and f.split(os.path.sep)[-1].startswith("test")
961
+ ]
962
+ # Then we grab the corresponding test files.
963
+ test_map = create_module_to_test_map(reverse_map=reverse_map)
964
+ for f in modified_files:
965
+ if f in test_map:
966
+ test_files_to_run.extend(test_map[f])
967
+ test_files_to_run = sorted(set(test_files_to_run))
968
+ # Make sure we did not end up with a test file that was removed
969
+ test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()]
970
+
971
+ any(f.split(os.path.sep)[0] == "utils" for f in modified_files)
972
+
973
+ examples_tests_to_run = [f for f in test_files_to_run if f.startswith("examples")]
974
+ test_files_to_run = [f for f in test_files_to_run if not f.startswith("examples")]
975
+ print(f"\n### TEST TO RUN ###\n{_print_list(test_files_to_run)}")
976
+ if len(test_files_to_run) > 0:
977
+ with open(output_file, "w", encoding="utf-8") as f:
978
+ f.write(" ".join(test_files_to_run))
979
+
980
+ # Create a map that maps test categories to test files, i.e. `models/bert` -> [...test_modeling_bert.py, ...]
981
+
982
+ # Get all test directories (and some common test files) under `tests` and `tests/models` if `test_files_to_run`
983
+ # contains `tests` (i.e. when `setup.py` is changed).
984
+ if "tests" in test_files_to_run:
985
+ test_files_to_run = get_all_tests()
986
+
987
+ create_json_map(test_files_to_run, json_output_file)
988
+
989
+ print(f"\n### EXAMPLES TEST TO RUN ###\n{_print_list(examples_tests_to_run)}")
990
+ if len(examples_tests_to_run) > 0:
991
+ # We use `all` in the case `commit_flags["test_all"]` as well as in `create_circleci_config.py` for processing
992
+ if examples_tests_to_run == ["examples"]:
993
+ examples_tests_to_run = ["all"]
994
+ example_file = Path(output_file).parent / "examples_test_list.txt"
995
+ with open(example_file, "w", encoding="utf-8") as f:
996
+ f.write(" ".join(examples_tests_to_run))
997
+
998
+
999
+ def filter_tests(output_file: str, filters: List[str]):
1000
+ """
1001
+ Reads the content of the output file and filters out all the tests in a list of given folders.
1002
+
1003
+ Args:
1004
+ output_file (`str` or `os.PathLike`): The path to the output file of the tests fetcher.
1005
+ filters (`List[str]`): A list of folders to filter.
1006
+ """
1007
+ if not os.path.isfile(output_file):
1008
+ print("No test file found.")
1009
+ return
1010
+ with open(output_file, "r", encoding="utf-8") as f:
1011
+ test_files = f.read().split(" ")
1012
+
1013
+ if len(test_files) == 0 or test_files == [""]:
1014
+ print("No tests to filter.")
1015
+ return
1016
+
1017
+ if test_files == ["tests"]:
1018
+ test_files = [os.path.join("tests", f) for f in os.listdir("tests") if f not in ["__init__.py"] + filters]
1019
+ else:
1020
+ test_files = [f for f in test_files if f.split(os.path.sep)[1] not in filters]
1021
+
1022
+ with open(output_file, "w", encoding="utf-8") as f:
1023
+ f.write(" ".join(test_files))
1024
+
1025
+
1026
+ def parse_commit_message(commit_message: str) -> Dict[str, bool]:
1027
+ """
1028
+ Parses the commit message to detect if a command is there to skip, force all or part of the CI.
1029
+
1030
+ Args:
1031
+ commit_message (`str`): The commit message of the current commit.
1032
+
1033
+ Returns:
1034
+ `Dict[str, bool]`: A dictionary of strings to bools with keys the following keys: `"skip"`,
1035
+ `"test_all_models"` and `"test_all"`.
1036
+ """
1037
+ if commit_message is None:
1038
+ return {"skip": False, "no_filter": False, "test_all": False}
1039
+
1040
+ command_search = re.search(r"\[([^\]]*)\]", commit_message)
1041
+ if command_search is not None:
1042
+ command = command_search.groups()[0]
1043
+ command = command.lower().replace("-", " ").replace("_", " ")
1044
+ skip = command in ["ci skip", "skip ci", "circleci skip", "skip circleci"]
1045
+ no_filter = set(command.split(" ")) == {"no", "filter"}
1046
+ test_all = set(command.split(" ")) == {"test", "all"}
1047
+ return {"skip": skip, "no_filter": no_filter, "test_all": test_all}
1048
+ else:
1049
+ return {"skip": False, "no_filter": False, "test_all": False}
1050
+
1051
+
1052
+ if __name__ == "__main__":
1053
+ parser = argparse.ArgumentParser()
1054
+ parser.add_argument(
1055
+ "--output_file", type=str, default="test_list.txt", help="Where to store the list of tests to run"
1056
+ )
1057
+ parser.add_argument(
1058
+ "--json_output_file",
1059
+ type=str,
1060
+ default="test_map.json",
1061
+ help="Where to store the tests to run in a dictionary format mapping test categories to test files",
1062
+ )
1063
+ parser.add_argument(
1064
+ "--diff_with_last_commit",
1065
+ action="store_true",
1066
+ help="To fetch the tests between the current commit and the last commit",
1067
+ )
1068
+ parser.add_argument(
1069
+ "--filter_tests",
1070
+ action="store_true",
1071
+ help="Will filter the pipeline/repo utils tests outside of the generated list of tests.",
1072
+ )
1073
+ parser.add_argument(
1074
+ "--print_dependencies_of",
1075
+ type=str,
1076
+ help="Will only print the tree of modules depending on the file passed.",
1077
+ default=None,
1078
+ )
1079
+ parser.add_argument(
1080
+ "--commit_message",
1081
+ type=str,
1082
+ help="The commit message (which could contain a command to force all tests or skip the CI).",
1083
+ default=None,
1084
+ )
1085
+ args = parser.parse_args()
1086
+ if args.print_dependencies_of is not None:
1087
+ print_tree_deps_of(args.print_dependencies_of)
1088
+ else:
1089
+ repo = Repo(PATH_TO_REPO)
1090
+ commit_message = repo.head.commit.message
1091
+ commit_flags = parse_commit_message(commit_message)
1092
+ if commit_flags["skip"]:
1093
+ print("Force-skipping the CI")
1094
+ quit()
1095
+ if commit_flags["no_filter"]:
1096
+ print("Running all tests fetched without filtering.")
1097
+ if commit_flags["test_all"]:
1098
+ print("Force-launching all tests")
1099
+
1100
+ diff_with_last_commit = args.diff_with_last_commit
1101
+ if not diff_with_last_commit and not repo.head.is_detached and repo.head.ref == repo.refs.main:
1102
+ print("main branch detected, fetching tests against last commit.")
1103
+ diff_with_last_commit = True
1104
+
1105
+ if not commit_flags["test_all"]:
1106
+ try:
1107
+ infer_tests_to_run(
1108
+ args.output_file,
1109
+ diff_with_last_commit=diff_with_last_commit,
1110
+ json_output_file=args.json_output_file,
1111
+ )
1112
+ filter_tests(args.output_file, ["repo_utils"])
1113
+ update_test_map_with_core_pipelines(json_output_file=args.json_output_file)
1114
+
1115
+ except Exception as e:
1116
+ print(f"\nError when trying to grab the relevant tests: {e}\n\nRunning all tests.")
1117
+ commit_flags["test_all"] = True
1118
+
1119
+ if commit_flags["test_all"]:
1120
+ with open(args.output_file, "w", encoding="utf-8") as f:
1121
+ f.write("tests")
1122
+ example_file = Path(args.output_file).parent / "examples_test_list.txt"
1123
+ with open(example_file, "w", encoding="utf-8") as f:
1124
+ f.write("all")
1125
+
1126
+ test_files_to_run = get_all_tests()
1127
+ create_json_map(test_files_to_run, args.json_output_file)
1128
+ update_test_map_with_core_pipelines(json_output_file=args.json_output_file)
tasks/tasksmith-f40a643a6ef9/environment/source/utils/update_metadata.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Utility that updates the metadata of the Diffusers library in the repository `huggingface/diffusers-metadata`.
17
+
18
+ Usage for an update (as used by the GitHub action `update_metadata`):
19
+
20
+ ```bash
21
+ python utils/update_metadata.py
22
+ ```
23
+
24
+ Script modified from:
25
+ https://github.com/huggingface/transformers/blob/main/utils/update_metadata.py
26
+ """
27
+
28
+ import argparse
29
+ import os
30
+ import tempfile
31
+
32
+ import pandas as pd
33
+ from datasets import Dataset
34
+ from huggingface_hub import hf_hub_download, upload_folder
35
+
36
+ from diffusers.pipelines.auto_pipeline import (
37
+ AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
38
+ AUTO_INPAINT_PIPELINES_MAPPING,
39
+ AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
40
+ )
41
+
42
+
43
+ PIPELINE_TAG_JSON = "pipeline_tags.json"
44
+
45
+
46
+ def get_supported_pipeline_table() -> dict:
47
+ """
48
+ Generates a dictionary containing the supported auto classes for each pipeline type,
49
+ using the content of the auto modules.
50
+ """
51
+ # All supported pipelines for automatic mapping.
52
+ all_supported_pipeline_classes = [
53
+ (class_name.__name__, "text-to-image", "AutoPipelineForText2Image")
54
+ for _, class_name in AUTO_TEXT2IMAGE_PIPELINES_MAPPING.items()
55
+ ]
56
+ all_supported_pipeline_classes += [
57
+ (class_name.__name__, "image-to-image", "AutoPipelineForImage2Image")
58
+ for _, class_name in AUTO_IMAGE2IMAGE_PIPELINES_MAPPING.items()
59
+ ]
60
+ all_supported_pipeline_classes += [
61
+ (class_name.__name__, "image-to-image", "AutoPipelineForInpainting")
62
+ for _, class_name in AUTO_INPAINT_PIPELINES_MAPPING.items()
63
+ ]
64
+ all_supported_pipeline_classes = list(set(all_supported_pipeline_classes))
65
+ all_supported_pipeline_classes.sort(key=lambda x: x[0])
66
+
67
+ data = {}
68
+ data["pipeline_class"] = [sample[0] for sample in all_supported_pipeline_classes]
69
+ data["pipeline_tag"] = [sample[1] for sample in all_supported_pipeline_classes]
70
+ data["auto_class"] = [sample[2] for sample in all_supported_pipeline_classes]
71
+
72
+ return data
73
+
74
+
75
+ def update_metadata(commit_sha: str):
76
+ """
77
+ Update the metadata for the Diffusers repo in `huggingface/diffusers-metadata`.
78
+
79
+ Args:
80
+ commit_sha (`str`): The commit SHA on Diffusers corresponding to this update.
81
+ """
82
+ pipelines_table = get_supported_pipeline_table()
83
+ pipelines_table = pd.DataFrame(pipelines_table)
84
+ pipelines_dataset = Dataset.from_pandas(pipelines_table)
85
+
86
+ hub_pipeline_tags_json = hf_hub_download(
87
+ repo_id="huggingface/diffusers-metadata",
88
+ filename=PIPELINE_TAG_JSON,
89
+ repo_type="dataset",
90
+ )
91
+ with open(hub_pipeline_tags_json) as f:
92
+ hub_pipeline_tags_json = f.read()
93
+
94
+ with tempfile.TemporaryDirectory() as tmp_dir:
95
+ pipelines_dataset.to_json(os.path.join(tmp_dir, PIPELINE_TAG_JSON))
96
+
97
+ with open(os.path.join(tmp_dir, PIPELINE_TAG_JSON)) as f:
98
+ pipeline_tags_json = f.read()
99
+
100
+ hub_pipeline_tags_equal = hub_pipeline_tags_json == pipeline_tags_json
101
+ if hub_pipeline_tags_equal:
102
+ print("No updates, not pushing the metadata files.")
103
+ return
104
+
105
+ if commit_sha is not None:
106
+ commit_message = (
107
+ f"Update with commit {commit_sha}\n\nSee: https://github.com/huggingface/diffusers/commit/{commit_sha}"
108
+ )
109
+ else:
110
+ commit_message = "Update"
111
+
112
+ upload_folder(
113
+ repo_id="huggingface/diffusers-metadata",
114
+ folder_path=tmp_dir,
115
+ repo_type="dataset",
116
+ commit_message=commit_message,
117
+ )
118
+
119
+
120
+ if __name__ == "__main__":
121
+ parser = argparse.ArgumentParser()
122
+ parser.add_argument("--commit_sha", default=None, type=str, help="The sha of the commit going with this update.")
123
+ args = parser.parse_args()
124
+
125
+ update_metadata(args.commit_sha)
tasks/tasksmith-f40a643a6ef9/instruction.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Add LoRA loading/saving support to `HiDreamImagePipeline` and add a `force_inference_output` option to `HiDreamImageTransformer2DModel`.
2
+
3
+ **1. `HiDreamImageLoraLoaderMixin`**
4
+
5
+ Create a new mixin class `HiDreamImageLoraLoaderMixin` (exported from `diffusers.loaders`) that provides LoRA adapter management for the HiDream Image pipeline:
6
+
7
+ - `lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)` — class method that loads and returns a raw LoRA state dict, filtering out any DoRA-scale keys with a warning.
8
+ - `load_lora_weights(pretrained_model_name_or_path_or_dict, adapter_name=None, hotswap=False, **kwargs)` — validates that all keys contain `"lora"`, then loads them into `self.transformer` via `load_lora_into_transformer`.
9
+ - `load_lora_into_transformer(state_dict, transformer, adapter_name=None, ...)` — class method that calls `transformer.load_lora_adapter(...)`.
10
+ - `save_lora_weights(save_directory, transformer_lora_layers, ...)` — class method; raises `ValueError` if `transformer_lora_layers` is falsy; packs the weights under the `"transformer"` prefix (so every saved key starts with `"transformer."`) and writes `pytorch_lora_weights.safetensors`.
11
+ - `fuse_lora` and `unfuse_lora` — delegate to the parent `LoraBaseMixin`.
12
+ - `_lora_loadable_modules = ["transformer"]`
13
+
14
+ Make `HiDreamImagePipeline` inherit from this mixin in addition to `DiffusionPipeline`.
15
+
16
+ Add `HiDreamImageTransformer2DModel` to the PEFT weight-conversion registry so that LoRA weights are passed through without conversion (identity lambda).
17
+
18
+ **2. `force_inference_output` on `HiDreamImageTransformer2DModel`**
19
+
20
+ Add a `force_inference_output: bool = False` constructor argument to `HiDreamImageTransformer2DModel` (stored in `config`). When `True`:
21
+
22
+ - **MoE gate**: the auxiliary load-balancing loss is **not** computed (returns `None`) even when the model is in `model.train()` mode.
23
+ - **MoE block forward**: the training-mode token dispatch (repeating tokens for each expert) is **not** used; inference-mode dispatch is used instead.
24
+ - **`unpatchify`**: the training-mode output layout is **not** applied; the inference-mode branch is used.
25
+
26
+ When `force_inference_output=False` (the default), existing training-mode behavior is preserved: auxiliary loss is computed and training-mode dispatch is used.
27
+
28
+ The DreamBooth training script loads the transformer with `force_inference_output=True` so that LoRA fine-tuning does not interfere with MoE training dynamics.
29
+
30
+ Work in `/workspace`. Submit your fix in Python source files under `src/diffusers`, `examples/dreambooth/train_dreambooth_lora_hidream.py`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files.
tasks/tasksmith-f40a643a6ef9/solution/reference/examples/dreambooth/train_dreambooth_lora_hidream.py ADDED
@@ -0,0 +1,1721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+
16
+ import argparse
17
+ import copy
18
+ import itertools
19
+ import logging
20
+ import math
21
+ import os
22
+ import random
23
+ import shutil
24
+ import warnings
25
+ from contextlib import nullcontext
26
+ from pathlib import Path
27
+
28
+ import numpy as np
29
+ import torch
30
+ import torch.utils.checkpoint
31
+ import transformers
32
+ from accelerate import Accelerator
33
+ from accelerate.logging import get_logger
34
+ from accelerate.utils import DistributedDataParallelKwargs, ProjectConfiguration, set_seed
35
+ from huggingface_hub import create_repo, upload_folder
36
+ from huggingface_hub.utils import insecure_hashlib
37
+ from peft import LoraConfig, set_peft_model_state_dict
38
+ from peft.utils import get_peft_model_state_dict
39
+ from PIL import Image
40
+ from PIL.ImageOps import exif_transpose
41
+ from torch.utils.data import Dataset
42
+ from torchvision import transforms
43
+ from torchvision.transforms.functional import crop
44
+ from tqdm.auto import tqdm
45
+ from transformers import AutoTokenizer, CLIPTokenizer, LlamaForCausalLM, PretrainedConfig, T5Tokenizer
46
+
47
+ import diffusers
48
+ from diffusers import (
49
+ AutoencoderKL,
50
+ FlowMatchEulerDiscreteScheduler,
51
+ HiDreamImagePipeline,
52
+ HiDreamImageTransformer2DModel,
53
+ )
54
+ from diffusers.optimization import get_scheduler
55
+ from diffusers.training_utils import (
56
+ cast_training_params,
57
+ compute_density_for_timestep_sampling,
58
+ compute_loss_weighting_for_sd3,
59
+ free_memory,
60
+ )
61
+ from diffusers.utils import (
62
+ check_min_version,
63
+ convert_unet_state_dict_to_peft,
64
+ is_wandb_available,
65
+ )
66
+ from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
67
+ from diffusers.utils.import_utils import is_torch_npu_available
68
+ from diffusers.utils.torch_utils import is_compiled_module
69
+
70
+
71
+ if is_wandb_available():
72
+ import wandb
73
+
74
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
75
+ check_min_version("0.33.0.dev0")
76
+
77
+ logger = get_logger(__name__)
78
+
79
+ if is_torch_npu_available():
80
+ torch.npu.config.allow_internal_format = False
81
+
82
+
83
+ def save_model_card(
84
+ repo_id: str,
85
+ images=None,
86
+ base_model: str = None,
87
+ instance_prompt=None,
88
+ validation_prompt=None,
89
+ repo_folder=None,
90
+ ):
91
+ widget_dict = []
92
+ if images is not None:
93
+ for i, image in enumerate(images):
94
+ image.save(os.path.join(repo_folder, f"image_{i}.png"))
95
+ widget_dict.append(
96
+ {"text": validation_prompt if validation_prompt else " ", "output": {"url": f"image_{i}.png"}}
97
+ )
98
+
99
+ model_description = f"""
100
+ # HiDream Image DreamBooth LoRA - {repo_id}
101
+
102
+ <Gallery />
103
+
104
+ ## Model description
105
+
106
+ These are {repo_id} DreamBooth LoRA weights for {base_model}.
107
+
108
+ The weights were trained using [DreamBooth](https://dreambooth.github.io/) with the [HiDream Image diffusers trainer](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/README_hidream.md).
109
+
110
+ ## Trigger words
111
+
112
+ You should use `{instance_prompt}` to trigger the image generation.
113
+
114
+ ## Download model
115
+
116
+ [Download the *.safetensors LoRA]({repo_id}/tree/main) in the Files & versions tab.
117
+
118
+ ## Use it with the [🧨 diffusers library](https://github.com/huggingface/diffusers)
119
+
120
+ ```py
121
+ >>> import torch
122
+ >>> from transformers import PreTrainedTokenizerFast, LlamaForCausalLM
123
+ >>> from diffusers import UniPCMultistepScheduler, HiDreamImagePipeline
124
+
125
+ >>> scheduler = UniPCMultistepScheduler(
126
+ ... flow_shift=3.0, prediction_type="flow_prediction", use_flow_sigmas=True
127
+ ... )
128
+
129
+ >>> tokenizer_4 = PreTrainedTokenizerFast.from_pretrained("meta-llama/Meta-Llama-3.1-8B-Instruct")
130
+ >>> text_encoder_4 = LlamaForCausalLM.from_pretrained(
131
+ ... "meta-llama/Meta-Llama-3.1-8B-Instruct",
132
+ ... output_hidden_states=True,
133
+ ... output_attentions=True,
134
+ ... torch_dtype=torch.bfloat16,
135
+ ... )
136
+
137
+ >>> pipe = HiDreamImagePipeline.from_pretrained(
138
+ ... "HiDream-ai/HiDream-I1-Full",
139
+ ... scheduler=scheduler,
140
+ ... tokenizer_4=tokenizer_4,
141
+ ... text_encoder_4=text_encoder_4,
142
+ ... torch_dtype=torch.bfloat16,
143
+ ... )
144
+ >>> pipe.enable_model_cpu_offload()
145
+ >>> pipe.load_lora_weights(f"{repo_id}")
146
+ >>> image = pipe(f"{instance_prompt}").images[0]
147
+
148
+
149
+ ```
150
+
151
+ For more details, including weighting, merging and fusing LoRAs, check the [documentation on loading LoRAs in diffusers](https://huggingface.co/docs/diffusers/main/en/using-diffusers/loading_adapters)
152
+ """
153
+ model_card = load_or_create_model_card(
154
+ repo_id_or_path=repo_id,
155
+ from_training=True,
156
+ license="mit",
157
+ base_model=base_model,
158
+ prompt=instance_prompt,
159
+ model_description=model_description,
160
+ widget=widget_dict,
161
+ )
162
+ tags = [
163
+ "text-to-image",
164
+ "diffusers-training",
165
+ "diffusers",
166
+ "lora",
167
+ "hidream",
168
+ "hidream-diffusers",
169
+ "template:sd-lora",
170
+ ]
171
+
172
+ model_card = populate_model_card(model_card, tags=tags)
173
+ model_card.save(os.path.join(repo_folder, "README.md"))
174
+
175
+
176
+ def load_text_encoders(class_one, class_two, class_three):
177
+ text_encoder_one = class_one.from_pretrained(
178
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
179
+ )
180
+ text_encoder_two = class_two.from_pretrained(
181
+ args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision, variant=args.variant
182
+ )
183
+ text_encoder_three = class_three.from_pretrained(
184
+ args.pretrained_model_name_or_path, subfolder="text_encoder_3", revision=args.revision, variant=args.variant
185
+ )
186
+ text_encoder_four = LlamaForCausalLM.from_pretrained(
187
+ args.pretrained_text_encoder_4_name_or_path,
188
+ output_hidden_states=True,
189
+ output_attentions=True,
190
+ torch_dtype=torch.bfloat16,
191
+ )
192
+ return text_encoder_one, text_encoder_two, text_encoder_three, text_encoder_four
193
+
194
+
195
+ def log_validation(
196
+ pipeline,
197
+ args,
198
+ accelerator,
199
+ pipeline_args,
200
+ epoch,
201
+ torch_dtype,
202
+ is_final_validation=False,
203
+ ):
204
+ logger.info(
205
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
206
+ f" {args.validation_prompt}."
207
+ )
208
+ pipeline = pipeline.to(accelerator.device, dtype=torch_dtype)
209
+ pipeline.set_progress_bar_config(disable=True)
210
+
211
+ # run inference
212
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed is not None else None
213
+ autocast_ctx = torch.autocast(accelerator.device.type) if not is_final_validation else nullcontext()
214
+
215
+ # pre-calculate prompt embeds, pooled prompt embeds, text ids because t5 does not support autocast
216
+ with torch.no_grad():
217
+ (
218
+ prompt_embeds_t5,
219
+ negative_prompt_embeds_t5,
220
+ prompt_embeds_llama3,
221
+ negative_prompt_embeds_llama3,
222
+ pooled_prompt_embeds,
223
+ negative_pooled_prompt_embeds,
224
+ ) = pipeline.encode_prompt(
225
+ pipeline_args["prompt"],
226
+ )
227
+ images = []
228
+ for _ in range(args.num_validation_images):
229
+ with autocast_ctx:
230
+ image = pipeline(
231
+ prompt_embeds_t5=prompt_embeds_t5,
232
+ prompt_embeds_llama3=prompt_embeds_llama3,
233
+ negative_prompt_embeds_t5=negative_prompt_embeds_t5,
234
+ negative_prompt_embeds_llama3=negative_prompt_embeds_llama3,
235
+ pooled_prompt_embeds=pooled_prompt_embeds,
236
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
237
+ generator=generator,
238
+ ).images[0]
239
+ images.append(image)
240
+
241
+ for tracker in accelerator.trackers:
242
+ phase_name = "test" if is_final_validation else "validation"
243
+ if tracker.name == "tensorboard":
244
+ np_images = np.stack([np.asarray(img) for img in images])
245
+ tracker.writer.add_images(phase_name, np_images, epoch, dataformats="NHWC")
246
+ if tracker.name == "wandb":
247
+ tracker.log(
248
+ {
249
+ phase_name: [
250
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}") for i, image in enumerate(images)
251
+ ]
252
+ }
253
+ )
254
+
255
+ del pipeline
256
+ if torch.cuda.is_available():
257
+ torch.cuda.empty_cache()
258
+
259
+ return images
260
+
261
+
262
+ def import_model_class_from_model_name_or_path(
263
+ pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
264
+ ):
265
+ text_encoder_config = PretrainedConfig.from_pretrained(
266
+ pretrained_model_name_or_path, subfolder=subfolder, revision=revision
267
+ )
268
+ model_class = text_encoder_config.architectures[0]
269
+ if model_class == "CLIPTextModelWithProjection" or model_class == "CLIPTextModel":
270
+ from transformers import CLIPTextModelWithProjection
271
+
272
+ return CLIPTextModelWithProjection
273
+ elif model_class == "T5EncoderModel":
274
+ from transformers import T5EncoderModel
275
+
276
+ return T5EncoderModel
277
+ else:
278
+ raise ValueError(f"{model_class} is not supported.")
279
+
280
+
281
+ def parse_args(input_args=None):
282
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
283
+ parser.add_argument(
284
+ "--pretrained_model_name_or_path",
285
+ type=str,
286
+ default=None,
287
+ required=True,
288
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
289
+ )
290
+ parser.add_argument(
291
+ "--pretrained_tokenizer_4_name_or_path",
292
+ type=str,
293
+ default="meta-llama/Meta-Llama-3.1-8B-Instruct",
294
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
295
+ )
296
+ parser.add_argument(
297
+ "--pretrained_text_encoder_4_name_or_path",
298
+ type=str,
299
+ default="meta-llama/Meta-Llama-3.1-8B-Instruct",
300
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
301
+ )
302
+ parser.add_argument(
303
+ "--revision",
304
+ type=str,
305
+ default=None,
306
+ required=False,
307
+ help="Revision of pretrained model identifier from huggingface.co/models.",
308
+ )
309
+ parser.add_argument(
310
+ "--variant",
311
+ type=str,
312
+ default=None,
313
+ help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
314
+ )
315
+ parser.add_argument(
316
+ "--dataset_name",
317
+ type=str,
318
+ default=None,
319
+ help=(
320
+ "The name of the Dataset (from the HuggingFace hub) containing the training data of instance images (could be your own, possibly private,"
321
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
322
+ " or to a folder containing files that 🤗 Datasets can understand."
323
+ ),
324
+ )
325
+ parser.add_argument(
326
+ "--dataset_config_name",
327
+ type=str,
328
+ default=None,
329
+ help="The config of the Dataset, leave as None if there's only one config.",
330
+ )
331
+ parser.add_argument(
332
+ "--instance_data_dir",
333
+ type=str,
334
+ default=None,
335
+ help=("A folder containing the training data. "),
336
+ )
337
+
338
+ parser.add_argument(
339
+ "--cache_dir",
340
+ type=str,
341
+ default=None,
342
+ help="The directory where the downloaded models and datasets will be stored.",
343
+ )
344
+
345
+ parser.add_argument(
346
+ "--image_column",
347
+ type=str,
348
+ default="image",
349
+ help="The column of the dataset containing the target image. By "
350
+ "default, the standard Image Dataset maps out 'file_name' "
351
+ "to 'image'.",
352
+ )
353
+ parser.add_argument(
354
+ "--caption_column",
355
+ type=str,
356
+ default=None,
357
+ help="The column of the dataset containing the instance prompt for each image",
358
+ )
359
+
360
+ parser.add_argument("--repeats", type=int, default=1, help="How many times to repeat the training data.")
361
+
362
+ parser.add_argument(
363
+ "--class_data_dir",
364
+ type=str,
365
+ default=None,
366
+ required=False,
367
+ help="A folder containing the training data of class images.",
368
+ )
369
+ parser.add_argument(
370
+ "--instance_prompt",
371
+ type=str,
372
+ default=None,
373
+ required=True,
374
+ help="The prompt with identifier specifying the instance, e.g. 'photo of a TOK dog', 'in the style of TOK'",
375
+ )
376
+ parser.add_argument(
377
+ "--class_prompt",
378
+ type=str,
379
+ default=None,
380
+ help="The prompt to specify images in the same class as provided instance images.",
381
+ )
382
+ parser.add_argument(
383
+ "--max_sequence_length",
384
+ type=int,
385
+ default=128,
386
+ help="Maximum sequence length to use with t5 and llama encoders",
387
+ )
388
+
389
+ parser.add_argument(
390
+ "--validation_prompt",
391
+ type=str,
392
+ default=None,
393
+ help="A prompt that is used during validation to verify that the model is learning.",
394
+ )
395
+ parser.add_argument(
396
+ "--final_validation_prompt",
397
+ type=str,
398
+ default=None,
399
+ help="A prompt that is used during a final validation to verify that the model is learning. Ignored if `--validation_prompt` is provided.",
400
+ )
401
+ parser.add_argument(
402
+ "--num_validation_images",
403
+ type=int,
404
+ default=4,
405
+ help="Number of images that should be generated during validation with `validation_prompt`.",
406
+ )
407
+ parser.add_argument(
408
+ "--validation_epochs",
409
+ type=int,
410
+ default=50,
411
+ help=(
412
+ "Run dreambooth validation every X epochs. Dreambooth validation consists of running the prompt"
413
+ " `args.validation_prompt` multiple times: `args.num_validation_images`."
414
+ ),
415
+ )
416
+ parser.add_argument(
417
+ "--rank",
418
+ type=int,
419
+ default=4,
420
+ help=("The dimension of the LoRA update matrices."),
421
+ )
422
+ parser.add_argument(
423
+ "--with_prior_preservation",
424
+ default=False,
425
+ action="store_true",
426
+ help="Flag to add prior preservation loss.",
427
+ )
428
+ parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.")
429
+ parser.add_argument(
430
+ "--num_class_images",
431
+ type=int,
432
+ default=100,
433
+ help=(
434
+ "Minimal class images for prior preservation loss. If there are not enough images already present in"
435
+ " class_data_dir, additional images will be sampled with class_prompt."
436
+ ),
437
+ )
438
+ parser.add_argument(
439
+ "--output_dir",
440
+ type=str,
441
+ default="hidream-dreambooth-lora",
442
+ help="The output directory where the model predictions and checkpoints will be written.",
443
+ )
444
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
445
+ parser.add_argument(
446
+ "--resolution",
447
+ type=int,
448
+ default=512,
449
+ help=(
450
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
451
+ " resolution"
452
+ ),
453
+ )
454
+ parser.add_argument(
455
+ "--center_crop",
456
+ default=False,
457
+ action="store_true",
458
+ help=(
459
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
460
+ " cropped. The images will be resized to the resolution first before cropping."
461
+ ),
462
+ )
463
+ parser.add_argument(
464
+ "--random_flip",
465
+ action="store_true",
466
+ help="whether to randomly flip images horizontally",
467
+ )
468
+ parser.add_argument(
469
+ "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
470
+ )
471
+ parser.add_argument(
472
+ "--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
473
+ )
474
+ parser.add_argument("--num_train_epochs", type=int, default=1)
475
+ parser.add_argument(
476
+ "--max_train_steps",
477
+ type=int,
478
+ default=None,
479
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
480
+ )
481
+ parser.add_argument(
482
+ "--checkpointing_steps",
483
+ type=int,
484
+ default=500,
485
+ help=(
486
+ "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
487
+ " checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
488
+ " training using `--resume_from_checkpoint`."
489
+ ),
490
+ )
491
+ parser.add_argument(
492
+ "--checkpoints_total_limit",
493
+ type=int,
494
+ default=None,
495
+ help=("Max number of checkpoints to store."),
496
+ )
497
+ parser.add_argument(
498
+ "--resume_from_checkpoint",
499
+ type=str,
500
+ default=None,
501
+ help=(
502
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
503
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
504
+ ),
505
+ )
506
+ parser.add_argument(
507
+ "--gradient_accumulation_steps",
508
+ type=int,
509
+ default=1,
510
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
511
+ )
512
+ parser.add_argument(
513
+ "--gradient_checkpointing",
514
+ action="store_true",
515
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
516
+ )
517
+ parser.add_argument(
518
+ "--learning_rate",
519
+ type=float,
520
+ default=1e-4,
521
+ help="Initial learning rate (after the potential warmup period) to use.",
522
+ )
523
+ parser.add_argument(
524
+ "--scale_lr",
525
+ action="store_true",
526
+ default=False,
527
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
528
+ )
529
+ parser.add_argument(
530
+ "--lr_scheduler",
531
+ type=str,
532
+ default="constant",
533
+ help=(
534
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
535
+ ' "constant", "constant_with_warmup"]'
536
+ ),
537
+ )
538
+ parser.add_argument(
539
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
540
+ )
541
+ parser.add_argument(
542
+ "--lr_num_cycles",
543
+ type=int,
544
+ default=1,
545
+ help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
546
+ )
547
+ parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
548
+ parser.add_argument(
549
+ "--dataloader_num_workers",
550
+ type=int,
551
+ default=0,
552
+ help=(
553
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
554
+ ),
555
+ )
556
+ parser.add_argument(
557
+ "--weighting_scheme",
558
+ type=str,
559
+ default="none",
560
+ choices=["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"],
561
+ help=('We default to the "none" weighting scheme for uniform sampling and uniform loss'),
562
+ )
563
+ parser.add_argument(
564
+ "--logit_mean", type=float, default=0.0, help="mean to use when using the `'logit_normal'` weighting scheme."
565
+ )
566
+ parser.add_argument(
567
+ "--logit_std", type=float, default=1.0, help="std to use when using the `'logit_normal'` weighting scheme."
568
+ )
569
+ parser.add_argument(
570
+ "--mode_scale",
571
+ type=float,
572
+ default=1.29,
573
+ help="Scale of mode weighting scheme. Only effective when using the `'mode'` as the `weighting_scheme`.",
574
+ )
575
+ parser.add_argument(
576
+ "--optimizer",
577
+ type=str,
578
+ default="AdamW",
579
+ help=('The optimizer type to use. Choose between ["AdamW", "prodigy"]'),
580
+ )
581
+
582
+ parser.add_argument(
583
+ "--use_8bit_adam",
584
+ action="store_true",
585
+ help="Whether or not to use 8-bit Adam from bitsandbytes. Ignored if optimizer is not set to AdamW",
586
+ )
587
+
588
+ parser.add_argument(
589
+ "--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam and Prodigy optimizers."
590
+ )
591
+ parser.add_argument(
592
+ "--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam and Prodigy optimizers."
593
+ )
594
+ parser.add_argument(
595
+ "--prodigy_beta3",
596
+ type=float,
597
+ default=None,
598
+ help="coefficients for computing the Prodigy stepsize using running averages. If set to None, "
599
+ "uses the value of square root of beta2. Ignored if optimizer is adamW",
600
+ )
601
+ parser.add_argument("--prodigy_decouple", type=bool, default=True, help="Use AdamW style decoupled weight decay")
602
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-04, help="Weight decay to use for unet params")
603
+ parser.add_argument(
604
+ "--lora_layers",
605
+ type=str,
606
+ default=None,
607
+ help=(
608
+ 'The transformer modules to apply LoRA training on. Please specify the layers in a comma seperated. E.g. - "to_k,to_q,to_v" will result in lora training of attention layers only'
609
+ ),
610
+ )
611
+
612
+ parser.add_argument(
613
+ "--adam_epsilon",
614
+ type=float,
615
+ default=1e-08,
616
+ help="Epsilon value for the Adam optimizer and Prodigy optimizers.",
617
+ )
618
+
619
+ parser.add_argument(
620
+ "--prodigy_use_bias_correction",
621
+ type=bool,
622
+ default=True,
623
+ help="Turn on Adam's bias correction. True by default. Ignored if optimizer is adamW",
624
+ )
625
+ parser.add_argument(
626
+ "--prodigy_safeguard_warmup",
627
+ type=bool,
628
+ default=True,
629
+ help="Remove lr from the denominator of D estimate to avoid issues during warm-up stage. True by default. "
630
+ "Ignored if optimizer is adamW",
631
+ )
632
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
633
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
634
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
635
+ parser.add_argument(
636
+ "--hub_model_id",
637
+ type=str,
638
+ default=None,
639
+ help="The name of the repository to keep in sync with the local `output_dir`.",
640
+ )
641
+ parser.add_argument(
642
+ "--logging_dir",
643
+ type=str,
644
+ default="logs",
645
+ help=(
646
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
647
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
648
+ ),
649
+ )
650
+ parser.add_argument(
651
+ "--allow_tf32",
652
+ action="store_true",
653
+ help=(
654
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
655
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
656
+ ),
657
+ )
658
+ parser.add_argument(
659
+ "--cache_latents",
660
+ action="store_true",
661
+ default=False,
662
+ help="Cache the VAE latents",
663
+ )
664
+ parser.add_argument(
665
+ "--report_to",
666
+ type=str,
667
+ default="tensorboard",
668
+ help=(
669
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
670
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
671
+ ),
672
+ )
673
+ parser.add_argument(
674
+ "--mixed_precision",
675
+ type=str,
676
+ default=None,
677
+ choices=["no", "fp16", "bf16"],
678
+ help=(
679
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
680
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
681
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
682
+ ),
683
+ )
684
+ parser.add_argument(
685
+ "--upcast_before_saving",
686
+ action="store_true",
687
+ default=False,
688
+ help=(
689
+ "Whether to upcast the trained transformer layers to float32 before saving (at the end of training). "
690
+ "Defaults to precision dtype used for training to save memory"
691
+ ),
692
+ )
693
+ parser.add_argument(
694
+ "--offload",
695
+ action="store_true",
696
+ help="Whether to offload the VAE and the text encoder to CPU when they are not used.",
697
+ )
698
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
699
+
700
+ if input_args is not None:
701
+ args = parser.parse_args(input_args)
702
+ else:
703
+ args = parser.parse_args()
704
+
705
+ if args.dataset_name is None and args.instance_data_dir is None:
706
+ raise ValueError("Specify either `--dataset_name` or `--instance_data_dir`")
707
+
708
+ if args.dataset_name is not None and args.instance_data_dir is not None:
709
+ raise ValueError("Specify only one of `--dataset_name` or `--instance_data_dir`")
710
+
711
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
712
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
713
+ args.local_rank = env_local_rank
714
+
715
+ if args.with_prior_preservation:
716
+ if args.class_data_dir is None:
717
+ raise ValueError("You must specify a data directory for class images.")
718
+ if args.class_prompt is None:
719
+ raise ValueError("You must specify prompt for class images.")
720
+ else:
721
+ # logger is not available yet
722
+ if args.class_data_dir is not None:
723
+ warnings.warn("You need not use --class_data_dir without --with_prior_preservation.")
724
+ if args.class_prompt is not None:
725
+ warnings.warn("You need not use --class_prompt without --with_prior_preservation.")
726
+
727
+ return args
728
+
729
+
730
+ class DreamBoothDataset(Dataset):
731
+ """
732
+ A dataset to prepare the instance and class images with the prompts for fine-tuning the model.
733
+ It pre-processes the images.
734
+ """
735
+
736
+ def __init__(
737
+ self,
738
+ instance_data_root,
739
+ instance_prompt,
740
+ class_prompt,
741
+ class_data_root=None,
742
+ class_num=None,
743
+ size=1024,
744
+ repeats=1,
745
+ center_crop=False,
746
+ ):
747
+ self.size = size
748
+ self.center_crop = center_crop
749
+
750
+ self.instance_prompt = instance_prompt
751
+ self.custom_instance_prompts = None
752
+ self.class_prompt = class_prompt
753
+
754
+ # if --dataset_name is provided or a metadata jsonl file is provided in the local --instance_data directory,
755
+ # we load the training data using load_dataset
756
+ if args.dataset_name is not None:
757
+ try:
758
+ from datasets import load_dataset
759
+ except ImportError:
760
+ raise ImportError(
761
+ "You are trying to load your data using the datasets library. If you wish to train using custom "
762
+ "captions please install the datasets library: `pip install datasets`. If you wish to load a "
763
+ "local folder containing images only, specify --instance_data_dir instead."
764
+ )
765
+ # Downloading and loading a dataset from the hub.
766
+ # See more about loading custom images at
767
+ # https://huggingface.co/docs/datasets/v2.0.0/en/dataset_script
768
+ dataset = load_dataset(
769
+ args.dataset_name,
770
+ args.dataset_config_name,
771
+ cache_dir=args.cache_dir,
772
+ )
773
+ # Preprocessing the datasets.
774
+ column_names = dataset["train"].column_names
775
+
776
+ # 6. Get the column names for input/target.
777
+ if args.image_column is None:
778
+ image_column = column_names[0]
779
+ logger.info(f"image column defaulting to {image_column}")
780
+ else:
781
+ image_column = args.image_column
782
+ if image_column not in column_names:
783
+ raise ValueError(
784
+ f"`--image_column` value '{args.image_column}' not found in dataset columns. Dataset columns are: {', '.join(column_names)}"
785
+ )
786
+ instance_images = dataset["train"][image_column]
787
+
788
+ if args.caption_column is None:
789
+ logger.info(
790
+ "No caption column provided, defaulting to instance_prompt for all images. If your dataset "
791
+ "contains captions/prompts for the images, make sure to specify the "
792
+ "column as --caption_column"
793
+ )
794
+ self.custom_instance_prompts = None
795
+ else:
796
+ if args.caption_column not in column_names:
797
+ raise ValueError(
798
+ f"`--caption_column` value '{args.caption_column}' not found in dataset columns. Dataset columns are: {', '.join(column_names)}"
799
+ )
800
+ custom_instance_prompts = dataset["train"][args.caption_column]
801
+ # create final list of captions according to --repeats
802
+ self.custom_instance_prompts = []
803
+ for caption in custom_instance_prompts:
804
+ self.custom_instance_prompts.extend(itertools.repeat(caption, repeats))
805
+ else:
806
+ self.instance_data_root = Path(instance_data_root)
807
+ if not self.instance_data_root.exists():
808
+ raise ValueError("Instance images root doesn't exists.")
809
+
810
+ instance_images = [Image.open(path) for path in list(Path(instance_data_root).iterdir())]
811
+ self.custom_instance_prompts = None
812
+
813
+ self.instance_images = []
814
+ for img in instance_images:
815
+ self.instance_images.extend(itertools.repeat(img, repeats))
816
+
817
+ self.pixel_values = []
818
+ train_resize = transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR)
819
+ train_crop = transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size)
820
+ train_flip = transforms.RandomHorizontalFlip(p=1.0)
821
+ train_transforms = transforms.Compose(
822
+ [
823
+ transforms.ToTensor(),
824
+ transforms.Normalize([0.5], [0.5]),
825
+ ]
826
+ )
827
+ for image in self.instance_images:
828
+ image = exif_transpose(image)
829
+ if not image.mode == "RGB":
830
+ image = image.convert("RGB")
831
+ image = train_resize(image)
832
+ if args.random_flip and random.random() < 0.5:
833
+ # flip
834
+ image = train_flip(image)
835
+ if args.center_crop:
836
+ y1 = max(0, int(round((image.height - args.resolution) / 2.0)))
837
+ x1 = max(0, int(round((image.width - args.resolution) / 2.0)))
838
+ image = train_crop(image)
839
+ else:
840
+ y1, x1, h, w = train_crop.get_params(image, (args.resolution, args.resolution))
841
+ image = crop(image, y1, x1, h, w)
842
+ image = train_transforms(image)
843
+ self.pixel_values.append(image)
844
+
845
+ self.num_instance_images = len(self.instance_images)
846
+ self._length = self.num_instance_images
847
+
848
+ if class_data_root is not None:
849
+ self.class_data_root = Path(class_data_root)
850
+ self.class_data_root.mkdir(parents=True, exist_ok=True)
851
+ self.class_images_path = list(self.class_data_root.iterdir())
852
+ if class_num is not None:
853
+ self.num_class_images = min(len(self.class_images_path), class_num)
854
+ else:
855
+ self.num_class_images = len(self.class_images_path)
856
+ self._length = max(self.num_class_images, self.num_instance_images)
857
+ else:
858
+ self.class_data_root = None
859
+
860
+ self.image_transforms = transforms.Compose(
861
+ [
862
+ transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),
863
+ transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),
864
+ transforms.ToTensor(),
865
+ transforms.Normalize([0.5], [0.5]),
866
+ ]
867
+ )
868
+
869
+ def __len__(self):
870
+ return self._length
871
+
872
+ def __getitem__(self, index):
873
+ example = {}
874
+ instance_image = self.pixel_values[index % self.num_instance_images]
875
+ example["instance_images"] = instance_image
876
+
877
+ if self.custom_instance_prompts:
878
+ caption = self.custom_instance_prompts[index % self.num_instance_images]
879
+ if caption:
880
+ example["instance_prompt"] = caption
881
+ else:
882
+ example["instance_prompt"] = self.instance_prompt
883
+
884
+ else: # custom prompts were provided, but length does not match size of image dataset
885
+ example["instance_prompt"] = self.instance_prompt
886
+
887
+ if self.class_data_root:
888
+ class_image = Image.open(self.class_images_path[index % self.num_class_images])
889
+ class_image = exif_transpose(class_image)
890
+
891
+ if not class_image.mode == "RGB":
892
+ class_image = class_image.convert("RGB")
893
+ example["class_images"] = self.image_transforms(class_image)
894
+ example["class_prompt"] = self.class_prompt
895
+
896
+ return example
897
+
898
+
899
+ def collate_fn(examples, with_prior_preservation=False):
900
+ pixel_values = [example["instance_images"] for example in examples]
901
+ prompts = [example["instance_prompt"] for example in examples]
902
+
903
+ # Concat class and instance examples for prior preservation.
904
+ # We do this to avoid doing two forward passes.
905
+ if with_prior_preservation:
906
+ pixel_values += [example["class_images"] for example in examples]
907
+ prompts += [example["class_prompt"] for example in examples]
908
+
909
+ pixel_values = torch.stack(pixel_values)
910
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
911
+
912
+ batch = {"pixel_values": pixel_values, "prompts": prompts}
913
+ return batch
914
+
915
+
916
+ class PromptDataset(Dataset):
917
+ "A simple dataset to prepare the prompts to generate class images on multiple GPUs."
918
+
919
+ def __init__(self, prompt, num_samples):
920
+ self.prompt = prompt
921
+ self.num_samples = num_samples
922
+
923
+ def __len__(self):
924
+ return self.num_samples
925
+
926
+ def __getitem__(self, index):
927
+ example = {}
928
+ example["prompt"] = self.prompt
929
+ example["index"] = index
930
+ return example
931
+
932
+
933
+ def main(args):
934
+ if args.report_to == "wandb" and args.hub_token is not None:
935
+ raise ValueError(
936
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
937
+ " Please use `huggingface-cli login` to authenticate with the Hub."
938
+ )
939
+
940
+ if torch.backends.mps.is_available() and args.mixed_precision == "bf16":
941
+ # due to pytorch#99272, MPS does not yet support bfloat16.
942
+ raise ValueError(
943
+ "Mixed precision training with bfloat16 is not supported on MPS. Please use fp16 (recommended) or fp32 instead."
944
+ )
945
+
946
+ logging_dir = Path(args.output_dir, args.logging_dir)
947
+
948
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
949
+ kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
950
+ accelerator = Accelerator(
951
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
952
+ mixed_precision=args.mixed_precision,
953
+ log_with=args.report_to,
954
+ project_config=accelerator_project_config,
955
+ kwargs_handlers=[kwargs],
956
+ )
957
+
958
+ # Disable AMP for MPS.
959
+ if torch.backends.mps.is_available():
960
+ accelerator.native_amp = False
961
+
962
+ if args.report_to == "wandb":
963
+ if not is_wandb_available():
964
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
965
+
966
+ # Make one log on every process with the configuration for debugging.
967
+ logging.basicConfig(
968
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
969
+ datefmt="%m/%d/%Y %H:%M:%S",
970
+ level=logging.INFO,
971
+ )
972
+ logger.info(accelerator.state, main_process_only=False)
973
+ if accelerator.is_local_main_process:
974
+ transformers.utils.logging.set_verbosity_warning()
975
+ diffusers.utils.logging.set_verbosity_info()
976
+ else:
977
+ transformers.utils.logging.set_verbosity_error()
978
+ diffusers.utils.logging.set_verbosity_error()
979
+
980
+ # If passed along, set the training seed now.
981
+ if args.seed is not None:
982
+ set_seed(args.seed)
983
+
984
+ # Generate class images if prior preservation is enabled.
985
+ if args.with_prior_preservation:
986
+ class_images_dir = Path(args.class_data_dir)
987
+ if not class_images_dir.exists():
988
+ class_images_dir.mkdir(parents=True)
989
+ cur_class_images = len(list(class_images_dir.iterdir()))
990
+
991
+ if cur_class_images < args.num_class_images:
992
+ pipeline = HiDreamImagePipeline.from_pretrained(
993
+ args.pretrained_model_name_or_path,
994
+ torch_dtype=torch.bfloat16 if args.mixed_precision == "bf16" else torch.float16,
995
+ revision=args.revision,
996
+ variant=args.variant,
997
+ )
998
+ pipeline.set_progress_bar_config(disable=True)
999
+
1000
+ num_new_images = args.num_class_images - cur_class_images
1001
+ logger.info(f"Number of class images to sample: {num_new_images}.")
1002
+
1003
+ sample_dataset = PromptDataset(args.class_prompt, num_new_images)
1004
+ sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)
1005
+
1006
+ sample_dataloader = accelerator.prepare(sample_dataloader)
1007
+ pipeline.to(accelerator.device)
1008
+
1009
+ for example in tqdm(
1010
+ sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process
1011
+ ):
1012
+ images = pipeline(example["prompt"]).images
1013
+
1014
+ for i, image in enumerate(images):
1015
+ hash_image = insecure_hashlib.sha1(image.tobytes()).hexdigest()
1016
+ image_filename = class_images_dir / f"{example['index'][i] + cur_class_images}-{hash_image}.jpg"
1017
+ image.save(image_filename)
1018
+
1019
+ del pipeline
1020
+ free_memory()
1021
+
1022
+ # Handle the repository creation
1023
+ if accelerator.is_main_process:
1024
+ if args.output_dir is not None:
1025
+ os.makedirs(args.output_dir, exist_ok=True)
1026
+
1027
+ if args.push_to_hub:
1028
+ repo_id = create_repo(
1029
+ repo_id=args.hub_model_id or Path(args.output_dir).name,
1030
+ exist_ok=True,
1031
+ ).repo_id
1032
+
1033
+ # Load the tokenizers
1034
+ tokenizer_one = CLIPTokenizer.from_pretrained(
1035
+ args.pretrained_model_name_or_path,
1036
+ subfolder="tokenizer",
1037
+ revision=args.revision,
1038
+ )
1039
+ tokenizer_two = CLIPTokenizer.from_pretrained(
1040
+ args.pretrained_model_name_or_path,
1041
+ subfolder="tokenizer_2",
1042
+ revision=args.revision,
1043
+ )
1044
+ tokenizer_three = T5Tokenizer.from_pretrained(
1045
+ args.pretrained_model_name_or_path,
1046
+ subfolder="tokenizer_3",
1047
+ revision=args.revision,
1048
+ )
1049
+
1050
+ tokenizer_four = AutoTokenizer.from_pretrained(
1051
+ args.pretrained_tokenizer_4_name_or_path,
1052
+ revision=args.revision,
1053
+ )
1054
+ tokenizer_four.pad_token = tokenizer_four.eos_token
1055
+
1056
+ # import correct text encoder classes
1057
+ text_encoder_cls_one = import_model_class_from_model_name_or_path(
1058
+ args.pretrained_model_name_or_path, args.revision
1059
+ )
1060
+ text_encoder_cls_two = import_model_class_from_model_name_or_path(
1061
+ args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
1062
+ )
1063
+ text_encoder_cls_three = import_model_class_from_model_name_or_path(
1064
+ args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_3"
1065
+ )
1066
+
1067
+ # Load scheduler and models
1068
+ noise_scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
1069
+ args.pretrained_model_name_or_path, subfolder="scheduler", revision=args.revision, shift=3.0
1070
+ )
1071
+ noise_scheduler_copy = copy.deepcopy(noise_scheduler)
1072
+ text_encoder_one, text_encoder_two, text_encoder_three, text_encoder_four = load_text_encoders(
1073
+ text_encoder_cls_one, text_encoder_cls_two, text_encoder_cls_three
1074
+ )
1075
+
1076
+ vae = AutoencoderKL.from_pretrained(
1077
+ args.pretrained_model_name_or_path,
1078
+ subfolder="vae",
1079
+ revision=args.revision,
1080
+ variant=args.variant,
1081
+ )
1082
+ transformer = HiDreamImageTransformer2DModel.from_pretrained(
1083
+ args.pretrained_model_name_or_path,
1084
+ subfolder="transformer",
1085
+ revision=args.revision,
1086
+ variant=args.variant,
1087
+ force_inference_output=True,
1088
+ )
1089
+
1090
+ # We only train the additional adapter LoRA layers
1091
+ transformer.requires_grad_(False)
1092
+ vae.requires_grad_(False)
1093
+ text_encoder_one.requires_grad_(False)
1094
+ text_encoder_two.requires_grad_(False)
1095
+ text_encoder_three.requires_grad_(False)
1096
+ text_encoder_four.requires_grad_(False)
1097
+
1098
+ # For mixed precision training we cast all non-trainable weights (vae, text_encoder and transformer) to half-precision
1099
+ # as these weights are only used for inference, keeping weights in full precision is not required.
1100
+ weight_dtype = torch.float32
1101
+ if accelerator.mixed_precision == "fp16":
1102
+ weight_dtype = torch.float16
1103
+ elif accelerator.mixed_precision == "bf16":
1104
+ weight_dtype = torch.bfloat16
1105
+
1106
+ if torch.backends.mps.is_available() and weight_dtype == torch.bfloat16:
1107
+ # due to pytorch#99272, MPS does not yet support bfloat16.
1108
+ raise ValueError(
1109
+ "Mixed precision training with bfloat16 is not supported on MPS. Please use fp16 (recommended) or fp32 instead."
1110
+ )
1111
+
1112
+ to_kwargs = {"dtype": weight_dtype, "device": accelerator.device} if not args.offload else {"dtype": weight_dtype}
1113
+ # flux vae is stable in bf16 so load it in weight_dtype to reduce memory
1114
+ vae.to(**to_kwargs)
1115
+ text_encoder_one.to(**to_kwargs)
1116
+ text_encoder_two.to(**to_kwargs)
1117
+ text_encoder_three.to(**to_kwargs)
1118
+ text_encoder_four.to(**to_kwargs)
1119
+ # we never offload the transformer to CPU, so we can just use the accelerator device
1120
+ transformer.to(accelerator.device, dtype=weight_dtype)
1121
+
1122
+ # Initialize a text encoding pipeline and keep it to CPU for now.
1123
+ text_encoding_pipeline = HiDreamImagePipeline.from_pretrained(
1124
+ args.pretrained_model_name_or_path,
1125
+ vae=None,
1126
+ transformer=None,
1127
+ text_encoder=text_encoder_one,
1128
+ tokenizer=tokenizer_one,
1129
+ text_encoder_2=text_encoder_two,
1130
+ tokenizer_2=tokenizer_two,
1131
+ text_encoder_3=text_encoder_three,
1132
+ tokenizer_3=tokenizer_three,
1133
+ text_encoder_4=text_encoder_four,
1134
+ tokenizer_4=tokenizer_four,
1135
+ )
1136
+
1137
+ if args.gradient_checkpointing:
1138
+ transformer.enable_gradient_checkpointing()
1139
+
1140
+ if args.lora_layers is not None:
1141
+ target_modules = [layer.strip() for layer in args.lora_layers.split(",")]
1142
+ else:
1143
+ target_modules = ["to_k", "to_q", "to_v", "to_out.0"]
1144
+
1145
+ # now we will add new LoRA weights the transformer layers
1146
+ transformer_lora_config = LoraConfig(
1147
+ r=args.rank,
1148
+ lora_alpha=args.rank,
1149
+ init_lora_weights="gaussian",
1150
+ target_modules=target_modules,
1151
+ )
1152
+ transformer.add_adapter(transformer_lora_config)
1153
+
1154
+ def unwrap_model(model):
1155
+ model = accelerator.unwrap_model(model)
1156
+ model = model._orig_mod if is_compiled_module(model) else model
1157
+ return model
1158
+
1159
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
1160
+ def save_model_hook(models, weights, output_dir):
1161
+ if accelerator.is_main_process:
1162
+ transformer_lora_layers_to_save = None
1163
+
1164
+ for model in models:
1165
+ if isinstance(model, type(unwrap_model(transformer))):
1166
+ transformer_lora_layers_to_save = get_peft_model_state_dict(model)
1167
+ else:
1168
+ raise ValueError(f"unexpected save model: {model.__class__}")
1169
+
1170
+ # make sure to pop weight so that corresponding model is not saved again
1171
+ weights.pop()
1172
+
1173
+ HiDreamImagePipeline.save_lora_weights(
1174
+ output_dir,
1175
+ transformer_lora_layers=transformer_lora_layers_to_save,
1176
+ )
1177
+
1178
+ def load_model_hook(models, input_dir):
1179
+ transformer_ = None
1180
+
1181
+ while len(models) > 0:
1182
+ model = models.pop()
1183
+
1184
+ if isinstance(model, type(unwrap_model(transformer))):
1185
+ transformer_ = model
1186
+ else:
1187
+ raise ValueError(f"unexpected save model: {model.__class__}")
1188
+
1189
+ lora_state_dict = HiDreamImagePipeline.lora_state_dict(input_dir)
1190
+
1191
+ transformer_state_dict = {
1192
+ f"{k.replace('transformer.', '')}": v for k, v in lora_state_dict.items() if k.startswith("transformer.")
1193
+ }
1194
+ transformer_state_dict = convert_unet_state_dict_to_peft(transformer_state_dict)
1195
+ incompatible_keys = set_peft_model_state_dict(transformer_, transformer_state_dict, adapter_name="default")
1196
+ if incompatible_keys is not None:
1197
+ # check only for unexpected keys
1198
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
1199
+ if unexpected_keys:
1200
+ logger.warning(
1201
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
1202
+ f" {unexpected_keys}. "
1203
+ )
1204
+
1205
+ # Make sure the trainable params are in float32. This is again needed since the base models
1206
+ # are in `weight_dtype`. More details:
1207
+ # https://github.com/huggingface/diffusers/pull/6514#discussion_r1449796804
1208
+ if args.mixed_precision == "fp16":
1209
+ models = [transformer_]
1210
+ # only upcast trainable parameters (LoRA) into fp32
1211
+ cast_training_params(models)
1212
+
1213
+ accelerator.register_save_state_pre_hook(save_model_hook)
1214
+ accelerator.register_load_state_pre_hook(load_model_hook)
1215
+
1216
+ # Enable TF32 for faster training on Ampere GPUs,
1217
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
1218
+ if args.allow_tf32 and torch.cuda.is_available():
1219
+ torch.backends.cuda.matmul.allow_tf32 = True
1220
+
1221
+ if args.scale_lr:
1222
+ args.learning_rate = (
1223
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
1224
+ )
1225
+
1226
+ # Make sure the trainable params are in float32.
1227
+ if args.mixed_precision == "fp16":
1228
+ models = [transformer]
1229
+ # only upcast trainable parameters (LoRA) into fp32
1230
+ cast_training_params(models, dtype=torch.float32)
1231
+
1232
+ transformer_lora_parameters = list(filter(lambda p: p.requires_grad, transformer.parameters()))
1233
+
1234
+ # Optimization parameters
1235
+ transformer_parameters_with_lr = {"params": transformer_lora_parameters, "lr": args.learning_rate}
1236
+ params_to_optimize = [transformer_parameters_with_lr]
1237
+
1238
+ # Optimizer creation
1239
+ if not (args.optimizer.lower() == "prodigy" or args.optimizer.lower() == "adamw"):
1240
+ logger.warning(
1241
+ f"Unsupported choice of optimizer: {args.optimizer}.Supported optimizers include [adamW, prodigy]."
1242
+ "Defaulting to adamW"
1243
+ )
1244
+ args.optimizer = "adamw"
1245
+
1246
+ if args.use_8bit_adam and not args.optimizer.lower() == "adamw":
1247
+ logger.warning(
1248
+ f"use_8bit_adam is ignored when optimizer is not set to 'AdamW'. Optimizer was "
1249
+ f"set to {args.optimizer.lower()}"
1250
+ )
1251
+
1252
+ if args.optimizer.lower() == "adamw":
1253
+ if args.use_8bit_adam:
1254
+ try:
1255
+ import bitsandbytes as bnb
1256
+ except ImportError:
1257
+ raise ImportError(
1258
+ "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
1259
+ )
1260
+
1261
+ optimizer_class = bnb.optim.AdamW8bit
1262
+ else:
1263
+ optimizer_class = torch.optim.AdamW
1264
+
1265
+ optimizer = optimizer_class(
1266
+ params_to_optimize,
1267
+ betas=(args.adam_beta1, args.adam_beta2),
1268
+ weight_decay=args.adam_weight_decay,
1269
+ eps=args.adam_epsilon,
1270
+ )
1271
+
1272
+ if args.optimizer.lower() == "prodigy":
1273
+ try:
1274
+ import prodigyopt
1275
+ except ImportError:
1276
+ raise ImportError("To use Prodigy, please install the prodigyopt library: `pip install prodigyopt`")
1277
+
1278
+ optimizer_class = prodigyopt.Prodigy
1279
+
1280
+ if args.learning_rate <= 0.1:
1281
+ logger.warning(
1282
+ "Learning rate is too low. When using prodigy, it's generally better to set learning rate around 1.0"
1283
+ )
1284
+
1285
+ optimizer = optimizer_class(
1286
+ params_to_optimize,
1287
+ betas=(args.adam_beta1, args.adam_beta2),
1288
+ beta3=args.prodigy_beta3,
1289
+ weight_decay=args.adam_weight_decay,
1290
+ eps=args.adam_epsilon,
1291
+ decouple=args.prodigy_decouple,
1292
+ use_bias_correction=args.prodigy_use_bias_correction,
1293
+ safeguard_warmup=args.prodigy_safeguard_warmup,
1294
+ )
1295
+
1296
+ # Dataset and DataLoaders creation:
1297
+ train_dataset = DreamBoothDataset(
1298
+ instance_data_root=args.instance_data_dir,
1299
+ instance_prompt=args.instance_prompt,
1300
+ class_prompt=args.class_prompt,
1301
+ class_data_root=args.class_data_dir if args.with_prior_preservation else None,
1302
+ class_num=args.num_class_images,
1303
+ size=args.resolution,
1304
+ repeats=args.repeats,
1305
+ center_crop=args.center_crop,
1306
+ )
1307
+
1308
+ train_dataloader = torch.utils.data.DataLoader(
1309
+ train_dataset,
1310
+ batch_size=args.train_batch_size,
1311
+ shuffle=True,
1312
+ collate_fn=lambda examples: collate_fn(examples, args.with_prior_preservation),
1313
+ num_workers=args.dataloader_num_workers,
1314
+ )
1315
+
1316
+ def compute_text_embeddings(prompt, text_encoding_pipeline):
1317
+ if args.offload:
1318
+ text_encoding_pipeline = text_encoding_pipeline.to(accelerator.device)
1319
+ with torch.no_grad():
1320
+ t5_prompt_embeds, _, llama3_prompt_embeds, _, pooled_prompt_embeds, _ = (
1321
+ text_encoding_pipeline.encode_prompt(prompt=prompt, max_sequence_length=args.max_sequence_length)
1322
+ )
1323
+ if args.offload: # back to cpu
1324
+ text_encoding_pipeline = text_encoding_pipeline.to("cpu")
1325
+ return t5_prompt_embeds, llama3_prompt_embeds, pooled_prompt_embeds
1326
+
1327
+ # If no type of tuning is done on the text_encoder and custom instance prompts are NOT
1328
+ # provided (i.e. the --instance_prompt is used for all images), we encode the instance prompt once to avoid
1329
+ # the redundant encoding.
1330
+ if not train_dataset.custom_instance_prompts:
1331
+ (
1332
+ instance_prompt_hidden_states_t5,
1333
+ instance_prompt_hidden_states_llama3,
1334
+ instance_pooled_prompt_embeds,
1335
+ ) = compute_text_embeddings(args.instance_prompt, text_encoding_pipeline)
1336
+
1337
+ # Handle class prompt for prior-preservation.
1338
+ if args.with_prior_preservation:
1339
+ (
1340
+ class_prompt_hidden_states_t5,
1341
+ class_prompt_hidden_states_llama3,
1342
+ class_pooled_prompt_embeds,
1343
+ ) = compute_text_embeddings(args.class_prompt, text_encoding_pipeline)
1344
+
1345
+ # Clear the memory here
1346
+ if not train_dataset.custom_instance_prompts:
1347
+ # delete tokenizers and text ecnoders except for llama (tokenizer & te four)
1348
+ # as it's needed for inference with pipeline
1349
+ del text_encoder_one, text_encoder_two, text_encoder_three, tokenizer_one, tokenizer_two, tokenizer_three
1350
+ if not args.validation_prompt:
1351
+ del tokenizer_four, text_encoder_four
1352
+ free_memory()
1353
+
1354
+ # If custom instance prompts are NOT provided (i.e. the instance prompt is used for all images),
1355
+ # pack the statically computed variables appropriately here. This is so that we don't
1356
+ # have to pass them to the dataloader.
1357
+ if not train_dataset.custom_instance_prompts:
1358
+ t5_prompt_embeds = instance_prompt_hidden_states_t5
1359
+ llama3_prompt_embeds = instance_prompt_hidden_states_llama3
1360
+ pooled_prompt_embeds = instance_pooled_prompt_embeds
1361
+ if args.with_prior_preservation:
1362
+ t5_prompt_embeds = torch.cat([instance_prompt_hidden_states_t5, class_prompt_hidden_states_t5], dim=0)
1363
+ llama3_prompt_embeds = torch.cat(
1364
+ [instance_prompt_hidden_states_llama3, class_prompt_hidden_states_llama3], dim=0
1365
+ )
1366
+ pooled_prompt_embeds = torch.cat([pooled_prompt_embeds, class_pooled_prompt_embeds], dim=0)
1367
+
1368
+ vae_config_scaling_factor = vae.config.scaling_factor
1369
+ vae_config_shift_factor = vae.config.shift_factor
1370
+ if args.cache_latents:
1371
+ latents_cache = []
1372
+ if args.offload:
1373
+ vae = vae.to(accelerator.device)
1374
+ for batch in tqdm(train_dataloader, desc="Caching latents"):
1375
+ with torch.no_grad():
1376
+ batch["pixel_values"] = batch["pixel_values"].to(
1377
+ accelerator.device, non_blocking=True, dtype=vae.dtype
1378
+ )
1379
+ latents_cache.append(vae.encode(batch["pixel_values"]).latent_dist)
1380
+
1381
+ if args.validation_prompt is None:
1382
+ del vae
1383
+ free_memory()
1384
+
1385
+ # Scheduler and math around the number of training steps.
1386
+ overrode_max_train_steps = False
1387
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
1388
+ if args.max_train_steps is None:
1389
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
1390
+ overrode_max_train_steps = True
1391
+
1392
+ lr_scheduler = get_scheduler(
1393
+ args.lr_scheduler,
1394
+ optimizer=optimizer,
1395
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
1396
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
1397
+ num_cycles=args.lr_num_cycles,
1398
+ power=args.lr_power,
1399
+ )
1400
+
1401
+ # Prepare everything with our `accelerator`.
1402
+ transformer, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
1403
+ transformer, optimizer, train_dataloader, lr_scheduler
1404
+ )
1405
+
1406
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
1407
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
1408
+ if overrode_max_train_steps:
1409
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
1410
+ # Afterwards we recalculate our number of training epochs
1411
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
1412
+
1413
+ # We need to initialize the trackers we use, and also store our configuration.
1414
+ # The trackers initializes automatically on the main process.
1415
+ if accelerator.is_main_process:
1416
+ tracker_name = "dreambooth-hidream-lora"
1417
+ accelerator.init_trackers(tracker_name, config=vars(args))
1418
+
1419
+ # Train!
1420
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
1421
+
1422
+ logger.info("***** Running training *****")
1423
+ logger.info(f" Num examples = {len(train_dataset)}")
1424
+ logger.info(f" Num batches each epoch = {len(train_dataloader)}")
1425
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
1426
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
1427
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
1428
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
1429
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
1430
+ global_step = 0
1431
+ first_epoch = 0
1432
+
1433
+ # Potentially load in the weights and states from a previous save
1434
+ if args.resume_from_checkpoint:
1435
+ if args.resume_from_checkpoint != "latest":
1436
+ path = os.path.basename(args.resume_from_checkpoint)
1437
+ else:
1438
+ # Get the mos recent checkpoint
1439
+ dirs = os.listdir(args.output_dir)
1440
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
1441
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
1442
+ path = dirs[-1] if len(dirs) > 0 else None
1443
+
1444
+ if path is None:
1445
+ accelerator.print(
1446
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
1447
+ )
1448
+ args.resume_from_checkpoint = None
1449
+ initial_global_step = 0
1450
+ else:
1451
+ accelerator.print(f"Resuming from checkpoint {path}")
1452
+ accelerator.load_state(os.path.join(args.output_dir, path))
1453
+ global_step = int(path.split("-")[1])
1454
+
1455
+ initial_global_step = global_step
1456
+ first_epoch = global_step // num_update_steps_per_epoch
1457
+
1458
+ else:
1459
+ initial_global_step = 0
1460
+
1461
+ progress_bar = tqdm(
1462
+ range(0, args.max_train_steps),
1463
+ initial=initial_global_step,
1464
+ desc="Steps",
1465
+ # Only show the progress bar once on each machine.
1466
+ disable=not accelerator.is_local_main_process,
1467
+ )
1468
+
1469
+ def get_sigmas(timesteps, n_dim=4, dtype=torch.float32):
1470
+ sigmas = noise_scheduler_copy.sigmas.to(device=accelerator.device, dtype=dtype)
1471
+ schedule_timesteps = noise_scheduler_copy.timesteps.to(accelerator.device)
1472
+ timesteps = timesteps.to(accelerator.device)
1473
+ step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
1474
+
1475
+ sigma = sigmas[step_indices].flatten()
1476
+ while len(sigma.shape) < n_dim:
1477
+ sigma = sigma.unsqueeze(-1)
1478
+ return sigma
1479
+
1480
+ for epoch in range(first_epoch, args.num_train_epochs):
1481
+ transformer.train()
1482
+
1483
+ for step, batch in enumerate(train_dataloader):
1484
+ models_to_accumulate = [transformer]
1485
+ prompts = batch["prompts"]
1486
+
1487
+ with accelerator.accumulate(models_to_accumulate):
1488
+ # encode batch prompts when custom prompts are provided for each image -
1489
+ if train_dataset.custom_instance_prompts:
1490
+ t5_prompt_embeds, llama3_prompt_embeds, pooled_prompt_embeds = compute_text_embeddings(
1491
+ prompts, text_encoding_pipeline
1492
+ )
1493
+ else:
1494
+ t5_prompt_embeds = t5_prompt_embeds.repeat(len(prompts), 1, 1)
1495
+ llama3_prompt_embeds = llama3_prompt_embeds.repeat(1, len(prompts), 1, 1)
1496
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(len(prompts), 1)
1497
+ # Convert images to latent space
1498
+ if args.cache_latents:
1499
+ model_input = latents_cache[step].sample()
1500
+ else:
1501
+ if args.offload:
1502
+ vae = vae.to(accelerator.device)
1503
+ pixel_values = batch["pixel_values"].to(dtype=vae.dtype)
1504
+ model_input = vae.encode(pixel_values).latent_dist.sample()
1505
+ if args.offload:
1506
+ vae = vae.to("cpu")
1507
+ model_input = (model_input - vae_config_shift_factor) * vae_config_scaling_factor
1508
+ model_input = model_input.to(dtype=weight_dtype)
1509
+
1510
+ # Sample noise that we'll add to the latents
1511
+ noise = torch.randn_like(model_input)
1512
+ bsz = model_input.shape[0]
1513
+
1514
+ # Sample a random timestep for each image
1515
+ # for weighting schemes where we sample timesteps non-uniformly
1516
+ u = compute_density_for_timestep_sampling(
1517
+ weighting_scheme=args.weighting_scheme,
1518
+ batch_size=bsz,
1519
+ logit_mean=args.logit_mean,
1520
+ logit_std=args.logit_std,
1521
+ mode_scale=args.mode_scale,
1522
+ )
1523
+ indices = (u * noise_scheduler_copy.config.num_train_timesteps).long()
1524
+ timesteps = noise_scheduler_copy.timesteps[indices].to(device=model_input.device)
1525
+
1526
+ # Add noise according to flow matching.
1527
+ # zt = (1 - texp) * x + texp * z1
1528
+ sigmas = get_sigmas(timesteps, n_dim=model_input.ndim, dtype=model_input.dtype)
1529
+ noisy_model_input = (1.0 - sigmas) * model_input + sigmas * noise
1530
+ # Predict the noise residual
1531
+ model_pred = transformer(
1532
+ hidden_states=noisy_model_input,
1533
+ encoder_hidden_states_t5=t5_prompt_embeds,
1534
+ encoder_hidden_states_llama3=llama3_prompt_embeds,
1535
+ pooled_embeds=pooled_prompt_embeds,
1536
+ timesteps=timesteps,
1537
+ return_dict=False,
1538
+ )[0]
1539
+ model_pred = model_pred * -1
1540
+ # these weighting schemes use a uniform timestep sampling
1541
+ # and instead post-weight the loss
1542
+ weighting = compute_loss_weighting_for_sd3(weighting_scheme=args.weighting_scheme, sigmas=sigmas)
1543
+
1544
+ target = noise - model_input
1545
+ if args.with_prior_preservation:
1546
+ # Chunk the noise and model_pred into two parts and compute the loss on each part separately.
1547
+ model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0)
1548
+ target, target_prior = torch.chunk(target, 2, dim=0)
1549
+
1550
+ # Compute prior loss
1551
+ prior_loss = torch.mean(
1552
+ (weighting.float() * (model_pred_prior.float() - target_prior.float()) ** 2).reshape(
1553
+ target_prior.shape[0], -1
1554
+ ),
1555
+ 1,
1556
+ )
1557
+ prior_loss = prior_loss.mean()
1558
+
1559
+ # Compute regular loss.
1560
+ loss = torch.mean(
1561
+ (weighting.float() * (model_pred.float() - target.float()) ** 2).reshape(target.shape[0], -1),
1562
+ 1,
1563
+ )
1564
+ loss = loss.mean()
1565
+
1566
+ if args.with_prior_preservation:
1567
+ # Add the prior loss to the instance loss.
1568
+ loss = loss + args.prior_loss_weight * prior_loss
1569
+
1570
+ accelerator.backward(loss)
1571
+ if accelerator.sync_gradients:
1572
+ params_to_clip = transformer.parameters()
1573
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
1574
+
1575
+ optimizer.step()
1576
+ lr_scheduler.step()
1577
+ optimizer.zero_grad()
1578
+
1579
+ # Checks if the accelerator has performed an optimization step behind the scenes
1580
+ if accelerator.sync_gradients:
1581
+ progress_bar.update(1)
1582
+ global_step += 1
1583
+
1584
+ if accelerator.is_main_process:
1585
+ if global_step % args.checkpointing_steps == 0:
1586
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
1587
+ if args.checkpoints_total_limit is not None:
1588
+ checkpoints = os.listdir(args.output_dir)
1589
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
1590
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
1591
+
1592
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
1593
+ if len(checkpoints) >= args.checkpoints_total_limit:
1594
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
1595
+ removing_checkpoints = checkpoints[0:num_to_remove]
1596
+
1597
+ logger.info(
1598
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
1599
+ )
1600
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
1601
+
1602
+ for removing_checkpoint in removing_checkpoints:
1603
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
1604
+ shutil.rmtree(removing_checkpoint)
1605
+
1606
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
1607
+ accelerator.save_state(save_path)
1608
+ logger.info(f"Saved state to {save_path}")
1609
+
1610
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
1611
+ progress_bar.set_postfix(**logs)
1612
+ accelerator.log(logs, step=global_step)
1613
+
1614
+ if global_step >= args.max_train_steps:
1615
+ break
1616
+
1617
+ if accelerator.is_main_process:
1618
+ if args.validation_prompt is not None and epoch % args.validation_epochs == 0:
1619
+ # create pipeline
1620
+ pipeline = HiDreamImagePipeline.from_pretrained(
1621
+ args.pretrained_model_name_or_path,
1622
+ tokenizer_4=tokenizer_four,
1623
+ text_encoder_4=text_encoder_four,
1624
+ transformer=accelerator.unwrap_model(transformer),
1625
+ revision=args.revision,
1626
+ variant=args.variant,
1627
+ torch_dtype=weight_dtype,
1628
+ )
1629
+ pipeline_args = {"prompt": args.validation_prompt}
1630
+ images = log_validation(
1631
+ pipeline=pipeline,
1632
+ args=args,
1633
+ accelerator=accelerator,
1634
+ pipeline_args=pipeline_args,
1635
+ torch_dtype=weight_dtype,
1636
+ epoch=epoch,
1637
+ )
1638
+ free_memory()
1639
+
1640
+ images = None
1641
+ del pipeline
1642
+
1643
+ # Save the lora layers
1644
+ accelerator.wait_for_everyone()
1645
+ if accelerator.is_main_process:
1646
+ transformer = unwrap_model(transformer)
1647
+ if args.upcast_before_saving:
1648
+ transformer.to(torch.float32)
1649
+ else:
1650
+ transformer = transformer.to(weight_dtype)
1651
+ transformer_lora_layers = get_peft_model_state_dict(transformer)
1652
+
1653
+ HiDreamImagePipeline.save_lora_weights(
1654
+ save_directory=args.output_dir,
1655
+ transformer_lora_layers=transformer_lora_layers,
1656
+ )
1657
+
1658
+ # Final inference
1659
+ # Load previous pipeline
1660
+ tokenizer_4 = AutoTokenizer.from_pretrained(args.pretrained_tokenizer_4_name_or_path)
1661
+ tokenizer_4.pad_token = tokenizer_4.eos_token
1662
+ text_encoder_4 = LlamaForCausalLM.from_pretrained(
1663
+ args.pretrained_text_encoder_4_name_or_path,
1664
+ output_hidden_states=True,
1665
+ output_attentions=True,
1666
+ torch_dtype=torch.bfloat16,
1667
+ )
1668
+ pipeline = HiDreamImagePipeline.from_pretrained(
1669
+ args.pretrained_model_name_or_path,
1670
+ tokenizer_4=tokenizer_4,
1671
+ text_encoder_4=text_encoder_4,
1672
+ revision=args.revision,
1673
+ variant=args.variant,
1674
+ torch_dtype=weight_dtype,
1675
+ )
1676
+ # load attention processors
1677
+ pipeline.load_lora_weights(args.output_dir)
1678
+
1679
+ # run inference
1680
+ images = []
1681
+ if (args.validation_prompt and args.num_validation_images > 0) or (args.final_validation_prompt):
1682
+ prompt_to_use = args.validation_prompt if args.validation_prompt else args.final_validation_prompt
1683
+ args.num_validation_images = args.num_validation_images if args.num_validation_images else 1
1684
+ pipeline_args = {"prompt": prompt_to_use, "num_images_per_prompt": args.num_validation_images}
1685
+ images = log_validation(
1686
+ pipeline=pipeline,
1687
+ args=args,
1688
+ accelerator=accelerator,
1689
+ pipeline_args=pipeline_args,
1690
+ epoch=epoch,
1691
+ is_final_validation=True,
1692
+ torch_dtype=weight_dtype,
1693
+ )
1694
+
1695
+ validation_prpmpt = args.validation_prompt if args.validation_prompt else args.final_validation_prompt
1696
+ save_model_card(
1697
+ (args.hub_model_id or Path(args.output_dir).name) if not args.push_to_hub else repo_id,
1698
+ images=images,
1699
+ base_model=args.pretrained_model_name_or_path,
1700
+ instance_prompt=args.instance_prompt,
1701
+ validation_prompt=validation_prpmpt,
1702
+ repo_folder=args.output_dir,
1703
+ )
1704
+
1705
+ if args.push_to_hub:
1706
+ upload_folder(
1707
+ repo_id=repo_id,
1708
+ folder_path=args.output_dir,
1709
+ commit_message="End of training",
1710
+ ignore_patterns=["step_*", "epoch_*"],
1711
+ )
1712
+
1713
+ images = None
1714
+ del pipeline
1715
+
1716
+ accelerator.end_training()
1717
+
1718
+
1719
+ if __name__ == "__main__":
1720
+ args = parse_args()
1721
+ main(args)
tasks/tasksmith-f40a643a6ef9/solution/reference/src/diffusers/loaders/__init__.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING
2
+
3
+ from ..utils import DIFFUSERS_SLOW_IMPORT, _LazyModule, deprecate
4
+ from ..utils.import_utils import is_peft_available, is_torch_available, is_transformers_available
5
+
6
+
7
+ def text_encoder_lora_state_dict(text_encoder):
8
+ deprecate(
9
+ "text_encoder_load_state_dict in `models`",
10
+ "0.27.0",
11
+ "`text_encoder_lora_state_dict` is deprecated and will be removed in 0.27.0. Make sure to retrieve the weights using `get_peft_model`. See https://huggingface.co/docs/peft/v0.6.2/en/quicktour#peftmodel for more information.",
12
+ )
13
+ state_dict = {}
14
+
15
+ for name, module in text_encoder_attn_modules(text_encoder):
16
+ for k, v in module.q_proj.lora_linear_layer.state_dict().items():
17
+ state_dict[f"{name}.q_proj.lora_linear_layer.{k}"] = v
18
+
19
+ for k, v in module.k_proj.lora_linear_layer.state_dict().items():
20
+ state_dict[f"{name}.k_proj.lora_linear_layer.{k}"] = v
21
+
22
+ for k, v in module.v_proj.lora_linear_layer.state_dict().items():
23
+ state_dict[f"{name}.v_proj.lora_linear_layer.{k}"] = v
24
+
25
+ for k, v in module.out_proj.lora_linear_layer.state_dict().items():
26
+ state_dict[f"{name}.out_proj.lora_linear_layer.{k}"] = v
27
+
28
+ return state_dict
29
+
30
+
31
+ if is_transformers_available():
32
+
33
+ def text_encoder_attn_modules(text_encoder):
34
+ deprecate(
35
+ "text_encoder_attn_modules in `models`",
36
+ "0.27.0",
37
+ "`text_encoder_lora_state_dict` is deprecated and will be removed in 0.27.0. Make sure to retrieve the weights using `get_peft_model`. See https://huggingface.co/docs/peft/v0.6.2/en/quicktour#peftmodel for more information.",
38
+ )
39
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection
40
+
41
+ attn_modules = []
42
+
43
+ if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
44
+ for i, layer in enumerate(text_encoder.text_model.encoder.layers):
45
+ name = f"text_model.encoder.layers.{i}.self_attn"
46
+ mod = layer.self_attn
47
+ attn_modules.append((name, mod))
48
+ else:
49
+ raise ValueError(f"do not know how to get attention modules for: {text_encoder.__class__.__name__}")
50
+
51
+ return attn_modules
52
+
53
+
54
+ _import_structure = {}
55
+
56
+ if is_torch_available():
57
+ _import_structure["single_file_model"] = ["FromOriginalModelMixin"]
58
+ _import_structure["transformer_flux"] = ["FluxTransformer2DLoadersMixin"]
59
+ _import_structure["transformer_sd3"] = ["SD3Transformer2DLoadersMixin"]
60
+ _import_structure["unet"] = ["UNet2DConditionLoadersMixin"]
61
+ _import_structure["utils"] = ["AttnProcsLayers"]
62
+ if is_transformers_available():
63
+ _import_structure["single_file"] = ["FromSingleFileMixin"]
64
+ _import_structure["lora_pipeline"] = [
65
+ "AmusedLoraLoaderMixin",
66
+ "StableDiffusionLoraLoaderMixin",
67
+ "SD3LoraLoaderMixin",
68
+ "AuraFlowLoraLoaderMixin",
69
+ "StableDiffusionXLLoraLoaderMixin",
70
+ "LTXVideoLoraLoaderMixin",
71
+ "LoraLoaderMixin",
72
+ "FluxLoraLoaderMixin",
73
+ "CogVideoXLoraLoaderMixin",
74
+ "CogView4LoraLoaderMixin",
75
+ "Mochi1LoraLoaderMixin",
76
+ "HunyuanVideoLoraLoaderMixin",
77
+ "SanaLoraLoaderMixin",
78
+ "Lumina2LoraLoaderMixin",
79
+ "WanLoraLoaderMixin",
80
+ "HiDreamImageLoraLoaderMixin",
81
+ ]
82
+ _import_structure["textual_inversion"] = ["TextualInversionLoaderMixin"]
83
+ _import_structure["ip_adapter"] = [
84
+ "IPAdapterMixin",
85
+ "FluxIPAdapterMixin",
86
+ "SD3IPAdapterMixin",
87
+ ]
88
+
89
+ _import_structure["peft"] = ["PeftAdapterMixin"]
90
+
91
+
92
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
93
+ if is_torch_available():
94
+ from .single_file_model import FromOriginalModelMixin
95
+ from .transformer_flux import FluxTransformer2DLoadersMixin
96
+ from .transformer_sd3 import SD3Transformer2DLoadersMixin
97
+ from .unet import UNet2DConditionLoadersMixin
98
+ from .utils import AttnProcsLayers
99
+
100
+ if is_transformers_available():
101
+ from .ip_adapter import (
102
+ FluxIPAdapterMixin,
103
+ IPAdapterMixin,
104
+ SD3IPAdapterMixin,
105
+ )
106
+ from .lora_pipeline import (
107
+ AmusedLoraLoaderMixin,
108
+ AuraFlowLoraLoaderMixin,
109
+ CogVideoXLoraLoaderMixin,
110
+ CogView4LoraLoaderMixin,
111
+ FluxLoraLoaderMixin,
112
+ HiDreamImageLoraLoaderMixin,
113
+ HunyuanVideoLoraLoaderMixin,
114
+ LoraLoaderMixin,
115
+ LTXVideoLoraLoaderMixin,
116
+ Lumina2LoraLoaderMixin,
117
+ Mochi1LoraLoaderMixin,
118
+ SanaLoraLoaderMixin,
119
+ SD3LoraLoaderMixin,
120
+ StableDiffusionLoraLoaderMixin,
121
+ StableDiffusionXLLoraLoaderMixin,
122
+ WanLoraLoaderMixin,
123
+ )
124
+ from .single_file import FromSingleFileMixin
125
+ from .textual_inversion import TextualInversionLoaderMixin
126
+
127
+ from .peft import PeftAdapterMixin
128
+ else:
129
+ import sys
130
+
131
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
tasks/tasksmith-f40a643a6ef9/solution/reference/src/diffusers/loaders/lora_pipeline.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-f40a643a6ef9/solution/reference/src/diffusers/loaders/peft.py ADDED
@@ -0,0 +1,862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import inspect
16
+ import os
17
+ from functools import partial
18
+ from pathlib import Path
19
+ from typing import Dict, List, Literal, Optional, Union
20
+
21
+ import safetensors
22
+ import torch
23
+
24
+ from ..utils import (
25
+ MIN_PEFT_VERSION,
26
+ USE_PEFT_BACKEND,
27
+ check_peft_version,
28
+ convert_unet_state_dict_to_peft,
29
+ delete_adapter_layers,
30
+ get_adapter_name,
31
+ get_peft_kwargs,
32
+ is_peft_available,
33
+ is_peft_version,
34
+ logging,
35
+ set_adapter_layers,
36
+ set_weights_and_activate_adapters,
37
+ )
38
+ from .lora_base import _fetch_state_dict, _func_optionally_disable_offloading
39
+ from .unet_loader_utils import _maybe_expand_lora_scales
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+ _SET_ADAPTER_SCALE_FN_MAPPING = {
45
+ "UNet2DConditionModel": _maybe_expand_lora_scales,
46
+ "UNetMotionModel": _maybe_expand_lora_scales,
47
+ "SD3Transformer2DModel": lambda model_cls, weights: weights,
48
+ "FluxTransformer2DModel": lambda model_cls, weights: weights,
49
+ "CogVideoXTransformer3DModel": lambda model_cls, weights: weights,
50
+ "ConsisIDTransformer3DModel": lambda model_cls, weights: weights,
51
+ "MochiTransformer3DModel": lambda model_cls, weights: weights,
52
+ "HunyuanVideoTransformer3DModel": lambda model_cls, weights: weights,
53
+ "LTXVideoTransformer3DModel": lambda model_cls, weights: weights,
54
+ "SanaTransformer2DModel": lambda model_cls, weights: weights,
55
+ "AuraFlowTransformer2DModel": lambda model_cls, weights: weights,
56
+ "Lumina2Transformer2DModel": lambda model_cls, weights: weights,
57
+ "WanTransformer3DModel": lambda model_cls, weights: weights,
58
+ "CogView4Transformer2DModel": lambda model_cls, weights: weights,
59
+ "HiDreamImageTransformer2DModel": lambda model_cls, weights: weights,
60
+ }
61
+
62
+
63
+ def _maybe_raise_error_for_ambiguity(config):
64
+ rank_pattern = config["rank_pattern"].copy()
65
+ target_modules = config["target_modules"]
66
+
67
+ for key in list(rank_pattern.keys()):
68
+ # try to detect ambiguity
69
+ # `target_modules` can also be a str, in which case this loop would loop
70
+ # over the chars of the str. The technically correct way to match LoRA keys
71
+ # in PEFT is to use LoraModel._check_target_module_exists (lora_config, key).
72
+ # But this cuts it for now.
73
+ exact_matches = [mod for mod in target_modules if mod == key]
74
+ substring_matches = [mod for mod in target_modules if key in mod and mod != key]
75
+
76
+ if exact_matches and substring_matches:
77
+ if is_peft_version("<", "0.14.1"):
78
+ raise ValueError(
79
+ "There are ambiguous keys present in this LoRA. To load it, please update your `peft` installation - `pip install -U peft`."
80
+ )
81
+
82
+
83
+ class PeftAdapterMixin:
84
+ """
85
+ A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
86
+ more details about adapters and injecting them in a base model, check out the PEFT
87
+ [documentation](https://huggingface.co/docs/peft/index).
88
+
89
+ Install the latest version of PEFT, and use this mixin to:
90
+
91
+ - Attach new adapters in the model.
92
+ - Attach multiple adapters and iteratively activate/deactivate them.
93
+ - Activate/deactivate all adapters from the model.
94
+ - Get a list of the active adapters.
95
+ """
96
+
97
+ _hf_peft_config_loaded = False
98
+ # kwargs for prepare_model_for_compiled_hotswap, if required
99
+ _prepare_lora_hotswap_kwargs: Optional[dict] = None
100
+
101
+ @classmethod
102
+ # Copied from diffusers.loaders.lora_base.LoraBaseMixin._optionally_disable_offloading
103
+ def _optionally_disable_offloading(cls, _pipeline):
104
+ """
105
+ Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
106
+
107
+ Args:
108
+ _pipeline (`DiffusionPipeline`):
109
+ The pipeline to disable offloading for.
110
+
111
+ Returns:
112
+ tuple:
113
+ A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
114
+ """
115
+ return _func_optionally_disable_offloading(_pipeline=_pipeline)
116
+
117
+ def load_lora_adapter(
118
+ self, pretrained_model_name_or_path_or_dict, prefix="transformer", hotswap: bool = False, **kwargs
119
+ ):
120
+ r"""
121
+ Loads a LoRA adapter into the underlying model.
122
+
123
+ Parameters:
124
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
125
+ Can be either:
126
+
127
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
128
+ the Hub.
129
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
130
+ with [`ModelMixin.save_pretrained`].
131
+ - A [torch state
132
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
133
+
134
+ prefix (`str`, *optional*): Prefix to filter the state dict.
135
+
136
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
137
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
138
+ is not used.
139
+ force_download (`bool`, *optional*, defaults to `False`):
140
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
141
+ cached versions if they exist.
142
+ proxies (`Dict[str, str]`, *optional*):
143
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
144
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
145
+ local_files_only (`bool`, *optional*, defaults to `False`):
146
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
147
+ won't be downloaded from the Hub.
148
+ token (`str` or *bool*, *optional*):
149
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
150
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
151
+ revision (`str`, *optional*, defaults to `"main"`):
152
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
153
+ allowed by Git.
154
+ subfolder (`str`, *optional*, defaults to `""`):
155
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
156
+ network_alphas (`Dict[str, float]`):
157
+ The value of the network alpha used for stable learning and preventing underflow. This value has the
158
+ same meaning as the `--network_alpha` option in the kohya-ss trainer script. Refer to [this
159
+ link](https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning).
160
+ low_cpu_mem_usage (`bool`, *optional*):
161
+ Speed up model loading by only loading the pretrained LoRA weights and not initializing the random
162
+ weights.
163
+ hotswap : (`bool`, *optional*)
164
+ Defaults to `False`. Whether to substitute an existing (LoRA) adapter with the newly loaded adapter
165
+ in-place. This means that, instead of loading an additional adapter, this will take the existing
166
+ adapter weights and replace them with the weights of the new adapter. This can be faster and more
167
+ memory efficient. However, the main advantage of hotswapping is that when the model is compiled with
168
+ torch.compile, loading the new adapter does not require recompilation of the model. When using
169
+ hotswapping, the passed `adapter_name` should be the name of an already loaded adapter.
170
+
171
+ If the new adapter and the old adapter have different ranks and/or LoRA alphas (i.e. scaling), you need
172
+ to call an additional method before loading the adapter:
173
+
174
+ ```py
175
+ pipeline = ... # load diffusers pipeline
176
+ max_rank = ... # the highest rank among all LoRAs that you want to load
177
+ # call *before* compiling and loading the LoRA adapter
178
+ pipeline.enable_lora_hotswap(target_rank=max_rank)
179
+ pipeline.load_lora_weights(file_name)
180
+ # optionally compile the model now
181
+ ```
182
+
183
+ Note that hotswapping adapters of the text encoder is not yet supported. There are some further
184
+ limitations to this technique, which are documented here:
185
+ https://huggingface.co/docs/peft/main/en/package_reference/hotswap
186
+ """
187
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
188
+ from peft.tuners.tuners_utils import BaseTunerLayer
189
+
190
+ cache_dir = kwargs.pop("cache_dir", None)
191
+ force_download = kwargs.pop("force_download", False)
192
+ proxies = kwargs.pop("proxies", None)
193
+ local_files_only = kwargs.pop("local_files_only", None)
194
+ token = kwargs.pop("token", None)
195
+ revision = kwargs.pop("revision", None)
196
+ subfolder = kwargs.pop("subfolder", None)
197
+ weight_name = kwargs.pop("weight_name", None)
198
+ use_safetensors = kwargs.pop("use_safetensors", None)
199
+ adapter_name = kwargs.pop("adapter_name", None)
200
+ network_alphas = kwargs.pop("network_alphas", None)
201
+ _pipeline = kwargs.pop("_pipeline", None)
202
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", False)
203
+ allow_pickle = False
204
+
205
+ if low_cpu_mem_usage and is_peft_version("<=", "0.13.0"):
206
+ raise ValueError(
207
+ "`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`."
208
+ )
209
+
210
+ user_agent = {
211
+ "file_type": "attn_procs_weights",
212
+ "framework": "pytorch",
213
+ }
214
+
215
+ state_dict = _fetch_state_dict(
216
+ pretrained_model_name_or_path_or_dict=pretrained_model_name_or_path_or_dict,
217
+ weight_name=weight_name,
218
+ use_safetensors=use_safetensors,
219
+ local_files_only=local_files_only,
220
+ cache_dir=cache_dir,
221
+ force_download=force_download,
222
+ proxies=proxies,
223
+ token=token,
224
+ revision=revision,
225
+ subfolder=subfolder,
226
+ user_agent=user_agent,
227
+ allow_pickle=allow_pickle,
228
+ )
229
+ if network_alphas is not None and prefix is None:
230
+ raise ValueError("`network_alphas` cannot be None when `prefix` is None.")
231
+
232
+ if prefix is not None:
233
+ state_dict = {k[len(f"{prefix}.") :]: v for k, v in state_dict.items() if k.startswith(f"{prefix}.")}
234
+
235
+ if len(state_dict) > 0:
236
+ if adapter_name in getattr(self, "peft_config", {}) and not hotswap:
237
+ raise ValueError(
238
+ f"Adapter name {adapter_name} already in use in the model - please select a new adapter name."
239
+ )
240
+ elif adapter_name not in getattr(self, "peft_config", {}) and hotswap:
241
+ raise ValueError(
242
+ f"Trying to hotswap LoRA adapter '{adapter_name}' but there is no existing adapter by that name. "
243
+ "Please choose an existing adapter name or set `hotswap=False` to prevent hotswapping."
244
+ )
245
+
246
+ # check with first key if is not in peft format
247
+ first_key = next(iter(state_dict.keys()))
248
+ if "lora_A" not in first_key:
249
+ state_dict = convert_unet_state_dict_to_peft(state_dict)
250
+
251
+ rank = {}
252
+ for key, val in state_dict.items():
253
+ # Cannot figure out rank from lora layers that don't have atleast 2 dimensions.
254
+ # Bias layers in LoRA only have a single dimension
255
+ if "lora_B" in key and val.ndim > 1:
256
+ # Check out https://github.com/huggingface/peft/pull/2419 for the `^` symbol.
257
+ # We may run into some ambiguous configuration values when a model has module
258
+ # names, sharing a common prefix (`proj_out.weight` and `blocks.transformer.proj_out.weight`,
259
+ # for example) and they have different LoRA ranks.
260
+ rank[f"^{key}"] = val.shape[1]
261
+
262
+ if network_alphas is not None and len(network_alphas) >= 1:
263
+ alpha_keys = [k for k in network_alphas.keys() if k.startswith(f"{prefix}.")]
264
+ network_alphas = {k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys}
265
+
266
+ lora_config_kwargs = get_peft_kwargs(rank, network_alpha_dict=network_alphas, peft_state_dict=state_dict)
267
+ _maybe_raise_error_for_ambiguity(lora_config_kwargs)
268
+
269
+ if "use_dora" in lora_config_kwargs:
270
+ if lora_config_kwargs["use_dora"]:
271
+ if is_peft_version("<", "0.9.0"):
272
+ raise ValueError(
273
+ "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
274
+ )
275
+ else:
276
+ if is_peft_version("<", "0.9.0"):
277
+ lora_config_kwargs.pop("use_dora")
278
+
279
+ if "lora_bias" in lora_config_kwargs:
280
+ if lora_config_kwargs["lora_bias"]:
281
+ if is_peft_version("<=", "0.13.2"):
282
+ raise ValueError(
283
+ "You need `peft` 0.14.0 at least to use `lora_bias` in LoRAs. Please upgrade your installation of `peft`."
284
+ )
285
+ else:
286
+ if is_peft_version("<=", "0.13.2"):
287
+ lora_config_kwargs.pop("lora_bias")
288
+
289
+ lora_config = LoraConfig(**lora_config_kwargs)
290
+ # adapter_name
291
+ if adapter_name is None:
292
+ adapter_name = get_adapter_name(self)
293
+
294
+ # <Unsafe code
295
+ # We can be sure that the following works as it just sets attention processors, lora layers and puts all in the same dtype
296
+ # Now we remove any existing hooks to `_pipeline`.
297
+
298
+ # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
299
+ # otherwise loading LoRA weights will lead to an error
300
+ is_model_cpu_offload, is_sequential_cpu_offload = self._optionally_disable_offloading(_pipeline)
301
+
302
+ peft_kwargs = {}
303
+ if is_peft_version(">=", "0.13.1"):
304
+ peft_kwargs["low_cpu_mem_usage"] = low_cpu_mem_usage
305
+
306
+ if hotswap or (self._prepare_lora_hotswap_kwargs is not None):
307
+ if is_peft_version(">", "0.14.0"):
308
+ from peft.utils.hotswap import (
309
+ check_hotswap_configs_compatible,
310
+ hotswap_adapter_from_state_dict,
311
+ prepare_model_for_compiled_hotswap,
312
+ )
313
+ else:
314
+ msg = (
315
+ "Hotswapping requires PEFT > v0.14. Please upgrade PEFT to a higher version or install it "
316
+ "from source."
317
+ )
318
+ raise ImportError(msg)
319
+
320
+ if hotswap:
321
+
322
+ def map_state_dict_for_hotswap(sd):
323
+ # For hotswapping, we need the adapter name to be present in the state dict keys
324
+ new_sd = {}
325
+ for k, v in sd.items():
326
+ if k.endswith("lora_A.weight") or key.endswith("lora_B.weight"):
327
+ k = k[: -len(".weight")] + f".{adapter_name}.weight"
328
+ elif k.endswith("lora_B.bias"): # lora_bias=True option
329
+ k = k[: -len(".bias")] + f".{adapter_name}.bias"
330
+ new_sd[k] = v
331
+ return new_sd
332
+
333
+ # To handle scenarios where we cannot successfully set state dict. If it's unsucessful,
334
+ # we should also delete the `peft_config` associated to the `adapter_name`.
335
+ try:
336
+ if hotswap:
337
+ state_dict = map_state_dict_for_hotswap(state_dict)
338
+ check_hotswap_configs_compatible(self.peft_config[adapter_name], lora_config)
339
+ try:
340
+ hotswap_adapter_from_state_dict(
341
+ model=self,
342
+ state_dict=state_dict,
343
+ adapter_name=adapter_name,
344
+ config=lora_config,
345
+ )
346
+ except Exception as e:
347
+ logger.error(f"Hotswapping {adapter_name} was unsucessful with the following error: \n{e}")
348
+ raise
349
+ # the hotswap function raises if there are incompatible keys, so if we reach this point we can set
350
+ # it to None
351
+ incompatible_keys = None
352
+ else:
353
+ inject_adapter_in_model(lora_config, self, adapter_name=adapter_name, **peft_kwargs)
354
+ incompatible_keys = set_peft_model_state_dict(self, state_dict, adapter_name, **peft_kwargs)
355
+
356
+ if self._prepare_lora_hotswap_kwargs is not None:
357
+ # For hotswapping of compiled models or adapters with different ranks.
358
+ # If the user called enable_lora_hotswap, we need to ensure it is called:
359
+ # - after the first adapter was loaded
360
+ # - before the model is compiled and the 2nd adapter is being hotswapped in
361
+ # Therefore, it needs to be called here
362
+ prepare_model_for_compiled_hotswap(
363
+ self, config=lora_config, **self._prepare_lora_hotswap_kwargs
364
+ )
365
+ # We only want to call prepare_model_for_compiled_hotswap once
366
+ self._prepare_lora_hotswap_kwargs = None
367
+
368
+ # Set peft config loaded flag to True if module has been successfully injected and incompatible keys retrieved
369
+ if not self._hf_peft_config_loaded:
370
+ self._hf_peft_config_loaded = True
371
+ except Exception as e:
372
+ # In case `inject_adapter_in_model()` was unsuccessful even before injecting the `peft_config`.
373
+ if hasattr(self, "peft_config"):
374
+ for module in self.modules():
375
+ if isinstance(module, BaseTunerLayer):
376
+ active_adapters = module.active_adapters
377
+ for active_adapter in active_adapters:
378
+ if adapter_name in active_adapter:
379
+ module.delete_adapter(adapter_name)
380
+
381
+ self.peft_config.pop(adapter_name)
382
+ logger.error(f"Loading {adapter_name} was unsucessful with the following error: \n{e}")
383
+ raise
384
+
385
+ warn_msg = ""
386
+ if incompatible_keys is not None:
387
+ # Check only for unexpected keys.
388
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
389
+ if unexpected_keys:
390
+ lora_unexpected_keys = [k for k in unexpected_keys if "lora_" in k and adapter_name in k]
391
+ if lora_unexpected_keys:
392
+ warn_msg = (
393
+ f"Loading adapter weights from state_dict led to unexpected keys found in the model:"
394
+ f" {', '.join(lora_unexpected_keys)}. "
395
+ )
396
+
397
+ # Filter missing keys specific to the current adapter.
398
+ missing_keys = getattr(incompatible_keys, "missing_keys", None)
399
+ if missing_keys:
400
+ lora_missing_keys = [k for k in missing_keys if "lora_" in k and adapter_name in k]
401
+ if lora_missing_keys:
402
+ warn_msg += (
403
+ f"Loading adapter weights from state_dict led to missing keys in the model:"
404
+ f" {', '.join(lora_missing_keys)}."
405
+ )
406
+
407
+ if warn_msg:
408
+ logger.warning(warn_msg)
409
+
410
+ # Offload back.
411
+ if is_model_cpu_offload:
412
+ _pipeline.enable_model_cpu_offload()
413
+ elif is_sequential_cpu_offload:
414
+ _pipeline.enable_sequential_cpu_offload()
415
+ # Unsafe code />
416
+
417
+ if prefix is not None and not state_dict:
418
+ logger.warning(
419
+ f"No LoRA keys associated to {self.__class__.__name__} found with the {prefix=}. "
420
+ "This is safe to ignore if LoRA state dict didn't originally have any "
421
+ f"{self.__class__.__name__} related params. You can also try specifying `prefix=None` "
422
+ "to resolve the warning. Otherwise, open an issue if you think it's unexpected: "
423
+ "https://github.com/huggingface/diffusers/issues/new"
424
+ )
425
+
426
+ def save_lora_adapter(
427
+ self,
428
+ save_directory,
429
+ adapter_name: str = "default",
430
+ upcast_before_saving: bool = False,
431
+ safe_serialization: bool = True,
432
+ weight_name: Optional[str] = None,
433
+ ):
434
+ """
435
+ Save the LoRA parameters corresponding to the underlying model.
436
+
437
+ Arguments:
438
+ save_directory (`str` or `os.PathLike`):
439
+ Directory to save LoRA parameters to. Will be created if it doesn't exist.
440
+ adapter_name: (`str`, defaults to "default"): The name of the adapter to serialize. Useful when the
441
+ underlying model has multiple adapters loaded.
442
+ upcast_before_saving (`bool`, defaults to `False`):
443
+ Whether to cast the underlying model to `torch.float32` before serialization.
444
+ save_function (`Callable`):
445
+ The function to use to save the state dictionary. Useful during distributed training when you need to
446
+ replace `torch.save` with another method. Can be configured with the environment variable
447
+ `DIFFUSERS_SAVE_MODE`.
448
+ safe_serialization (`bool`, *optional*, defaults to `True`):
449
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
450
+ weight_name: (`str`, *optional*, defaults to `None`): Name of the file to serialize the state dict with.
451
+ """
452
+ from peft.utils import get_peft_model_state_dict
453
+
454
+ from .lora_base import LORA_WEIGHT_NAME, LORA_WEIGHT_NAME_SAFE
455
+
456
+ if adapter_name is None:
457
+ adapter_name = get_adapter_name(self)
458
+
459
+ if adapter_name not in getattr(self, "peft_config", {}):
460
+ raise ValueError(f"Adapter name {adapter_name} not found in the model.")
461
+
462
+ lora_layers_to_save = get_peft_model_state_dict(
463
+ self.to(dtype=torch.float32 if upcast_before_saving else None), adapter_name=adapter_name
464
+ )
465
+ if os.path.isfile(save_directory):
466
+ raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")
467
+
468
+ if safe_serialization:
469
+
470
+ def save_function(weights, filename):
471
+ return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
472
+
473
+ else:
474
+ save_function = torch.save
475
+
476
+ os.makedirs(save_directory, exist_ok=True)
477
+
478
+ if weight_name is None:
479
+ if safe_serialization:
480
+ weight_name = LORA_WEIGHT_NAME_SAFE
481
+ else:
482
+ weight_name = LORA_WEIGHT_NAME
483
+
484
+ # TODO: we could consider saving the `peft_config` as well.
485
+ save_path = Path(save_directory, weight_name).as_posix()
486
+ save_function(lora_layers_to_save, save_path)
487
+ logger.info(f"Model weights saved in {save_path}")
488
+
489
+ def set_adapters(
490
+ self,
491
+ adapter_names: Union[List[str], str],
492
+ weights: Optional[Union[float, Dict, List[float], List[Dict], List[None]]] = None,
493
+ ):
494
+ """
495
+ Set the currently active adapters for use in the UNet.
496
+
497
+ Args:
498
+ adapter_names (`List[str]` or `str`):
499
+ The names of the adapters to use.
500
+ adapter_weights (`Union[List[float], float]`, *optional*):
501
+ The adapter(s) weights to use with the UNet. If `None`, the weights are set to `1.0` for all the
502
+ adapters.
503
+
504
+ Example:
505
+
506
+ ```py
507
+ from diffusers import AutoPipelineForText2Image
508
+ import torch
509
+
510
+ pipeline = AutoPipelineForText2Image.from_pretrained(
511
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
512
+ ).to("cuda")
513
+ pipeline.load_lora_weights(
514
+ "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
515
+ )
516
+ pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
517
+ pipeline.set_adapters(["cinematic", "pixel"], adapter_weights=[0.5, 0.5])
518
+ ```
519
+ """
520
+ if not USE_PEFT_BACKEND:
521
+ raise ValueError("PEFT backend is required for `set_adapters()`.")
522
+
523
+ adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
524
+
525
+ # Expand weights into a list, one entry per adapter
526
+ # examples for e.g. 2 adapters: [{...}, 7] -> [7,7] ; None -> [None, None]
527
+ if not isinstance(weights, list):
528
+ weights = [weights] * len(adapter_names)
529
+
530
+ if len(adapter_names) != len(weights):
531
+ raise ValueError(
532
+ f"Length of adapter names {len(adapter_names)} is not equal to the length of their weights {len(weights)}."
533
+ )
534
+
535
+ # Set None values to default of 1.0
536
+ # e.g. [{...}, 7] -> [{...}, 7] ; [None, None] -> [1.0, 1.0]
537
+ weights = [w if w is not None else 1.0 for w in weights]
538
+
539
+ # e.g. [{...}, 7] -> [{expanded dict...}, 7]
540
+ scale_expansion_fn = _SET_ADAPTER_SCALE_FN_MAPPING[self.__class__.__name__]
541
+ weights = scale_expansion_fn(self, weights)
542
+
543
+ set_weights_and_activate_adapters(self, adapter_names, weights)
544
+
545
+ def add_adapter(self, adapter_config, adapter_name: str = "default") -> None:
546
+ r"""
547
+ Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned
548
+ to the adapter to follow the convention of the PEFT library.
549
+
550
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them in the PEFT
551
+ [documentation](https://huggingface.co/docs/peft).
552
+
553
+ Args:
554
+ adapter_config (`[~peft.PeftConfig]`):
555
+ The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt
556
+ methods.
557
+ adapter_name (`str`, *optional*, defaults to `"default"`):
558
+ The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
559
+ """
560
+ check_peft_version(min_version=MIN_PEFT_VERSION)
561
+
562
+ if not is_peft_available():
563
+ raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
564
+
565
+ from peft import PeftConfig, inject_adapter_in_model
566
+
567
+ if not self._hf_peft_config_loaded:
568
+ self._hf_peft_config_loaded = True
569
+ elif adapter_name in self.peft_config:
570
+ raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
571
+
572
+ if not isinstance(adapter_config, PeftConfig):
573
+ raise ValueError(
574
+ f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead."
575
+ )
576
+
577
+ # Unlike transformers, here we don't need to retrieve the name_or_path of the unet as the loading logic is
578
+ # handled by the `load_lora_layers` or `StableDiffusionLoraLoaderMixin`. Therefore we set it to `None` here.
579
+ adapter_config.base_model_name_or_path = None
580
+ inject_adapter_in_model(adapter_config, self, adapter_name)
581
+ self.set_adapter(adapter_name)
582
+
583
+ def set_adapter(self, adapter_name: Union[str, List[str]]) -> None:
584
+ """
585
+ Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.
586
+
587
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
588
+ [documentation](https://huggingface.co/docs/peft).
589
+
590
+ Args:
591
+ adapter_name (Union[str, List[str]])):
592
+ The list of adapters to set or the adapter name in the case of a single adapter.
593
+ """
594
+ check_peft_version(min_version=MIN_PEFT_VERSION)
595
+
596
+ if not self._hf_peft_config_loaded:
597
+ raise ValueError("No adapter loaded. Please load an adapter first.")
598
+
599
+ if isinstance(adapter_name, str):
600
+ adapter_name = [adapter_name]
601
+
602
+ missing = set(adapter_name) - set(self.peft_config)
603
+ if len(missing) > 0:
604
+ raise ValueError(
605
+ f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
606
+ f" current loaded adapters are: {list(self.peft_config.keys())}"
607
+ )
608
+
609
+ from peft.tuners.tuners_utils import BaseTunerLayer
610
+
611
+ _adapters_has_been_set = False
612
+
613
+ for _, module in self.named_modules():
614
+ if isinstance(module, BaseTunerLayer):
615
+ if hasattr(module, "set_adapter"):
616
+ module.set_adapter(adapter_name)
617
+ # Previous versions of PEFT does not support multi-adapter inference
618
+ elif not hasattr(module, "set_adapter") and len(adapter_name) != 1:
619
+ raise ValueError(
620
+ "You are trying to set multiple adapters and you have a PEFT version that does not support multi-adapter inference. Please upgrade to the latest version of PEFT."
621
+ " `pip install -U peft` or `pip install -U git+https://github.com/huggingface/peft.git`"
622
+ )
623
+ else:
624
+ module.active_adapter = adapter_name
625
+ _adapters_has_been_set = True
626
+
627
+ if not _adapters_has_been_set:
628
+ raise ValueError(
629
+ "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
630
+ )
631
+
632
+ def disable_adapters(self) -> None:
633
+ r"""
634
+ Disable all adapters attached to the model and fallback to inference with the base model only.
635
+
636
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
637
+ [documentation](https://huggingface.co/docs/peft).
638
+ """
639
+ check_peft_version(min_version=MIN_PEFT_VERSION)
640
+
641
+ if not self._hf_peft_config_loaded:
642
+ raise ValueError("No adapter loaded. Please load an adapter first.")
643
+
644
+ from peft.tuners.tuners_utils import BaseTunerLayer
645
+
646
+ for _, module in self.named_modules():
647
+ if isinstance(module, BaseTunerLayer):
648
+ if hasattr(module, "enable_adapters"):
649
+ module.enable_adapters(enabled=False)
650
+ else:
651
+ # support for older PEFT versions
652
+ module.disable_adapters = True
653
+
654
+ def enable_adapters(self) -> None:
655
+ """
656
+ Enable adapters that are attached to the model. The model uses `self.active_adapters()` to retrieve the list of
657
+ adapters to enable.
658
+
659
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
660
+ [documentation](https://huggingface.co/docs/peft).
661
+ """
662
+ check_peft_version(min_version=MIN_PEFT_VERSION)
663
+
664
+ if not self._hf_peft_config_loaded:
665
+ raise ValueError("No adapter loaded. Please load an adapter first.")
666
+
667
+ from peft.tuners.tuners_utils import BaseTunerLayer
668
+
669
+ for _, module in self.named_modules():
670
+ if isinstance(module, BaseTunerLayer):
671
+ if hasattr(module, "enable_adapters"):
672
+ module.enable_adapters(enabled=True)
673
+ else:
674
+ # support for older PEFT versions
675
+ module.disable_adapters = False
676
+
677
+ def active_adapters(self) -> List[str]:
678
+ """
679
+ Gets the current list of active adapters of the model.
680
+
681
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
682
+ [documentation](https://huggingface.co/docs/peft).
683
+ """
684
+ check_peft_version(min_version=MIN_PEFT_VERSION)
685
+
686
+ if not is_peft_available():
687
+ raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
688
+
689
+ if not self._hf_peft_config_loaded:
690
+ raise ValueError("No adapter loaded. Please load an adapter first.")
691
+
692
+ from peft.tuners.tuners_utils import BaseTunerLayer
693
+
694
+ for _, module in self.named_modules():
695
+ if isinstance(module, BaseTunerLayer):
696
+ return module.active_adapter
697
+
698
+ def fuse_lora(self, lora_scale=1.0, safe_fusing=False, adapter_names=None):
699
+ if not USE_PEFT_BACKEND:
700
+ raise ValueError("PEFT backend is required for `fuse_lora()`.")
701
+
702
+ self.lora_scale = lora_scale
703
+ self._safe_fusing = safe_fusing
704
+ self.apply(partial(self._fuse_lora_apply, adapter_names=adapter_names))
705
+
706
+ def _fuse_lora_apply(self, module, adapter_names=None):
707
+ from peft.tuners.tuners_utils import BaseTunerLayer
708
+
709
+ merge_kwargs = {"safe_merge": self._safe_fusing}
710
+
711
+ if isinstance(module, BaseTunerLayer):
712
+ if self.lora_scale != 1.0:
713
+ module.scale_layer(self.lora_scale)
714
+
715
+ # For BC with prevous PEFT versions, we need to check the signature
716
+ # of the `merge` method to see if it supports the `adapter_names` argument.
717
+ supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
718
+ if "adapter_names" in supported_merge_kwargs:
719
+ merge_kwargs["adapter_names"] = adapter_names
720
+ elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
721
+ raise ValueError(
722
+ "The `adapter_names` argument is not supported with your PEFT version. Please upgrade"
723
+ " to the latest version of PEFT. `pip install -U peft`"
724
+ )
725
+
726
+ module.merge(**merge_kwargs)
727
+
728
+ def unfuse_lora(self):
729
+ if not USE_PEFT_BACKEND:
730
+ raise ValueError("PEFT backend is required for `unfuse_lora()`.")
731
+ self.apply(self._unfuse_lora_apply)
732
+
733
+ def _unfuse_lora_apply(self, module):
734
+ from peft.tuners.tuners_utils import BaseTunerLayer
735
+
736
+ if isinstance(module, BaseTunerLayer):
737
+ module.unmerge()
738
+
739
+ def unload_lora(self):
740
+ if not USE_PEFT_BACKEND:
741
+ raise ValueError("PEFT backend is required for `unload_lora()`.")
742
+
743
+ from ..utils import recurse_remove_peft_layers
744
+
745
+ recurse_remove_peft_layers(self)
746
+ if hasattr(self, "peft_config"):
747
+ del self.peft_config
748
+
749
+ def disable_lora(self):
750
+ """
751
+ Disables the active LoRA layers of the underlying model.
752
+
753
+ Example:
754
+
755
+ ```py
756
+ from diffusers import AutoPipelineForText2Image
757
+ import torch
758
+
759
+ pipeline = AutoPipelineForText2Image.from_pretrained(
760
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
761
+ ).to("cuda")
762
+ pipeline.load_lora_weights(
763
+ "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
764
+ )
765
+ pipeline.disable_lora()
766
+ ```
767
+ """
768
+ if not USE_PEFT_BACKEND:
769
+ raise ValueError("PEFT backend is required for this method.")
770
+ set_adapter_layers(self, enabled=False)
771
+
772
+ def enable_lora(self):
773
+ """
774
+ Enables the active LoRA layers of the underlying model.
775
+
776
+ Example:
777
+
778
+ ```py
779
+ from diffusers import AutoPipelineForText2Image
780
+ import torch
781
+
782
+ pipeline = AutoPipelineForText2Image.from_pretrained(
783
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
784
+ ).to("cuda")
785
+ pipeline.load_lora_weights(
786
+ "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
787
+ )
788
+ pipeline.enable_lora()
789
+ ```
790
+ """
791
+ if not USE_PEFT_BACKEND:
792
+ raise ValueError("PEFT backend is required for this method.")
793
+ set_adapter_layers(self, enabled=True)
794
+
795
+ def delete_adapters(self, adapter_names: Union[List[str], str]):
796
+ """
797
+ Delete an adapter's LoRA layers from the underlying model.
798
+
799
+ Args:
800
+ adapter_names (`Union[List[str], str]`):
801
+ The names (single string or list of strings) of the adapter to delete.
802
+
803
+ Example:
804
+
805
+ ```py
806
+ from diffusers import AutoPipelineForText2Image
807
+ import torch
808
+
809
+ pipeline = AutoPipelineForText2Image.from_pretrained(
810
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
811
+ ).to("cuda")
812
+ pipeline.load_lora_weights(
813
+ "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
814
+ )
815
+ pipeline.delete_adapters("cinematic")
816
+ ```
817
+ """
818
+ if not USE_PEFT_BACKEND:
819
+ raise ValueError("PEFT backend is required for this method.")
820
+
821
+ if isinstance(adapter_names, str):
822
+ adapter_names = [adapter_names]
823
+
824
+ for adapter_name in adapter_names:
825
+ delete_adapter_layers(self, adapter_name)
826
+
827
+ # Pop also the corresponding adapter from the config
828
+ if hasattr(self, "peft_config"):
829
+ self.peft_config.pop(adapter_name, None)
830
+
831
+ def enable_lora_hotswap(
832
+ self, target_rank: int = 128, check_compiled: Literal["error", "warn", "ignore"] = "error"
833
+ ) -> None:
834
+ """Enables the possibility to hotswap LoRA adapters.
835
+
836
+ Calling this method is only required when hotswapping adapters and if the model is compiled or if the ranks of
837
+ the loaded adapters differ.
838
+
839
+ Args:
840
+ target_rank (`int`, *optional*, defaults to `128`):
841
+ The highest rank among all the adapters that will be loaded.
842
+
843
+ check_compiled (`str`, *optional*, defaults to `"error"`):
844
+ How to handle the case when the model is already compiled, which should generally be avoided. The
845
+ options are:
846
+ - "error" (default): raise an error
847
+ - "warn": issue a warning
848
+ - "ignore": do nothing
849
+ """
850
+ if getattr(self, "peft_config", {}):
851
+ if check_compiled == "error":
852
+ raise RuntimeError("Call `enable_lora_hotswap` before loading the first adapter.")
853
+ elif check_compiled == "warn":
854
+ logger.warning(
855
+ "It is recommended to call `enable_lora_hotswap` before loading the first adapter to avoid recompilation."
856
+ )
857
+ elif check_compiled != "ignore":
858
+ raise ValueError(
859
+ f"check_compiles should be one of 'error', 'warn', or 'ignore', got '{check_compiled}' instead."
860
+ )
861
+
862
+ self._prepare_lora_hotswap_kwargs = {"target_rank": target_rank, "check_compiled": check_compiled}
tasks/tasksmith-f40a643a6ef9/solution/reference/src/diffusers/models/transformers/transformer_hidream_image.py ADDED
@@ -0,0 +1,942 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from ...configuration_utils import ConfigMixin, register_to_config
8
+ from ...loaders import PeftAdapterMixin
9
+ from ...models.modeling_outputs import Transformer2DModelOutput
10
+ from ...models.modeling_utils import ModelMixin
11
+ from ...utils import USE_PEFT_BACKEND, deprecate, logging, scale_lora_layers, unscale_lora_layers
12
+ from ...utils.torch_utils import maybe_allow_in_graph
13
+ from ..attention import Attention
14
+ from ..embeddings import TimestepEmbedding, Timesteps
15
+
16
+
17
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
18
+
19
+
20
+ class HiDreamImageFeedForwardSwiGLU(nn.Module):
21
+ def __init__(
22
+ self,
23
+ dim: int,
24
+ hidden_dim: int,
25
+ multiple_of: int = 256,
26
+ ffn_dim_multiplier: Optional[float] = None,
27
+ ):
28
+ super().__init__()
29
+ hidden_dim = int(2 * hidden_dim / 3)
30
+ # custom dim factor multiplier
31
+ if ffn_dim_multiplier is not None:
32
+ hidden_dim = int(ffn_dim_multiplier * hidden_dim)
33
+ hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
34
+
35
+ self.w1 = nn.Linear(dim, hidden_dim, bias=False)
36
+ self.w2 = nn.Linear(hidden_dim, dim, bias=False)
37
+ self.w3 = nn.Linear(dim, hidden_dim, bias=False)
38
+
39
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
40
+ return self.w2(torch.nn.functional.silu(self.w1(x)) * self.w3(x))
41
+
42
+
43
+ class HiDreamImagePooledEmbed(nn.Module):
44
+ def __init__(self, text_emb_dim, hidden_size):
45
+ super().__init__()
46
+ self.pooled_embedder = TimestepEmbedding(in_channels=text_emb_dim, time_embed_dim=hidden_size)
47
+
48
+ def forward(self, pooled_embed: torch.Tensor) -> torch.Tensor:
49
+ return self.pooled_embedder(pooled_embed)
50
+
51
+
52
+ class HiDreamImageTimestepEmbed(nn.Module):
53
+ def __init__(self, hidden_size, frequency_embedding_size=256):
54
+ super().__init__()
55
+ self.time_proj = Timesteps(num_channels=frequency_embedding_size, flip_sin_to_cos=True, downscale_freq_shift=0)
56
+ self.timestep_embedder = TimestepEmbedding(in_channels=frequency_embedding_size, time_embed_dim=hidden_size)
57
+
58
+ def forward(self, timesteps: torch.Tensor, wdtype: Optional[torch.dtype] = None):
59
+ t_emb = self.time_proj(timesteps).to(dtype=wdtype)
60
+ t_emb = self.timestep_embedder(t_emb)
61
+ return t_emb
62
+
63
+
64
+ class HiDreamImageOutEmbed(nn.Module):
65
+ def __init__(self, hidden_size, patch_size, out_channels):
66
+ super().__init__()
67
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
68
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
69
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
70
+
71
+ def forward(self, hidden_states: torch.Tensor, temb: torch.Tensor) -> torch.Tensor:
72
+ shift, scale = self.adaLN_modulation(temb).chunk(2, dim=1)
73
+ hidden_states = self.norm_final(hidden_states) * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
74
+ hidden_states = self.linear(hidden_states)
75
+ return hidden_states
76
+
77
+
78
+ class HiDreamImagePatchEmbed(nn.Module):
79
+ def __init__(
80
+ self,
81
+ patch_size=2,
82
+ in_channels=4,
83
+ out_channels=1024,
84
+ ):
85
+ super().__init__()
86
+ self.patch_size = patch_size
87
+ self.out_channels = out_channels
88
+ self.proj = nn.Linear(in_channels * patch_size * patch_size, out_channels, bias=True)
89
+
90
+ def forward(self, latent):
91
+ latent = self.proj(latent)
92
+ return latent
93
+
94
+
95
+ def rope(pos: torch.Tensor, dim: int, theta: int) -> torch.Tensor:
96
+ assert dim % 2 == 0, "The dimension must be even."
97
+
98
+ is_mps = pos.device.type == "mps"
99
+ is_npu = pos.device.type == "npu"
100
+
101
+ dtype = torch.float32 if (is_mps or is_npu) else torch.float64
102
+
103
+ scale = torch.arange(0, dim, 2, dtype=dtype, device=pos.device) / dim
104
+ omega = 1.0 / (theta**scale)
105
+
106
+ batch_size, seq_length = pos.shape
107
+ out = torch.einsum("...n,d->...nd", pos, omega)
108
+ cos_out = torch.cos(out)
109
+ sin_out = torch.sin(out)
110
+
111
+ stacked_out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
112
+ out = stacked_out.view(batch_size, -1, dim // 2, 2, 2)
113
+ return out.float()
114
+
115
+
116
+ class HiDreamImageEmbedND(nn.Module):
117
+ def __init__(self, theta: int, axes_dim: List[int]):
118
+ super().__init__()
119
+ self.theta = theta
120
+ self.axes_dim = axes_dim
121
+
122
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
123
+ n_axes = ids.shape[-1]
124
+ emb = torch.cat(
125
+ [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
126
+ dim=-3,
127
+ )
128
+ return emb.unsqueeze(2)
129
+
130
+
131
+ def apply_rope(xq: torch.Tensor, xk: torch.Tensor, freqs_cis: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
132
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
133
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
134
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
135
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
136
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
137
+
138
+
139
+ @maybe_allow_in_graph
140
+ class HiDreamAttention(Attention):
141
+ def __init__(
142
+ self,
143
+ query_dim: int,
144
+ heads: int = 8,
145
+ dim_head: int = 64,
146
+ upcast_attention: bool = False,
147
+ upcast_softmax: bool = False,
148
+ scale_qk: bool = True,
149
+ eps: float = 1e-5,
150
+ processor=None,
151
+ out_dim: int = None,
152
+ single: bool = False,
153
+ ):
154
+ super(Attention, self).__init__()
155
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
156
+ self.query_dim = query_dim
157
+ self.upcast_attention = upcast_attention
158
+ self.upcast_softmax = upcast_softmax
159
+ self.out_dim = out_dim if out_dim is not None else query_dim
160
+
161
+ self.scale_qk = scale_qk
162
+ self.scale = dim_head**-0.5 if self.scale_qk else 1.0
163
+
164
+ self.heads = out_dim // dim_head if out_dim is not None else heads
165
+ self.sliceable_head_dim = heads
166
+ self.single = single
167
+
168
+ self.to_q = nn.Linear(query_dim, self.inner_dim)
169
+ self.to_k = nn.Linear(self.inner_dim, self.inner_dim)
170
+ self.to_v = nn.Linear(self.inner_dim, self.inner_dim)
171
+ self.to_out = nn.Linear(self.inner_dim, self.out_dim)
172
+ self.q_rms_norm = nn.RMSNorm(self.inner_dim, eps)
173
+ self.k_rms_norm = nn.RMSNorm(self.inner_dim, eps)
174
+
175
+ if not single:
176
+ self.to_q_t = nn.Linear(query_dim, self.inner_dim)
177
+ self.to_k_t = nn.Linear(self.inner_dim, self.inner_dim)
178
+ self.to_v_t = nn.Linear(self.inner_dim, self.inner_dim)
179
+ self.to_out_t = nn.Linear(self.inner_dim, self.out_dim)
180
+ self.q_rms_norm_t = nn.RMSNorm(self.inner_dim, eps)
181
+ self.k_rms_norm_t = nn.RMSNorm(self.inner_dim, eps)
182
+
183
+ self.set_processor(processor)
184
+
185
+ def forward(
186
+ self,
187
+ norm_hidden_states: torch.Tensor,
188
+ hidden_states_masks: torch.Tensor = None,
189
+ norm_encoder_hidden_states: torch.Tensor = None,
190
+ image_rotary_emb: torch.Tensor = None,
191
+ ) -> torch.Tensor:
192
+ return self.processor(
193
+ self,
194
+ hidden_states=norm_hidden_states,
195
+ hidden_states_masks=hidden_states_masks,
196
+ encoder_hidden_states=norm_encoder_hidden_states,
197
+ image_rotary_emb=image_rotary_emb,
198
+ )
199
+
200
+
201
+ class HiDreamAttnProcessor:
202
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
203
+
204
+ def __call__(
205
+ self,
206
+ attn: HiDreamAttention,
207
+ hidden_states: torch.Tensor,
208
+ hidden_states_masks: Optional[torch.Tensor] = None,
209
+ encoder_hidden_states: Optional[torch.Tensor] = None,
210
+ image_rotary_emb: torch.Tensor = None,
211
+ *args,
212
+ **kwargs,
213
+ ) -> torch.Tensor:
214
+ dtype = hidden_states.dtype
215
+ batch_size = hidden_states.shape[0]
216
+
217
+ query_i = attn.q_rms_norm(attn.to_q(hidden_states)).to(dtype=dtype)
218
+ key_i = attn.k_rms_norm(attn.to_k(hidden_states)).to(dtype=dtype)
219
+ value_i = attn.to_v(hidden_states)
220
+
221
+ inner_dim = key_i.shape[-1]
222
+ head_dim = inner_dim // attn.heads
223
+
224
+ query_i = query_i.view(batch_size, -1, attn.heads, head_dim)
225
+ key_i = key_i.view(batch_size, -1, attn.heads, head_dim)
226
+ value_i = value_i.view(batch_size, -1, attn.heads, head_dim)
227
+ if hidden_states_masks is not None:
228
+ key_i = key_i * hidden_states_masks.view(batch_size, -1, 1, 1)
229
+
230
+ if not attn.single:
231
+ query_t = attn.q_rms_norm_t(attn.to_q_t(encoder_hidden_states)).to(dtype=dtype)
232
+ key_t = attn.k_rms_norm_t(attn.to_k_t(encoder_hidden_states)).to(dtype=dtype)
233
+ value_t = attn.to_v_t(encoder_hidden_states)
234
+
235
+ query_t = query_t.view(batch_size, -1, attn.heads, head_dim)
236
+ key_t = key_t.view(batch_size, -1, attn.heads, head_dim)
237
+ value_t = value_t.view(batch_size, -1, attn.heads, head_dim)
238
+
239
+ num_image_tokens = query_i.shape[1]
240
+ num_text_tokens = query_t.shape[1]
241
+ query = torch.cat([query_i, query_t], dim=1)
242
+ key = torch.cat([key_i, key_t], dim=1)
243
+ value = torch.cat([value_i, value_t], dim=1)
244
+ else:
245
+ query = query_i
246
+ key = key_i
247
+ value = value_i
248
+
249
+ if query.shape[-1] == image_rotary_emb.shape[-3] * 2:
250
+ query, key = apply_rope(query, key, image_rotary_emb)
251
+
252
+ else:
253
+ query_1, query_2 = query.chunk(2, dim=-1)
254
+ key_1, key_2 = key.chunk(2, dim=-1)
255
+ query_1, key_1 = apply_rope(query_1, key_1, image_rotary_emb)
256
+ query = torch.cat([query_1, query_2], dim=-1)
257
+ key = torch.cat([key_1, key_2], dim=-1)
258
+
259
+ hidden_states = F.scaled_dot_product_attention(
260
+ query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2), dropout_p=0.0, is_causal=False
261
+ )
262
+
263
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
264
+ hidden_states = hidden_states.to(query.dtype)
265
+
266
+ if not attn.single:
267
+ hidden_states_i, hidden_states_t = torch.split(hidden_states, [num_image_tokens, num_text_tokens], dim=1)
268
+ hidden_states_i = attn.to_out(hidden_states_i)
269
+ hidden_states_t = attn.to_out_t(hidden_states_t)
270
+ return hidden_states_i, hidden_states_t
271
+ else:
272
+ hidden_states = attn.to_out(hidden_states)
273
+ return hidden_states
274
+
275
+
276
+ # Modified from https://github.com/deepseek-ai/DeepSeek-V3/blob/main/inference/model.py
277
+ class MoEGate(nn.Module):
278
+ def __init__(
279
+ self,
280
+ embed_dim,
281
+ num_routed_experts=4,
282
+ num_activated_experts=2,
283
+ aux_loss_alpha=0.01,
284
+ _force_inference_output=False,
285
+ ):
286
+ super().__init__()
287
+ self.top_k = num_activated_experts
288
+ self.n_routed_experts = num_routed_experts
289
+
290
+ self.scoring_func = "softmax"
291
+ self.alpha = aux_loss_alpha
292
+ self.seq_aux = False
293
+
294
+ # topk selection algorithm
295
+ self.norm_topk_prob = False
296
+ self.gating_dim = embed_dim
297
+ self.weight = nn.Parameter(torch.randn(self.n_routed_experts, self.gating_dim) / embed_dim**0.5)
298
+
299
+ self._force_inference_output = _force_inference_output
300
+
301
+ def forward(self, hidden_states):
302
+ bsz, seq_len, h = hidden_states.shape
303
+ ### compute gating score
304
+ hidden_states = hidden_states.view(-1, h)
305
+ logits = F.linear(hidden_states, self.weight, None)
306
+ if self.scoring_func == "softmax":
307
+ scores = logits.softmax(dim=-1)
308
+ else:
309
+ raise NotImplementedError(f"insupportable scoring function for MoE gating: {self.scoring_func}")
310
+
311
+ ### select top-k experts
312
+ topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
313
+
314
+ ### norm gate to sum 1
315
+ if self.top_k > 1 and self.norm_topk_prob:
316
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
317
+ topk_weight = topk_weight / denominator
318
+
319
+ ### expert-level computation auxiliary loss
320
+ if self.training and self.alpha > 0.0 and not self._force_inference_output:
321
+ scores_for_aux = scores
322
+ aux_topk = self.top_k
323
+ # always compute aux loss based on the naive greedy topk method
324
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
325
+ if self.seq_aux:
326
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
327
+ ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
328
+ ce.scatter_add_(
329
+ 1, topk_idx_for_aux_loss, torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)
330
+ ).div_(seq_len * aux_topk / self.n_routed_experts)
331
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
332
+ else:
333
+ mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
334
+ ce = mask_ce.float().mean(0)
335
+
336
+ Pi = scores_for_aux.mean(0)
337
+ fi = ce * self.n_routed_experts
338
+ aux_loss = (Pi * fi).sum() * self.alpha
339
+ else:
340
+ aux_loss = None
341
+ return topk_idx, topk_weight, aux_loss
342
+
343
+
344
+ # Modified from https://github.com/deepseek-ai/DeepSeek-V3/blob/main/inference/model.py
345
+ class MOEFeedForwardSwiGLU(nn.Module):
346
+ def __init__(
347
+ self,
348
+ dim: int,
349
+ hidden_dim: int,
350
+ num_routed_experts: int,
351
+ num_activated_experts: int,
352
+ _force_inference_output: bool = False,
353
+ ):
354
+ super().__init__()
355
+ self.shared_experts = HiDreamImageFeedForwardSwiGLU(dim, hidden_dim // 2)
356
+ self.experts = nn.ModuleList(
357
+ [HiDreamImageFeedForwardSwiGLU(dim, hidden_dim) for i in range(num_routed_experts)]
358
+ )
359
+ self._force_inference_output = _force_inference_output
360
+ self.gate = MoEGate(
361
+ embed_dim=dim,
362
+ num_routed_experts=num_routed_experts,
363
+ num_activated_experts=num_activated_experts,
364
+ _force_inference_output=_force_inference_output,
365
+ )
366
+ self.num_activated_experts = num_activated_experts
367
+
368
+ def forward(self, x):
369
+ wtype = x.dtype
370
+ identity = x
371
+ orig_shape = x.shape
372
+ topk_idx, topk_weight, aux_loss = self.gate(x)
373
+ x = x.view(-1, x.shape[-1])
374
+ flat_topk_idx = topk_idx.view(-1)
375
+ if self.training and not self._force_inference_output:
376
+ x = x.repeat_interleave(self.num_activated_experts, dim=0)
377
+ y = torch.empty_like(x, dtype=wtype)
378
+ for i, expert in enumerate(self.experts):
379
+ y[flat_topk_idx == i] = expert(x[flat_topk_idx == i]).to(dtype=wtype)
380
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
381
+ y = y.view(*orig_shape).to(dtype=wtype)
382
+ # y = AddAuxiliaryLoss.apply(y, aux_loss)
383
+ else:
384
+ y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
385
+ y = y + self.shared_experts(identity)
386
+ return y
387
+
388
+ @torch.no_grad()
389
+ def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
390
+ expert_cache = torch.zeros_like(x)
391
+ idxs = flat_expert_indices.argsort()
392
+ tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
393
+ token_idxs = idxs // self.num_activated_experts
394
+ for i, end_idx in enumerate(tokens_per_expert):
395
+ start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
396
+ if start_idx == end_idx:
397
+ continue
398
+ expert = self.experts[i]
399
+ exp_token_idx = token_idxs[start_idx:end_idx]
400
+ expert_tokens = x[exp_token_idx]
401
+ expert_out = expert(expert_tokens)
402
+ expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
403
+
404
+ # for fp16 and other dtype
405
+ expert_cache = expert_cache.to(expert_out.dtype)
406
+ expert_cache.scatter_reduce_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out, reduce="sum")
407
+ return expert_cache
408
+
409
+
410
+ class TextProjection(nn.Module):
411
+ def __init__(self, in_features, hidden_size):
412
+ super().__init__()
413
+ self.linear = nn.Linear(in_features=in_features, out_features=hidden_size, bias=False)
414
+
415
+ def forward(self, caption):
416
+ hidden_states = self.linear(caption)
417
+ return hidden_states
418
+
419
+
420
+ @maybe_allow_in_graph
421
+ class HiDreamImageSingleTransformerBlock(nn.Module):
422
+ def __init__(
423
+ self,
424
+ dim: int,
425
+ num_attention_heads: int,
426
+ attention_head_dim: int,
427
+ num_routed_experts: int = 4,
428
+ num_activated_experts: int = 2,
429
+ _force_inference_output: bool = False,
430
+ ):
431
+ super().__init__()
432
+ self.num_attention_heads = num_attention_heads
433
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim, 6 * dim, bias=True))
434
+
435
+ # 1. Attention
436
+ self.norm1_i = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
437
+ self.attn1 = HiDreamAttention(
438
+ query_dim=dim,
439
+ heads=num_attention_heads,
440
+ dim_head=attention_head_dim,
441
+ processor=HiDreamAttnProcessor(),
442
+ single=True,
443
+ )
444
+
445
+ # 3. Feed-forward
446
+ self.norm3_i = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
447
+ if num_routed_experts > 0:
448
+ self.ff_i = MOEFeedForwardSwiGLU(
449
+ dim=dim,
450
+ hidden_dim=4 * dim,
451
+ num_routed_experts=num_routed_experts,
452
+ num_activated_experts=num_activated_experts,
453
+ _force_inference_output=_force_inference_output,
454
+ )
455
+ else:
456
+ self.ff_i = HiDreamImageFeedForwardSwiGLU(dim=dim, hidden_dim=4 * dim)
457
+
458
+ def forward(
459
+ self,
460
+ hidden_states: torch.Tensor,
461
+ hidden_states_masks: Optional[torch.Tensor] = None,
462
+ encoder_hidden_states: Optional[torch.Tensor] = None,
463
+ temb: Optional[torch.Tensor] = None,
464
+ image_rotary_emb: torch.Tensor = None,
465
+ ) -> torch.Tensor:
466
+ wtype = hidden_states.dtype
467
+ shift_msa_i, scale_msa_i, gate_msa_i, shift_mlp_i, scale_mlp_i, gate_mlp_i = self.adaLN_modulation(temb)[
468
+ :, None
469
+ ].chunk(6, dim=-1)
470
+
471
+ # 1. MM-Attention
472
+ norm_hidden_states = self.norm1_i(hidden_states).to(dtype=wtype)
473
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa_i) + shift_msa_i
474
+ attn_output_i = self.attn1(
475
+ norm_hidden_states,
476
+ hidden_states_masks,
477
+ image_rotary_emb=image_rotary_emb,
478
+ )
479
+ hidden_states = gate_msa_i * attn_output_i + hidden_states
480
+
481
+ # 2. Feed-forward
482
+ norm_hidden_states = self.norm3_i(hidden_states).to(dtype=wtype)
483
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp_i) + shift_mlp_i
484
+ ff_output_i = gate_mlp_i * self.ff_i(norm_hidden_states.to(dtype=wtype))
485
+ hidden_states = ff_output_i + hidden_states
486
+ return hidden_states
487
+
488
+
489
+ @maybe_allow_in_graph
490
+ class HiDreamImageTransformerBlock(nn.Module):
491
+ def __init__(
492
+ self,
493
+ dim: int,
494
+ num_attention_heads: int,
495
+ attention_head_dim: int,
496
+ num_routed_experts: int = 4,
497
+ num_activated_experts: int = 2,
498
+ _force_inference_output: bool = False,
499
+ ):
500
+ super().__init__()
501
+ self.num_attention_heads = num_attention_heads
502
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim, 12 * dim, bias=True))
503
+
504
+ # 1. Attention
505
+ self.norm1_i = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
506
+ self.norm1_t = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
507
+ self.attn1 = HiDreamAttention(
508
+ query_dim=dim,
509
+ heads=num_attention_heads,
510
+ dim_head=attention_head_dim,
511
+ processor=HiDreamAttnProcessor(),
512
+ single=False,
513
+ )
514
+
515
+ # 3. Feed-forward
516
+ self.norm3_i = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
517
+ if num_routed_experts > 0:
518
+ self.ff_i = MOEFeedForwardSwiGLU(
519
+ dim=dim,
520
+ hidden_dim=4 * dim,
521
+ num_routed_experts=num_routed_experts,
522
+ num_activated_experts=num_activated_experts,
523
+ _force_inference_output=_force_inference_output,
524
+ )
525
+ else:
526
+ self.ff_i = HiDreamImageFeedForwardSwiGLU(dim=dim, hidden_dim=4 * dim)
527
+ self.norm3_t = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
528
+ self.ff_t = HiDreamImageFeedForwardSwiGLU(dim=dim, hidden_dim=4 * dim)
529
+
530
+ def forward(
531
+ self,
532
+ hidden_states: torch.Tensor,
533
+ hidden_states_masks: Optional[torch.Tensor] = None,
534
+ encoder_hidden_states: Optional[torch.Tensor] = None,
535
+ temb: Optional[torch.Tensor] = None,
536
+ image_rotary_emb: torch.Tensor = None,
537
+ ) -> torch.Tensor:
538
+ wtype = hidden_states.dtype
539
+ (
540
+ shift_msa_i,
541
+ scale_msa_i,
542
+ gate_msa_i,
543
+ shift_mlp_i,
544
+ scale_mlp_i,
545
+ gate_mlp_i,
546
+ shift_msa_t,
547
+ scale_msa_t,
548
+ gate_msa_t,
549
+ shift_mlp_t,
550
+ scale_mlp_t,
551
+ gate_mlp_t,
552
+ ) = self.adaLN_modulation(temb)[:, None].chunk(12, dim=-1)
553
+
554
+ # 1. MM-Attention
555
+ norm_hidden_states = self.norm1_i(hidden_states).to(dtype=wtype)
556
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa_i) + shift_msa_i
557
+ norm_encoder_hidden_states = self.norm1_t(encoder_hidden_states).to(dtype=wtype)
558
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + scale_msa_t) + shift_msa_t
559
+
560
+ attn_output_i, attn_output_t = self.attn1(
561
+ norm_hidden_states,
562
+ hidden_states_masks,
563
+ norm_encoder_hidden_states,
564
+ image_rotary_emb=image_rotary_emb,
565
+ )
566
+
567
+ hidden_states = gate_msa_i * attn_output_i + hidden_states
568
+ encoder_hidden_states = gate_msa_t * attn_output_t + encoder_hidden_states
569
+
570
+ # 2. Feed-forward
571
+ norm_hidden_states = self.norm3_i(hidden_states).to(dtype=wtype)
572
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp_i) + shift_mlp_i
573
+ norm_encoder_hidden_states = self.norm3_t(encoder_hidden_states).to(dtype=wtype)
574
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + scale_mlp_t) + shift_mlp_t
575
+
576
+ ff_output_i = gate_mlp_i * self.ff_i(norm_hidden_states)
577
+ ff_output_t = gate_mlp_t * self.ff_t(norm_encoder_hidden_states)
578
+ hidden_states = ff_output_i + hidden_states
579
+ encoder_hidden_states = ff_output_t + encoder_hidden_states
580
+ return hidden_states, encoder_hidden_states
581
+
582
+
583
+ class HiDreamBlock(nn.Module):
584
+ def __init__(self, block: Union[HiDreamImageTransformerBlock, HiDreamImageSingleTransformerBlock]):
585
+ super().__init__()
586
+ self.block = block
587
+
588
+ def forward(
589
+ self,
590
+ hidden_states: torch.Tensor,
591
+ hidden_states_masks: Optional[torch.Tensor] = None,
592
+ encoder_hidden_states: Optional[torch.Tensor] = None,
593
+ temb: Optional[torch.Tensor] = None,
594
+ image_rotary_emb: torch.Tensor = None,
595
+ ) -> torch.Tensor:
596
+ return self.block(
597
+ hidden_states=hidden_states,
598
+ hidden_states_masks=hidden_states_masks,
599
+ encoder_hidden_states=encoder_hidden_states,
600
+ temb=temb,
601
+ image_rotary_emb=image_rotary_emb,
602
+ )
603
+
604
+
605
+ class HiDreamImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
606
+ _supports_gradient_checkpointing = True
607
+ _no_split_modules = ["HiDreamImageTransformerBlock", "HiDreamImageSingleTransformerBlock"]
608
+
609
+ @register_to_config
610
+ def __init__(
611
+ self,
612
+ patch_size: Optional[int] = None,
613
+ in_channels: int = 64,
614
+ out_channels: Optional[int] = None,
615
+ num_layers: int = 16,
616
+ num_single_layers: int = 32,
617
+ attention_head_dim: int = 128,
618
+ num_attention_heads: int = 20,
619
+ caption_channels: List[int] = None,
620
+ text_emb_dim: int = 2048,
621
+ num_routed_experts: int = 4,
622
+ num_activated_experts: int = 2,
623
+ axes_dims_rope: Tuple[int, int] = (32, 32),
624
+ max_resolution: Tuple[int, int] = (128, 128),
625
+ llama_layers: List[int] = None,
626
+ force_inference_output: bool = False,
627
+ ):
628
+ super().__init__()
629
+ self.out_channels = out_channels or in_channels
630
+ self.inner_dim = num_attention_heads * attention_head_dim
631
+
632
+ self.t_embedder = HiDreamImageTimestepEmbed(self.inner_dim)
633
+ self.p_embedder = HiDreamImagePooledEmbed(text_emb_dim, self.inner_dim)
634
+ self.x_embedder = HiDreamImagePatchEmbed(
635
+ patch_size=patch_size,
636
+ in_channels=in_channels,
637
+ out_channels=self.inner_dim,
638
+ )
639
+ self.pe_embedder = HiDreamImageEmbedND(theta=10000, axes_dim=axes_dims_rope)
640
+
641
+ self.double_stream_blocks = nn.ModuleList(
642
+ [
643
+ HiDreamBlock(
644
+ HiDreamImageTransformerBlock(
645
+ dim=self.inner_dim,
646
+ num_attention_heads=num_attention_heads,
647
+ attention_head_dim=attention_head_dim,
648
+ num_routed_experts=num_routed_experts,
649
+ num_activated_experts=num_activated_experts,
650
+ _force_inference_output=force_inference_output,
651
+ )
652
+ )
653
+ for _ in range(num_layers)
654
+ ]
655
+ )
656
+
657
+ self.single_stream_blocks = nn.ModuleList(
658
+ [
659
+ HiDreamBlock(
660
+ HiDreamImageSingleTransformerBlock(
661
+ dim=self.inner_dim,
662
+ num_attention_heads=num_attention_heads,
663
+ attention_head_dim=attention_head_dim,
664
+ num_routed_experts=num_routed_experts,
665
+ num_activated_experts=num_activated_experts,
666
+ _force_inference_output=force_inference_output,
667
+ )
668
+ )
669
+ for _ in range(num_single_layers)
670
+ ]
671
+ )
672
+
673
+ self.final_layer = HiDreamImageOutEmbed(self.inner_dim, patch_size, self.out_channels)
674
+
675
+ caption_channels = [caption_channels[1]] * (num_layers + num_single_layers) + [caption_channels[0]]
676
+ caption_projection = []
677
+ for caption_channel in caption_channels:
678
+ caption_projection.append(TextProjection(in_features=caption_channel, hidden_size=self.inner_dim))
679
+ self.caption_projection = nn.ModuleList(caption_projection)
680
+ self.max_seq = max_resolution[0] * max_resolution[1] // (patch_size * patch_size)
681
+
682
+ self.gradient_checkpointing = False
683
+
684
+ def unpatchify(self, x: torch.Tensor, img_sizes: List[Tuple[int, int]], is_training: bool) -> List[torch.Tensor]:
685
+ if is_training and not self.config.force_inference_output:
686
+ B, S, F = x.shape
687
+ C = F // (self.config.patch_size * self.config.patch_size)
688
+ x = (
689
+ x.reshape(B, S, self.config.patch_size, self.config.patch_size, C)
690
+ .permute(0, 4, 1, 2, 3)
691
+ .reshape(B, C, S, self.config.patch_size * self.config.patch_size)
692
+ )
693
+ else:
694
+ x_arr = []
695
+ p1 = self.config.patch_size
696
+ p2 = self.config.patch_size
697
+ for i, img_size in enumerate(img_sizes):
698
+ pH, pW = img_size
699
+ t = x[i, : pH * pW].reshape(1, pH, pW, -1)
700
+ F_token = t.shape[-1]
701
+ C = F_token // (p1 * p2)
702
+ t = t.reshape(1, pH, pW, p1, p2, C)
703
+ t = t.permute(0, 5, 1, 3, 2, 4)
704
+ t = t.reshape(1, C, pH * p1, pW * p2)
705
+ x_arr.append(t)
706
+ x = torch.cat(x_arr, dim=0)
707
+ return x
708
+
709
+ def patchify(self, hidden_states):
710
+ batch_size, channels, height, width = hidden_states.shape
711
+ patch_size = self.config.patch_size
712
+ patch_height, patch_width = height // patch_size, width // patch_size
713
+ device = hidden_states.device
714
+ dtype = hidden_states.dtype
715
+
716
+ # create img_sizes
717
+ img_sizes = torch.tensor([patch_height, patch_width], dtype=torch.int64, device=device).reshape(-1)
718
+ img_sizes = img_sizes.unsqueeze(0).repeat(batch_size, 1)
719
+
720
+ # create hidden_states_masks
721
+ if hidden_states.shape[-2] != hidden_states.shape[-1]:
722
+ hidden_states_masks = torch.zeros((batch_size, self.max_seq), dtype=dtype, device=device)
723
+ hidden_states_masks[:, : patch_height * patch_width] = 1.0
724
+ else:
725
+ hidden_states_masks = None
726
+
727
+ # create img_ids
728
+ img_ids = torch.zeros(patch_height, patch_width, 3, device=device)
729
+ row_indices = torch.arange(patch_height, device=device)[:, None]
730
+ col_indices = torch.arange(patch_width, device=device)[None, :]
731
+ img_ids[..., 1] = img_ids[..., 1] + row_indices
732
+ img_ids[..., 2] = img_ids[..., 2] + col_indices
733
+ img_ids = img_ids.reshape(patch_height * patch_width, -1)
734
+
735
+ if hidden_states.shape[-2] != hidden_states.shape[-1]:
736
+ # Handle non-square latents
737
+ img_ids_pad = torch.zeros(self.max_seq, 3, device=device)
738
+ img_ids_pad[: patch_height * patch_width, :] = img_ids
739
+ img_ids = img_ids_pad.unsqueeze(0).repeat(batch_size, 1, 1)
740
+ else:
741
+ img_ids = img_ids.unsqueeze(0).repeat(batch_size, 1, 1)
742
+
743
+ # patchify hidden_states
744
+ if hidden_states.shape[-2] != hidden_states.shape[-1]:
745
+ # Handle non-square latents
746
+ out = torch.zeros(
747
+ (batch_size, channels, self.max_seq, patch_size * patch_size),
748
+ dtype=dtype,
749
+ device=device,
750
+ )
751
+ hidden_states = hidden_states.reshape(
752
+ batch_size, channels, patch_height, patch_size, patch_width, patch_size
753
+ )
754
+ hidden_states = hidden_states.permute(0, 1, 2, 4, 3, 5)
755
+ hidden_states = hidden_states.reshape(
756
+ batch_size, channels, patch_height * patch_width, patch_size * patch_size
757
+ )
758
+ out[:, :, 0 : patch_height * patch_width] = hidden_states
759
+ hidden_states = out
760
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(
761
+ batch_size, self.max_seq, patch_size * patch_size * channels
762
+ )
763
+
764
+ else:
765
+ # Handle square latents
766
+ hidden_states = hidden_states.reshape(
767
+ batch_size, channels, patch_height, patch_size, patch_width, patch_size
768
+ )
769
+ hidden_states = hidden_states.permute(0, 2, 4, 3, 5, 1)
770
+ hidden_states = hidden_states.reshape(
771
+ batch_size, patch_height * patch_width, patch_size * patch_size * channels
772
+ )
773
+
774
+ return hidden_states, hidden_states_masks, img_sizes, img_ids
775
+
776
+ def forward(
777
+ self,
778
+ hidden_states: torch.Tensor,
779
+ timesteps: torch.LongTensor = None,
780
+ encoder_hidden_states_t5: torch.Tensor = None,
781
+ encoder_hidden_states_llama3: torch.Tensor = None,
782
+ pooled_embeds: torch.Tensor = None,
783
+ img_ids: Optional[torch.Tensor] = None,
784
+ img_sizes: Optional[List[Tuple[int, int]]] = None,
785
+ hidden_states_masks: Optional[torch.Tensor] = None,
786
+ attention_kwargs: Optional[Dict[str, Any]] = None,
787
+ return_dict: bool = True,
788
+ **kwargs,
789
+ ):
790
+ encoder_hidden_states = kwargs.get("encoder_hidden_states", None)
791
+
792
+ if encoder_hidden_states is not None:
793
+ deprecation_message = "The `encoder_hidden_states` argument is deprecated. Please use `encoder_hidden_states_t5` and `encoder_hidden_states_llama3` instead."
794
+ deprecate("encoder_hidden_states", "0.34.0", deprecation_message)
795
+ encoder_hidden_states_t5 = encoder_hidden_states[0]
796
+ encoder_hidden_states_llama3 = encoder_hidden_states[1]
797
+
798
+ if img_ids is not None and img_sizes is not None and hidden_states_masks is None:
799
+ deprecation_message = (
800
+ "Passing `img_ids` and `img_sizes` with unpachified `hidden_states` is deprecated and will be ignored."
801
+ )
802
+ deprecate("img_ids", "0.34.0", deprecation_message)
803
+
804
+ if hidden_states_masks is not None and (img_ids is None or img_sizes is None):
805
+ raise ValueError("if `hidden_states_masks` is passed, `img_ids` and `img_sizes` must also be passed.")
806
+ elif hidden_states_masks is not None and hidden_states.ndim != 3:
807
+ raise ValueError(
808
+ "if `hidden_states_masks` is passed, `hidden_states` must be a 3D tensors with shape (batch_size, patch_height * patch_width, patch_size * patch_size * channels)"
809
+ )
810
+
811
+ if attention_kwargs is not None:
812
+ attention_kwargs = attention_kwargs.copy()
813
+ lora_scale = attention_kwargs.pop("scale", 1.0)
814
+ else:
815
+ lora_scale = 1.0
816
+
817
+ if USE_PEFT_BACKEND:
818
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
819
+ scale_lora_layers(self, lora_scale)
820
+ else:
821
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
822
+ logger.warning(
823
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
824
+ )
825
+
826
+ # spatial forward
827
+ batch_size = hidden_states.shape[0]
828
+ hidden_states_type = hidden_states.dtype
829
+
830
+ # Patchify the input
831
+ if hidden_states_masks is None:
832
+ hidden_states, hidden_states_masks, img_sizes, img_ids = self.patchify(hidden_states)
833
+
834
+ # Embed the hidden states
835
+ hidden_states = self.x_embedder(hidden_states)
836
+
837
+ # 0. time
838
+ timesteps = self.t_embedder(timesteps, hidden_states_type)
839
+ p_embedder = self.p_embedder(pooled_embeds)
840
+ temb = timesteps + p_embedder
841
+
842
+ encoder_hidden_states = [encoder_hidden_states_llama3[k] for k in self.config.llama_layers]
843
+
844
+ if self.caption_projection is not None:
845
+ new_encoder_hidden_states = []
846
+ for i, enc_hidden_state in enumerate(encoder_hidden_states):
847
+ enc_hidden_state = self.caption_projection[i](enc_hidden_state)
848
+ enc_hidden_state = enc_hidden_state.view(batch_size, -1, hidden_states.shape[-1])
849
+ new_encoder_hidden_states.append(enc_hidden_state)
850
+ encoder_hidden_states = new_encoder_hidden_states
851
+ encoder_hidden_states_t5 = self.caption_projection[-1](encoder_hidden_states_t5)
852
+ encoder_hidden_states_t5 = encoder_hidden_states_t5.view(batch_size, -1, hidden_states.shape[-1])
853
+ encoder_hidden_states.append(encoder_hidden_states_t5)
854
+
855
+ txt_ids = torch.zeros(
856
+ batch_size,
857
+ encoder_hidden_states[-1].shape[1]
858
+ + encoder_hidden_states[-2].shape[1]
859
+ + encoder_hidden_states[0].shape[1],
860
+ 3,
861
+ device=img_ids.device,
862
+ dtype=img_ids.dtype,
863
+ )
864
+ ids = torch.cat((img_ids, txt_ids), dim=1)
865
+ image_rotary_emb = self.pe_embedder(ids)
866
+
867
+ # 2. Blocks
868
+ block_id = 0
869
+ initial_encoder_hidden_states = torch.cat([encoder_hidden_states[-1], encoder_hidden_states[-2]], dim=1)
870
+ initial_encoder_hidden_states_seq_len = initial_encoder_hidden_states.shape[1]
871
+ for bid, block in enumerate(self.double_stream_blocks):
872
+ cur_llama31_encoder_hidden_states = encoder_hidden_states[block_id]
873
+ cur_encoder_hidden_states = torch.cat(
874
+ [initial_encoder_hidden_states, cur_llama31_encoder_hidden_states], dim=1
875
+ )
876
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
877
+ hidden_states, initial_encoder_hidden_states = self._gradient_checkpointing_func(
878
+ block,
879
+ hidden_states,
880
+ hidden_states_masks,
881
+ cur_encoder_hidden_states,
882
+ temb,
883
+ image_rotary_emb,
884
+ )
885
+ else:
886
+ hidden_states, initial_encoder_hidden_states = block(
887
+ hidden_states=hidden_states,
888
+ hidden_states_masks=hidden_states_masks,
889
+ encoder_hidden_states=cur_encoder_hidden_states,
890
+ temb=temb,
891
+ image_rotary_emb=image_rotary_emb,
892
+ )
893
+ initial_encoder_hidden_states = initial_encoder_hidden_states[:, :initial_encoder_hidden_states_seq_len]
894
+ block_id += 1
895
+
896
+ image_tokens_seq_len = hidden_states.shape[1]
897
+ hidden_states = torch.cat([hidden_states, initial_encoder_hidden_states], dim=1)
898
+ hidden_states_seq_len = hidden_states.shape[1]
899
+ if hidden_states_masks is not None:
900
+ encoder_attention_mask_ones = torch.ones(
901
+ (batch_size, initial_encoder_hidden_states.shape[1] + cur_llama31_encoder_hidden_states.shape[1]),
902
+ device=hidden_states_masks.device,
903
+ dtype=hidden_states_masks.dtype,
904
+ )
905
+ hidden_states_masks = torch.cat([hidden_states_masks, encoder_attention_mask_ones], dim=1)
906
+
907
+ for bid, block in enumerate(self.single_stream_blocks):
908
+ cur_llama31_encoder_hidden_states = encoder_hidden_states[block_id]
909
+ hidden_states = torch.cat([hidden_states, cur_llama31_encoder_hidden_states], dim=1)
910
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
911
+ hidden_states = self._gradient_checkpointing_func(
912
+ block,
913
+ hidden_states,
914
+ hidden_states_masks,
915
+ None,
916
+ temb,
917
+ image_rotary_emb,
918
+ )
919
+ else:
920
+ hidden_states = block(
921
+ hidden_states=hidden_states,
922
+ hidden_states_masks=hidden_states_masks,
923
+ encoder_hidden_states=None,
924
+ temb=temb,
925
+ image_rotary_emb=image_rotary_emb,
926
+ )
927
+ hidden_states = hidden_states[:, :hidden_states_seq_len]
928
+ block_id += 1
929
+
930
+ hidden_states = hidden_states[:, :image_tokens_seq_len, ...]
931
+ output = self.final_layer(hidden_states, temb)
932
+ output = self.unpatchify(output, img_sizes, self.training)
933
+ if hidden_states_masks is not None:
934
+ hidden_states_masks = hidden_states_masks[:, :image_tokens_seq_len]
935
+
936
+ if USE_PEFT_BACKEND:
937
+ # remove `lora_scale` from each PEFT layer
938
+ unscale_lora_layers(self, lora_scale)
939
+
940
+ if not return_dict:
941
+ return (output,)
942
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/solution/reference/src/diffusers/pipelines/hidream_image/pipeline_hidream_image.py ADDED
@@ -0,0 +1,1012 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import math
3
+ from typing import Any, Callable, Dict, List, Optional, Union
4
+
5
+ import torch
6
+ from transformers import (
7
+ CLIPTextModelWithProjection,
8
+ CLIPTokenizer,
9
+ LlamaForCausalLM,
10
+ PreTrainedTokenizerFast,
11
+ T5EncoderModel,
12
+ T5Tokenizer,
13
+ )
14
+
15
+ from ...image_processor import VaeImageProcessor
16
+ from ...loaders import HiDreamImageLoraLoaderMixin
17
+ from ...models import AutoencoderKL, HiDreamImageTransformer2DModel
18
+ from ...schedulers import FlowMatchEulerDiscreteScheduler, UniPCMultistepScheduler
19
+ from ...utils import deprecate, is_torch_xla_available, logging, replace_example_docstring
20
+ from ...utils.torch_utils import randn_tensor
21
+ from ..pipeline_utils import DiffusionPipeline
22
+ from .pipeline_output import HiDreamImagePipelineOutput
23
+
24
+
25
+ if is_torch_xla_available():
26
+ import torch_xla.core.xla_model as xm
27
+
28
+ XLA_AVAILABLE = True
29
+ else:
30
+ XLA_AVAILABLE = False
31
+
32
+
33
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
+
35
+ EXAMPLE_DOC_STRING = """
36
+ Examples:
37
+ ```py
38
+ >>> import torch
39
+ >>> from transformers import PreTrainedTokenizerFast, LlamaForCausalLM
40
+ >>> from diffusers import UniPCMultistepScheduler, HiDreamImagePipeline
41
+
42
+
43
+ >>> tokenizer_4 = PreTrainedTokenizerFast.from_pretrained("meta-llama/Meta-Llama-3.1-8B-Instruct")
44
+ >>> text_encoder_4 = LlamaForCausalLM.from_pretrained(
45
+ ... "meta-llama/Meta-Llama-3.1-8B-Instruct",
46
+ ... output_hidden_states=True,
47
+ ... output_attentions=True,
48
+ ... torch_dtype=torch.bfloat16,
49
+ ... )
50
+
51
+ >>> pipe = HiDreamImagePipeline.from_pretrained(
52
+ ... "HiDream-ai/HiDream-I1-Full",
53
+ ... tokenizer_4=tokenizer_4,
54
+ ... text_encoder_4=text_encoder_4,
55
+ ... torch_dtype=torch.bfloat16,
56
+ ... )
57
+ >>> pipe.enable_model_cpu_offload()
58
+
59
+ >>> image = pipe(
60
+ ... 'A cat holding a sign that says "Hi-Dreams.ai".',
61
+ ... height=1024,
62
+ ... width=1024,
63
+ ... guidance_scale=5.0,
64
+ ... num_inference_steps=50,
65
+ ... generator=torch.Generator("cuda").manual_seed(0),
66
+ ... ).images[0]
67
+ >>> image.save("output.png")
68
+ ```
69
+ """
70
+
71
+
72
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
73
+ def calculate_shift(
74
+ image_seq_len,
75
+ base_seq_len: int = 256,
76
+ max_seq_len: int = 4096,
77
+ base_shift: float = 0.5,
78
+ max_shift: float = 1.15,
79
+ ):
80
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
81
+ b = base_shift - m * base_seq_len
82
+ mu = image_seq_len * m + b
83
+ return mu
84
+
85
+
86
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
87
+ def retrieve_timesteps(
88
+ scheduler,
89
+ num_inference_steps: Optional[int] = None,
90
+ device: Optional[Union[str, torch.device]] = None,
91
+ timesteps: Optional[List[int]] = None,
92
+ sigmas: Optional[List[float]] = None,
93
+ **kwargs,
94
+ ):
95
+ r"""
96
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
97
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
98
+
99
+ Args:
100
+ scheduler (`SchedulerMixin`):
101
+ The scheduler to get timesteps from.
102
+ num_inference_steps (`int`):
103
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
104
+ must be `None`.
105
+ device (`str` or `torch.device`, *optional*):
106
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
107
+ timesteps (`List[int]`, *optional*):
108
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
109
+ `num_inference_steps` and `sigmas` must be `None`.
110
+ sigmas (`List[float]`, *optional*):
111
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
112
+ `num_inference_steps` and `timesteps` must be `None`.
113
+
114
+ Returns:
115
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
116
+ second element is the number of inference steps.
117
+ """
118
+ if timesteps is not None and sigmas is not None:
119
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
120
+ if timesteps is not None:
121
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
122
+ if not accepts_timesteps:
123
+ raise ValueError(
124
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
125
+ f" timestep schedules. Please check whether you are using the correct scheduler."
126
+ )
127
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
128
+ timesteps = scheduler.timesteps
129
+ num_inference_steps = len(timesteps)
130
+ elif sigmas is not None:
131
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
132
+ if not accept_sigmas:
133
+ raise ValueError(
134
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
135
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
136
+ )
137
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
138
+ timesteps = scheduler.timesteps
139
+ num_inference_steps = len(timesteps)
140
+ else:
141
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
142
+ timesteps = scheduler.timesteps
143
+ return timesteps, num_inference_steps
144
+
145
+
146
+ class HiDreamImagePipeline(DiffusionPipeline, HiDreamImageLoraLoaderMixin):
147
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->text_encoder_3->text_encoder_4->transformer->vae"
148
+ _callback_tensor_inputs = ["latents", "prompt_embeds_t5", "prompt_embeds_llama3", "pooled_prompt_embeds"]
149
+
150
+ def __init__(
151
+ self,
152
+ scheduler: FlowMatchEulerDiscreteScheduler,
153
+ vae: AutoencoderKL,
154
+ text_encoder: CLIPTextModelWithProjection,
155
+ tokenizer: CLIPTokenizer,
156
+ text_encoder_2: CLIPTextModelWithProjection,
157
+ tokenizer_2: CLIPTokenizer,
158
+ text_encoder_3: T5EncoderModel,
159
+ tokenizer_3: T5Tokenizer,
160
+ text_encoder_4: LlamaForCausalLM,
161
+ tokenizer_4: PreTrainedTokenizerFast,
162
+ transformer: HiDreamImageTransformer2DModel,
163
+ ):
164
+ super().__init__()
165
+
166
+ self.register_modules(
167
+ vae=vae,
168
+ text_encoder=text_encoder,
169
+ text_encoder_2=text_encoder_2,
170
+ text_encoder_3=text_encoder_3,
171
+ text_encoder_4=text_encoder_4,
172
+ tokenizer=tokenizer,
173
+ tokenizer_2=tokenizer_2,
174
+ tokenizer_3=tokenizer_3,
175
+ tokenizer_4=tokenizer_4,
176
+ scheduler=scheduler,
177
+ transformer=transformer,
178
+ )
179
+ self.vae_scale_factor = (
180
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
181
+ )
182
+ # HiDreamImage latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
183
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
184
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
185
+ self.default_sample_size = 128
186
+ if getattr(self, "tokenizer_4", None) is not None:
187
+ self.tokenizer_4.pad_token = self.tokenizer_4.eos_token
188
+
189
+ def _get_t5_prompt_embeds(
190
+ self,
191
+ prompt: Union[str, List[str]] = None,
192
+ max_sequence_length: int = 128,
193
+ device: Optional[torch.device] = None,
194
+ dtype: Optional[torch.dtype] = None,
195
+ ):
196
+ device = device or self._execution_device
197
+ dtype = dtype or self.text_encoder_3.dtype
198
+
199
+ prompt = [prompt] if isinstance(prompt, str) else prompt
200
+
201
+ text_inputs = self.tokenizer_3(
202
+ prompt,
203
+ padding="max_length",
204
+ max_length=min(max_sequence_length, self.tokenizer_3.model_max_length),
205
+ truncation=True,
206
+ add_special_tokens=True,
207
+ return_tensors="pt",
208
+ )
209
+ text_input_ids = text_inputs.input_ids
210
+ attention_mask = text_inputs.attention_mask
211
+ untruncated_ids = self.tokenizer_3(prompt, padding="longest", return_tensors="pt").input_ids
212
+
213
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
214
+ removed_text = self.tokenizer_3.batch_decode(
215
+ untruncated_ids[:, min(max_sequence_length, self.tokenizer_3.model_max_length) - 1 : -1]
216
+ )
217
+ logger.warning(
218
+ "The following part of your input was truncated because `max_sequence_length` is set to "
219
+ f" {min(max_sequence_length, self.tokenizer_3.model_max_length)} tokens: {removed_text}"
220
+ )
221
+
222
+ prompt_embeds = self.text_encoder_3(text_input_ids.to(device), attention_mask=attention_mask.to(device))[0]
223
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
224
+ return prompt_embeds
225
+
226
+ def _get_clip_prompt_embeds(
227
+ self,
228
+ tokenizer,
229
+ text_encoder,
230
+ prompt: Union[str, List[str]],
231
+ max_sequence_length: int = 128,
232
+ device: Optional[torch.device] = None,
233
+ dtype: Optional[torch.dtype] = None,
234
+ ):
235
+ device = device or self._execution_device
236
+ dtype = dtype or text_encoder.dtype
237
+
238
+ prompt = [prompt] if isinstance(prompt, str) else prompt
239
+
240
+ text_inputs = tokenizer(
241
+ prompt,
242
+ padding="max_length",
243
+ max_length=min(max_sequence_length, 218),
244
+ truncation=True,
245
+ return_tensors="pt",
246
+ )
247
+
248
+ text_input_ids = text_inputs.input_ids
249
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
250
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
251
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, 218 - 1 : -1])
252
+ logger.warning(
253
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
254
+ f" {218} tokens: {removed_text}"
255
+ )
256
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
257
+
258
+ # Use pooled output of CLIPTextModel
259
+ prompt_embeds = prompt_embeds[0]
260
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
261
+ return prompt_embeds
262
+
263
+ def _get_llama3_prompt_embeds(
264
+ self,
265
+ prompt: Union[str, List[str]] = None,
266
+ max_sequence_length: int = 128,
267
+ device: Optional[torch.device] = None,
268
+ dtype: Optional[torch.dtype] = None,
269
+ ):
270
+ device = device or self._execution_device
271
+ dtype = dtype or self.text_encoder_4.dtype
272
+
273
+ prompt = [prompt] if isinstance(prompt, str) else prompt
274
+
275
+ text_inputs = self.tokenizer_4(
276
+ prompt,
277
+ padding="max_length",
278
+ max_length=min(max_sequence_length, self.tokenizer_4.model_max_length),
279
+ truncation=True,
280
+ add_special_tokens=True,
281
+ return_tensors="pt",
282
+ )
283
+ text_input_ids = text_inputs.input_ids
284
+ attention_mask = text_inputs.attention_mask
285
+ untruncated_ids = self.tokenizer_4(prompt, padding="longest", return_tensors="pt").input_ids
286
+
287
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
288
+ removed_text = self.tokenizer_4.batch_decode(
289
+ untruncated_ids[:, min(max_sequence_length, self.tokenizer_4.model_max_length) - 1 : -1]
290
+ )
291
+ logger.warning(
292
+ "The following part of your input was truncated because `max_sequence_length` is set to "
293
+ f" {min(max_sequence_length, self.tokenizer_4.model_max_length)} tokens: {removed_text}"
294
+ )
295
+
296
+ outputs = self.text_encoder_4(
297
+ text_input_ids.to(device),
298
+ attention_mask=attention_mask.to(device),
299
+ output_hidden_states=True,
300
+ output_attentions=True,
301
+ )
302
+
303
+ prompt_embeds = outputs.hidden_states[1:]
304
+ prompt_embeds = torch.stack(prompt_embeds, dim=0)
305
+ return prompt_embeds
306
+
307
+ def encode_prompt(
308
+ self,
309
+ prompt: Optional[Union[str, List[str]]] = None,
310
+ prompt_2: Optional[Union[str, List[str]]] = None,
311
+ prompt_3: Optional[Union[str, List[str]]] = None,
312
+ prompt_4: Optional[Union[str, List[str]]] = None,
313
+ device: Optional[torch.device] = None,
314
+ dtype: Optional[torch.dtype] = None,
315
+ num_images_per_prompt: int = 1,
316
+ do_classifier_free_guidance: bool = True,
317
+ negative_prompt: Optional[Union[str, List[str]]] = None,
318
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
319
+ negative_prompt_3: Optional[Union[str, List[str]]] = None,
320
+ negative_prompt_4: Optional[Union[str, List[str]]] = None,
321
+ prompt_embeds_t5: Optional[List[torch.FloatTensor]] = None,
322
+ prompt_embeds_llama3: Optional[List[torch.FloatTensor]] = None,
323
+ negative_prompt_embeds_t5: Optional[List[torch.FloatTensor]] = None,
324
+ negative_prompt_embeds_llama3: Optional[List[torch.FloatTensor]] = None,
325
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
326
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
327
+ max_sequence_length: int = 128,
328
+ lora_scale: Optional[float] = None,
329
+ ):
330
+ prompt = [prompt] if isinstance(prompt, str) else prompt
331
+ if prompt is not None:
332
+ batch_size = len(prompt)
333
+ else:
334
+ batch_size = pooled_prompt_embeds.shape[0]
335
+
336
+ device = device or self._execution_device
337
+
338
+ if pooled_prompt_embeds is None:
339
+ pooled_prompt_embeds_1 = self._get_clip_prompt_embeds(
340
+ self.tokenizer, self.text_encoder, prompt, max_sequence_length, device, dtype
341
+ )
342
+
343
+ if do_classifier_free_guidance and negative_pooled_prompt_embeds is None:
344
+ negative_prompt = negative_prompt or ""
345
+ negative_prompt = [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
346
+
347
+ if len(negative_prompt) > 1 and len(negative_prompt) != batch_size:
348
+ raise ValueError(f"negative_prompt must be of length 1 or {batch_size}")
349
+
350
+ negative_pooled_prompt_embeds_1 = self._get_clip_prompt_embeds(
351
+ self.tokenizer, self.text_encoder, negative_prompt, max_sequence_length, device, dtype
352
+ )
353
+
354
+ if negative_pooled_prompt_embeds_1.shape[0] == 1 and batch_size > 1:
355
+ negative_pooled_prompt_embeds_1 = negative_pooled_prompt_embeds_1.repeat(batch_size, 1)
356
+
357
+ if pooled_prompt_embeds is None:
358
+ prompt_2 = prompt_2 or prompt
359
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
360
+
361
+ if len(prompt_2) > 1 and len(prompt_2) != batch_size:
362
+ raise ValueError(f"prompt_2 must be of length 1 or {batch_size}")
363
+
364
+ pooled_prompt_embeds_2 = self._get_clip_prompt_embeds(
365
+ self.tokenizer_2, self.text_encoder_2, prompt_2, max_sequence_length, device, dtype
366
+ )
367
+
368
+ if pooled_prompt_embeds_2.shape[0] == 1 and batch_size > 1:
369
+ pooled_prompt_embeds_2 = pooled_prompt_embeds_2.repeat(batch_size, 1)
370
+
371
+ if do_classifier_free_guidance and negative_pooled_prompt_embeds is None:
372
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
373
+ negative_prompt_2 = [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
374
+
375
+ if len(negative_prompt_2) > 1 and len(negative_prompt_2) != batch_size:
376
+ raise ValueError(f"negative_prompt_2 must be of length 1 or {batch_size}")
377
+
378
+ negative_pooled_prompt_embeds_2 = self._get_clip_prompt_embeds(
379
+ self.tokenizer_2, self.text_encoder_2, negative_prompt_2, max_sequence_length, device, dtype
380
+ )
381
+
382
+ if negative_pooled_prompt_embeds_2.shape[0] == 1 and batch_size > 1:
383
+ negative_pooled_prompt_embeds_2 = negative_pooled_prompt_embeds_2.repeat(batch_size, 1)
384
+
385
+ if pooled_prompt_embeds is None:
386
+ pooled_prompt_embeds = torch.cat([pooled_prompt_embeds_1, pooled_prompt_embeds_2], dim=-1)
387
+
388
+ if do_classifier_free_guidance and negative_pooled_prompt_embeds is None:
389
+ negative_pooled_prompt_embeds = torch.cat(
390
+ [negative_pooled_prompt_embeds_1, negative_pooled_prompt_embeds_2], dim=-1
391
+ )
392
+
393
+ if prompt_embeds_t5 is None:
394
+ prompt_3 = prompt_3 or prompt
395
+ prompt_3 = [prompt_3] if isinstance(prompt_3, str) else prompt_3
396
+
397
+ if len(prompt_3) > 1 and len(prompt_3) != batch_size:
398
+ raise ValueError(f"prompt_3 must be of length 1 or {batch_size}")
399
+
400
+ prompt_embeds_t5 = self._get_t5_prompt_embeds(prompt_3, max_sequence_length, device, dtype)
401
+
402
+ if prompt_embeds_t5.shape[0] == 1 and batch_size > 1:
403
+ prompt_embeds_t5 = prompt_embeds_t5.repeat(batch_size, 1, 1)
404
+
405
+ if do_classifier_free_guidance and negative_prompt_embeds_t5 is None:
406
+ negative_prompt_3 = negative_prompt_3 or negative_prompt
407
+ negative_prompt_3 = [negative_prompt_3] if isinstance(negative_prompt_3, str) else negative_prompt_3
408
+
409
+ if len(negative_prompt_3) > 1 and len(negative_prompt_3) != batch_size:
410
+ raise ValueError(f"negative_prompt_3 must be of length 1 or {batch_size}")
411
+
412
+ negative_prompt_embeds_t5 = self._get_t5_prompt_embeds(
413
+ negative_prompt_3, max_sequence_length, device, dtype
414
+ )
415
+
416
+ if negative_prompt_embeds_t5.shape[0] == 1 and batch_size > 1:
417
+ negative_prompt_embeds_t5 = negative_prompt_embeds_t5.repeat(batch_size, 1, 1)
418
+
419
+ if prompt_embeds_llama3 is None:
420
+ prompt_4 = prompt_4 or prompt
421
+ prompt_4 = [prompt_4] if isinstance(prompt_4, str) else prompt_4
422
+
423
+ if len(prompt_4) > 1 and len(prompt_4) != batch_size:
424
+ raise ValueError(f"prompt_4 must be of length 1 or {batch_size}")
425
+
426
+ prompt_embeds_llama3 = self._get_llama3_prompt_embeds(prompt_4, max_sequence_length, device, dtype)
427
+
428
+ if prompt_embeds_llama3.shape[0] == 1 and batch_size > 1:
429
+ prompt_embeds_llama3 = prompt_embeds_llama3.repeat(1, batch_size, 1, 1)
430
+
431
+ if do_classifier_free_guidance and negative_prompt_embeds_llama3 is None:
432
+ negative_prompt_4 = negative_prompt_4 or negative_prompt
433
+ negative_prompt_4 = [negative_prompt_4] if isinstance(negative_prompt_4, str) else negative_prompt_4
434
+
435
+ if len(negative_prompt_4) > 1 and len(negative_prompt_4) != batch_size:
436
+ raise ValueError(f"negative_prompt_4 must be of length 1 or {batch_size}")
437
+
438
+ negative_prompt_embeds_llama3 = self._get_llama3_prompt_embeds(
439
+ negative_prompt_4, max_sequence_length, device, dtype
440
+ )
441
+
442
+ if negative_prompt_embeds_llama3.shape[0] == 1 and batch_size > 1:
443
+ negative_prompt_embeds_llama3 = negative_prompt_embeds_llama3.repeat(1, batch_size, 1, 1)
444
+
445
+ # duplicate pooled_prompt_embeds for each generation per prompt
446
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt)
447
+ pooled_prompt_embeds = pooled_prompt_embeds.view(batch_size * num_images_per_prompt, -1)
448
+
449
+ # duplicate t5_prompt_embeds for batch_size and num_images_per_prompt
450
+ bs_embed, seq_len, _ = prompt_embeds_t5.shape
451
+ if bs_embed == 1 and batch_size > 1:
452
+ prompt_embeds_t5 = prompt_embeds_t5.repeat(batch_size, 1, 1)
453
+ elif bs_embed > 1 and bs_embed != batch_size:
454
+ raise ValueError(f"cannot duplicate prompt_embeds_t5 of batch size {bs_embed}")
455
+ prompt_embeds_t5 = prompt_embeds_t5.repeat(1, num_images_per_prompt, 1)
456
+ prompt_embeds_t5 = prompt_embeds_t5.view(batch_size * num_images_per_prompt, seq_len, -1)
457
+
458
+ # duplicate llama3_prompt_embeds for batch_size and num_images_per_prompt
459
+ _, bs_embed, seq_len, dim = prompt_embeds_llama3.shape
460
+ if bs_embed == 1 and batch_size > 1:
461
+ prompt_embeds_llama3 = prompt_embeds_llama3.repeat(1, batch_size, 1, 1)
462
+ elif bs_embed > 1 and bs_embed != batch_size:
463
+ raise ValueError(f"cannot duplicate prompt_embeds_llama3 of batch size {bs_embed}")
464
+ prompt_embeds_llama3 = prompt_embeds_llama3.repeat(1, 1, num_images_per_prompt, 1)
465
+ prompt_embeds_llama3 = prompt_embeds_llama3.view(-1, batch_size * num_images_per_prompt, seq_len, dim)
466
+
467
+ if do_classifier_free_guidance:
468
+ # duplicate negative_pooled_prompt_embeds for batch_size and num_images_per_prompt
469
+ bs_embed, seq_len = negative_pooled_prompt_embeds.shape
470
+ if bs_embed == 1 and batch_size > 1:
471
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(batch_size, 1)
472
+ elif bs_embed > 1 and bs_embed != batch_size:
473
+ raise ValueError(f"cannot duplicate negative_pooled_prompt_embeds of batch size {bs_embed}")
474
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt)
475
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.view(batch_size * num_images_per_prompt, -1)
476
+
477
+ # duplicate negative_t5_prompt_embeds for batch_size and num_images_per_prompt
478
+ bs_embed, seq_len, _ = negative_prompt_embeds_t5.shape
479
+ if bs_embed == 1 and batch_size > 1:
480
+ negative_prompt_embeds_t5 = negative_prompt_embeds_t5.repeat(batch_size, 1, 1)
481
+ elif bs_embed > 1 and bs_embed != batch_size:
482
+ raise ValueError(f"cannot duplicate negative_prompt_embeds_t5 of batch size {bs_embed}")
483
+ negative_prompt_embeds_t5 = negative_prompt_embeds_t5.repeat(1, num_images_per_prompt, 1)
484
+ negative_prompt_embeds_t5 = negative_prompt_embeds_t5.view(batch_size * num_images_per_prompt, seq_len, -1)
485
+
486
+ # duplicate negative_prompt_embeds_llama3 for batch_size and num_images_per_prompt
487
+ _, bs_embed, seq_len, dim = negative_prompt_embeds_llama3.shape
488
+ if bs_embed == 1 and batch_size > 1:
489
+ negative_prompt_embeds_llama3 = negative_prompt_embeds_llama3.repeat(1, batch_size, 1, 1)
490
+ elif bs_embed > 1 and bs_embed != batch_size:
491
+ raise ValueError(f"cannot duplicate negative_prompt_embeds_llama3 of batch size {bs_embed}")
492
+ negative_prompt_embeds_llama3 = negative_prompt_embeds_llama3.repeat(1, 1, num_images_per_prompt, 1)
493
+ negative_prompt_embeds_llama3 = negative_prompt_embeds_llama3.view(
494
+ -1, batch_size * num_images_per_prompt, seq_len, dim
495
+ )
496
+
497
+ return (
498
+ prompt_embeds_t5,
499
+ negative_prompt_embeds_t5,
500
+ prompt_embeds_llama3,
501
+ negative_prompt_embeds_llama3,
502
+ pooled_prompt_embeds,
503
+ negative_pooled_prompt_embeds,
504
+ )
505
+
506
+ def enable_vae_slicing(self):
507
+ r"""
508
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
509
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
510
+ """
511
+ self.vae.enable_slicing()
512
+
513
+ def disable_vae_slicing(self):
514
+ r"""
515
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
516
+ computing decoding in one step.
517
+ """
518
+ self.vae.disable_slicing()
519
+
520
+ def enable_vae_tiling(self):
521
+ r"""
522
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
523
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
524
+ processing larger images.
525
+ """
526
+ self.vae.enable_tiling()
527
+
528
+ def disable_vae_tiling(self):
529
+ r"""
530
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
531
+ computing decoding in one step.
532
+ """
533
+ self.vae.disable_tiling()
534
+
535
+ def check_inputs(
536
+ self,
537
+ prompt,
538
+ prompt_2,
539
+ prompt_3,
540
+ prompt_4,
541
+ negative_prompt=None,
542
+ negative_prompt_2=None,
543
+ negative_prompt_3=None,
544
+ negative_prompt_4=None,
545
+ prompt_embeds_t5=None,
546
+ prompt_embeds_llama3=None,
547
+ negative_prompt_embeds_t5=None,
548
+ negative_prompt_embeds_llama3=None,
549
+ pooled_prompt_embeds=None,
550
+ negative_pooled_prompt_embeds=None,
551
+ callback_on_step_end_tensor_inputs=None,
552
+ ):
553
+ if callback_on_step_end_tensor_inputs is not None and not all(
554
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
555
+ ):
556
+ raise ValueError(
557
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
558
+ )
559
+
560
+ if prompt is not None and pooled_prompt_embeds is not None:
561
+ raise ValueError(
562
+ f"Cannot forward both `prompt`: {prompt} and `pooled_prompt_embeds`: {pooled_prompt_embeds}. Please make sure to"
563
+ " only forward one of the two."
564
+ )
565
+ elif prompt_2 is not None and pooled_prompt_embeds is not None:
566
+ raise ValueError(
567
+ f"Cannot forward both `prompt_2`: {prompt_2} and `pooled_prompt_embeds`: {pooled_prompt_embeds}. Please make sure to"
568
+ " only forward one of the two."
569
+ )
570
+ elif prompt_3 is not None and prompt_embeds_t5 is not None:
571
+ raise ValueError(
572
+ f"Cannot forward both `prompt_3`: {prompt_3} and `prompt_embeds_t5`: {prompt_embeds_t5}. Please make sure to"
573
+ " only forward one of the two."
574
+ )
575
+ elif prompt_4 is not None and prompt_embeds_llama3 is not None:
576
+ raise ValueError(
577
+ f"Cannot forward both `prompt_4`: {prompt_4} and `prompt_embeds_llama3`: {prompt_embeds_llama3}. Please make sure to"
578
+ " only forward one of the two."
579
+ )
580
+ elif prompt is None and pooled_prompt_embeds is None:
581
+ raise ValueError(
582
+ "Provide either `prompt` or `pooled_prompt_embeds`. Cannot leave both `prompt` and `pooled_prompt_embeds` undefined."
583
+ )
584
+ elif prompt is None and prompt_embeds_t5 is None:
585
+ raise ValueError(
586
+ "Provide either `prompt` or `prompt_embeds_t5`. Cannot leave both `prompt` and `prompt_embeds_t5` undefined."
587
+ )
588
+ elif prompt is None and prompt_embeds_llama3 is None:
589
+ raise ValueError(
590
+ "Provide either `prompt` or `prompt_embeds_llama3`. Cannot leave both `prompt` and `prompt_embeds_llama3` undefined."
591
+ )
592
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
593
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
594
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
595
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
596
+ elif prompt_3 is not None and (not isinstance(prompt_3, str) and not isinstance(prompt_3, list)):
597
+ raise ValueError(f"`prompt_3` has to be of type `str` or `list` but is {type(prompt_3)}")
598
+ elif prompt_4 is not None and (not isinstance(prompt_4, str) and not isinstance(prompt_4, list)):
599
+ raise ValueError(f"`prompt_4` has to be of type `str` or `list` but is {type(prompt_4)}")
600
+
601
+ if negative_prompt is not None and negative_pooled_prompt_embeds is not None:
602
+ raise ValueError(
603
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_pooled_prompt_embeds`:"
604
+ f" {negative_pooled_prompt_embeds}. Please make sure to only forward one of the two."
605
+ )
606
+ elif negative_prompt_2 is not None and negative_pooled_prompt_embeds is not None:
607
+ raise ValueError(
608
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_pooled_prompt_embeds`:"
609
+ f" {negative_pooled_prompt_embeds}. Please make sure to only forward one of the two."
610
+ )
611
+ elif negative_prompt_3 is not None and negative_prompt_embeds_t5 is not None:
612
+ raise ValueError(
613
+ f"Cannot forward both `negative_prompt_3`: {negative_prompt_3} and `negative_prompt_embeds_t5`:"
614
+ f" {negative_prompt_embeds_t5}. Please make sure to only forward one of the two."
615
+ )
616
+ elif negative_prompt_4 is not None and negative_prompt_embeds_llama3 is not None:
617
+ raise ValueError(
618
+ f"Cannot forward both `negative_prompt_4`: {negative_prompt_4} and `negative_prompt_embeds_llama3`:"
619
+ f" {negative_prompt_embeds_llama3}. Please make sure to only forward one of the two."
620
+ )
621
+
622
+ if pooled_prompt_embeds is not None and negative_pooled_prompt_embeds is not None:
623
+ if pooled_prompt_embeds.shape != negative_pooled_prompt_embeds.shape:
624
+ raise ValueError(
625
+ "`pooled_prompt_embeds` and `negative_pooled_prompt_embeds` must have the same shape when passed directly, but"
626
+ f" got: `pooled_prompt_embeds` {pooled_prompt_embeds.shape} != `negative_pooled_prompt_embeds`"
627
+ f" {negative_pooled_prompt_embeds.shape}."
628
+ )
629
+ if prompt_embeds_t5 is not None and negative_prompt_embeds_t5 is not None:
630
+ if prompt_embeds_t5.shape != negative_prompt_embeds_t5.shape:
631
+ raise ValueError(
632
+ "`prompt_embeds_t5` and `negative_prompt_embeds_t5` must have the same shape when passed directly, but"
633
+ f" got: `prompt_embeds_t5` {prompt_embeds_t5.shape} != `negative_prompt_embeds_t5`"
634
+ f" {negative_prompt_embeds_t5.shape}."
635
+ )
636
+ if prompt_embeds_llama3 is not None and negative_prompt_embeds_llama3 is not None:
637
+ if prompt_embeds_llama3.shape != negative_prompt_embeds_llama3.shape:
638
+ raise ValueError(
639
+ "`prompt_embeds_llama3` and `negative_prompt_embeds_llama3` must have the same shape when passed directly, but"
640
+ f" got: `prompt_embeds_llama3` {prompt_embeds_llama3.shape} != `negative_prompt_embeds_llama3`"
641
+ f" {negative_prompt_embeds_llama3.shape}."
642
+ )
643
+
644
+ def prepare_latents(
645
+ self,
646
+ batch_size,
647
+ num_channels_latents,
648
+ height,
649
+ width,
650
+ dtype,
651
+ device,
652
+ generator,
653
+ latents=None,
654
+ ):
655
+ # VAE applies 8x compression on images but we must also account for packing which requires
656
+ # latent height and width to be divisible by 2.
657
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
658
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
659
+
660
+ shape = (batch_size, num_channels_latents, height, width)
661
+
662
+ if latents is None:
663
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
664
+ else:
665
+ if latents.shape != shape:
666
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
667
+ latents = latents.to(device)
668
+ return latents
669
+
670
+ @property
671
+ def guidance_scale(self):
672
+ return self._guidance_scale
673
+
674
+ @property
675
+ def do_classifier_free_guidance(self):
676
+ return self._guidance_scale > 1
677
+
678
+ @property
679
+ def attention_kwargs(self):
680
+ return self._attention_kwargs
681
+
682
+ @property
683
+ def num_timesteps(self):
684
+ return self._num_timesteps
685
+
686
+ @property
687
+ def interrupt(self):
688
+ return self._interrupt
689
+
690
+ @torch.no_grad()
691
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
692
+ def __call__(
693
+ self,
694
+ prompt: Union[str, List[str]] = None,
695
+ prompt_2: Optional[Union[str, List[str]]] = None,
696
+ prompt_3: Optional[Union[str, List[str]]] = None,
697
+ prompt_4: Optional[Union[str, List[str]]] = None,
698
+ height: Optional[int] = None,
699
+ width: Optional[int] = None,
700
+ num_inference_steps: int = 50,
701
+ sigmas: Optional[List[float]] = None,
702
+ guidance_scale: float = 5.0,
703
+ negative_prompt: Optional[Union[str, List[str]]] = None,
704
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
705
+ negative_prompt_3: Optional[Union[str, List[str]]] = None,
706
+ negative_prompt_4: Optional[Union[str, List[str]]] = None,
707
+ num_images_per_prompt: Optional[int] = 1,
708
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
709
+ latents: Optional[torch.FloatTensor] = None,
710
+ prompt_embeds_t5: Optional[torch.FloatTensor] = None,
711
+ prompt_embeds_llama3: Optional[torch.FloatTensor] = None,
712
+ negative_prompt_embeds_t5: Optional[torch.FloatTensor] = None,
713
+ negative_prompt_embeds_llama3: Optional[torch.FloatTensor] = None,
714
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
715
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
716
+ output_type: Optional[str] = "pil",
717
+ return_dict: bool = True,
718
+ attention_kwargs: Optional[Dict[str, Any]] = None,
719
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
720
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
721
+ max_sequence_length: int = 128,
722
+ **kwargs,
723
+ ):
724
+ r"""
725
+ Function invoked when calling the pipeline for generation.
726
+
727
+ Args:
728
+ prompt (`str` or `List[str]`, *optional*):
729
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
730
+ instead.
731
+ prompt_2 (`str` or `List[str]`, *optional*):
732
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
733
+ will be used instead.
734
+ prompt_3 (`str` or `List[str]`, *optional*):
735
+ The prompt or prompts to be sent to `tokenizer_3` and `text_encoder_3`. If not defined, `prompt` is
736
+ will be used instead.
737
+ prompt_4 (`str` or `List[str]`, *optional*):
738
+ The prompt or prompts to be sent to `tokenizer_4` and `text_encoder_4`. If not defined, `prompt` is
739
+ will be used instead.
740
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
741
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
742
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
743
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
744
+ num_inference_steps (`int`, *optional*, defaults to 50):
745
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
746
+ expense of slower inference.
747
+ sigmas (`List[float]`, *optional*):
748
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
749
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
750
+ will be used.
751
+ guidance_scale (`float`, *optional*, defaults to 3.5):
752
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
753
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
754
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
755
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
756
+ usually at the expense of lower image quality.
757
+ negative_prompt (`str` or `List[str]`, *optional*):
758
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
759
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
760
+ not greater than `1`).
761
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
762
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
763
+ `text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
764
+ negative_prompt_3 (`str` or `List[str]`, *optional*):
765
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_3` and
766
+ `text_encoder_3`. If not defined, `negative_prompt` is used in all the text-encoders.
767
+ negative_prompt_4 (`str` or `List[str]`, *optional*):
768
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_4` and
769
+ `text_encoder_4`. If not defined, `negative_prompt` is used in all the text-encoders.
770
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
771
+ The number of images to generate per prompt.
772
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
773
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
774
+ to make generation deterministic.
775
+ latents (`torch.FloatTensor`, *optional*):
776
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
777
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
778
+ tensor will ge generated by sampling using the supplied random `generator`.
779
+ prompt_embeds (`torch.FloatTensor`, *optional*):
780
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
781
+ provided, text embeddings will be generated from `prompt` input argument.
782
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
783
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
784
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
785
+ argument.
786
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
787
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
788
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
789
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
790
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
791
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
792
+ input argument.
793
+ output_type (`str`, *optional*, defaults to `"pil"`):
794
+ The output format of the generate image. Choose between
795
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
796
+ return_dict (`bool`, *optional*, defaults to `True`):
797
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
798
+ attention_kwargs (`dict`, *optional*):
799
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
800
+ `self.processor` in
801
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
802
+ callback_on_step_end (`Callable`, *optional*):
803
+ A function that calls at the end of each denoising steps during the inference. The function is called
804
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
805
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
806
+ `callback_on_step_end_tensor_inputs`.
807
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
808
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
809
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
810
+ `._callback_tensor_inputs` attribute of your pipeline class.
811
+ max_sequence_length (`int` defaults to 128): Maximum sequence length to use with the `prompt`.
812
+
813
+ Examples:
814
+
815
+ Returns:
816
+ [`~pipelines.hidream_image.HiDreamImagePipelineOutput`] or `tuple`:
817
+ [`~pipelines.hidream_image.HiDreamImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When
818
+ returning a tuple, the first element is a list with the generated. images.
819
+ """
820
+
821
+ prompt_embeds = kwargs.get("prompt_embeds", None)
822
+ negative_prompt_embeds = kwargs.get("negative_prompt_embeds", None)
823
+
824
+ if prompt_embeds is not None:
825
+ deprecation_message = "The `prompt_embeds` argument is deprecated. Please use `prompt_embeds_t5` and `prompt_embeds_llama3` instead."
826
+ deprecate("prompt_embeds", "0.34.0", deprecation_message)
827
+ prompt_embeds_t5 = prompt_embeds[0]
828
+ prompt_embeds_llama3 = prompt_embeds[1]
829
+
830
+ if negative_prompt_embeds is not None:
831
+ deprecation_message = "The `negative_prompt_embeds` argument is deprecated. Please use `negative_prompt_embeds_t5` and `negative_prompt_embeds_llama3` instead."
832
+ deprecate("negative_prompt_embeds", "0.34.0", deprecation_message)
833
+ negative_prompt_embeds_t5 = negative_prompt_embeds[0]
834
+ negative_prompt_embeds_llama3 = negative_prompt_embeds[1]
835
+
836
+ height = height or self.default_sample_size * self.vae_scale_factor
837
+ width = width or self.default_sample_size * self.vae_scale_factor
838
+
839
+ division = self.vae_scale_factor * 2
840
+ S_max = (self.default_sample_size * self.vae_scale_factor) ** 2
841
+ scale = S_max / (width * height)
842
+ scale = math.sqrt(scale)
843
+ width, height = int(width * scale // division * division), int(height * scale // division * division)
844
+
845
+ # 1. Check inputs. Raise error if not correct
846
+ self.check_inputs(
847
+ prompt,
848
+ prompt_2,
849
+ prompt_3,
850
+ prompt_4,
851
+ negative_prompt=negative_prompt,
852
+ negative_prompt_2=negative_prompt_2,
853
+ negative_prompt_3=negative_prompt_3,
854
+ negative_prompt_4=negative_prompt_4,
855
+ prompt_embeds_t5=prompt_embeds_t5,
856
+ prompt_embeds_llama3=prompt_embeds_llama3,
857
+ negative_prompt_embeds_t5=negative_prompt_embeds_t5,
858
+ negative_prompt_embeds_llama3=negative_prompt_embeds_llama3,
859
+ pooled_prompt_embeds=pooled_prompt_embeds,
860
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
861
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
862
+ )
863
+
864
+ self._guidance_scale = guidance_scale
865
+ self._attention_kwargs = attention_kwargs
866
+ self._interrupt = False
867
+
868
+ # 2. Define call parameters
869
+ if prompt is not None and isinstance(prompt, str):
870
+ batch_size = 1
871
+ elif prompt is not None and isinstance(prompt, list):
872
+ batch_size = len(prompt)
873
+ elif pooled_prompt_embeds is not None:
874
+ batch_size = pooled_prompt_embeds.shape[0]
875
+
876
+ device = self._execution_device
877
+
878
+ # 3. Encode prompt
879
+ lora_scale = self.attention_kwargs.get("scale", None) if self.attention_kwargs is not None else None
880
+ (
881
+ prompt_embeds_t5,
882
+ negative_prompt_embeds_t5,
883
+ prompt_embeds_llama3,
884
+ negative_prompt_embeds_llama3,
885
+ pooled_prompt_embeds,
886
+ negative_pooled_prompt_embeds,
887
+ ) = self.encode_prompt(
888
+ prompt=prompt,
889
+ prompt_2=prompt_2,
890
+ prompt_3=prompt_3,
891
+ prompt_4=prompt_4,
892
+ negative_prompt=negative_prompt,
893
+ negative_prompt_2=negative_prompt_2,
894
+ negative_prompt_3=negative_prompt_3,
895
+ negative_prompt_4=negative_prompt_4,
896
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
897
+ prompt_embeds_t5=prompt_embeds_t5,
898
+ prompt_embeds_llama3=prompt_embeds_llama3,
899
+ negative_prompt_embeds_t5=negative_prompt_embeds_t5,
900
+ negative_prompt_embeds_llama3=negative_prompt_embeds_llama3,
901
+ pooled_prompt_embeds=pooled_prompt_embeds,
902
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
903
+ device=device,
904
+ num_images_per_prompt=num_images_per_prompt,
905
+ max_sequence_length=max_sequence_length,
906
+ lora_scale=lora_scale,
907
+ )
908
+
909
+ if self.do_classifier_free_guidance:
910
+ prompt_embeds_t5 = torch.cat([negative_prompt_embeds_t5, prompt_embeds_t5], dim=0)
911
+ prompt_embeds_llama3 = torch.cat([negative_prompt_embeds_llama3, prompt_embeds_llama3], dim=1)
912
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
913
+
914
+ # 4. Prepare latent variables
915
+ num_channels_latents = self.transformer.config.in_channels
916
+ latents = self.prepare_latents(
917
+ batch_size * num_images_per_prompt,
918
+ num_channels_latents,
919
+ height,
920
+ width,
921
+ pooled_prompt_embeds.dtype,
922
+ device,
923
+ generator,
924
+ latents,
925
+ )
926
+
927
+ # 5. Prepare timesteps
928
+ mu = calculate_shift(self.transformer.max_seq)
929
+ scheduler_kwargs = {"mu": mu}
930
+ if isinstance(self.scheduler, UniPCMultistepScheduler):
931
+ self.scheduler.set_timesteps(num_inference_steps, device=device) # , shift=math.exp(mu))
932
+ timesteps = self.scheduler.timesteps
933
+ else:
934
+ timesteps, num_inference_steps = retrieve_timesteps(
935
+ self.scheduler,
936
+ num_inference_steps,
937
+ device,
938
+ sigmas=sigmas,
939
+ **scheduler_kwargs,
940
+ )
941
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
942
+ self._num_timesteps = len(timesteps)
943
+
944
+ # 6. Denoising loop
945
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
946
+ for i, t in enumerate(timesteps):
947
+ if self.interrupt:
948
+ continue
949
+
950
+ # expand the latents if we are doing classifier free guidance
951
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
952
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
953
+ timestep = t.expand(latent_model_input.shape[0])
954
+
955
+ noise_pred = self.transformer(
956
+ hidden_states=latent_model_input,
957
+ timesteps=timestep,
958
+ encoder_hidden_states_t5=prompt_embeds_t5,
959
+ encoder_hidden_states_llama3=prompt_embeds_llama3,
960
+ pooled_embeds=pooled_prompt_embeds,
961
+ return_dict=False,
962
+ )[0]
963
+ noise_pred = -noise_pred
964
+
965
+ # perform guidance
966
+ if self.do_classifier_free_guidance:
967
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
968
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
969
+
970
+ # compute the previous noisy sample x_t -> x_t-1
971
+ latents_dtype = latents.dtype
972
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
973
+
974
+ if latents.dtype != latents_dtype:
975
+ if torch.backends.mps.is_available():
976
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
977
+ latents = latents.to(latents_dtype)
978
+
979
+ if callback_on_step_end is not None:
980
+ callback_kwargs = {}
981
+ for k in callback_on_step_end_tensor_inputs:
982
+ callback_kwargs[k] = locals()[k]
983
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
984
+
985
+ latents = callback_outputs.pop("latents", latents)
986
+ prompt_embeds_t5 = callback_outputs.pop("prompt_embeds_t5", prompt_embeds_t5)
987
+ prompt_embeds_llama3 = callback_outputs.pop("prompt_embeds_llama3", prompt_embeds_llama3)
988
+ pooled_prompt_embeds = callback_outputs.pop("pooled_prompt_embeds", pooled_prompt_embeds)
989
+
990
+ # call the callback, if provided
991
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
992
+ progress_bar.update()
993
+
994
+ if XLA_AVAILABLE:
995
+ xm.mark_step()
996
+
997
+ if output_type == "latent":
998
+ image = latents
999
+
1000
+ else:
1001
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
1002
+
1003
+ image = self.vae.decode(latents, return_dict=False)[0]
1004
+ image = self.image_processor.postprocess(image, output_type=output_type)
1005
+
1006
+ # Offload all models
1007
+ self.maybe_free_model_hooks()
1008
+
1009
+ if not return_dict:
1010
+ return (image,)
1011
+
1012
+ return HiDreamImagePipelineOutput(images=image)
tasks/tasksmith-f40a643a6ef9/solution/solve.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ mkdir -p -- /workspace/examples/dreambooth
4
+ cp /solution/reference/examples/dreambooth/train_dreambooth_lora_hidream.py /workspace/examples/dreambooth/train_dreambooth_lora_hidream.py
5
+ mkdir -p -- /workspace/src/diffusers/loaders
6
+ cp /solution/reference/src/diffusers/loaders/__init__.py /workspace/src/diffusers/loaders/__init__.py
7
+ mkdir -p -- /workspace/src/diffusers/loaders
8
+ cp /solution/reference/src/diffusers/loaders/lora_pipeline.py /workspace/src/diffusers/loaders/lora_pipeline.py
9
+ mkdir -p -- /workspace/src/diffusers/loaders
10
+ cp /solution/reference/src/diffusers/loaders/peft.py /workspace/src/diffusers/loaders/peft.py
11
+ mkdir -p -- /workspace/src/diffusers/models/transformers
12
+ cp /solution/reference/src/diffusers/models/transformers/transformer_hidream_image.py /workspace/src/diffusers/models/transformers/transformer_hidream_image.py
13
+ mkdir -p -- /workspace/src/diffusers/pipelines/hidream_image
14
+ cp /solution/reference/src/diffusers/pipelines/hidream_image/pipeline_hidream_image.py /workspace/src/diffusers/pipelines/hidream_image/pipeline_hidream_image.py
tasks/tasksmith-f40a643a6ef9/task.toml ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.3"
2
+
3
+ [task]
4
+ name = "repo2rlenv/tasksmith-f40a643a6ef9"
5
+
6
+ [metadata.repo2env]
7
+ recipe = "tasksmith"
8
+ recipe_version = "1"
9
+ source_url = "https://github.com/huggingface/diffusers/pull/11281"
10
+ source_head = "ed97dba00a7d673ede2c833ab159d026ce3a7d00"
11
+ source_base = "6ab62c743183fff206239af931921908ae3ce133"
12
+ workspace_strategy = "head_minus_source_patch"
13
+ source_diff_sha256 = "61b28ea6dd4b251cfd65b12da72caeb3a7c91fc1c08c26e133d9ad68fe34c627"
14
+ acceptance_profile = "practical-generation-v1"
15
+ upstream_test_policy = "retain"
16
+ reward_kinds = [
17
+ "test_execution",
18
+ ]
19
+ quality_status = "exported"
20
+ fail_to_pass_count = 8
21
+ pass_to_pass_count = 2
22
+ bundle_hash = "sha256:07be47aad2d8c6fe1f62e23d4c8670cfff027c5be3594ef17c2237e1c231adbc"
23
+
24
+ [metadata.repo2env.evaluation]
25
+ schema_version = "1"
26
+ status = "verified"
27
+ stage = "complete"
28
+ reason_codes = [
29
+ "quality_verified",
30
+ ]
31
+ detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile."
32
+ checked_at = "2026-09-14T05:40:06.782182Z"
33
+ provenance = "assisted"
34
+ subject_bundle_hash = "sha256:07be47aad2d8c6fe1f62e23d4c8670cfff027c5be3594ef17c2237e1c231adbc"
35
+ profile = "practical-generation-v1"
36
+ source_task_path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/5b4ba8286fef/candidates/f40a643a6ef9/quality/revisions/r0/tasksmith-f40a643a6ef9"
37
+ source_task_toml_sha256 = "2e5eea9fbd8bf72c3626efcd0221847a9b921af92a39c49fdbc0a13bf1fadf58"
38
+
39
+ [[metadata.repo2env.evaluation.evidence]]
40
+ kind = "quality_result"
41
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/5b4ba8286fef/candidates/f40a643a6ef9/quality/result.json"
42
+ sha256 = "b0f6a67f63a01901280a927f0e4e7770667f73125fc17b8ccbddf9c77ba8d677"
43
+ subject_bundle_hash = "sha256:07be47aad2d8c6fe1f62e23d4c8670cfff027c5be3594ef17c2237e1c231adbc"
44
+
45
+ [[metadata.repo2env.evaluation.evidence]]
46
+ kind = "baseline"
47
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/5b4ba8286fef/candidates/f40a643a6ef9/quality/trials/r0-baseline/tsbatch-50714e834186-5b4ba8286fef-q-f40a643a-r0-baseline/tasksmith-f40a643a6ef9__Yoe46AV/result.json"
48
+ sha256 = "2c0d67aac6d819125220bfb7330d2e7d5721bc0fb9a01514200897c72dd478de"
49
+ subject_bundle_hash = "sha256:07be47aad2d8c6fe1f62e23d4c8670cfff027c5be3594ef17c2237e1c231adbc"
50
+ harbor_task_checksum = "5d9748134d847ed40cf8e052f9e50233d873307f77c06d51af9145a6d58166a4"
51
+
52
+ [[metadata.repo2env.evaluation.evidence]]
53
+ kind = "oracle"
54
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/5b4ba8286fef/candidates/f40a643a6ef9/quality/trials/r0-oracle/tsbatch-50714e834186-5b4ba8286fef-q-f40a643a-r0-oracle/tasksmith-f40a643a6ef9__cQ3NE2u/result.json"
55
+ sha256 = "f6bde8fe17661f9a1769c35084f2aa53148441d344eaaa0758dc6c9105d9916a"
56
+ subject_bundle_hash = "sha256:07be47aad2d8c6fe1f62e23d4c8670cfff027c5be3594ef17c2237e1c231adbc"
57
+ harbor_task_checksum = "5d9748134d847ed40cf8e052f9e50233d873307f77c06d51af9145a6d58166a4"
58
+
59
+ [[metadata.repo2env.evaluation.evidence]]
60
+ kind = "probe"
61
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/5b4ba8286fef/candidates/f40a643a6ef9/quality/trials/r0-probe0/tsbatch-50714e834186-5b4ba8286fef-q-f40a643a-r0-probe0/tasksmith-f40a643a6ef9__5J3k7Sd/result.json"
62
+ sha256 = "d8841086371010b1a6a5dbba9be48dfdf7ca56237a69deb4fb214eab7faf1931"
63
+ subject_bundle_hash = "sha256:4b5ce53ea7aae2b663f84055eac72617c1fbdcad1303a064829c398172428691"
64
+ harbor_task_checksum = "3182b6a60c4f0b44cbb97c241b029e745fdc6c5abfa8bfa808cef79c7c4b6cef"
65
+
66
+ [[metadata.repo2env.evaluation.evidence]]
67
+ kind = "probe"
68
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/5b4ba8286fef/candidates/f40a643a6ef9/quality/trials/r0-probe1/tsbatch-50714e834186-5b4ba8286fef-q-f40a643a-r0-probe1/tasksmith-f40a643a6ef9__BVRSJCR/result.json"
69
+ sha256 = "56980d0a2e5c5f5bcbe76b8978e6bdc911ecc3cd702b5ba29d481e9da0fc2be2"
70
+ subject_bundle_hash = "sha256:9f7861a6b127927cc4a872aadd575a4ee30c8930dcea2f6b600c8f06c3970d84"
71
+ harbor_task_checksum = "b7d5cb565fc1f261803c8b684f74c58e65190ab30209b2b356cda8661170b295"
72
+
73
+ [[metadata.repo2env.evaluation.evidence]]
74
+ kind = "probe"
75
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/5b4ba8286fef/candidates/f40a643a6ef9/quality/trials/r0-probe2/tsbatch-50714e834186-5b4ba8286fef-q-f40a643a-r0-probe2/tasksmith-f40a643a6ef9__xHnAFTf/result.json"
76
+ sha256 = "f50679b56f555be745b8df5937d2df72c62e792556286fe6b2ae783e7da844d7"
77
+ subject_bundle_hash = "sha256:76ab653d3a4532e4556a6e62b0309c3f54a425553e009b637a73089258f61465"
78
+ harbor_task_checksum = "edc426a92f6926467ce9a3ad15916a0b1ebea6edc338f3559e1351c856494629"
79
+
80
+ [[metadata.repo2env.evaluation.evidence]]
81
+ kind = "rollout"
82
+ path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/5b4ba8286fef/candidates/f40a643a6ef9/quality/trials/r0-rollout/tsbatch-50714e834186-5b4ba8286fef-q-f40a643a-r0-rollout/tasksmith-f40a643a6ef9__u2KiYW7/result.json"
83
+ sha256 = "fe2c0e017f46e243655c5a119c70453be40add3263c19e69bf4e82c04da4e1e8"
84
+ subject_bundle_hash = "sha256:07be47aad2d8c6fe1f62e23d4c8670cfff027c5be3594ef17c2237e1c231adbc"
85
+ harbor_task_checksum = "5d9748134d847ed40cf8e052f9e50233d873307f77c06d51af9145a6d58166a4"
86
+
87
+ [metadata.repo2env.quality_requirements]
88
+ probe_focus = [
89
+ "model_behavior",
90
+ ]
91
+
92
+ [environment]
93
+ cpus = 1
94
+ memory_mb = 2048
95
+ build_timeout_sec = 600
96
+ network_mode = "no-network"
97
+
98
+ [agent]
99
+ timeout_sec = 600
100
+ user = "learner"
101
+ network_mode = "no-network"
102
+
103
+ [verifier]
104
+ timeout_sec = 210
105
+ user = "root"
106
+ network_mode = "no-network"
107
+ environment_mode = "separate"
108
+
109
+ [verifier.environment]
110
+ network_mode = "no-network"
111
+ cpus = 2
112
+ memory_mb = 8192
113
+
114
+ [[artifacts]]
115
+ source = "/workspace/src/diffusers"
116
+ exclude = [
117
+ "__pycache__",
118
+ "*.pyc",
119
+ ".pytest_cache",
120
+ ]
121
+
122
+ [[artifacts]]
123
+ source = "/workspace/examples/dreambooth/train_dreambooth_lora_hidream.py"
124
+ exclude = [
125
+ "__pycache__",
126
+ "*.pyc",
127
+ ".pytest_cache",
128
+ ]
tasks/tasksmith-f40a643a6ef9/tests/Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /workspace
3
+ RUN python -m pip install --no-cache-dir numpy==2.5.3 packaging==26.3 parameterized==0.9.0 pillow==12.3.0 pytest==8.4.2 setuptools==78.1.0 wheel==0.48.0 torch==2.11.0+cpu --extra-index-url https://download.pytorch.org/whl/cpu transformers==4.50.3 peft==0.14.0 huggingface-hub==0.36.2 safetensors==0.4.3 accelerate==1.4.0 sentencepiece==0.2.0 tokenizers==0.21.1 filelock regex requests pyyaml tqdm requests_mock
4
+ RUN HF_HUB_OFFLINE=0 TRANSFORMERS_OFFLINE=0 python -c 'exec('"'"'"""Standalone image-build program; never import target models or receive credentials."""\n\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nfrom pathlib import Path\n\n\ndef fetch_assets(assets: list[dict], cache: Path) -> None:\n from huggingface_hub import get_hf_file_metadata, hf_hub_download, hf_hub_url\n\n manifests = []\n for asset in assets:\n sizes = {}\n for filename in asset["filenames"]:\n metadata = get_hf_file_metadata(\n hf_hub_url(asset["repo_id"], filename, revision=asset["revision"]), token=False\n )\n if metadata.commit_hash != asset["revision"] or metadata.size is None:\n raise ValueError("Hub metadata must resolve to the pinned revision and known size")\n sizes[filename] = metadata.size\n if sum(sizes.values()) > asset["max_bytes"]:\n raise ValueError(f"Asset exceeds download allowance: {asset[\'"'"'repo_id\'"'"']}")\n records = []\n for filename, size in sizes.items():\n path = Path(\n hf_hub_download(\n repo_id=asset["repo_id"],\n filename=filename,\n revision=asset["revision"],\n cache_dir=cache,\n token=False,\n )\n )\n if path.stat().st_size != size:\n raise ValueError("Downloaded asset size differs from pinned metadata")\n with path.open("rb") as stream:\n digest = hashlib.file_digest(stream, "sha256").hexdigest()\n records.append({"filename": filename, "bytes": size, "sha256": digest})\n # Upstream tests often omit revision. Their offline \'"'"'main\'"'"' lookup must\n # resolve to this explicit immutable pin, never the current Hub branch.\n ref = cache / ("models--" + asset["repo_id"].replace("/", "--")) / "refs/main"\n ref.parent.mkdir(parents=True, exist_ok=True)\n ref.write_text(asset["revision"])\n manifests.append({**asset, "files": records, "offline_main": asset["revision"]})\n cache.mkdir(parents=True, exist_ok=True)\n (cache / "tasksmith-assets.json").write_text(json.dumps(manifests, indent=2) + "\\n")\n\nfetch_assets(json.loads(\'"'"'[{"filenames": ["config.json", "generation_config.json", "model.safetensors", "special_tokens_map.json", "tokenizer.json", "tokenizer.model", "tokenizer_config.json"], "max_bytes": 16000000, "repo_id": "hf-internal-testing/tiny-random-LlamaForCausalLM", "revision": "9fb191250dd56d0ba7ec9785a025ed29c03d5998"}, {"filenames": ["config.json", "merges.txt", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json", "vocab.json"], "max_bytes": 1000000, "repo_id": "hf-internal-testing/tiny-random-clip", "revision": "04b741590ff4e18ef4d778c72afe3ca3a680a0c7"}, {"filenames": ["config.json", "pytorch_model.bin", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json"], "max_bytes": 10000000, "repo_id": "hf-internal-testing/tiny-random-t5", "revision": "2f582cd79ed5795b71539951d237945bc1c5ac7e"}]\'"'"'), Path(\'"'"'/opt/tasksmith-hf/hub\'"'"'))\n'"'"')'
5
+ ENV HF_HOME=/opt/tasksmith-hf HF_HUB_CACHE=/opt/tasksmith-hf/hub
6
+ COPY source /workspace
7
+ RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e .
8
+ ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
9
+ ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
10
+ RUN useradd -m -u 1001 grader
11
+ COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/
12
+ RUN chmod 755 /tests && chmod 644 /tests/*
tasks/tasksmith-f40a643a6ef9/tests/contract.json ADDED
@@ -0,0 +1,647 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "expected_passes": [
3
+ "tests.tasksmith_behavior::test_force_inference_output_false_computes_aux_loss_in_train_mode",
4
+ "tests.tasksmith_behavior::test_force_inference_output_true_skips_aux_loss_in_train_mode",
5
+ "tests.tasksmith_behavior::test_hidream_lora_mixin_importable",
6
+ "tests.tasksmith_behavior::test_hidream_pipeline_inherits_lora_mixin",
7
+ "tests.tasksmith_behavior::test_save_lora_weights_file_and_key_format",
8
+ "tests.tasksmith_behavior::test_save_lora_weights_raises_without_layers",
9
+ "tests.tasksmith_behavior::test_transformer_accepts_force_inference_output_in_config",
10
+ "tests.tasksmith_behavior::test_transformer_lora_adapter_state_dict_keys",
11
+ "tests.pipelines.hidream.test_pipeline_hidream.HiDreamImagePipelineFastTests::test_inference",
12
+ "tests.pipelines.hidream.test_pipeline_hidream.HiDreamImagePipelineFastTests::test_inference_batch_single_identical",
13
+ "tests.tasksmith_behavior::test_hidream_public_lora_local_roundtrip_changes_output"
14
+ ],
15
+ "immutable_assets": {
16
+ "src/diffusers/experimental/README.md": "00a7a60c98d3ca9b01da66f419323298576a66fc174544c2af4f8b8a9924c49a",
17
+ "src/diffusers/models/README.md": "c87bf0458e841215dd72c409304c93e02a6cbdbf978fee3868063cd2df3c4114",
18
+ "src/diffusers/pipelines/README.md": "2181e893d1bb560593421ac404c7d4d2f923616b2adce5316bdb328e68a320bb",
19
+ "src/diffusers/pipelines/deprecated/README.md": "1eec80a862921748539f185bb696101e4bd026fd3b069c99596b7ce378ec3c20",
20
+ "src/diffusers/pipelines/stable_diffusion/README.md": "15a6c36242c777cb9359f46fb865a1d5f79aa5655f85384bc208f94f66eeeb14",
21
+ "src/diffusers/py.typed": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
22
+ "src/diffusers/schedulers/README.md": "c548789356385c59bfffbec89ad91867e846af659226c7e109f98a1cb2a83c57",
23
+ "src/diffusers/utils/model_card_template.md": "6611a1ce39cc4f6a0f2db1e70b451844d129542fa8907f8c2ca8ef918b21f83b"
24
+ },
25
+ "optional_files": [
26
+ "examples/dreambooth/train_dreambooth_lora_hidream.py"
27
+ ],
28
+ "submitted_files": [
29
+ "examples/dreambooth/train_dreambooth_lora_hidream.py",
30
+ "src/diffusers/__init__.py",
31
+ "src/diffusers/callbacks.py",
32
+ "src/diffusers/commands/__init__.py",
33
+ "src/diffusers/commands/diffusers_cli.py",
34
+ "src/diffusers/commands/env.py",
35
+ "src/diffusers/commands/fp16_safetensors.py",
36
+ "src/diffusers/configuration_utils.py",
37
+ "src/diffusers/dependency_versions_check.py",
38
+ "src/diffusers/dependency_versions_table.py",
39
+ "src/diffusers/experimental/__init__.py",
40
+ "src/diffusers/experimental/rl/__init__.py",
41
+ "src/diffusers/experimental/rl/value_guided_sampling.py",
42
+ "src/diffusers/hooks/__init__.py",
43
+ "src/diffusers/hooks/faster_cache.py",
44
+ "src/diffusers/hooks/group_offloading.py",
45
+ "src/diffusers/hooks/hooks.py",
46
+ "src/diffusers/hooks/layerwise_casting.py",
47
+ "src/diffusers/hooks/pyramid_attention_broadcast.py",
48
+ "src/diffusers/image_processor.py",
49
+ "src/diffusers/loaders/__init__.py",
50
+ "src/diffusers/loaders/ip_adapter.py",
51
+ "src/diffusers/loaders/lora_base.py",
52
+ "src/diffusers/loaders/lora_conversion_utils.py",
53
+ "src/diffusers/loaders/lora_pipeline.py",
54
+ "src/diffusers/loaders/peft.py",
55
+ "src/diffusers/loaders/single_file.py",
56
+ "src/diffusers/loaders/single_file_model.py",
57
+ "src/diffusers/loaders/single_file_utils.py",
58
+ "src/diffusers/loaders/textual_inversion.py",
59
+ "src/diffusers/loaders/transformer_flux.py",
60
+ "src/diffusers/loaders/transformer_sd3.py",
61
+ "src/diffusers/loaders/unet.py",
62
+ "src/diffusers/loaders/unet_loader_utils.py",
63
+ "src/diffusers/loaders/utils.py",
64
+ "src/diffusers/models/__init__.py",
65
+ "src/diffusers/models/activations.py",
66
+ "src/diffusers/models/adapter.py",
67
+ "src/diffusers/models/attention.py",
68
+ "src/diffusers/models/attention_flax.py",
69
+ "src/diffusers/models/attention_processor.py",
70
+ "src/diffusers/models/auto_model.py",
71
+ "src/diffusers/models/autoencoders/__init__.py",
72
+ "src/diffusers/models/autoencoders/autoencoder_asym_kl.py",
73
+ "src/diffusers/models/autoencoders/autoencoder_dc.py",
74
+ "src/diffusers/models/autoencoders/autoencoder_kl.py",
75
+ "src/diffusers/models/autoencoders/autoencoder_kl_allegro.py",
76
+ "src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py",
77
+ "src/diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py",
78
+ "src/diffusers/models/autoencoders/autoencoder_kl_ltx.py",
79
+ "src/diffusers/models/autoencoders/autoencoder_kl_magvit.py",
80
+ "src/diffusers/models/autoencoders/autoencoder_kl_mochi.py",
81
+ "src/diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py",
82
+ "src/diffusers/models/autoencoders/autoencoder_kl_wan.py",
83
+ "src/diffusers/models/autoencoders/autoencoder_oobleck.py",
84
+ "src/diffusers/models/autoencoders/autoencoder_tiny.py",
85
+ "src/diffusers/models/autoencoders/consistency_decoder_vae.py",
86
+ "src/diffusers/models/autoencoders/vae.py",
87
+ "src/diffusers/models/autoencoders/vq_model.py",
88
+ "src/diffusers/models/cache_utils.py",
89
+ "src/diffusers/models/controlnet.py",
90
+ "src/diffusers/models/controlnet_flux.py",
91
+ "src/diffusers/models/controlnet_sd3.py",
92
+ "src/diffusers/models/controlnet_sparsectrl.py",
93
+ "src/diffusers/models/controlnets/__init__.py",
94
+ "src/diffusers/models/controlnets/controlnet.py",
95
+ "src/diffusers/models/controlnets/controlnet_flax.py",
96
+ "src/diffusers/models/controlnets/controlnet_flux.py",
97
+ "src/diffusers/models/controlnets/controlnet_hunyuan.py",
98
+ "src/diffusers/models/controlnets/controlnet_sana.py",
99
+ "src/diffusers/models/controlnets/controlnet_sd3.py",
100
+ "src/diffusers/models/controlnets/controlnet_sparsectrl.py",
101
+ "src/diffusers/models/controlnets/controlnet_union.py",
102
+ "src/diffusers/models/controlnets/controlnet_xs.py",
103
+ "src/diffusers/models/controlnets/multicontrolnet.py",
104
+ "src/diffusers/models/controlnets/multicontrolnet_union.py",
105
+ "src/diffusers/models/downsampling.py",
106
+ "src/diffusers/models/embeddings.py",
107
+ "src/diffusers/models/embeddings_flax.py",
108
+ "src/diffusers/models/lora.py",
109
+ "src/diffusers/models/model_loading_utils.py",
110
+ "src/diffusers/models/modeling_flax_pytorch_utils.py",
111
+ "src/diffusers/models/modeling_flax_utils.py",
112
+ "src/diffusers/models/modeling_outputs.py",
113
+ "src/diffusers/models/modeling_pytorch_flax_utils.py",
114
+ "src/diffusers/models/modeling_utils.py",
115
+ "src/diffusers/models/normalization.py",
116
+ "src/diffusers/models/resnet.py",
117
+ "src/diffusers/models/resnet_flax.py",
118
+ "src/diffusers/models/transformers/__init__.py",
119
+ "src/diffusers/models/transformers/auraflow_transformer_2d.py",
120
+ "src/diffusers/models/transformers/cogvideox_transformer_3d.py",
121
+ "src/diffusers/models/transformers/consisid_transformer_3d.py",
122
+ "src/diffusers/models/transformers/dit_transformer_2d.py",
123
+ "src/diffusers/models/transformers/dual_transformer_2d.py",
124
+ "src/diffusers/models/transformers/hunyuan_transformer_2d.py",
125
+ "src/diffusers/models/transformers/latte_transformer_3d.py",
126
+ "src/diffusers/models/transformers/lumina_nextdit2d.py",
127
+ "src/diffusers/models/transformers/pixart_transformer_2d.py",
128
+ "src/diffusers/models/transformers/prior_transformer.py",
129
+ "src/diffusers/models/transformers/sana_transformer.py",
130
+ "src/diffusers/models/transformers/stable_audio_transformer.py",
131
+ "src/diffusers/models/transformers/t5_film_transformer.py",
132
+ "src/diffusers/models/transformers/transformer_2d.py",
133
+ "src/diffusers/models/transformers/transformer_allegro.py",
134
+ "src/diffusers/models/transformers/transformer_cogview3plus.py",
135
+ "src/diffusers/models/transformers/transformer_cogview4.py",
136
+ "src/diffusers/models/transformers/transformer_easyanimate.py",
137
+ "src/diffusers/models/transformers/transformer_flux.py",
138
+ "src/diffusers/models/transformers/transformer_hidream_image.py",
139
+ "src/diffusers/models/transformers/transformer_hunyuan_video.py",
140
+ "src/diffusers/models/transformers/transformer_ltx.py",
141
+ "src/diffusers/models/transformers/transformer_lumina2.py",
142
+ "src/diffusers/models/transformers/transformer_mochi.py",
143
+ "src/diffusers/models/transformers/transformer_omnigen.py",
144
+ "src/diffusers/models/transformers/transformer_sd3.py",
145
+ "src/diffusers/models/transformers/transformer_temporal.py",
146
+ "src/diffusers/models/transformers/transformer_wan.py",
147
+ "src/diffusers/models/unets/__init__.py",
148
+ "src/diffusers/models/unets/unet_1d.py",
149
+ "src/diffusers/models/unets/unet_1d_blocks.py",
150
+ "src/diffusers/models/unets/unet_2d.py",
151
+ "src/diffusers/models/unets/unet_2d_blocks.py",
152
+ "src/diffusers/models/unets/unet_2d_blocks_flax.py",
153
+ "src/diffusers/models/unets/unet_2d_condition.py",
154
+ "src/diffusers/models/unets/unet_2d_condition_flax.py",
155
+ "src/diffusers/models/unets/unet_3d_blocks.py",
156
+ "src/diffusers/models/unets/unet_3d_condition.py",
157
+ "src/diffusers/models/unets/unet_i2vgen_xl.py",
158
+ "src/diffusers/models/unets/unet_kandinsky3.py",
159
+ "src/diffusers/models/unets/unet_motion_model.py",
160
+ "src/diffusers/models/unets/unet_spatio_temporal_condition.py",
161
+ "src/diffusers/models/unets/unet_stable_cascade.py",
162
+ "src/diffusers/models/unets/uvit_2d.py",
163
+ "src/diffusers/models/upsampling.py",
164
+ "src/diffusers/models/vae_flax.py",
165
+ "src/diffusers/models/vq_model.py",
166
+ "src/diffusers/optimization.py",
167
+ "src/diffusers/pipelines/__init__.py",
168
+ "src/diffusers/pipelines/allegro/__init__.py",
169
+ "src/diffusers/pipelines/allegro/pipeline_allegro.py",
170
+ "src/diffusers/pipelines/allegro/pipeline_output.py",
171
+ "src/diffusers/pipelines/amused/__init__.py",
172
+ "src/diffusers/pipelines/amused/pipeline_amused.py",
173
+ "src/diffusers/pipelines/amused/pipeline_amused_img2img.py",
174
+ "src/diffusers/pipelines/amused/pipeline_amused_inpaint.py",
175
+ "src/diffusers/pipelines/animatediff/__init__.py",
176
+ "src/diffusers/pipelines/animatediff/pipeline_animatediff.py",
177
+ "src/diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py",
178
+ "src/diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py",
179
+ "src/diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py",
180
+ "src/diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py",
181
+ "src/diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py",
182
+ "src/diffusers/pipelines/animatediff/pipeline_output.py",
183
+ "src/diffusers/pipelines/audioldm/__init__.py",
184
+ "src/diffusers/pipelines/audioldm/pipeline_audioldm.py",
185
+ "src/diffusers/pipelines/audioldm2/__init__.py",
186
+ "src/diffusers/pipelines/audioldm2/modeling_audioldm2.py",
187
+ "src/diffusers/pipelines/audioldm2/pipeline_audioldm2.py",
188
+ "src/diffusers/pipelines/aura_flow/__init__.py",
189
+ "src/diffusers/pipelines/aura_flow/pipeline_aura_flow.py",
190
+ "src/diffusers/pipelines/auto_pipeline.py",
191
+ "src/diffusers/pipelines/blip_diffusion/__init__.py",
192
+ "src/diffusers/pipelines/blip_diffusion/blip_image_processing.py",
193
+ "src/diffusers/pipelines/blip_diffusion/modeling_blip2.py",
194
+ "src/diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py",
195
+ "src/diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py",
196
+ "src/diffusers/pipelines/cogvideo/__init__.py",
197
+ "src/diffusers/pipelines/cogvideo/pipeline_cogvideox.py",
198
+ "src/diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py",
199
+ "src/diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py",
200
+ "src/diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py",
201
+ "src/diffusers/pipelines/cogvideo/pipeline_output.py",
202
+ "src/diffusers/pipelines/cogview3/__init__.py",
203
+ "src/diffusers/pipelines/cogview3/pipeline_cogview3plus.py",
204
+ "src/diffusers/pipelines/cogview3/pipeline_output.py",
205
+ "src/diffusers/pipelines/cogview4/__init__.py",
206
+ "src/diffusers/pipelines/cogview4/pipeline_cogview4.py",
207
+ "src/diffusers/pipelines/cogview4/pipeline_cogview4_control.py",
208
+ "src/diffusers/pipelines/cogview4/pipeline_output.py",
209
+ "src/diffusers/pipelines/consisid/__init__.py",
210
+ "src/diffusers/pipelines/consisid/consisid_utils.py",
211
+ "src/diffusers/pipelines/consisid/pipeline_consisid.py",
212
+ "src/diffusers/pipelines/consisid/pipeline_output.py",
213
+ "src/diffusers/pipelines/consistency_models/__init__.py",
214
+ "src/diffusers/pipelines/consistency_models/pipeline_consistency_models.py",
215
+ "src/diffusers/pipelines/controlnet/__init__.py",
216
+ "src/diffusers/pipelines/controlnet/multicontrolnet.py",
217
+ "src/diffusers/pipelines/controlnet/pipeline_controlnet.py",
218
+ "src/diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py",
219
+ "src/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py",
220
+ "src/diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py",
221
+ "src/diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py",
222
+ "src/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py",
223
+ "src/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py",
224
+ "src/diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py",
225
+ "src/diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py",
226
+ "src/diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py",
227
+ "src/diffusers/pipelines/controlnet/pipeline_flax_controlnet.py",
228
+ "src/diffusers/pipelines/controlnet_hunyuandit/__init__.py",
229
+ "src/diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py",
230
+ "src/diffusers/pipelines/controlnet_sd3/__init__.py",
231
+ "src/diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py",
232
+ "src/diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py",
233
+ "src/diffusers/pipelines/controlnet_xs/__init__.py",
234
+ "src/diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py",
235
+ "src/diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py",
236
+ "src/diffusers/pipelines/dance_diffusion/__init__.py",
237
+ "src/diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py",
238
+ "src/diffusers/pipelines/ddim/__init__.py",
239
+ "src/diffusers/pipelines/ddim/pipeline_ddim.py",
240
+ "src/diffusers/pipelines/ddpm/__init__.py",
241
+ "src/diffusers/pipelines/ddpm/pipeline_ddpm.py",
242
+ "src/diffusers/pipelines/deepfloyd_if/__init__.py",
243
+ "src/diffusers/pipelines/deepfloyd_if/pipeline_if.py",
244
+ "src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py",
245
+ "src/diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py",
246
+ "src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py",
247
+ "src/diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py",
248
+ "src/diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py",
249
+ "src/diffusers/pipelines/deepfloyd_if/pipeline_output.py",
250
+ "src/diffusers/pipelines/deepfloyd_if/safety_checker.py",
251
+ "src/diffusers/pipelines/deepfloyd_if/timesteps.py",
252
+ "src/diffusers/pipelines/deepfloyd_if/watermark.py",
253
+ "src/diffusers/pipelines/deprecated/__init__.py",
254
+ "src/diffusers/pipelines/deprecated/alt_diffusion/__init__.py",
255
+ "src/diffusers/pipelines/deprecated/alt_diffusion/modeling_roberta_series.py",
256
+ "src/diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py",
257
+ "src/diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py",
258
+ "src/diffusers/pipelines/deprecated/alt_diffusion/pipeline_output.py",
259
+ "src/diffusers/pipelines/deprecated/audio_diffusion/__init__.py",
260
+ "src/diffusers/pipelines/deprecated/audio_diffusion/mel.py",
261
+ "src/diffusers/pipelines/deprecated/audio_diffusion/pipeline_audio_diffusion.py",
262
+ "src/diffusers/pipelines/deprecated/latent_diffusion_uncond/__init__.py",
263
+ "src/diffusers/pipelines/deprecated/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py",
264
+ "src/diffusers/pipelines/deprecated/pndm/__init__.py",
265
+ "src/diffusers/pipelines/deprecated/pndm/pipeline_pndm.py",
266
+ "src/diffusers/pipelines/deprecated/repaint/__init__.py",
267
+ "src/diffusers/pipelines/deprecated/repaint/pipeline_repaint.py",
268
+ "src/diffusers/pipelines/deprecated/score_sde_ve/__init__.py",
269
+ "src/diffusers/pipelines/deprecated/score_sde_ve/pipeline_score_sde_ve.py",
270
+ "src/diffusers/pipelines/deprecated/spectrogram_diffusion/__init__.py",
271
+ "src/diffusers/pipelines/deprecated/spectrogram_diffusion/continuous_encoder.py",
272
+ "src/diffusers/pipelines/deprecated/spectrogram_diffusion/midi_utils.py",
273
+ "src/diffusers/pipelines/deprecated/spectrogram_diffusion/notes_encoder.py",
274
+ "src/diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py",
275
+ "src/diffusers/pipelines/deprecated/stable_diffusion_variants/__init__.py",
276
+ "src/diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py",
277
+ "src/diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_onnx_stable_diffusion_inpaint_legacy.py",
278
+ "src/diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py",
279
+ "src/diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py",
280
+ "src/diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py",
281
+ "src/diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py",
282
+ "src/diffusers/pipelines/deprecated/stochastic_karras_ve/__init__.py",
283
+ "src/diffusers/pipelines/deprecated/stochastic_karras_ve/pipeline_stochastic_karras_ve.py",
284
+ "src/diffusers/pipelines/deprecated/versatile_diffusion/__init__.py",
285
+ "src/diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py",
286
+ "src/diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py",
287
+ "src/diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py",
288
+ "src/diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py",
289
+ "src/diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py",
290
+ "src/diffusers/pipelines/deprecated/vq_diffusion/__init__.py",
291
+ "src/diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py",
292
+ "src/diffusers/pipelines/dit/__init__.py",
293
+ "src/diffusers/pipelines/dit/pipeline_dit.py",
294
+ "src/diffusers/pipelines/easyanimate/__init__.py",
295
+ "src/diffusers/pipelines/easyanimate/pipeline_easyanimate.py",
296
+ "src/diffusers/pipelines/easyanimate/pipeline_easyanimate_control.py",
297
+ "src/diffusers/pipelines/easyanimate/pipeline_easyanimate_inpaint.py",
298
+ "src/diffusers/pipelines/easyanimate/pipeline_output.py",
299
+ "src/diffusers/pipelines/flux/__init__.py",
300
+ "src/diffusers/pipelines/flux/modeling_flux.py",
301
+ "src/diffusers/pipelines/flux/pipeline_flux.py",
302
+ "src/diffusers/pipelines/flux/pipeline_flux_control.py",
303
+ "src/diffusers/pipelines/flux/pipeline_flux_control_img2img.py",
304
+ "src/diffusers/pipelines/flux/pipeline_flux_control_inpaint.py",
305
+ "src/diffusers/pipelines/flux/pipeline_flux_controlnet.py",
306
+ "src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py",
307
+ "src/diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py",
308
+ "src/diffusers/pipelines/flux/pipeline_flux_fill.py",
309
+ "src/diffusers/pipelines/flux/pipeline_flux_img2img.py",
310
+ "src/diffusers/pipelines/flux/pipeline_flux_inpaint.py",
311
+ "src/diffusers/pipelines/flux/pipeline_flux_prior_redux.py",
312
+ "src/diffusers/pipelines/flux/pipeline_output.py",
313
+ "src/diffusers/pipelines/free_init_utils.py",
314
+ "src/diffusers/pipelines/free_noise_utils.py",
315
+ "src/diffusers/pipelines/hidream_image/__init__.py",
316
+ "src/diffusers/pipelines/hidream_image/pipeline_hidream_image.py",
317
+ "src/diffusers/pipelines/hidream_image/pipeline_output.py",
318
+ "src/diffusers/pipelines/hunyuan_video/__init__.py",
319
+ "src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_skyreels_image2video.py",
320
+ "src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py",
321
+ "src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video_image2video.py",
322
+ "src/diffusers/pipelines/hunyuan_video/pipeline_output.py",
323
+ "src/diffusers/pipelines/hunyuandit/__init__.py",
324
+ "src/diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py",
325
+ "src/diffusers/pipelines/i2vgen_xl/__init__.py",
326
+ "src/diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py",
327
+ "src/diffusers/pipelines/kandinsky/__init__.py",
328
+ "src/diffusers/pipelines/kandinsky/pipeline_kandinsky.py",
329
+ "src/diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py",
330
+ "src/diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py",
331
+ "src/diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py",
332
+ "src/diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py",
333
+ "src/diffusers/pipelines/kandinsky/text_encoder.py",
334
+ "src/diffusers/pipelines/kandinsky2_2/__init__.py",
335
+ "src/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py",
336
+ "src/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py",
337
+ "src/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py",
338
+ "src/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py",
339
+ "src/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py",
340
+ "src/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py",
341
+ "src/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py",
342
+ "src/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py",
343
+ "src/diffusers/pipelines/kandinsky3/__init__.py",
344
+ "src/diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py",
345
+ "src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py",
346
+ "src/diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py",
347
+ "src/diffusers/pipelines/kolors/__init__.py",
348
+ "src/diffusers/pipelines/kolors/pipeline_kolors.py",
349
+ "src/diffusers/pipelines/kolors/pipeline_kolors_img2img.py",
350
+ "src/diffusers/pipelines/kolors/pipeline_output.py",
351
+ "src/diffusers/pipelines/kolors/text_encoder.py",
352
+ "src/diffusers/pipelines/kolors/tokenizer.py",
353
+ "src/diffusers/pipelines/latent_consistency_models/__init__.py",
354
+ "src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py",
355
+ "src/diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py",
356
+ "src/diffusers/pipelines/latent_diffusion/__init__.py",
357
+ "src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py",
358
+ "src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion_superresolution.py",
359
+ "src/diffusers/pipelines/latte/__init__.py",
360
+ "src/diffusers/pipelines/latte/pipeline_latte.py",
361
+ "src/diffusers/pipelines/ledits_pp/__init__.py",
362
+ "src/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py",
363
+ "src/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py",
364
+ "src/diffusers/pipelines/ledits_pp/pipeline_output.py",
365
+ "src/diffusers/pipelines/ltx/__init__.py",
366
+ "src/diffusers/pipelines/ltx/pipeline_ltx.py",
367
+ "src/diffusers/pipelines/ltx/pipeline_ltx_condition.py",
368
+ "src/diffusers/pipelines/ltx/pipeline_ltx_image2video.py",
369
+ "src/diffusers/pipelines/ltx/pipeline_output.py",
370
+ "src/diffusers/pipelines/lumina/__init__.py",
371
+ "src/diffusers/pipelines/lumina/pipeline_lumina.py",
372
+ "src/diffusers/pipelines/lumina2/__init__.py",
373
+ "src/diffusers/pipelines/lumina2/pipeline_lumina2.py",
374
+ "src/diffusers/pipelines/marigold/__init__.py",
375
+ "src/diffusers/pipelines/marigold/marigold_image_processing.py",
376
+ "src/diffusers/pipelines/marigold/pipeline_marigold_depth.py",
377
+ "src/diffusers/pipelines/marigold/pipeline_marigold_intrinsics.py",
378
+ "src/diffusers/pipelines/marigold/pipeline_marigold_normals.py",
379
+ "src/diffusers/pipelines/mochi/__init__.py",
380
+ "src/diffusers/pipelines/mochi/pipeline_mochi.py",
381
+ "src/diffusers/pipelines/mochi/pipeline_output.py",
382
+ "src/diffusers/pipelines/musicldm/__init__.py",
383
+ "src/diffusers/pipelines/musicldm/pipeline_musicldm.py",
384
+ "src/diffusers/pipelines/omnigen/__init__.py",
385
+ "src/diffusers/pipelines/omnigen/pipeline_omnigen.py",
386
+ "src/diffusers/pipelines/omnigen/processor_omnigen.py",
387
+ "src/diffusers/pipelines/onnx_utils.py",
388
+ "src/diffusers/pipelines/pag/__init__.py",
389
+ "src/diffusers/pipelines/pag/pag_utils.py",
390
+ "src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py",
391
+ "src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py",
392
+ "src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py",
393
+ "src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py",
394
+ "src/diffusers/pipelines/pag/pipeline_pag_hunyuandit.py",
395
+ "src/diffusers/pipelines/pag/pipeline_pag_kolors.py",
396
+ "src/diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py",
397
+ "src/diffusers/pipelines/pag/pipeline_pag_sana.py",
398
+ "src/diffusers/pipelines/pag/pipeline_pag_sd.py",
399
+ "src/diffusers/pipelines/pag/pipeline_pag_sd_3.py",
400
+ "src/diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py",
401
+ "src/diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py",
402
+ "src/diffusers/pipelines/pag/pipeline_pag_sd_img2img.py",
403
+ "src/diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py",
404
+ "src/diffusers/pipelines/pag/pipeline_pag_sd_xl.py",
405
+ "src/diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py",
406
+ "src/diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py",
407
+ "src/diffusers/pipelines/paint_by_example/__init__.py",
408
+ "src/diffusers/pipelines/paint_by_example/image_encoder.py",
409
+ "src/diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py",
410
+ "src/diffusers/pipelines/pia/__init__.py",
411
+ "src/diffusers/pipelines/pia/pipeline_pia.py",
412
+ "src/diffusers/pipelines/pipeline_flax_utils.py",
413
+ "src/diffusers/pipelines/pipeline_loading_utils.py",
414
+ "src/diffusers/pipelines/pipeline_utils.py",
415
+ "src/diffusers/pipelines/pixart_alpha/__init__.py",
416
+ "src/diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py",
417
+ "src/diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py",
418
+ "src/diffusers/pipelines/sana/__init__.py",
419
+ "src/diffusers/pipelines/sana/pipeline_output.py",
420
+ "src/diffusers/pipelines/sana/pipeline_sana.py",
421
+ "src/diffusers/pipelines/sana/pipeline_sana_controlnet.py",
422
+ "src/diffusers/pipelines/sana/pipeline_sana_sprint.py",
423
+ "src/diffusers/pipelines/semantic_stable_diffusion/__init__.py",
424
+ "src/diffusers/pipelines/semantic_stable_diffusion/pipeline_output.py",
425
+ "src/diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py",
426
+ "src/diffusers/pipelines/shap_e/__init__.py",
427
+ "src/diffusers/pipelines/shap_e/camera.py",
428
+ "src/diffusers/pipelines/shap_e/pipeline_shap_e.py",
429
+ "src/diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py",
430
+ "src/diffusers/pipelines/shap_e/renderer.py",
431
+ "src/diffusers/pipelines/stable_audio/__init__.py",
432
+ "src/diffusers/pipelines/stable_audio/modeling_stable_audio.py",
433
+ "src/diffusers/pipelines/stable_audio/pipeline_stable_audio.py",
434
+ "src/diffusers/pipelines/stable_cascade/__init__.py",
435
+ "src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py",
436
+ "src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py",
437
+ "src/diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py",
438
+ "src/diffusers/pipelines/stable_diffusion/__init__.py",
439
+ "src/diffusers/pipelines/stable_diffusion/clip_image_project_model.py",
440
+ "src/diffusers/pipelines/stable_diffusion/convert_from_ckpt.py",
441
+ "src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py",
442
+ "src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_img2img.py",
443
+ "src/diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_inpaint.py",
444
+ "src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py",
445
+ "src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py",
446
+ "src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py",
447
+ "src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py",
448
+ "src/diffusers/pipelines/stable_diffusion/pipeline_output.py",
449
+ "src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py",
450
+ "src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py",
451
+ "src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py",
452
+ "src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py",
453
+ "src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py",
454
+ "src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py",
455
+ "src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py",
456
+ "src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py",
457
+ "src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py",
458
+ "src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py",
459
+ "src/diffusers/pipelines/stable_diffusion/safety_checker.py",
460
+ "src/diffusers/pipelines/stable_diffusion/safety_checker_flax.py",
461
+ "src/diffusers/pipelines/stable_diffusion/stable_unclip_image_normalizer.py",
462
+ "src/diffusers/pipelines/stable_diffusion_3/__init__.py",
463
+ "src/diffusers/pipelines/stable_diffusion_3/pipeline_output.py",
464
+ "src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py",
465
+ "src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py",
466
+ "src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py",
467
+ "src/diffusers/pipelines/stable_diffusion_attend_and_excite/__init__.py",
468
+ "src/diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py",
469
+ "src/diffusers/pipelines/stable_diffusion_diffedit/__init__.py",
470
+ "src/diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py",
471
+ "src/diffusers/pipelines/stable_diffusion_gligen/__init__.py",
472
+ "src/diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py",
473
+ "src/diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py",
474
+ "src/diffusers/pipelines/stable_diffusion_k_diffusion/__init__.py",
475
+ "src/diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py",
476
+ "src/diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py",
477
+ "src/diffusers/pipelines/stable_diffusion_ldm3d/__init__.py",
478
+ "src/diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py",
479
+ "src/diffusers/pipelines/stable_diffusion_panorama/__init__.py",
480
+ "src/diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py",
481
+ "src/diffusers/pipelines/stable_diffusion_safe/__init__.py",
482
+ "src/diffusers/pipelines/stable_diffusion_safe/pipeline_output.py",
483
+ "src/diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py",
484
+ "src/diffusers/pipelines/stable_diffusion_safe/safety_checker.py",
485
+ "src/diffusers/pipelines/stable_diffusion_sag/__init__.py",
486
+ "src/diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py",
487
+ "src/diffusers/pipelines/stable_diffusion_xl/__init__.py",
488
+ "src/diffusers/pipelines/stable_diffusion_xl/pipeline_flax_stable_diffusion_xl.py",
489
+ "src/diffusers/pipelines/stable_diffusion_xl/pipeline_output.py",
490
+ "src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py",
491
+ "src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py",
492
+ "src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py",
493
+ "src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py",
494
+ "src/diffusers/pipelines/stable_diffusion_xl/watermark.py",
495
+ "src/diffusers/pipelines/stable_video_diffusion/__init__.py",
496
+ "src/diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py",
497
+ "src/diffusers/pipelines/t2i_adapter/__init__.py",
498
+ "src/diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py",
499
+ "src/diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py",
500
+ "src/diffusers/pipelines/text_to_video_synthesis/__init__.py",
501
+ "src/diffusers/pipelines/text_to_video_synthesis/pipeline_output.py",
502
+ "src/diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py",
503
+ "src/diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py",
504
+ "src/diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py",
505
+ "src/diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py",
506
+ "src/diffusers/pipelines/transformers_loading_utils.py",
507
+ "src/diffusers/pipelines/unclip/__init__.py",
508
+ "src/diffusers/pipelines/unclip/pipeline_unclip.py",
509
+ "src/diffusers/pipelines/unclip/pipeline_unclip_image_variation.py",
510
+ "src/diffusers/pipelines/unclip/text_proj.py",
511
+ "src/diffusers/pipelines/unidiffuser/__init__.py",
512
+ "src/diffusers/pipelines/unidiffuser/modeling_text_decoder.py",
513
+ "src/diffusers/pipelines/unidiffuser/modeling_uvit.py",
514
+ "src/diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py",
515
+ "src/diffusers/pipelines/wan/__init__.py",
516
+ "src/diffusers/pipelines/wan/pipeline_output.py",
517
+ "src/diffusers/pipelines/wan/pipeline_wan.py",
518
+ "src/diffusers/pipelines/wan/pipeline_wan_i2v.py",
519
+ "src/diffusers/pipelines/wan/pipeline_wan_video2video.py",
520
+ "src/diffusers/pipelines/wuerstchen/__init__.py",
521
+ "src/diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py",
522
+ "src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py",
523
+ "src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_diffnext.py",
524
+ "src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py",
525
+ "src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py",
526
+ "src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py",
527
+ "src/diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py",
528
+ "src/diffusers/quantizers/__init__.py",
529
+ "src/diffusers/quantizers/auto.py",
530
+ "src/diffusers/quantizers/base.py",
531
+ "src/diffusers/quantizers/bitsandbytes/__init__.py",
532
+ "src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py",
533
+ "src/diffusers/quantizers/bitsandbytes/utils.py",
534
+ "src/diffusers/quantizers/gguf/__init__.py",
535
+ "src/diffusers/quantizers/gguf/gguf_quantizer.py",
536
+ "src/diffusers/quantizers/gguf/utils.py",
537
+ "src/diffusers/quantizers/quantization_config.py",
538
+ "src/diffusers/quantizers/quanto/__init__.py",
539
+ "src/diffusers/quantizers/quanto/quanto_quantizer.py",
540
+ "src/diffusers/quantizers/quanto/utils.py",
541
+ "src/diffusers/quantizers/torchao/__init__.py",
542
+ "src/diffusers/quantizers/torchao/torchao_quantizer.py",
543
+ "src/diffusers/schedulers/__init__.py",
544
+ "src/diffusers/schedulers/deprecated/__init__.py",
545
+ "src/diffusers/schedulers/deprecated/scheduling_karras_ve.py",
546
+ "src/diffusers/schedulers/deprecated/scheduling_sde_vp.py",
547
+ "src/diffusers/schedulers/scheduling_amused.py",
548
+ "src/diffusers/schedulers/scheduling_consistency_decoder.py",
549
+ "src/diffusers/schedulers/scheduling_consistency_models.py",
550
+ "src/diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py",
551
+ "src/diffusers/schedulers/scheduling_ddim.py",
552
+ "src/diffusers/schedulers/scheduling_ddim_cogvideox.py",
553
+ "src/diffusers/schedulers/scheduling_ddim_flax.py",
554
+ "src/diffusers/schedulers/scheduling_ddim_inverse.py",
555
+ "src/diffusers/schedulers/scheduling_ddim_parallel.py",
556
+ "src/diffusers/schedulers/scheduling_ddpm.py",
557
+ "src/diffusers/schedulers/scheduling_ddpm_flax.py",
558
+ "src/diffusers/schedulers/scheduling_ddpm_parallel.py",
559
+ "src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py",
560
+ "src/diffusers/schedulers/scheduling_deis_multistep.py",
561
+ "src/diffusers/schedulers/scheduling_dpm_cogvideox.py",
562
+ "src/diffusers/schedulers/scheduling_dpmsolver_multistep.py",
563
+ "src/diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py",
564
+ "src/diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py",
565
+ "src/diffusers/schedulers/scheduling_dpmsolver_sde.py",
566
+ "src/diffusers/schedulers/scheduling_dpmsolver_singlestep.py",
567
+ "src/diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py",
568
+ "src/diffusers/schedulers/scheduling_edm_euler.py",
569
+ "src/diffusers/schedulers/scheduling_euler_ancestral_discrete.py",
570
+ "src/diffusers/schedulers/scheduling_euler_discrete.py",
571
+ "src/diffusers/schedulers/scheduling_euler_discrete_flax.py",
572
+ "src/diffusers/schedulers/scheduling_flow_match_euler_discrete.py",
573
+ "src/diffusers/schedulers/scheduling_flow_match_heun_discrete.py",
574
+ "src/diffusers/schedulers/scheduling_flow_match_lcm.py",
575
+ "src/diffusers/schedulers/scheduling_heun_discrete.py",
576
+ "src/diffusers/schedulers/scheduling_ipndm.py",
577
+ "src/diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py",
578
+ "src/diffusers/schedulers/scheduling_k_dpm_2_discrete.py",
579
+ "src/diffusers/schedulers/scheduling_karras_ve_flax.py",
580
+ "src/diffusers/schedulers/scheduling_lcm.py",
581
+ "src/diffusers/schedulers/scheduling_lms_discrete.py",
582
+ "src/diffusers/schedulers/scheduling_lms_discrete_flax.py",
583
+ "src/diffusers/schedulers/scheduling_pndm.py",
584
+ "src/diffusers/schedulers/scheduling_pndm_flax.py",
585
+ "src/diffusers/schedulers/scheduling_repaint.py",
586
+ "src/diffusers/schedulers/scheduling_sasolver.py",
587
+ "src/diffusers/schedulers/scheduling_scm.py",
588
+ "src/diffusers/schedulers/scheduling_sde_ve.py",
589
+ "src/diffusers/schedulers/scheduling_sde_ve_flax.py",
590
+ "src/diffusers/schedulers/scheduling_tcd.py",
591
+ "src/diffusers/schedulers/scheduling_unclip.py",
592
+ "src/diffusers/schedulers/scheduling_unipc_multistep.py",
593
+ "src/diffusers/schedulers/scheduling_utils.py",
594
+ "src/diffusers/schedulers/scheduling_utils_flax.py",
595
+ "src/diffusers/schedulers/scheduling_vq_diffusion.py",
596
+ "src/diffusers/training_utils.py",
597
+ "src/diffusers/utils/__init__.py",
598
+ "src/diffusers/utils/accelerate_utils.py",
599
+ "src/diffusers/utils/constants.py",
600
+ "src/diffusers/utils/deprecation_utils.py",
601
+ "src/diffusers/utils/doc_utils.py",
602
+ "src/diffusers/utils/dummy_bitsandbytes_objects.py",
603
+ "src/diffusers/utils/dummy_flax_and_transformers_objects.py",
604
+ "src/diffusers/utils/dummy_flax_objects.py",
605
+ "src/diffusers/utils/dummy_gguf_objects.py",
606
+ "src/diffusers/utils/dummy_note_seq_objects.py",
607
+ "src/diffusers/utils/dummy_onnx_objects.py",
608
+ "src/diffusers/utils/dummy_optimum_quanto_objects.py",
609
+ "src/diffusers/utils/dummy_pt_objects.py",
610
+ "src/diffusers/utils/dummy_torch_and_librosa_objects.py",
611
+ "src/diffusers/utils/dummy_torch_and_scipy_objects.py",
612
+ "src/diffusers/utils/dummy_torch_and_torchsde_objects.py",
613
+ "src/diffusers/utils/dummy_torch_and_transformers_and_k_diffusion_objects.py",
614
+ "src/diffusers/utils/dummy_torch_and_transformers_and_onnx_objects.py",
615
+ "src/diffusers/utils/dummy_torch_and_transformers_and_opencv_objects.py",
616
+ "src/diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py",
617
+ "src/diffusers/utils/dummy_torch_and_transformers_objects.py",
618
+ "src/diffusers/utils/dummy_torchao_objects.py",
619
+ "src/diffusers/utils/dummy_transformers_and_torch_and_note_seq_objects.py",
620
+ "src/diffusers/utils/dynamic_modules_utils.py",
621
+ "src/diffusers/utils/export_utils.py",
622
+ "src/diffusers/utils/hub_utils.py",
623
+ "src/diffusers/utils/import_utils.py",
624
+ "src/diffusers/utils/loading_utils.py",
625
+ "src/diffusers/utils/logging.py",
626
+ "src/diffusers/utils/outputs.py",
627
+ "src/diffusers/utils/peft_utils.py",
628
+ "src/diffusers/utils/pil_utils.py",
629
+ "src/diffusers/utils/remote_utils.py",
630
+ "src/diffusers/utils/source_code_parsing_utils.py",
631
+ "src/diffusers/utils/state_dict_utils.py",
632
+ "src/diffusers/utils/testing_utils.py",
633
+ "src/diffusers/utils/torch_utils.py",
634
+ "src/diffusers/utils/typing_utils.py",
635
+ "src/diffusers/utils/versions.py",
636
+ "src/diffusers/video_processor.py"
637
+ ],
638
+ "submitted_roots": [
639
+ "src/diffusers"
640
+ ],
641
+ "test_paths": [
642
+ "tests/pipelines/hidream/test_pipeline_hidream.py::HiDreamImagePipelineFastTests::test_inference",
643
+ "tests/pipelines/hidream/test_pipeline_hidream.py::HiDreamImagePipelineFastTests::test_inference_batch_single_identical",
644
+ "tests/tasksmith_behavior.py"
645
+ ],
646
+ "timeout_sec": 180
647
+ }
tasks/tasksmith-f40a643a6ef9/tests/grade.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone trusted entry point; copied into each separate verifier image.
2
+
3
+ No Repo2RLEnv installation is needed to grade an exported task. Submitted Python
4
+ runs as an unprivileged user; this parent owns the result parser and reward file.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import importlib.util
11
+ import json
12
+ import os
13
+ import signal
14
+ import stat
15
+ import subprocess
16
+ import sys
17
+ import tempfile
18
+ from pathlib import Path
19
+
20
+
21
+ def child_environment(temporary: str) -> dict[str, str]:
22
+ """Preserve prepared runtime assets without inheriting controller credentials."""
23
+ return {
24
+ **{
25
+ key: os.environ[key]
26
+ for key in (
27
+ "LD_LIBRARY_PATH",
28
+ "CUDA_VISIBLE_DEVICES",
29
+ "NVIDIA_VISIBLE_DEVICES",
30
+ "NVIDIA_DRIVER_CAPABILITIES",
31
+ "NCCL_SOCKET_IFNAME",
32
+ "GLOO_SOCKET_IFNAME",
33
+ "HF_HOME",
34
+ "HF_HUB_CACHE",
35
+ "HF_HUB_OFFLINE",
36
+ "TRANSFORMERS_OFFLINE",
37
+ "HF_DATASETS_OFFLINE",
38
+ )
39
+ if key in os.environ
40
+ },
41
+ "PATH": str(Path(sys.executable).parent) + ":/usr/local/bin:/usr/bin:/bin",
42
+ "HOME": temporary,
43
+ "PYTHONDONTWRITEBYTECODE": "1",
44
+ "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
45
+ }
46
+
47
+
48
+ def validate_submission(workspace: Path, contract: dict) -> None:
49
+ """Validate private staging and remove inert backups before importing Python."""
50
+ submitted = set(contract["submitted_files"])
51
+ backups: set[str] = set()
52
+ optional = submitted & set(contract.get("optional_files", []))
53
+ paths = submitted - optional
54
+ for relative in optional:
55
+ path = workspace / relative
56
+ if any(component.is_symlink() for component in (path, *path.parents)):
57
+ raise ValueError("Submitted source contains a symlink")
58
+ # Added standalone modules may be absent in the baseline. If supplied,
59
+ # apply the same regular-file and size checks as every required module.
60
+ if path.exists():
61
+ paths.add(relative)
62
+ roots = contract.get("submitted_roots", [])
63
+ immutable = contract.get("immutable_assets", {})
64
+ paths.update(immutable)
65
+ for relative in roots:
66
+ root = workspace / relative
67
+ if root.is_symlink() or not root.is_dir():
68
+ raise ValueError("Submitted source root is missing or linked")
69
+ for path in root.rglob("*"):
70
+ if path.is_symlink():
71
+ raise ValueError("Submitted source contains a symlink")
72
+ if path.is_dir():
73
+ continue
74
+ name = path.relative_to(workspace).as_posix()
75
+ if path.suffix != ".py" and name not in immutable:
76
+ if name not in submitted and path.name.endswith((".py.bak", ".py~")):
77
+ backups.add(name)
78
+ else:
79
+ raise ValueError("Only Python source files may be added")
80
+ paths.add(name)
81
+ for relative in sorted(paths):
82
+ path = workspace / relative
83
+ for component in (path, *path.parents):
84
+ if component.is_symlink():
85
+ raise ValueError("Submitted source contains a symlink")
86
+ if (
87
+ not path.is_file()
88
+ or not stat.S_ISREG(path.stat().st_mode)
89
+ or path.stat().st_size > 8 * 1024 * 1024
90
+ ):
91
+ raise ValueError("Submitted source is not a bounded regular file")
92
+ if (
93
+ relative in immutable
94
+ and hashlib.sha256(path.read_bytes()).hexdigest() != immutable[relative]
95
+ ):
96
+ raise ValueError("Non-Python source assets must remain unchanged")
97
+ if relative not in backups:
98
+ os.chown(path, 0, 0)
99
+ path.chmod(0o644)
100
+ # Only the verifier's collected copy is cleaned. The learner workspace and
101
+ # archived submission retain their bytes. Validate every path first so a
102
+ # backup cannot bypass linked, oversized, required, or immutable file checks.
103
+ for relative in sorted(backups):
104
+ (workspace / relative).unlink()
105
+
106
+
107
+ def main() -> None:
108
+ directory = Path("/tests")
109
+ parser_spec = importlib.util.spec_from_file_location(
110
+ "test_results", directory / "test_results.py"
111
+ )
112
+ parser = importlib.util.module_from_spec(parser_spec)
113
+ sys.modules[parser_spec.name] = parser
114
+ parser_spec.loader.exec_module(parser)
115
+ contract = json.loads((directory / "contract.json").read_text())
116
+ logs = Path("/logs/verifier")
117
+ logs.mkdir(parents=True, exist_ok=True)
118
+ logs.chmod(0o755)
119
+ reward = logs / "reward.txt"
120
+ reward.write_text("0\n")
121
+ reward.chmod(0o644)
122
+ try:
123
+ validate_submission(Path("/workspace"), contract)
124
+ except (ValueError, OSError) as exc:
125
+ (logs / "result.json").write_text(json.dumps({"passed": False, "reason": str(exc)}))
126
+ return
127
+ with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary:
128
+ working = Path(temporary)
129
+ os.chown(working, 1001, 1001)
130
+ working.chmod(0o700)
131
+ report = working / "results.xml"
132
+ command = [
133
+ sys.executable,
134
+ "-I",
135
+ "/tests/test_driver.py",
136
+ *contract["test_paths"],
137
+ "-q",
138
+ "--tb=short",
139
+ "-p",
140
+ "no:cacheprovider",
141
+ f"--junitxml={report}",
142
+ ]
143
+ with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr:
144
+ process = subprocess.Popen(
145
+ command,
146
+ cwd="/workspace",
147
+ stdout=stdout,
148
+ stderr=stderr,
149
+ user=1001,
150
+ group=1001,
151
+ extra_groups=[],
152
+ start_new_session=True,
153
+ env=child_environment(temporary),
154
+ )
155
+ try:
156
+ code = process.wait(timeout=contract["timeout_sec"])
157
+ finally:
158
+ # Terminate descendants too: they must not keep modifying the
159
+ # child-owned report while the trusted parent checks it.
160
+ try:
161
+ os.killpg(process.pid, signal.SIGKILL)
162
+ except ProcessLookupError:
163
+ pass
164
+ process.wait()
165
+ if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024:
166
+ (logs / "result.json").write_text(
167
+ json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"})
168
+ )
169
+ return
170
+ text = report.read_text()
171
+ (logs / "results.xml").write_text(text)
172
+ try:
173
+ parsed = parser.parse_junit(text, returncode=code)
174
+ except ValueError as exc:
175
+ (logs / "result.json").write_text(
176
+ json.dumps({"passed": False, "returncode": code, "reason": str(exc)})
177
+ )
178
+ return
179
+ expected = set(contract["expected_passes"])
180
+ passed = code == 0 and bool(expected) and parsed.passed == expected
181
+ (logs / "result.json").write_text(
182
+ json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses})
183
+ )
184
+ reward.write_text("1\n" if passed else "0\n")
185
+
186
+
187
+ if __name__ == "__main__":
188
+ main()
tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "\U0001F41B Bug Report"
2
+ description: Report a bug on Diffusers
3
+ labels: [ "bug" ]
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ Thanks a lot for taking the time to file this issue 🤗.
9
+ Issues do not only help to improve the library, but also publicly document common problems, questions, workflows for the whole community!
10
+ Thus, issues are of the same importance as pull requests when contributing to this library ❤️.
11
+ In order to make your issue as **useful for the community as possible**, let's try to stick to some simple guidelines:
12
+ - 1. Please try to be as precise and concise as possible.
13
+ *Give your issue a fitting title. Assume that someone which very limited knowledge of Diffusers can understand your issue. Add links to the source code, documentation other issues, pull requests etc...*
14
+ - 2. If your issue is about something not working, **always** provide a reproducible code snippet. The reader should be able to reproduce your issue by **only copy-pasting your code snippet into a Python shell**.
15
+ *The community cannot solve your issue if it cannot reproduce it. If your bug is related to training, add your training script and make everything needed to train public. Otherwise, just add a simple Python code snippet.*
16
+ - 3. Add the **minimum** amount of code / context that is needed to understand, reproduce your issue.
17
+ *Make the life of maintainers easy. `diffusers` is getting many issues every day. Make sure your issue is about one bug and one bug only. Make sure you add only the context, code needed to understand your issues - nothing more. Generally, every issue is a way of documenting this library, try to make it a good documentation entry.*
18
+ - 4. For issues related to community pipelines (i.e., the pipelines located in the `examples/community` folder), please tag the author of the pipeline in your issue thread as those pipelines are not maintained.
19
+ - type: markdown
20
+ attributes:
21
+ value: |
22
+ For more in-detail information on how to write good issues you can have a look [here](https://huggingface.co/course/chapter8/5?fw=pt).
23
+ - type: textarea
24
+ id: bug-description
25
+ attributes:
26
+ label: Describe the bug
27
+ description: A clear and concise description of what the bug is. If you intend to submit a pull request for this issue, tell us in the description. Thanks!
28
+ placeholder: Bug description
29
+ validations:
30
+ required: true
31
+ - type: textarea
32
+ id: reproduction
33
+ attributes:
34
+ label: Reproduction
35
+ description: Please provide a minimal reproducible code which we can copy/paste and reproduce the issue.
36
+ placeholder: Reproduction
37
+ validations:
38
+ required: true
39
+ - type: textarea
40
+ id: logs
41
+ attributes:
42
+ label: Logs
43
+ description: "Please include the Python logs if you can."
44
+ render: shell
45
+ - type: textarea
46
+ id: system-info
47
+ attributes:
48
+ label: System Info
49
+ description: Please share your system info with us. You can run the command `diffusers-cli env` and copy-paste its output below.
50
+ placeholder: Diffusers version, platform, Python version, ...
51
+ validations:
52
+ required: true
53
+ - type: textarea
54
+ id: who-can-help
55
+ attributes:
56
+ label: Who can help?
57
+ description: |
58
+ Your issue will be replied to more quickly if you can figure out the right person to tag with @.
59
+ If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
60
+
61
+ All issues are read by one of the core maintainers, so if you don't know who to tag, just leave this blank and
62
+ a core maintainer will ping the right person.
63
+
64
+ Please tag a maximum of 2 people.
65
+
66
+ Questions on DiffusionPipeline (Saving, Loading, From pretrained, ...): @sayakpaul @DN6
67
+
68
+ Questions on pipelines:
69
+ - Stable Diffusion @yiyixuxu @asomoza
70
+ - Stable Diffusion XL @yiyixuxu @sayakpaul @DN6
71
+ - Stable Diffusion 3: @yiyixuxu @sayakpaul @DN6 @asomoza
72
+ - Kandinsky @yiyixuxu
73
+ - ControlNet @sayakpaul @yiyixuxu @DN6
74
+ - T2I Adapter @sayakpaul @yiyixuxu @DN6
75
+ - IF @DN6
76
+ - Text-to-Video / Video-to-Video @DN6 @a-r-r-o-w
77
+ - Wuerstchen @DN6
78
+ - Other: @yiyixuxu @DN6
79
+ - Improving generation quality: @asomoza
80
+
81
+ Questions on models:
82
+ - UNet @DN6 @yiyixuxu @sayakpaul
83
+ - VAE @sayakpaul @DN6 @yiyixuxu
84
+ - Transformers/Attention @DN6 @yiyixuxu @sayakpaul
85
+
86
+ Questions on single file checkpoints: @DN6
87
+
88
+ Questions on Schedulers: @yiyixuxu
89
+
90
+ Questions on LoRA: @sayakpaul
91
+
92
+ Questions on Textual Inversion: @sayakpaul
93
+
94
+ Questions on Training:
95
+ - DreamBooth @sayakpaul
96
+ - Text-to-Image Fine-tuning @sayakpaul
97
+ - Textual Inversion @sayakpaul
98
+ - ControlNet @sayakpaul
99
+
100
+ Questions on Tests: @DN6 @sayakpaul @yiyixuxu
101
+
102
+ Questions on Documentation: @stevhliu
103
+
104
+ Questions on JAX- and MPS-related things: @pcuenca
105
+
106
+ Questions on audio pipelines: @sanchit-gandhi
107
+
108
+
109
+
110
+ placeholder: "@Username ..."
tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/config.yml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ contact_links:
2
+ - name: Questions / Discussions
3
+ url: https://github.com/huggingface/diffusers/discussions
4
+ about: General usage questions and community discussions
tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/feature_request.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: "\U0001F680 Feature Request"
3
+ about: Suggest an idea for this project
4
+ title: ''
5
+ labels: ''
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **Is your feature request related to a problem? Please describe.**
11
+ A clear and concise description of what the problem is. Ex. I'm always frustrated when [...].
12
+
13
+ **Describe the solution you'd like.**
14
+ A clear and concise description of what you want to happen.
15
+
16
+ **Describe alternatives you've considered.**
17
+ A clear and concise description of any alternative solutions or features you've considered.
18
+
19
+ **Additional context.**
20
+ Add any other context or screenshots about the feature request here.
tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/feedback.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: "💬 Feedback about API Design"
3
+ about: Give feedback about the current API design
4
+ title: ''
5
+ labels: ''
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **What API design would you like to have changed or added to the library? Why?**
11
+
12
+ **What use case would this enable or better enable? Can you give us a code example?**
tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/new-model-addition.yml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "\U0001F31F New Model/Pipeline/Scheduler Addition"
2
+ description: Submit a proposal/request to implement a new diffusion model/pipeline/scheduler
3
+ labels: [ "New model/pipeline/scheduler" ]
4
+
5
+ body:
6
+ - type: textarea
7
+ id: description-request
8
+ validations:
9
+ required: true
10
+ attributes:
11
+ label: Model/Pipeline/Scheduler description
12
+ description: |
13
+ Put any and all important information relative to the model/pipeline/scheduler
14
+
15
+ - type: checkboxes
16
+ id: information-tasks
17
+ attributes:
18
+ label: Open source status
19
+ description: |
20
+ Please note that if the model implementation isn't available or if the weights aren't open-source, we are less likely to implement it in `diffusers`.
21
+ options:
22
+ - label: "The model implementation is available."
23
+ - label: "The model weights are available (Only relevant if addition is not a scheduler)."
24
+
25
+ - type: textarea
26
+ id: additional-info
27
+ attributes:
28
+ label: Provide useful links for the implementation
29
+ description: |
30
+ Please provide information regarding the implementation, the weights, and the authors.
31
+ Please mention the authors by @gh-username if you're aware of their usernames.
tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/remote-vae-pilot-feedback.yml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "\U0001F31F Remote VAE"
2
+ description: Feedback for remote VAE pilot
3
+ labels: [ "Remote VAE" ]
4
+
5
+ body:
6
+ - type: textarea
7
+ id: positive
8
+ validations:
9
+ required: true
10
+ attributes:
11
+ label: Did you like the remote VAE solution?
12
+ description: |
13
+ If you liked it, we would appreciate it if you could elaborate what you liked.
14
+
15
+ - type: textarea
16
+ id: feedback
17
+ validations:
18
+ required: true
19
+ attributes:
20
+ label: What can be improved about the current solution?
21
+ description: |
22
+ Let us know the things you would like to see improved. Note that we will work optimizing the solution once the pilot is over and we have usage.
23
+
24
+ - type: textarea
25
+ id: others
26
+ validations:
27
+ required: true
28
+ attributes:
29
+ label: What other VAEs you would like to see if the pilot goes well?
30
+ description: |
31
+ Provide a list of the VAEs you would like to see in the future if the pilot goes well.
32
+
33
+ - type: textarea
34
+ id: additional-info
35
+ attributes:
36
+ label: Notify the members of the team
37
+ description: |
38
+ Tag the following folks when submitting this feedback: @hlky @sayakpaul
tasks/tasksmith-f40a643a6ef9/tests/source/.github/ISSUE_TEMPLATE/translate.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: 🌐 Translating a New Language?
3
+ about: Start a new translation effort in your language
4
+ title: '[<languageCode>] Translating docs to <languageName>'
5
+ labels: WIP
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ <!--
11
+ Note: Please search to see if an issue already exists for the language you are trying to translate.
12
+ -->
13
+
14
+ Hi!
15
+
16
+ Let's bring the documentation to all the <languageName>-speaking community 🌐.
17
+
18
+ Who would want to translate? Please follow the 🤗 [TRANSLATING guide](https://github.com/huggingface/diffusers/blob/main/docs/TRANSLATING.md). Here is a list of the files ready for translation. Let us know in this issue if you'd like to translate any, and we'll add your name to the list.
19
+
20
+ Some notes:
21
+
22
+ * Please translate using an informal tone (imagine you are talking with a friend about Diffusers 🤗).
23
+ * Please translate in a gender-neutral way.
24
+ * Add your translations to the folder called `<languageCode>` inside the [source folder](https://github.com/huggingface/diffusers/tree/main/docs/source).
25
+ * Register your translation in `<languageCode>/_toctree.yml`; please follow the order of the [English version](https://github.com/huggingface/diffusers/blob/main/docs/source/en/_toctree.yml).
26
+ * Once you're finished, open a pull request and tag this issue by including #issue-number in the description, where issue-number is the number of this issue. Please ping @stevhliu for review.
27
+ * 🙋 If you'd like others to help you with the translation, you can also post in the 🤗 [forums](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63).
28
+
29
+ Thank you so much for your help! 🤗
tasks/tasksmith-f40a643a6ef9/tests/source/.github/PULL_REQUEST_TEMPLATE.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # What does this PR do?
2
+
3
+ <!--
4
+ Congratulations! You've made it this far! You're not quite done yet though.
5
+
6
+ Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.
7
+
8
+ Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.
9
+
10
+ Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
11
+ -->
12
+
13
+ <!-- Remove if not applicable -->
14
+
15
+ Fixes # (issue)
16
+
17
+
18
+ ## Before submitting
19
+ - [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
20
+ - [ ] Did you read the [contributor guideline](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md)?
21
+ - [ ] Did you read our [philosophy doc](https://github.com/huggingface/diffusers/blob/main/PHILOSOPHY.md) (important for complex PRs)?
22
+ - [ ] Was this discussed/approved via a GitHub issue or the [forum](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63)? Please add a link to it if that's the case.
23
+ - [ ] Did you make sure to update the documentation with your changes? Here are the
24
+ [documentation guidelines](https://github.com/huggingface/diffusers/tree/main/docs), and
25
+ [here are tips on formatting docstrings](https://github.com/huggingface/diffusers/tree/main/docs#writing-source-documentation).
26
+ - [ ] Did you write any new necessary tests?
27
+
28
+
29
+ ## Who can review?
30
+
31
+ Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
32
+ members/contributors who may be interested in your PR.
33
+
34
+ <!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @.
35
+
36
+ If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
37
+ Please tag fewer than 3 people.
38
+
39
+ Core library:
40
+
41
+ - Schedulers: @yiyixuxu
42
+ - Pipelines and pipeline callbacks: @yiyixuxu and @asomoza
43
+ - Training examples: @sayakpaul
44
+ - Docs: @stevhliu and @sayakpaul
45
+ - JAX and MPS: @pcuenca
46
+ - Audio: @sanchit-gandhi
47
+ - General functionalities: @sayakpaul @yiyixuxu @DN6
48
+
49
+ Integrations:
50
+
51
+ - deepspeed: HF Trainer/Accelerate: @SunMarc
52
+ - PEFT: @sayakpaul @BenjaminBossan
53
+
54
+ HF projects:
55
+
56
+ - accelerate: [different repo](https://github.com/huggingface/accelerate)
57
+ - datasets: [different repo](https://github.com/huggingface/datasets)
58
+ - transformers: [different repo](https://github.com/huggingface/transformers)
59
+ - safetensors: [different repo](https://github.com/huggingface/safetensors)
60
+
61
+ -->
tasks/tasksmith-f40a643a6ef9/tests/source/.github/actions/setup-miniconda/action.yml ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Set up conda environment for testing
2
+
3
+ description: Sets up miniconda in your ${RUNNER_TEMP} environment and gives you the ${CONDA_RUN} environment variable so you don't have to worry about polluting non-empeheral runners anymore
4
+
5
+ inputs:
6
+ python-version:
7
+ description: If set to any value, don't use sudo to clean the workspace
8
+ required: false
9
+ type: string
10
+ default: "3.9"
11
+ miniconda-version:
12
+ description: Miniconda version to install
13
+ required: false
14
+ type: string
15
+ default: "4.12.0"
16
+ environment-file:
17
+ description: Environment file to install dependencies from
18
+ required: false
19
+ type: string
20
+ default: ""
21
+
22
+ runs:
23
+ using: composite
24
+ steps:
25
+ # Use the same trick from https://github.com/marketplace/actions/setup-miniconda
26
+ # to refresh the cache daily. This is kind of optional though
27
+ - name: Get date
28
+ id: get-date
29
+ shell: bash
30
+ run: echo "today=$(/bin/date -u '+%Y%m%d')d" >> $GITHUB_OUTPUT
31
+ - name: Setup miniconda cache
32
+ id: miniconda-cache
33
+ uses: actions/cache@v2
34
+ with:
35
+ path: ${{ runner.temp }}/miniconda
36
+ key: miniconda-${{ runner.os }}-${{ runner.arch }}-${{ inputs.python-version }}-${{ steps.get-date.outputs.today }}
37
+ - name: Install miniconda (${{ inputs.miniconda-version }})
38
+ if: steps.miniconda-cache.outputs.cache-hit != 'true'
39
+ env:
40
+ MINICONDA_VERSION: ${{ inputs.miniconda-version }}
41
+ shell: bash -l {0}
42
+ run: |
43
+ MINICONDA_INSTALL_PATH="${RUNNER_TEMP}/miniconda"
44
+ mkdir -p "${MINICONDA_INSTALL_PATH}"
45
+ case ${RUNNER_OS}-${RUNNER_ARCH} in
46
+ Linux-X64)
47
+ MINICONDA_ARCH="Linux-x86_64"
48
+ ;;
49
+ macOS-ARM64)
50
+ MINICONDA_ARCH="MacOSX-arm64"
51
+ ;;
52
+ macOS-X64)
53
+ MINICONDA_ARCH="MacOSX-x86_64"
54
+ ;;
55
+ *)
56
+ echo "::error::Platform ${RUNNER_OS}-${RUNNER_ARCH} currently unsupported using this action"
57
+ exit 1
58
+ ;;
59
+ esac
60
+ MINICONDA_URL="https://repo.anaconda.com/miniconda/Miniconda3-py39_${MINICONDA_VERSION}-${MINICONDA_ARCH}.sh"
61
+ curl -fsSL "${MINICONDA_URL}" -o "${MINICONDA_INSTALL_PATH}/miniconda.sh"
62
+ bash "${MINICONDA_INSTALL_PATH}/miniconda.sh" -b -u -p "${MINICONDA_INSTALL_PATH}"
63
+ rm -rf "${MINICONDA_INSTALL_PATH}/miniconda.sh"
64
+ - name: Update GitHub path to include miniconda install
65
+ shell: bash
66
+ run: |
67
+ MINICONDA_INSTALL_PATH="${RUNNER_TEMP}/miniconda"
68
+ echo "${MINICONDA_INSTALL_PATH}/bin" >> $GITHUB_PATH
69
+ - name: Setup miniconda env cache (with env file)
70
+ id: miniconda-env-cache-env-file
71
+ if: ${{ runner.os }} == 'macOS' && ${{ inputs.environment-file }} != ''
72
+ uses: actions/cache@v2
73
+ with:
74
+ path: ${{ runner.temp }}/conda-python-${{ inputs.python-version }}
75
+ key: miniconda-env-${{ runner.os }}-${{ runner.arch }}-${{ inputs.python-version }}-${{ steps.get-date.outputs.today }}-${{ hashFiles(inputs.environment-file) }}
76
+ - name: Setup miniconda env cache (without env file)
77
+ id: miniconda-env-cache
78
+ if: ${{ runner.os }} == 'macOS' && ${{ inputs.environment-file }} == ''
79
+ uses: actions/cache@v2
80
+ with:
81
+ path: ${{ runner.temp }}/conda-python-${{ inputs.python-version }}
82
+ key: miniconda-env-${{ runner.os }}-${{ runner.arch }}-${{ inputs.python-version }}-${{ steps.get-date.outputs.today }}
83
+ - name: Setup conda environment with python (v${{ inputs.python-version }})
84
+ if: steps.miniconda-env-cache-env-file.outputs.cache-hit != 'true' && steps.miniconda-env-cache.outputs.cache-hit != 'true'
85
+ shell: bash
86
+ env:
87
+ PYTHON_VERSION: ${{ inputs.python-version }}
88
+ ENV_FILE: ${{ inputs.environment-file }}
89
+ run: |
90
+ CONDA_BASE_ENV="${RUNNER_TEMP}/conda-python-${PYTHON_VERSION}"
91
+ ENV_FILE_FLAG=""
92
+ if [[ -f "${ENV_FILE}" ]]; then
93
+ ENV_FILE_FLAG="--file ${ENV_FILE}"
94
+ elif [[ -n "${ENV_FILE}" ]]; then
95
+ echo "::warning::Specified env file (${ENV_FILE}) not found, not going to include it"
96
+ fi
97
+ conda create \
98
+ --yes \
99
+ --prefix "${CONDA_BASE_ENV}" \
100
+ "python=${PYTHON_VERSION}" \
101
+ ${ENV_FILE_FLAG} \
102
+ cmake=3.22 \
103
+ conda-build=3.21 \
104
+ ninja=1.10 \
105
+ pkg-config=0.29 \
106
+ wheel=0.37
107
+ - name: Clone the base conda environment and update GitHub env
108
+ shell: bash
109
+ env:
110
+ PYTHON_VERSION: ${{ inputs.python-version }}
111
+ CONDA_BASE_ENV: ${{ runner.temp }}/conda-python-${{ inputs.python-version }}
112
+ run: |
113
+ CONDA_ENV="${RUNNER_TEMP}/conda_environment_${GITHUB_RUN_ID}"
114
+ conda create \
115
+ --yes \
116
+ --prefix "${CONDA_ENV}" \
117
+ --clone "${CONDA_BASE_ENV}"
118
+ # TODO: conda-build could not be cloned because it hardcodes the path, so it
119
+ # could not be cached
120
+ conda install --yes -p ${CONDA_ENV} conda-build=3.21
121
+ echo "CONDA_ENV=${CONDA_ENV}" >> "${GITHUB_ENV}"
122
+ echo "CONDA_RUN=conda run -p ${CONDA_ENV} --no-capture-output" >> "${GITHUB_ENV}"
123
+ echo "CONDA_BUILD=conda run -p ${CONDA_ENV} conda-build" >> "${GITHUB_ENV}"
124
+ echo "CONDA_INSTALL=conda install -p ${CONDA_ENV}" >> "${GITHUB_ENV}"
125
+ - name: Get disk space usage and throw an error for low disk space
126
+ shell: bash
127
+ run: |
128
+ echo "Print the available disk space for manual inspection"
129
+ df -h
130
+ # Set the minimum requirement space to 4GB
131
+ MINIMUM_AVAILABLE_SPACE_IN_GB=4
132
+ MINIMUM_AVAILABLE_SPACE_IN_KB=$(($MINIMUM_AVAILABLE_SPACE_IN_GB * 1024 * 1024))
133
+ # Use KB to avoid floating point warning like 3.1GB
134
+ df -k | tr -s ' ' | cut -d' ' -f 4,9 | while read -r LINE;
135
+ do
136
+ AVAIL=$(echo $LINE | cut -f1 -d' ')
137
+ MOUNT=$(echo $LINE | cut -f2 -d' ')
138
+ if [ "$MOUNT" = "/" ]; then
139
+ if [ "$AVAIL" -lt "$MINIMUM_AVAILABLE_SPACE_IN_KB" ]; then
140
+ echo "There is only ${AVAIL}KB free space left in $MOUNT, which is less than the minimum requirement of ${MINIMUM_AVAILABLE_SPACE_IN_KB}KB. Please help create an issue to PyTorch Release Engineering via https://github.com/pytorch/test-infra/issues and provide the link to the workflow run."
141
+ exit 1;
142
+ else
143
+ echo "There is ${AVAIL}KB free space left in $MOUNT, continue"
144
+ fi
145
+ fi
146
+ done
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/benchmark.yml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Benchmarking tests
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ schedule:
6
+ - cron: "30 1 1,15 * *" # every 2 weeks on the 1st and the 15th of every month at 1:30 AM
7
+
8
+ env:
9
+ DIFFUSERS_IS_CI: yes
10
+ HF_HUB_ENABLE_HF_TRANSFER: 1
11
+ HF_HOME: /mnt/cache
12
+ OMP_NUM_THREADS: 8
13
+ MKL_NUM_THREADS: 8
14
+
15
+ jobs:
16
+ torch_pipelines_cuda_benchmark_tests:
17
+ env:
18
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL_BENCHMARK }}
19
+ name: Torch Core Pipelines CUDA Benchmarking Tests
20
+ strategy:
21
+ fail-fast: false
22
+ max-parallel: 1
23
+ runs-on:
24
+ group: aws-g6-4xlarge-plus
25
+ container:
26
+ image: diffusers/diffusers-pytorch-compile-cuda
27
+ options: --shm-size "16gb" --ipc host --gpus 0
28
+ steps:
29
+ - name: Checkout diffusers
30
+ uses: actions/checkout@v3
31
+ with:
32
+ fetch-depth: 2
33
+ - name: NVIDIA-SMI
34
+ run: |
35
+ nvidia-smi
36
+ - name: Install dependencies
37
+ run: |
38
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
39
+ python -m uv pip install -e [quality,test]
40
+ python -m uv pip install pandas peft
41
+ python -m uv pip uninstall transformers && python -m uv pip install transformers==4.48.0
42
+ - name: Environment
43
+ run: |
44
+ python utils/print_env.py
45
+ - name: Diffusers Benchmarking
46
+ env:
47
+ HF_TOKEN: ${{ secrets.DIFFUSERS_BOT_TOKEN }}
48
+ BASE_PATH: benchmark_outputs
49
+ run: |
50
+ export TOTAL_GPU_MEMORY=$(python -c "import torch; print(torch.cuda.get_device_properties(0).total_memory / (1024**3))")
51
+ cd benchmarks && mkdir ${BASE_PATH} && python run_all.py && python push_results.py
52
+
53
+ - name: Test suite reports artifacts
54
+ if: ${{ always() }}
55
+ uses: actions/upload-artifact@v4
56
+ with:
57
+ name: benchmark_test_reports
58
+ path: benchmarks/benchmark_outputs
59
+
60
+ - name: Report success status
61
+ if: ${{ success() }}
62
+ run: |
63
+ pip install requests && python utils/notify_benchmarking_status.py --status=success
64
+
65
+ - name: Report failure status
66
+ if: ${{ failure() }}
67
+ run: |
68
+ pip install requests && python utils/notify_benchmarking_status.py --status=failure
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/build_docker_images.yml ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Test, build, and push Docker images
2
+
3
+ on:
4
+ pull_request: # During PRs, we just check if the changes Dockerfiles can be successfully built
5
+ branches:
6
+ - main
7
+ paths:
8
+ - "docker/**"
9
+ workflow_dispatch:
10
+ schedule:
11
+ - cron: "0 0 * * *" # every day at midnight
12
+
13
+ concurrency:
14
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
15
+ cancel-in-progress: true
16
+
17
+ env:
18
+ REGISTRY: diffusers
19
+ CI_SLACK_CHANNEL: ${{ secrets.CI_DOCKER_CHANNEL }}
20
+
21
+ jobs:
22
+ test-build-docker-images:
23
+ runs-on:
24
+ group: aws-general-8-plus
25
+ if: github.event_name == 'pull_request'
26
+ steps:
27
+ - name: Set up Docker Buildx
28
+ uses: docker/setup-buildx-action@v1
29
+
30
+ - name: Check out code
31
+ uses: actions/checkout@v3
32
+
33
+ - name: Find Changed Dockerfiles
34
+ id: file_changes
35
+ uses: jitterbit/get-changed-files@v1
36
+ with:
37
+ format: "space-delimited"
38
+ token: ${{ secrets.GITHUB_TOKEN }}
39
+
40
+ - name: Build Changed Docker Images
41
+ run: |
42
+ CHANGED_FILES="${{ steps.file_changes.outputs.all }}"
43
+ for FILE in $CHANGED_FILES; do
44
+ if [[ "$FILE" == docker/*Dockerfile ]]; then
45
+ DOCKER_PATH="${FILE%/Dockerfile}"
46
+ DOCKER_TAG=$(basename "$DOCKER_PATH")
47
+ echo "Building Docker image for $DOCKER_TAG"
48
+ docker build -t "$DOCKER_TAG" "$DOCKER_PATH"
49
+ fi
50
+ done
51
+ if: steps.file_changes.outputs.all != ''
52
+
53
+ build-and-push-docker-images:
54
+ runs-on:
55
+ group: aws-general-8-plus
56
+ if: github.event_name != 'pull_request'
57
+
58
+ permissions:
59
+ contents: read
60
+ packages: write
61
+
62
+ strategy:
63
+ fail-fast: false
64
+ matrix:
65
+ image-name:
66
+ - diffusers-pytorch-cpu
67
+ - diffusers-pytorch-cuda
68
+ - diffusers-pytorch-compile-cuda
69
+ - diffusers-pytorch-xformers-cuda
70
+ - diffusers-pytorch-minimum-cuda
71
+ - diffusers-flax-cpu
72
+ - diffusers-flax-tpu
73
+ - diffusers-onnxruntime-cpu
74
+ - diffusers-onnxruntime-cuda
75
+ - diffusers-doc-builder
76
+
77
+ steps:
78
+ - name: Checkout repository
79
+ uses: actions/checkout@v3
80
+ - name: Set up Docker Buildx
81
+ uses: docker/setup-buildx-action@v1
82
+ - name: Login to Docker Hub
83
+ uses: docker/login-action@v2
84
+ with:
85
+ username: ${{ env.REGISTRY }}
86
+ password: ${{ secrets.DOCKERHUB_TOKEN }}
87
+ - name: Build and push
88
+ uses: docker/build-push-action@v3
89
+ with:
90
+ no-cache: true
91
+ context: ./docker/${{ matrix.image-name }}
92
+ push: true
93
+ tags: ${{ env.REGISTRY }}/${{ matrix.image-name }}:latest
94
+
95
+ - name: Post to a Slack channel
96
+ id: slack
97
+ uses: huggingface/hf-workflows/.github/actions/post-slack@main
98
+ with:
99
+ # Slack channel id, channel name, or user id to post message.
100
+ # See also: https://api.slack.com/methods/chat.postMessage#channels
101
+ slack_channel: ${{ env.CI_SLACK_CHANNEL }}
102
+ title: "🤗 Results of the ${{ matrix.image-name }} Docker Image build"
103
+ status: ${{ job.status }}
104
+ slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/build_documentation.yml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build documentation
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ - doc-builder*
8
+ - v*-release
9
+ - v*-patch
10
+ paths:
11
+ - "src/diffusers/**.py"
12
+ - "examples/**"
13
+ - "docs/**"
14
+
15
+ jobs:
16
+ build:
17
+ uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@main
18
+ with:
19
+ commit_sha: ${{ github.sha }}
20
+ install_libgl1: true
21
+ package: diffusers
22
+ notebook_folder: diffusers_doc
23
+ languages: en ko zh ja pt
24
+ custom_container: diffusers/diffusers-doc-builder
25
+ secrets:
26
+ token: ${{ secrets.HUGGINGFACE_PUSH }}
27
+ hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/build_pr_documentation.yml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build PR Documentation
2
+
3
+ on:
4
+ pull_request:
5
+ paths:
6
+ - "src/diffusers/**.py"
7
+ - "examples/**"
8
+ - "docs/**"
9
+
10
+ concurrency:
11
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
12
+ cancel-in-progress: true
13
+
14
+ jobs:
15
+ build:
16
+ uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@main
17
+ with:
18
+ commit_sha: ${{ github.event.pull_request.head.sha }}
19
+ pr_number: ${{ github.event.number }}
20
+ install_libgl1: true
21
+ package: diffusers
22
+ languages: en ko zh ja pt
23
+ custom_container: diffusers/diffusers-doc-builder
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/mirror_community_pipeline.yml ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Mirror Community Pipeline
2
+
3
+ on:
4
+ # Push changes on the main branch
5
+ push:
6
+ branches:
7
+ - main
8
+ paths:
9
+ - 'examples/community/**.py'
10
+
11
+ # And on tag creation (e.g. `v0.28.1`)
12
+ tags:
13
+ - '*'
14
+
15
+ # Manual trigger with ref input
16
+ workflow_dispatch:
17
+ inputs:
18
+ ref:
19
+ description: "Either 'main' or a tag ref"
20
+ required: true
21
+ default: 'main'
22
+
23
+ jobs:
24
+ mirror_community_pipeline:
25
+ env:
26
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL_COMMUNITY_MIRROR }}
27
+
28
+ runs-on: ubuntu-22.04
29
+ steps:
30
+ # Checkout to correct ref
31
+ # If workflow dispatch
32
+ # If ref is 'main', set:
33
+ # CHECKOUT_REF=refs/heads/main
34
+ # PATH_IN_REPO=main
35
+ # Else it must be a tag. Set:
36
+ # CHECKOUT_REF=refs/tags/{tag}
37
+ # PATH_IN_REPO={tag}
38
+ # If not workflow dispatch
39
+ # If ref is 'refs/heads/main' => set 'main'
40
+ # Else it must be a tag => set {tag}
41
+ - name: Set checkout_ref and path_in_repo
42
+ run: |
43
+ if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
44
+ if [ -z "${{ github.event.inputs.ref }}" ]; then
45
+ echo "Error: Missing ref input"
46
+ exit 1
47
+ elif [ "${{ github.event.inputs.ref }}" == "main" ]; then
48
+ echo "CHECKOUT_REF=refs/heads/main" >> $GITHUB_ENV
49
+ echo "PATH_IN_REPO=main" >> $GITHUB_ENV
50
+ else
51
+ echo "CHECKOUT_REF=refs/tags/${{ github.event.inputs.ref }}" >> $GITHUB_ENV
52
+ echo "PATH_IN_REPO=${{ github.event.inputs.ref }}" >> $GITHUB_ENV
53
+ fi
54
+ elif [ "${{ github.ref }}" == "refs/heads/main" ]; then
55
+ echo "CHECKOUT_REF=${{ github.ref }}" >> $GITHUB_ENV
56
+ echo "PATH_IN_REPO=main" >> $GITHUB_ENV
57
+ else
58
+ # e.g. refs/tags/v0.28.1 -> v0.28.1
59
+ echo "CHECKOUT_REF=${{ github.ref }}" >> $GITHUB_ENV
60
+ echo "PATH_IN_REPO=$(echo ${{ github.ref }} | sed 's/^refs\/tags\///')" >> $GITHUB_ENV
61
+ fi
62
+ - name: Print env vars
63
+ run: |
64
+ echo "CHECKOUT_REF: ${{ env.CHECKOUT_REF }}"
65
+ echo "PATH_IN_REPO: ${{ env.PATH_IN_REPO }}"
66
+ - uses: actions/checkout@v3
67
+ with:
68
+ ref: ${{ env.CHECKOUT_REF }}
69
+
70
+ # Setup + install dependencies
71
+ - name: Set up Python
72
+ uses: actions/setup-python@v4
73
+ with:
74
+ python-version: "3.10"
75
+ - name: Install dependencies
76
+ run: |
77
+ python -m pip install --upgrade pip
78
+ pip install --upgrade huggingface_hub
79
+
80
+ # Check secret is set
81
+ - name: whoami
82
+ run: huggingface-cli whoami
83
+ env:
84
+ HF_TOKEN: ${{ secrets.HF_TOKEN_MIRROR_COMMUNITY_PIPELINES }}
85
+
86
+ # Push to HF! (under subfolder based on checkout ref)
87
+ # https://huggingface.co/datasets/diffusers/community-pipelines-mirror
88
+ - name: Mirror community pipeline to HF
89
+ run: huggingface-cli upload diffusers/community-pipelines-mirror ./examples/community ${PATH_IN_REPO} --repo-type dataset
90
+ env:
91
+ PATH_IN_REPO: ${{ env.PATH_IN_REPO }}
92
+ HF_TOKEN: ${{ secrets.HF_TOKEN_MIRROR_COMMUNITY_PIPELINES }}
93
+
94
+ - name: Report success status
95
+ if: ${{ success() }}
96
+ run: |
97
+ pip install requests && python utils/notify_community_pipelines_mirror.py --status=success
98
+
99
+ - name: Report failure status
100
+ if: ${{ failure() }}
101
+ run: |
102
+ pip install requests && python utils/notify_community_pipelines_mirror.py --status=failure
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/nightly_tests.yml ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Nightly and release tests on main/release branch
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ schedule:
6
+ - cron: "0 0 * * *" # every day at midnight
7
+
8
+ env:
9
+ DIFFUSERS_IS_CI: yes
10
+ HF_HUB_ENABLE_HF_TRANSFER: 1
11
+ OMP_NUM_THREADS: 8
12
+ MKL_NUM_THREADS: 8
13
+ PYTEST_TIMEOUT: 600
14
+ RUN_SLOW: yes
15
+ RUN_NIGHTLY: yes
16
+ PIPELINE_USAGE_CUTOFF: 5000
17
+ SLACK_API_TOKEN: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
18
+
19
+ jobs:
20
+ setup_torch_cuda_pipeline_matrix:
21
+ name: Setup Torch Pipelines CUDA Slow Tests Matrix
22
+ runs-on:
23
+ group: aws-general-8-plus
24
+ container:
25
+ image: diffusers/diffusers-pytorch-cpu
26
+ outputs:
27
+ pipeline_test_matrix: ${{ steps.fetch_pipeline_matrix.outputs.pipeline_test_matrix }}
28
+ steps:
29
+ - name: Checkout diffusers
30
+ uses: actions/checkout@v3
31
+ with:
32
+ fetch-depth: 2
33
+ - name: Install dependencies
34
+ run: |
35
+ pip install -e .[test]
36
+ pip install huggingface_hub
37
+ - name: Fetch Pipeline Matrix
38
+ id: fetch_pipeline_matrix
39
+ run: |
40
+ matrix=$(python utils/fetch_torch_cuda_pipeline_test_matrix.py)
41
+ echo $matrix
42
+ echo "pipeline_test_matrix=$matrix" >> $GITHUB_OUTPUT
43
+
44
+ - name: Pipeline Tests Artifacts
45
+ if: ${{ always() }}
46
+ uses: actions/upload-artifact@v4
47
+ with:
48
+ name: test-pipelines.json
49
+ path: reports
50
+
51
+ run_nightly_tests_for_torch_pipelines:
52
+ name: Nightly Torch Pipelines CUDA Tests
53
+ needs: setup_torch_cuda_pipeline_matrix
54
+ strategy:
55
+ fail-fast: false
56
+ max-parallel: 8
57
+ matrix:
58
+ module: ${{ fromJson(needs.setup_torch_cuda_pipeline_matrix.outputs.pipeline_test_matrix) }}
59
+ runs-on:
60
+ group: aws-g4dn-2xlarge
61
+ container:
62
+ image: diffusers/diffusers-pytorch-cuda
63
+ options: --shm-size "16gb" --ipc host --gpus 0
64
+ steps:
65
+ - name: Checkout diffusers
66
+ uses: actions/checkout@v3
67
+ with:
68
+ fetch-depth: 2
69
+ - name: NVIDIA-SMI
70
+ run: nvidia-smi
71
+ - name: Install dependencies
72
+ run: |
73
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
74
+ python -m uv pip install -e [quality,test]
75
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
76
+ python -m uv pip install pytest-reportlog
77
+ - name: Environment
78
+ run: |
79
+ python utils/print_env.py
80
+ - name: Pipeline CUDA Test
81
+ env:
82
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
83
+ # https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms
84
+ CUBLAS_WORKSPACE_CONFIG: :16:8
85
+ run: |
86
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
87
+ -s -v -k "not Flax and not Onnx" \
88
+ --make-reports=tests_pipeline_${{ matrix.module }}_cuda \
89
+ --report-log=tests_pipeline_${{ matrix.module }}_cuda.log \
90
+ tests/pipelines/${{ matrix.module }}
91
+ - name: Failure short reports
92
+ if: ${{ failure() }}
93
+ run: |
94
+ cat reports/tests_pipeline_${{ matrix.module }}_cuda_stats.txt
95
+ cat reports/tests_pipeline_${{ matrix.module }}_cuda_failures_short.txt
96
+ - name: Test suite reports artifacts
97
+ if: ${{ always() }}
98
+ uses: actions/upload-artifact@v4
99
+ with:
100
+ name: pipeline_${{ matrix.module }}_test_reports
101
+ path: reports
102
+ - name: Generate Report and Notify Channel
103
+ if: always()
104
+ run: |
105
+ pip install slack_sdk tabulate
106
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
107
+
108
+ run_nightly_tests_for_other_torch_modules:
109
+ name: Nightly Torch CUDA Tests
110
+ runs-on:
111
+ group: aws-g4dn-2xlarge
112
+ container:
113
+ image: diffusers/diffusers-pytorch-cuda
114
+ options: --shm-size "16gb" --ipc host --gpus 0
115
+ defaults:
116
+ run:
117
+ shell: bash
118
+ strategy:
119
+ fail-fast: false
120
+ max-parallel: 2
121
+ matrix:
122
+ module: [models, schedulers, lora, others, single_file, examples]
123
+ steps:
124
+ - name: Checkout diffusers
125
+ uses: actions/checkout@v3
126
+ with:
127
+ fetch-depth: 2
128
+
129
+ - name: Install dependencies
130
+ run: |
131
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
132
+ python -m uv pip install -e [quality,test]
133
+ python -m uv pip install peft@git+https://github.com/huggingface/peft.git
134
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
135
+ python -m uv pip install pytest-reportlog
136
+ - name: Environment
137
+ run: python utils/print_env.py
138
+
139
+ - name: Run nightly PyTorch CUDA tests for non-pipeline modules
140
+ if: ${{ matrix.module != 'examples'}}
141
+ env:
142
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
143
+ # https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms
144
+ CUBLAS_WORKSPACE_CONFIG: :16:8
145
+ run: |
146
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
147
+ -s -v -k "not Flax and not Onnx" \
148
+ --make-reports=tests_torch_${{ matrix.module }}_cuda \
149
+ --report-log=tests_torch_${{ matrix.module }}_cuda.log \
150
+ tests/${{ matrix.module }}
151
+
152
+ - name: Run nightly example tests with Torch
153
+ if: ${{ matrix.module == 'examples' }}
154
+ env:
155
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
156
+ # https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms
157
+ CUBLAS_WORKSPACE_CONFIG: :16:8
158
+ run: |
159
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
160
+ -s -v --make-reports=examples_torch_cuda \
161
+ --report-log=examples_torch_cuda.log \
162
+ examples/
163
+
164
+ - name: Failure short reports
165
+ if: ${{ failure() }}
166
+ run: |
167
+ cat reports/tests_torch_${{ matrix.module }}_cuda_stats.txt
168
+ cat reports/tests_torch_${{ matrix.module }}_cuda_failures_short.txt
169
+
170
+ - name: Test suite reports artifacts
171
+ if: ${{ always() }}
172
+ uses: actions/upload-artifact@v4
173
+ with:
174
+ name: torch_${{ matrix.module }}_cuda_test_reports
175
+ path: reports
176
+
177
+ - name: Generate Report and Notify Channel
178
+ if: always()
179
+ run: |
180
+ pip install slack_sdk tabulate
181
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
182
+
183
+ run_big_gpu_torch_tests:
184
+ name: Torch tests on big GPU
185
+ strategy:
186
+ fail-fast: false
187
+ max-parallel: 2
188
+ runs-on:
189
+ group: aws-g6e-xlarge-plus
190
+ container:
191
+ image: diffusers/diffusers-pytorch-cuda
192
+ options: --shm-size "16gb" --ipc host --gpus 0
193
+ steps:
194
+ - name: Checkout diffusers
195
+ uses: actions/checkout@v3
196
+ with:
197
+ fetch-depth: 2
198
+ - name: NVIDIA-SMI
199
+ run: nvidia-smi
200
+ - name: Install dependencies
201
+ run: |
202
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
203
+ python -m uv pip install -e [quality,test]
204
+ python -m uv pip install peft@git+https://github.com/huggingface/peft.git
205
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
206
+ python -m uv pip install pytest-reportlog
207
+ - name: Environment
208
+ run: |
209
+ python utils/print_env.py
210
+ - name: Selected Torch CUDA Test on big GPU
211
+ env:
212
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
213
+ # https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms
214
+ CUBLAS_WORKSPACE_CONFIG: :16:8
215
+ BIG_GPU_MEMORY: 40
216
+ run: |
217
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
218
+ -m "big_gpu_with_torch_cuda" \
219
+ --make-reports=tests_big_gpu_torch_cuda \
220
+ --report-log=tests_big_gpu_torch_cuda.log \
221
+ tests/
222
+ - name: Failure short reports
223
+ if: ${{ failure() }}
224
+ run: |
225
+ cat reports/tests_big_gpu_torch_cuda_stats.txt
226
+ cat reports/tests_big_gpu_torch_cuda_failures_short.txt
227
+ - name: Test suite reports artifacts
228
+ if: ${{ always() }}
229
+ uses: actions/upload-artifact@v4
230
+ with:
231
+ name: torch_cuda_big_gpu_test_reports
232
+ path: reports
233
+ - name: Generate Report and Notify Channel
234
+ if: always()
235
+ run: |
236
+ pip install slack_sdk tabulate
237
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
238
+
239
+ torch_minimum_version_cuda_tests:
240
+ name: Torch Minimum Version CUDA Tests
241
+ runs-on:
242
+ group: aws-g4dn-2xlarge
243
+ container:
244
+ image: diffusers/diffusers-pytorch-minimum-cuda
245
+ options: --shm-size "16gb" --ipc host --gpus 0
246
+ defaults:
247
+ run:
248
+ shell: bash
249
+ steps:
250
+ - name: Checkout diffusers
251
+ uses: actions/checkout@v3
252
+ with:
253
+ fetch-depth: 2
254
+
255
+ - name: Install dependencies
256
+ run: |
257
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
258
+ python -m uv pip install -e [quality,test]
259
+ python -m uv pip install peft@git+https://github.com/huggingface/peft.git
260
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
261
+
262
+ - name: Environment
263
+ run: |
264
+ python utils/print_env.py
265
+
266
+ - name: Run PyTorch CUDA tests
267
+ env:
268
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
269
+ # https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms
270
+ CUBLAS_WORKSPACE_CONFIG: :16:8
271
+ run: |
272
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
273
+ -s -v -k "not Flax and not Onnx" \
274
+ --make-reports=tests_torch_minimum_version_cuda \
275
+ tests/models/test_modeling_common.py \
276
+ tests/pipelines/test_pipelines_common.py \
277
+ tests/pipelines/test_pipeline_utils.py \
278
+ tests/pipelines/test_pipelines.py \
279
+ tests/pipelines/test_pipelines_auto.py \
280
+ tests/schedulers/test_schedulers.py \
281
+ tests/others
282
+
283
+ - name: Failure short reports
284
+ if: ${{ failure() }}
285
+ run: |
286
+ cat reports/tests_torch_minimum_version_cuda_stats.txt
287
+ cat reports/tests_torch_minimum_version_cuda_failures_short.txt
288
+
289
+ - name: Test suite reports artifacts
290
+ if: ${{ always() }}
291
+ uses: actions/upload-artifact@v4
292
+ with:
293
+ name: torch_minimum_version_cuda_test_reports
294
+ path: reports
295
+
296
+ run_flax_tpu_tests:
297
+ name: Nightly Flax TPU Tests
298
+ runs-on:
299
+ group: gcp-ct5lp-hightpu-8t
300
+ if: github.event_name == 'schedule'
301
+
302
+ container:
303
+ image: diffusers/diffusers-flax-tpu
304
+ options: --shm-size "16gb" --ipc host --privileged ${{ vars.V5_LITEPOD_8_ENV}} -v /mnt/hf_cache:/mnt/hf_cache
305
+ defaults:
306
+ run:
307
+ shell: bash
308
+ steps:
309
+ - name: Checkout diffusers
310
+ uses: actions/checkout@v3
311
+ with:
312
+ fetch-depth: 2
313
+
314
+ - name: Install dependencies
315
+ run: |
316
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
317
+ python -m uv pip install -e [quality,test]
318
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
319
+ python -m uv pip install pytest-reportlog
320
+
321
+ - name: Environment
322
+ run: python utils/print_env.py
323
+
324
+ - name: Run nightly Flax TPU tests
325
+ env:
326
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
327
+ run: |
328
+ python -m pytest -n 0 \
329
+ -s -v -k "Flax" \
330
+ --make-reports=tests_flax_tpu \
331
+ --report-log=tests_flax_tpu.log \
332
+ tests/
333
+
334
+ - name: Failure short reports
335
+ if: ${{ failure() }}
336
+ run: |
337
+ cat reports/tests_flax_tpu_stats.txt
338
+ cat reports/tests_flax_tpu_failures_short.txt
339
+
340
+ - name: Test suite reports artifacts
341
+ if: ${{ always() }}
342
+ uses: actions/upload-artifact@v4
343
+ with:
344
+ name: flax_tpu_test_reports
345
+ path: reports
346
+
347
+ - name: Generate Report and Notify Channel
348
+ if: always()
349
+ run: |
350
+ pip install slack_sdk tabulate
351
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
352
+
353
+ run_nightly_onnx_tests:
354
+ name: Nightly ONNXRuntime CUDA tests on Ubuntu
355
+ runs-on:
356
+ group: aws-g4dn-2xlarge
357
+ container:
358
+ image: diffusers/diffusers-onnxruntime-cuda
359
+ options: --gpus 0 --shm-size "16gb" --ipc host
360
+
361
+ steps:
362
+ - name: Checkout diffusers
363
+ uses: actions/checkout@v3
364
+ with:
365
+ fetch-depth: 2
366
+
367
+ - name: NVIDIA-SMI
368
+ run: nvidia-smi
369
+
370
+ - name: Install dependencies
371
+ run: |
372
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
373
+ python -m uv pip install -e [quality,test]
374
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
375
+ python -m uv pip install pytest-reportlog
376
+ - name: Environment
377
+ run: python utils/print_env.py
378
+
379
+ - name: Run Nightly ONNXRuntime CUDA tests
380
+ env:
381
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
382
+ run: |
383
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
384
+ -s -v -k "Onnx" \
385
+ --make-reports=tests_onnx_cuda \
386
+ --report-log=tests_onnx_cuda.log \
387
+ tests/
388
+
389
+ - name: Failure short reports
390
+ if: ${{ failure() }}
391
+ run: |
392
+ cat reports/tests_onnx_cuda_stats.txt
393
+ cat reports/tests_onnx_cuda_failures_short.txt
394
+
395
+ - name: Test suite reports artifacts
396
+ if: ${{ always() }}
397
+ uses: actions/upload-artifact@v4
398
+ with:
399
+ name: tests_onnx_cuda_reports
400
+ path: reports
401
+
402
+ - name: Generate Report and Notify Channel
403
+ if: always()
404
+ run: |
405
+ pip install slack_sdk tabulate
406
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
407
+
408
+ run_nightly_quantization_tests:
409
+ name: Torch quantization nightly tests
410
+ strategy:
411
+ fail-fast: false
412
+ max-parallel: 2
413
+ matrix:
414
+ config:
415
+ - backend: "bitsandbytes"
416
+ test_location: "bnb"
417
+ additional_deps: ["peft"]
418
+ - backend: "gguf"
419
+ test_location: "gguf"
420
+ additional_deps: ["peft"]
421
+ - backend: "torchao"
422
+ test_location: "torchao"
423
+ additional_deps: []
424
+ - backend: "optimum_quanto"
425
+ test_location: "quanto"
426
+ additional_deps: []
427
+ runs-on:
428
+ group: aws-g6e-xlarge-plus
429
+ container:
430
+ image: diffusers/diffusers-pytorch-cuda
431
+ options: --shm-size "20gb" --ipc host --gpus 0
432
+ steps:
433
+ - name: Checkout diffusers
434
+ uses: actions/checkout@v3
435
+ with:
436
+ fetch-depth: 2
437
+ - name: NVIDIA-SMI
438
+ run: nvidia-smi
439
+ - name: Install dependencies
440
+ run: |
441
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
442
+ python -m uv pip install -e [quality,test]
443
+ python -m uv pip install -U ${{ matrix.config.backend }}
444
+ if [ "${{ join(matrix.config.additional_deps, ' ') }}" != "" ]; then
445
+ python -m uv pip install ${{ join(matrix.config.additional_deps, ' ') }}
446
+ fi
447
+ python -m uv pip install pytest-reportlog
448
+ - name: Environment
449
+ run: |
450
+ python utils/print_env.py
451
+ - name: ${{ matrix.config.backend }} quantization tests on GPU
452
+ env:
453
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
454
+ # https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms
455
+ CUBLAS_WORKSPACE_CONFIG: :16:8
456
+ BIG_GPU_MEMORY: 40
457
+ run: |
458
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
459
+ --make-reports=tests_${{ matrix.config.backend }}_torch_cuda \
460
+ --report-log=tests_${{ matrix.config.backend }}_torch_cuda.log \
461
+ tests/quantization/${{ matrix.config.test_location }}
462
+ - name: Failure short reports
463
+ if: ${{ failure() }}
464
+ run: |
465
+ cat reports/tests_${{ matrix.config.backend }}_torch_cuda_stats.txt
466
+ cat reports/tests_${{ matrix.config.backend }}_torch_cuda_failures_short.txt
467
+ - name: Test suite reports artifacts
468
+ if: ${{ always() }}
469
+ uses: actions/upload-artifact@v4
470
+ with:
471
+ name: torch_cuda_${{ matrix.config.backend }}_reports
472
+ path: reports
473
+ - name: Generate Report and Notify Channel
474
+ if: always()
475
+ run: |
476
+ pip install slack_sdk tabulate
477
+ python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
478
+
479
+ # M1 runner currently not well supported
480
+ # TODO: (Dhruv) add these back when we setup better testing for Apple Silicon
481
+ # run_nightly_tests_apple_m1:
482
+ # name: Nightly PyTorch MPS tests on MacOS
483
+ # runs-on: [ self-hosted, apple-m1 ]
484
+ # if: github.event_name == 'schedule'
485
+ #
486
+ # steps:
487
+ # - name: Checkout diffusers
488
+ # uses: actions/checkout@v3
489
+ # with:
490
+ # fetch-depth: 2
491
+ #
492
+ # - name: Clean checkout
493
+ # shell: arch -arch arm64 bash {0}
494
+ # run: |
495
+ # git clean -fxd
496
+ # - name: Setup miniconda
497
+ # uses: ./.github/actions/setup-miniconda
498
+ # with:
499
+ # python-version: 3.9
500
+ #
501
+ # - name: Install dependencies
502
+ # shell: arch -arch arm64 bash {0}
503
+ # run: |
504
+ # ${CONDA_RUN} python -m pip install --upgrade pip uv
505
+ # ${CONDA_RUN} python -m uv pip install -e [quality,test]
506
+ # ${CONDA_RUN} python -m uv pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cpu
507
+ # ${CONDA_RUN} python -m uv pip install accelerate@git+https://github.com/huggingface/accelerate
508
+ # ${CONDA_RUN} python -m uv pip install pytest-reportlog
509
+ # - name: Environment
510
+ # shell: arch -arch arm64 bash {0}
511
+ # run: |
512
+ # ${CONDA_RUN} python utils/print_env.py
513
+ # - name: Run nightly PyTorch tests on M1 (MPS)
514
+ # shell: arch -arch arm64 bash {0}
515
+ # env:
516
+ # HF_HOME: /System/Volumes/Data/mnt/cache
517
+ # HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
518
+ # run: |
519
+ # ${CONDA_RUN} python -m pytest -n 1 -s -v --make-reports=tests_torch_mps \
520
+ # --report-log=tests_torch_mps.log \
521
+ # tests/
522
+ # - name: Failure short reports
523
+ # if: ${{ failure() }}
524
+ # run: cat reports/tests_torch_mps_failures_short.txt
525
+ #
526
+ # - name: Test suite reports artifacts
527
+ # if: ${{ always() }}
528
+ # uses: actions/upload-artifact@v4
529
+ # with:
530
+ # name: torch_mps_test_reports
531
+ # path: reports
532
+ #
533
+ # - name: Generate Report and Notify Channel
534
+ # if: always()
535
+ # run: |
536
+ # pip install slack_sdk tabulate
537
+ # python utils/log_reports.py >> $GITHUB_STEP_SUMMARY run_nightly_tests_apple_m1:
538
+ # name: Nightly PyTorch MPS tests on MacOS
539
+ # runs-on: [ self-hosted, apple-m1 ]
540
+ # if: github.event_name == 'schedule'
541
+ #
542
+ # steps:
543
+ # - name: Checkout diffusers
544
+ # uses: actions/checkout@v3
545
+ # with:
546
+ # fetch-depth: 2
547
+ #
548
+ # - name: Clean checkout
549
+ # shell: arch -arch arm64 bash {0}
550
+ # run: |
551
+ # git clean -fxd
552
+ # - name: Setup miniconda
553
+ # uses: ./.github/actions/setup-miniconda
554
+ # with:
555
+ # python-version: 3.9
556
+ #
557
+ # - name: Install dependencies
558
+ # shell: arch -arch arm64 bash {0}
559
+ # run: |
560
+ # ${CONDA_RUN} python -m pip install --upgrade pip uv
561
+ # ${CONDA_RUN} python -m uv pip install -e [quality,test]
562
+ # ${CONDA_RUN} python -m uv pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cpu
563
+ # ${CONDA_RUN} python -m uv pip install accelerate@git+https://github.com/huggingface/accelerate
564
+ # ${CONDA_RUN} python -m uv pip install pytest-reportlog
565
+ # - name: Environment
566
+ # shell: arch -arch arm64 bash {0}
567
+ # run: |
568
+ # ${CONDA_RUN} python utils/print_env.py
569
+ # - name: Run nightly PyTorch tests on M1 (MPS)
570
+ # shell: arch -arch arm64 bash {0}
571
+ # env:
572
+ # HF_HOME: /System/Volumes/Data/mnt/cache
573
+ # HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
574
+ # run: |
575
+ # ${CONDA_RUN} python -m pytest -n 1 -s -v --make-reports=tests_torch_mps \
576
+ # --report-log=tests_torch_mps.log \
577
+ # tests/
578
+ # - name: Failure short reports
579
+ # if: ${{ failure() }}
580
+ # run: cat reports/tests_torch_mps_failures_short.txt
581
+ #
582
+ # - name: Test suite reports artifacts
583
+ # if: ${{ always() }}
584
+ # uses: actions/upload-artifact@v4
585
+ # with:
586
+ # name: torch_mps_test_reports
587
+ # path: reports
588
+ #
589
+ # - name: Generate Report and Notify Channel
590
+ # if: always()
591
+ # run: |
592
+ # pip install slack_sdk tabulate
593
+ # python utils/log_reports.py >> $GITHUB_STEP_SUMMARY
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/notify_slack_about_release.yml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Notify Slack about a release
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ release:
6
+ types: [published]
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-22.04
11
+
12
+ steps:
13
+ - uses: actions/checkout@v3
14
+
15
+ - name: Setup Python
16
+ uses: actions/setup-python@v4
17
+ with:
18
+ python-version: '3.8'
19
+
20
+ - name: Notify Slack about the release
21
+ env:
22
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
23
+ run: pip install requests && python utils/notify_slack_about_release.py
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_dependency_test.yml ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run dependency tests
2
+
3
+ on:
4
+ pull_request:
5
+ branches:
6
+ - main
7
+ paths:
8
+ - "src/diffusers/**.py"
9
+ push:
10
+ branches:
11
+ - main
12
+
13
+ concurrency:
14
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
15
+ cancel-in-progress: true
16
+
17
+ jobs:
18
+ check_dependencies:
19
+ runs-on: ubuntu-22.04
20
+ steps:
21
+ - uses: actions/checkout@v3
22
+ - name: Set up Python
23
+ uses: actions/setup-python@v4
24
+ with:
25
+ python-version: "3.8"
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
29
+ python -m pip install --upgrade pip uv
30
+ python -m uv pip install -e .
31
+ python -m uv pip install pytest
32
+ - name: Check for soft dependencies
33
+ run: |
34
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
35
+ pytest tests/others/test_dependencies.py
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_flax_dependency_test.yml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Flax dependency tests
2
+
3
+ on:
4
+ pull_request:
5
+ branches:
6
+ - main
7
+ paths:
8
+ - "src/diffusers/**.py"
9
+ push:
10
+ branches:
11
+ - main
12
+
13
+ concurrency:
14
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
15
+ cancel-in-progress: true
16
+
17
+ jobs:
18
+ check_flax_dependencies:
19
+ runs-on: ubuntu-22.04
20
+ steps:
21
+ - uses: actions/checkout@v3
22
+ - name: Set up Python
23
+ uses: actions/setup-python@v4
24
+ with:
25
+ python-version: "3.8"
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
29
+ python -m pip install --upgrade pip uv
30
+ python -m uv pip install -e .
31
+ python -m uv pip install "jax[cpu]>=0.2.16,!=0.3.2"
32
+ python -m uv pip install "flax>=0.4.1"
33
+ python -m uv pip install "jaxlib>=0.1.65"
34
+ python -m uv pip install pytest
35
+ - name: Check for soft dependencies
36
+ run: |
37
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
38
+ pytest tests/others/test_dependencies.py
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_style_bot.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: PR Style Bot
2
+
3
+ on:
4
+ issue_comment:
5
+ types: [created]
6
+
7
+ permissions:
8
+ contents: write
9
+ pull-requests: write
10
+
11
+ jobs:
12
+ style:
13
+ uses: huggingface/huggingface_hub/.github/workflows/style-bot-action.yml@main
14
+ with:
15
+ python_quality_dependencies: "[quality]"
16
+ secrets:
17
+ bot_token: ${{ secrets.GITHUB_TOKEN }}
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_test_fetcher.yml ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Fast tests for PRs - Test Fetcher
2
+
3
+ on: workflow_dispatch
4
+
5
+ env:
6
+ DIFFUSERS_IS_CI: yes
7
+ OMP_NUM_THREADS: 4
8
+ MKL_NUM_THREADS: 4
9
+ PYTEST_TIMEOUT: 60
10
+
11
+ concurrency:
12
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
13
+ cancel-in-progress: true
14
+
15
+ jobs:
16
+ setup_pr_tests:
17
+ name: Setup PR Tests
18
+ runs-on:
19
+ group: aws-general-8-plus
20
+ container:
21
+ image: diffusers/diffusers-pytorch-cpu
22
+ options: --shm-size "16gb" --ipc host -v /mnt/hf_cache:/mnt/cache/
23
+ defaults:
24
+ run:
25
+ shell: bash
26
+ outputs:
27
+ matrix: ${{ steps.set_matrix.outputs.matrix }}
28
+ test_map: ${{ steps.set_matrix.outputs.test_map }}
29
+ steps:
30
+ - name: Checkout diffusers
31
+ uses: actions/checkout@v3
32
+ with:
33
+ fetch-depth: 0
34
+ - name: Install dependencies
35
+ run: |
36
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
37
+ python -m uv pip install -e [quality,test]
38
+ - name: Environment
39
+ run: |
40
+ python utils/print_env.py
41
+ echo $(git --version)
42
+ - name: Fetch Tests
43
+ run: |
44
+ python utils/tests_fetcher.py | tee test_preparation.txt
45
+ - name: Report fetched tests
46
+ uses: actions/upload-artifact@v3
47
+ with:
48
+ name: test_fetched
49
+ path: test_preparation.txt
50
+ - id: set_matrix
51
+ name: Create Test Matrix
52
+ # The `keys` is used as GitHub actions matrix for jobs, i.e. `models`, `pipelines`, etc.
53
+ # The `test_map` is used to get the actual identified test files under each key.
54
+ # If no test to run (so no `test_map.json` file), create a dummy map (empty matrix will fail)
55
+ run: |
56
+ if [ -f test_map.json ]; then
57
+ keys=$(python3 -c 'import json; fp = open("test_map.json"); test_map = json.load(fp); fp.close(); d = list(test_map.keys()); print(json.dumps(d))')
58
+ test_map=$(python3 -c 'import json; fp = open("test_map.json"); test_map = json.load(fp); fp.close(); print(json.dumps(test_map))')
59
+ else
60
+ keys=$(python3 -c 'keys = ["dummy"]; print(keys)')
61
+ test_map=$(python3 -c 'test_map = {"dummy": []}; print(test_map)')
62
+ fi
63
+ echo $keys
64
+ echo $test_map
65
+ echo "matrix=$keys" >> $GITHUB_OUTPUT
66
+ echo "test_map=$test_map" >> $GITHUB_OUTPUT
67
+
68
+ run_pr_tests:
69
+ name: Run PR Tests
70
+ needs: setup_pr_tests
71
+ if: contains(fromJson(needs.setup_pr_tests.outputs.matrix), 'dummy') != true
72
+ strategy:
73
+ fail-fast: false
74
+ max-parallel: 2
75
+ matrix:
76
+ modules: ${{ fromJson(needs.setup_pr_tests.outputs.matrix) }}
77
+ runs-on:
78
+ group: aws-general-8-plus
79
+ container:
80
+ image: diffusers/diffusers-pytorch-cpu
81
+ options: --shm-size "16gb" --ipc host -v /mnt/hf_cache:/mnt/cache/
82
+ defaults:
83
+ run:
84
+ shell: bash
85
+ steps:
86
+ - name: Checkout diffusers
87
+ uses: actions/checkout@v3
88
+ with:
89
+ fetch-depth: 2
90
+
91
+ - name: Install dependencies
92
+ run: |
93
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
94
+ python -m pip install -e [quality,test]
95
+ python -m pip install accelerate
96
+
97
+ - name: Environment
98
+ run: |
99
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
100
+ python utils/print_env.py
101
+
102
+ - name: Run all selected tests on CPU
103
+ run: |
104
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
105
+ python -m pytest -n 2 --dist=loadfile -v --make-reports=${{ matrix.modules }}_tests_cpu ${{ fromJson(needs.setup_pr_tests.outputs.test_map)[matrix.modules] }}
106
+
107
+ - name: Failure short reports
108
+ if: ${{ failure() }}
109
+ continue-on-error: true
110
+ run: |
111
+ cat reports/${{ matrix.modules }}_tests_cpu_stats.txt
112
+ cat reports/${{ matrix.modules }}_tests_cpu_failures_short.txt
113
+
114
+ - name: Test suite reports artifacts
115
+ if: ${{ always() }}
116
+ uses: actions/upload-artifact@v3
117
+ with:
118
+ name: ${{ matrix.modules }}_test_reports
119
+ path: reports
120
+
121
+ run_staging_tests:
122
+ strategy:
123
+ fail-fast: false
124
+ matrix:
125
+ config:
126
+ - name: Hub tests for models, schedulers, and pipelines
127
+ framework: hub_tests_pytorch
128
+ runner: aws-general-8-plus
129
+ image: diffusers/diffusers-pytorch-cpu
130
+ report: torch_hub
131
+
132
+ name: ${{ matrix.config.name }}
133
+ runs-on:
134
+ group: ${{ matrix.config.runner }}
135
+ container:
136
+ image: ${{ matrix.config.image }}
137
+ options: --shm-size "16gb" --ipc host -v /mnt/hf_cache:/mnt/cache/
138
+
139
+ defaults:
140
+ run:
141
+ shell: bash
142
+
143
+ steps:
144
+ - name: Checkout diffusers
145
+ uses: actions/checkout@v3
146
+ with:
147
+ fetch-depth: 2
148
+
149
+ - name: Install dependencies
150
+ run: |
151
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
152
+ python -m pip install -e [quality,test]
153
+
154
+ - name: Environment
155
+ run: |
156
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
157
+ python utils/print_env.py
158
+
159
+ - name: Run Hub tests for models, schedulers, and pipelines on a staging env
160
+ if: ${{ matrix.config.framework == 'hub_tests_pytorch' }}
161
+ run: |
162
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
163
+ HUGGINGFACE_CO_STAGING=true python -m pytest \
164
+ -m "is_staging_test" \
165
+ --make-reports=tests_${{ matrix.config.report }} \
166
+ tests
167
+
168
+ - name: Failure short reports
169
+ if: ${{ failure() }}
170
+ run: cat reports/tests_${{ matrix.config.report }}_failures_short.txt
171
+
172
+ - name: Test suite reports artifacts
173
+ if: ${{ always() }}
174
+ uses: actions/upload-artifact@v4
175
+ with:
176
+ name: pr_${{ matrix.config.report }}_test_reports
177
+ path: reports
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_tests.yml ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Fast tests for PRs
2
+
3
+ on:
4
+ pull_request:
5
+ branches: [main]
6
+ paths:
7
+ - "src/diffusers/**.py"
8
+ - "benchmarks/**.py"
9
+ - "examples/**.py"
10
+ - "scripts/**.py"
11
+ - "tests/**.py"
12
+ - ".github/**.yml"
13
+ - "utils/**.py"
14
+ push:
15
+ branches:
16
+ - ci-*
17
+
18
+ concurrency:
19
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
20
+ cancel-in-progress: true
21
+
22
+ env:
23
+ DIFFUSERS_IS_CI: yes
24
+ HF_HUB_ENABLE_HF_TRANSFER: 1
25
+ OMP_NUM_THREADS: 4
26
+ MKL_NUM_THREADS: 4
27
+ PYTEST_TIMEOUT: 60
28
+
29
+ jobs:
30
+ check_code_quality:
31
+ runs-on: ubuntu-22.04
32
+ steps:
33
+ - uses: actions/checkout@v3
34
+ - name: Set up Python
35
+ uses: actions/setup-python@v4
36
+ with:
37
+ python-version: "3.8"
38
+ - name: Install dependencies
39
+ run: |
40
+ python -m pip install --upgrade pip
41
+ pip install .[quality]
42
+ - name: Check quality
43
+ run: make quality
44
+ - name: Check if failure
45
+ if: ${{ failure() }}
46
+ run: |
47
+ echo "Quality check failed. Please ensure the right dependency versions are installed with 'pip install -e .[quality]' and run 'make style && make quality'" >> $GITHUB_STEP_SUMMARY
48
+
49
+ check_repository_consistency:
50
+ needs: check_code_quality
51
+ runs-on: ubuntu-22.04
52
+ steps:
53
+ - uses: actions/checkout@v3
54
+ - name: Set up Python
55
+ uses: actions/setup-python@v4
56
+ with:
57
+ python-version: "3.8"
58
+ - name: Install dependencies
59
+ run: |
60
+ python -m pip install --upgrade pip
61
+ pip install .[quality]
62
+ - name: Check repo consistency
63
+ run: |
64
+ python utils/check_copies.py
65
+ python utils/check_dummies.py
66
+ python utils/check_support_list.py
67
+ make deps_table_check_updated
68
+ - name: Check if failure
69
+ if: ${{ failure() }}
70
+ run: |
71
+ echo "Repo consistency check failed. Please ensure the right dependency versions are installed with 'pip install -e .[quality]' and run 'make fix-copies'" >> $GITHUB_STEP_SUMMARY
72
+
73
+ run_fast_tests:
74
+ needs: [check_code_quality, check_repository_consistency]
75
+ strategy:
76
+ fail-fast: false
77
+ matrix:
78
+ config:
79
+ - name: Fast PyTorch Pipeline CPU tests
80
+ framework: pytorch_pipelines
81
+ runner: aws-highmemory-32-plus
82
+ image: diffusers/diffusers-pytorch-cpu
83
+ report: torch_cpu_pipelines
84
+ - name: Fast PyTorch Models & Schedulers CPU tests
85
+ framework: pytorch_models
86
+ runner: aws-general-8-plus
87
+ image: diffusers/diffusers-pytorch-cpu
88
+ report: torch_cpu_models_schedulers
89
+ - name: Fast Flax CPU tests
90
+ framework: flax
91
+ runner: aws-general-8-plus
92
+ image: diffusers/diffusers-flax-cpu
93
+ report: flax_cpu
94
+ - name: PyTorch Example CPU tests
95
+ framework: pytorch_examples
96
+ runner: aws-general-8-plus
97
+ image: diffusers/diffusers-pytorch-cpu
98
+ report: torch_example_cpu
99
+
100
+ name: ${{ matrix.config.name }}
101
+
102
+ runs-on:
103
+ group: ${{ matrix.config.runner }}
104
+
105
+ container:
106
+ image: ${{ matrix.config.image }}
107
+ options: --shm-size "16gb" --ipc host -v /mnt/hf_cache:/mnt/cache/
108
+
109
+ defaults:
110
+ run:
111
+ shell: bash
112
+
113
+ steps:
114
+ - name: Checkout diffusers
115
+ uses: actions/checkout@v3
116
+ with:
117
+ fetch-depth: 2
118
+
119
+ - name: Install dependencies
120
+ run: |
121
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
122
+ python -m uv pip install -e [quality,test]
123
+ pip uninstall transformers -y && python -m uv pip install -U transformers@git+https://github.com/huggingface/transformers.git --no-deps
124
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git --no-deps
125
+
126
+ - name: Environment
127
+ run: |
128
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
129
+ python utils/print_env.py
130
+
131
+ - name: Run fast PyTorch Pipeline CPU tests
132
+ if: ${{ matrix.config.framework == 'pytorch_pipelines' }}
133
+ run: |
134
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
135
+ python -m pytest -n 8 --max-worker-restart=0 --dist=loadfile \
136
+ -s -v -k "not Flax and not Onnx" \
137
+ --make-reports=tests_${{ matrix.config.report }} \
138
+ tests/pipelines
139
+
140
+ - name: Run fast PyTorch Model Scheduler CPU tests
141
+ if: ${{ matrix.config.framework == 'pytorch_models' }}
142
+ run: |
143
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
144
+ python -m pytest -n 4 --max-worker-restart=0 --dist=loadfile \
145
+ -s -v -k "not Flax and not Onnx and not Dependency" \
146
+ --make-reports=tests_${{ matrix.config.report }} \
147
+ tests/models tests/schedulers tests/others
148
+
149
+ - name: Run fast Flax TPU tests
150
+ if: ${{ matrix.config.framework == 'flax' }}
151
+ run: |
152
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
153
+ python -m pytest -n 4 --max-worker-restart=0 --dist=loadfile \
154
+ -s -v -k "Flax" \
155
+ --make-reports=tests_${{ matrix.config.report }} \
156
+ tests
157
+
158
+ - name: Run example PyTorch CPU tests
159
+ if: ${{ matrix.config.framework == 'pytorch_examples' }}
160
+ run: |
161
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
162
+ python -m uv pip install peft timm
163
+ python -m pytest -n 4 --max-worker-restart=0 --dist=loadfile \
164
+ --make-reports=tests_${{ matrix.config.report }} \
165
+ examples
166
+
167
+ - name: Failure short reports
168
+ if: ${{ failure() }}
169
+ run: cat reports/tests_${{ matrix.config.report }}_failures_short.txt
170
+
171
+ - name: Test suite reports artifacts
172
+ if: ${{ always() }}
173
+ uses: actions/upload-artifact@v4
174
+ with:
175
+ name: pr_${{ matrix.config.framework }}_${{ matrix.config.report }}_test_reports
176
+ path: reports
177
+
178
+ run_staging_tests:
179
+ needs: [check_code_quality, check_repository_consistency]
180
+ strategy:
181
+ fail-fast: false
182
+ matrix:
183
+ config:
184
+ - name: Hub tests for models, schedulers, and pipelines
185
+ framework: hub_tests_pytorch
186
+ runner:
187
+ group: aws-general-8-plus
188
+ image: diffusers/diffusers-pytorch-cpu
189
+ report: torch_hub
190
+
191
+ name: ${{ matrix.config.name }}
192
+
193
+ runs-on: ${{ matrix.config.runner }}
194
+
195
+ container:
196
+ image: ${{ matrix.config.image }}
197
+ options: --shm-size "16gb" --ipc host -v /mnt/hf_cache:/mnt/cache/
198
+
199
+ defaults:
200
+ run:
201
+ shell: bash
202
+
203
+ steps:
204
+ - name: Checkout diffusers
205
+ uses: actions/checkout@v3
206
+ with:
207
+ fetch-depth: 2
208
+
209
+ - name: Install dependencies
210
+ run: |
211
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
212
+ python -m uv pip install -e [quality,test]
213
+
214
+ - name: Environment
215
+ run: |
216
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
217
+ python utils/print_env.py
218
+
219
+ - name: Run Hub tests for models, schedulers, and pipelines on a staging env
220
+ if: ${{ matrix.config.framework == 'hub_tests_pytorch' }}
221
+ run: |
222
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
223
+ HUGGINGFACE_CO_STAGING=true python -m pytest \
224
+ -m "is_staging_test" \
225
+ --make-reports=tests_${{ matrix.config.report }} \
226
+ tests
227
+
228
+ - name: Failure short reports
229
+ if: ${{ failure() }}
230
+ run: cat reports/tests_${{ matrix.config.report }}_failures_short.txt
231
+
232
+ - name: Test suite reports artifacts
233
+ if: ${{ always() }}
234
+ uses: actions/upload-artifact@v4
235
+ with:
236
+ name: pr_${{ matrix.config.report }}_test_reports
237
+ path: reports
238
+
239
+ run_lora_tests:
240
+ needs: [check_code_quality, check_repository_consistency]
241
+ strategy:
242
+ fail-fast: false
243
+
244
+ name: LoRA tests with PEFT main
245
+
246
+ runs-on:
247
+ group: aws-general-8-plus
248
+
249
+ container:
250
+ image: diffusers/diffusers-pytorch-cpu
251
+ options: --shm-size "16gb" --ipc host -v /mnt/hf_cache:/mnt/cache/
252
+
253
+ defaults:
254
+ run:
255
+ shell: bash
256
+
257
+ steps:
258
+ - name: Checkout diffusers
259
+ uses: actions/checkout@v3
260
+ with:
261
+ fetch-depth: 2
262
+
263
+ - name: Install dependencies
264
+ run: |
265
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
266
+ python -m uv pip install -e [quality,test]
267
+ # TODO (sayakpaul, DN6): revisit `--no-deps`
268
+ python -m pip install -U peft@git+https://github.com/huggingface/peft.git --no-deps
269
+ python -m uv pip install -U transformers@git+https://github.com/huggingface/transformers.git --no-deps
270
+ python -m uv pip install -U tokenizers
271
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git --no-deps
272
+
273
+ - name: Environment
274
+ run: |
275
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
276
+ python utils/print_env.py
277
+
278
+ - name: Run fast PyTorch LoRA tests with PEFT
279
+ run: |
280
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
281
+ python -m pytest -n 4 --max-worker-restart=0 --dist=loadfile \
282
+ -s -v \
283
+ --make-reports=tests_peft_main \
284
+ tests/lora/
285
+ python -m pytest -n 4 --max-worker-restart=0 --dist=loadfile \
286
+ -s -v \
287
+ --make-reports=tests_models_lora_peft_main \
288
+ tests/models/ -k "lora"
289
+
290
+ - name: Failure short reports
291
+ if: ${{ failure() }}
292
+ run: |
293
+ cat reports/tests_lora_failures_short.txt
294
+ cat reports/tests_models_lora_failures_short.txt
295
+
296
+ - name: Test suite reports artifacts
297
+ if: ${{ always() }}
298
+ uses: actions/upload-artifact@v4
299
+ with:
300
+ name: pr_main_test_reports
301
+ path: reports
302
+
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_tests_gpu.yml ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Fast GPU Tests on PR
2
+
3
+ on:
4
+ pull_request:
5
+ branches: main
6
+ paths:
7
+ - "src/diffusers/models/modeling_utils.py"
8
+ - "src/diffusers/models/model_loading_utils.py"
9
+ - "src/diffusers/pipelines/pipeline_utils.py"
10
+ - "src/diffusers/pipeline_loading_utils.py"
11
+ - "src/diffusers/loaders/lora_base.py"
12
+ - "src/diffusers/loaders/lora_pipeline.py"
13
+ - "src/diffusers/loaders/peft.py"
14
+ - "tests/pipelines/test_pipelines_common.py"
15
+ - "tests/models/test_modeling_common.py"
16
+ workflow_dispatch:
17
+
18
+ concurrency:
19
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
20
+ cancel-in-progress: true
21
+
22
+ env:
23
+ DIFFUSERS_IS_CI: yes
24
+ OMP_NUM_THREADS: 8
25
+ MKL_NUM_THREADS: 8
26
+ HF_HUB_ENABLE_HF_TRANSFER: 1
27
+ PYTEST_TIMEOUT: 600
28
+ PIPELINE_USAGE_CUTOFF: 1000000000 # set high cutoff so that only always-test pipelines run
29
+
30
+ jobs:
31
+ check_code_quality:
32
+ runs-on: ubuntu-22.04
33
+ steps:
34
+ - uses: actions/checkout@v3
35
+ - name: Set up Python
36
+ uses: actions/setup-python@v4
37
+ with:
38
+ python-version: "3.8"
39
+ - name: Install dependencies
40
+ run: |
41
+ python -m pip install --upgrade pip
42
+ pip install .[quality]
43
+ - name: Check quality
44
+ run: make quality
45
+ - name: Check if failure
46
+ if: ${{ failure() }}
47
+ run: |
48
+ echo "Quality check failed. Please ensure the right dependency versions are installed with 'pip install -e .[quality]' and run 'make style && make quality'" >> $GITHUB_STEP_SUMMARY
49
+
50
+ check_repository_consistency:
51
+ needs: check_code_quality
52
+ runs-on: ubuntu-22.04
53
+ steps:
54
+ - uses: actions/checkout@v3
55
+ - name: Set up Python
56
+ uses: actions/setup-python@v4
57
+ with:
58
+ python-version: "3.8"
59
+ - name: Install dependencies
60
+ run: |
61
+ python -m pip install --upgrade pip
62
+ pip install .[quality]
63
+ - name: Check repo consistency
64
+ run: |
65
+ python utils/check_copies.py
66
+ python utils/check_dummies.py
67
+ python utils/check_support_list.py
68
+ make deps_table_check_updated
69
+ - name: Check if failure
70
+ if: ${{ failure() }}
71
+ run: |
72
+ echo "Repo consistency check failed. Please ensure the right dependency versions are installed with 'pip install -e .[quality]' and run 'make fix-copies'" >> $GITHUB_STEP_SUMMARY
73
+
74
+ setup_torch_cuda_pipeline_matrix:
75
+ needs: [check_code_quality, check_repository_consistency]
76
+ name: Setup Torch Pipelines CUDA Slow Tests Matrix
77
+ runs-on:
78
+ group: aws-general-8-plus
79
+ container:
80
+ image: diffusers/diffusers-pytorch-cpu
81
+ outputs:
82
+ pipeline_test_matrix: ${{ steps.fetch_pipeline_matrix.outputs.pipeline_test_matrix }}
83
+ steps:
84
+ - name: Checkout diffusers
85
+ uses: actions/checkout@v3
86
+ with:
87
+ fetch-depth: 2
88
+ - name: Install dependencies
89
+ run: |
90
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
91
+ python -m uv pip install -e [quality,test]
92
+ - name: Environment
93
+ run: |
94
+ python utils/print_env.py
95
+ - name: Fetch Pipeline Matrix
96
+ id: fetch_pipeline_matrix
97
+ run: |
98
+ matrix=$(python utils/fetch_torch_cuda_pipeline_test_matrix.py)
99
+ echo $matrix
100
+ echo "pipeline_test_matrix=$matrix" >> $GITHUB_OUTPUT
101
+ - name: Pipeline Tests Artifacts
102
+ if: ${{ always() }}
103
+ uses: actions/upload-artifact@v4
104
+ with:
105
+ name: test-pipelines.json
106
+ path: reports
107
+
108
+ torch_pipelines_cuda_tests:
109
+ name: Torch Pipelines CUDA Tests
110
+ needs: setup_torch_cuda_pipeline_matrix
111
+ strategy:
112
+ fail-fast: false
113
+ max-parallel: 8
114
+ matrix:
115
+ module: ${{ fromJson(needs.setup_torch_cuda_pipeline_matrix.outputs.pipeline_test_matrix) }}
116
+ runs-on:
117
+ group: aws-g4dn-2xlarge
118
+ container:
119
+ image: diffusers/diffusers-pytorch-cuda
120
+ options: --shm-size "16gb" --ipc host --gpus 0
121
+ steps:
122
+ - name: Checkout diffusers
123
+ uses: actions/checkout@v3
124
+ with:
125
+ fetch-depth: 2
126
+
127
+ - name: NVIDIA-SMI
128
+ run: |
129
+ nvidia-smi
130
+ - name: Install dependencies
131
+ run: |
132
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
133
+ python -m uv pip install -e [quality,test]
134
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
135
+ pip uninstall transformers -y && python -m uv pip install -U transformers@git+https://github.com/huggingface/transformers.git --no-deps
136
+
137
+ - name: Environment
138
+ run: |
139
+ python utils/print_env.py
140
+ - name: Extract tests
141
+ id: extract_tests
142
+ run: |
143
+ pattern=$(python utils/extract_tests_from_mixin.py --type pipeline)
144
+ echo "$pattern" > /tmp/test_pattern.txt
145
+ echo "pattern_file=/tmp/test_pattern.txt" >> $GITHUB_OUTPUT
146
+
147
+ - name: PyTorch CUDA checkpoint tests on Ubuntu
148
+ env:
149
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
150
+ # https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms
151
+ CUBLAS_WORKSPACE_CONFIG: :16:8
152
+ run: |
153
+ if [ "${{ matrix.module }}" = "ip_adapters" ]; then
154
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
155
+ -s -v -k "not Flax and not Onnx" \
156
+ --make-reports=tests_pipeline_${{ matrix.module }}_cuda \
157
+ tests/pipelines/${{ matrix.module }}
158
+ else
159
+ pattern=$(cat ${{ steps.extract_tests.outputs.pattern_file }})
160
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
161
+ -s -v -k "not Flax and not Onnx and $pattern" \
162
+ --make-reports=tests_pipeline_${{ matrix.module }}_cuda \
163
+ tests/pipelines/${{ matrix.module }}
164
+ fi
165
+
166
+ - name: Failure short reports
167
+ if: ${{ failure() }}
168
+ run: |
169
+ cat reports/tests_pipeline_${{ matrix.module }}_cuda_stats.txt
170
+ cat reports/tests_pipeline_${{ matrix.module }}_cuda_failures_short.txt
171
+ - name: Test suite reports artifacts
172
+ if: ${{ always() }}
173
+ uses: actions/upload-artifact@v4
174
+ with:
175
+ name: pipeline_${{ matrix.module }}_test_reports
176
+ path: reports
177
+
178
+ torch_cuda_tests:
179
+ name: Torch CUDA Tests
180
+ needs: [check_code_quality, check_repository_consistency]
181
+ runs-on:
182
+ group: aws-g4dn-2xlarge
183
+ container:
184
+ image: diffusers/diffusers-pytorch-cuda
185
+ options: --shm-size "16gb" --ipc host --gpus 0
186
+ defaults:
187
+ run:
188
+ shell: bash
189
+ strategy:
190
+ fail-fast: false
191
+ max-parallel: 2
192
+ matrix:
193
+ module: [models, schedulers, lora, others]
194
+ steps:
195
+ - name: Checkout diffusers
196
+ uses: actions/checkout@v3
197
+ with:
198
+ fetch-depth: 2
199
+
200
+ - name: Install dependencies
201
+ run: |
202
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
203
+ python -m uv pip install -e [quality,test]
204
+ python -m uv pip install peft@git+https://github.com/huggingface/peft.git
205
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
206
+ pip uninstall transformers -y && python -m uv pip install -U transformers@git+https://github.com/huggingface/transformers.git --no-deps
207
+
208
+ - name: Environment
209
+ run: |
210
+ python utils/print_env.py
211
+
212
+ - name: Extract tests
213
+ id: extract_tests
214
+ run: |
215
+ pattern=$(python utils/extract_tests_from_mixin.py --type ${{ matrix.module }})
216
+ echo "$pattern" > /tmp/test_pattern.txt
217
+ echo "pattern_file=/tmp/test_pattern.txt" >> $GITHUB_OUTPUT
218
+
219
+ - name: Run PyTorch CUDA tests
220
+ env:
221
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
222
+ # https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms
223
+ CUBLAS_WORKSPACE_CONFIG: :16:8
224
+ run: |
225
+ pattern=$(cat ${{ steps.extract_tests.outputs.pattern_file }})
226
+ if [ -z "$pattern" ]; then
227
+ python -m pytest -n 1 -sv --max-worker-restart=0 --dist=loadfile -k "not Flax and not Onnx" tests/${{ matrix.module }} \
228
+ --make-reports=tests_torch_cuda_${{ matrix.module }}
229
+ else
230
+ python -m pytest -n 1 -sv --max-worker-restart=0 --dist=loadfile -k "not Flax and not Onnx and $pattern" tests/${{ matrix.module }} \
231
+ --make-reports=tests_torch_cuda_${{ matrix.module }}
232
+ fi
233
+
234
+ - name: Failure short reports
235
+ if: ${{ failure() }}
236
+ run: |
237
+ cat reports/tests_torch_cuda_${{ matrix.module }}_stats.txt
238
+ cat reports/tests_torch_cuda_${{ matrix.module }}_failures_short.txt
239
+
240
+ - name: Test suite reports artifacts
241
+ if: ${{ always() }}
242
+ uses: actions/upload-artifact@v4
243
+ with:
244
+ name: torch_cuda_test_reports_${{ matrix.module }}
245
+ path: reports
246
+
247
+ run_examples_tests:
248
+ name: Examples PyTorch CUDA tests on Ubuntu
249
+ needs: [check_code_quality, check_repository_consistency]
250
+ runs-on:
251
+ group: aws-g4dn-2xlarge
252
+
253
+ container:
254
+ image: diffusers/diffusers-pytorch-cuda
255
+ options: --gpus 0 --shm-size "16gb" --ipc host
256
+ steps:
257
+ - name: Checkout diffusers
258
+ uses: actions/checkout@v3
259
+ with:
260
+ fetch-depth: 2
261
+
262
+ - name: NVIDIA-SMI
263
+ run: |
264
+ nvidia-smi
265
+ - name: Install dependencies
266
+ run: |
267
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
268
+ pip uninstall transformers -y && python -m uv pip install -U transformers@git+https://github.com/huggingface/transformers.git --no-deps
269
+ python -m uv pip install -e [quality,test,training]
270
+
271
+ - name: Environment
272
+ run: |
273
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
274
+ python utils/print_env.py
275
+
276
+ - name: Run example tests on GPU
277
+ env:
278
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
279
+ run: |
280
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
281
+ python -m uv pip install timm
282
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile -s -v --make-reports=examples_torch_cuda examples/
283
+
284
+ - name: Failure short reports
285
+ if: ${{ failure() }}
286
+ run: |
287
+ cat reports/examples_torch_cuda_stats.txt
288
+ cat reports/examples_torch_cuda_failures_short.txt
289
+
290
+ - name: Test suite reports artifacts
291
+ if: ${{ always() }}
292
+ uses: actions/upload-artifact@v4
293
+ with:
294
+ name: examples_test_reports
295
+ path: reports
296
+
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/pr_torch_dependency_test.yml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Torch dependency tests
2
+
3
+ on:
4
+ pull_request:
5
+ branches:
6
+ - main
7
+ paths:
8
+ - "src/diffusers/**.py"
9
+ push:
10
+ branches:
11
+ - main
12
+
13
+ concurrency:
14
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
15
+ cancel-in-progress: true
16
+
17
+ jobs:
18
+ check_torch_dependencies:
19
+ runs-on: ubuntu-22.04
20
+ steps:
21
+ - uses: actions/checkout@v3
22
+ - name: Set up Python
23
+ uses: actions/setup-python@v4
24
+ with:
25
+ python-version: "3.8"
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
29
+ python -m pip install --upgrade pip uv
30
+ python -m uv pip install -e .
31
+ python -m uv pip install torch torchvision torchaudio
32
+ python -m uv pip install pytest
33
+ - name: Check for soft dependencies
34
+ run: |
35
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
36
+ pytest tests/others/test_dependencies.py
tasks/tasksmith-f40a643a6ef9/tests/source/.github/workflows/push_tests.yml ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Fast GPU Tests on main
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ push:
6
+ branches:
7
+ - main
8
+ paths:
9
+ - "src/diffusers/**.py"
10
+ - "examples/**.py"
11
+ - "tests/**.py"
12
+
13
+ env:
14
+ DIFFUSERS_IS_CI: yes
15
+ OMP_NUM_THREADS: 8
16
+ MKL_NUM_THREADS: 8
17
+ HF_HUB_ENABLE_HF_TRANSFER: 1
18
+ PYTEST_TIMEOUT: 600
19
+ PIPELINE_USAGE_CUTOFF: 50000
20
+
21
+ jobs:
22
+ setup_torch_cuda_pipeline_matrix:
23
+ name: Setup Torch Pipelines CUDA Slow Tests Matrix
24
+ runs-on:
25
+ group: aws-general-8-plus
26
+ container:
27
+ image: diffusers/diffusers-pytorch-cpu
28
+ outputs:
29
+ pipeline_test_matrix: ${{ steps.fetch_pipeline_matrix.outputs.pipeline_test_matrix }}
30
+ steps:
31
+ - name: Checkout diffusers
32
+ uses: actions/checkout@v3
33
+ with:
34
+ fetch-depth: 2
35
+ - name: Install dependencies
36
+ run: |
37
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
38
+ python -m uv pip install -e [quality,test]
39
+ - name: Environment
40
+ run: |
41
+ python utils/print_env.py
42
+ - name: Fetch Pipeline Matrix
43
+ id: fetch_pipeline_matrix
44
+ run: |
45
+ matrix=$(python utils/fetch_torch_cuda_pipeline_test_matrix.py)
46
+ echo $matrix
47
+ echo "pipeline_test_matrix=$matrix" >> $GITHUB_OUTPUT
48
+ - name: Pipeline Tests Artifacts
49
+ if: ${{ always() }}
50
+ uses: actions/upload-artifact@v4
51
+ with:
52
+ name: test-pipelines.json
53
+ path: reports
54
+
55
+ torch_pipelines_cuda_tests:
56
+ name: Torch Pipelines CUDA Tests
57
+ needs: setup_torch_cuda_pipeline_matrix
58
+ strategy:
59
+ fail-fast: false
60
+ max-parallel: 8
61
+ matrix:
62
+ module: ${{ fromJson(needs.setup_torch_cuda_pipeline_matrix.outputs.pipeline_test_matrix) }}
63
+ runs-on:
64
+ group: aws-g4dn-2xlarge
65
+ container:
66
+ image: diffusers/diffusers-pytorch-cuda
67
+ options: --shm-size "16gb" --ipc host --gpus 0
68
+ steps:
69
+ - name: Checkout diffusers
70
+ uses: actions/checkout@v3
71
+ with:
72
+ fetch-depth: 2
73
+ - name: NVIDIA-SMI
74
+ run: |
75
+ nvidia-smi
76
+ - name: Install dependencies
77
+ run: |
78
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
79
+ python -m uv pip install -e [quality,test]
80
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
81
+ - name: Environment
82
+ run: |
83
+ python utils/print_env.py
84
+ - name: PyTorch CUDA checkpoint tests on Ubuntu
85
+ env:
86
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
87
+ # https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms
88
+ CUBLAS_WORKSPACE_CONFIG: :16:8
89
+ run: |
90
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
91
+ -s -v -k "not Flax and not Onnx" \
92
+ --make-reports=tests_pipeline_${{ matrix.module }}_cuda \
93
+ tests/pipelines/${{ matrix.module }}
94
+ - name: Failure short reports
95
+ if: ${{ failure() }}
96
+ run: |
97
+ cat reports/tests_pipeline_${{ matrix.module }}_cuda_stats.txt
98
+ cat reports/tests_pipeline_${{ matrix.module }}_cuda_failures_short.txt
99
+ - name: Test suite reports artifacts
100
+ if: ${{ always() }}
101
+ uses: actions/upload-artifact@v4
102
+ with:
103
+ name: pipeline_${{ matrix.module }}_test_reports
104
+ path: reports
105
+
106
+ torch_cuda_tests:
107
+ name: Torch CUDA Tests
108
+ runs-on:
109
+ group: aws-g4dn-2xlarge
110
+ container:
111
+ image: diffusers/diffusers-pytorch-cuda
112
+ options: --shm-size "16gb" --ipc host --gpus 0
113
+ defaults:
114
+ run:
115
+ shell: bash
116
+ strategy:
117
+ fail-fast: false
118
+ max-parallel: 2
119
+ matrix:
120
+ module: [models, schedulers, lora, others, single_file]
121
+ steps:
122
+ - name: Checkout diffusers
123
+ uses: actions/checkout@v3
124
+ with:
125
+ fetch-depth: 2
126
+
127
+ - name: Install dependencies
128
+ run: |
129
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
130
+ python -m uv pip install -e [quality,test]
131
+ python -m uv pip install peft@git+https://github.com/huggingface/peft.git
132
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
133
+
134
+ - name: Environment
135
+ run: |
136
+ python utils/print_env.py
137
+
138
+ - name: Run PyTorch CUDA tests
139
+ env:
140
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
141
+ # https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms
142
+ CUBLAS_WORKSPACE_CONFIG: :16:8
143
+ run: |
144
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
145
+ -s -v -k "not Flax and not Onnx" \
146
+ --make-reports=tests_torch_cuda_${{ matrix.module }} \
147
+ tests/${{ matrix.module }}
148
+
149
+ - name: Failure short reports
150
+ if: ${{ failure() }}
151
+ run: |
152
+ cat reports/tests_torch_cuda_${{ matrix.module }}_stats.txt
153
+ cat reports/tests_torch_cuda_${{ matrix.module }}_failures_short.txt
154
+
155
+ - name: Test suite reports artifacts
156
+ if: ${{ always() }}
157
+ uses: actions/upload-artifact@v4
158
+ with:
159
+ name: torch_cuda_test_reports_${{ matrix.module }}
160
+ path: reports
161
+
162
+ flax_tpu_tests:
163
+ name: Flax TPU Tests
164
+ runs-on:
165
+ group: gcp-ct5lp-hightpu-8t
166
+ container:
167
+ image: diffusers/diffusers-flax-tpu
168
+ options: --shm-size "16gb" --ipc host --privileged ${{ vars.V5_LITEPOD_8_ENV}} -v /mnt/hf_cache:/mnt/hf_cache
169
+ defaults:
170
+ run:
171
+ shell: bash
172
+ steps:
173
+ - name: Checkout diffusers
174
+ uses: actions/checkout@v3
175
+ with:
176
+ fetch-depth: 2
177
+
178
+ - name: Install dependencies
179
+ run: |
180
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
181
+ python -m uv pip install -e [quality,test]
182
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
183
+
184
+ - name: Environment
185
+ run: |
186
+ python utils/print_env.py
187
+
188
+ - name: Run Flax TPU tests
189
+ env:
190
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
191
+ run: |
192
+ python -m pytest -n 0 \
193
+ -s -v -k "Flax" \
194
+ --make-reports=tests_flax_tpu \
195
+ tests/
196
+
197
+ - name: Failure short reports
198
+ if: ${{ failure() }}
199
+ run: |
200
+ cat reports/tests_flax_tpu_stats.txt
201
+ cat reports/tests_flax_tpu_failures_short.txt
202
+
203
+ - name: Test suite reports artifacts
204
+ if: ${{ always() }}
205
+ uses: actions/upload-artifact@v4
206
+ with:
207
+ name: flax_tpu_test_reports
208
+ path: reports
209
+
210
+ onnx_cuda_tests:
211
+ name: ONNX CUDA Tests
212
+ runs-on:
213
+ group: aws-g4dn-2xlarge
214
+ container:
215
+ image: diffusers/diffusers-onnxruntime-cuda
216
+ options: --shm-size "16gb" --ipc host -v /mnt/cache/.cache/huggingface:/mnt/cache/ --gpus 0
217
+ defaults:
218
+ run:
219
+ shell: bash
220
+ steps:
221
+ - name: Checkout diffusers
222
+ uses: actions/checkout@v3
223
+ with:
224
+ fetch-depth: 2
225
+
226
+ - name: Install dependencies
227
+ run: |
228
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
229
+ python -m uv pip install -e [quality,test]
230
+ pip uninstall accelerate -y && python -m uv pip install -U accelerate@git+https://github.com/huggingface/accelerate.git
231
+
232
+ - name: Environment
233
+ run: |
234
+ python utils/print_env.py
235
+
236
+ - name: Run ONNXRuntime CUDA tests
237
+ env:
238
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
239
+ run: |
240
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile \
241
+ -s -v -k "Onnx" \
242
+ --make-reports=tests_onnx_cuda \
243
+ tests/
244
+
245
+ - name: Failure short reports
246
+ if: ${{ failure() }}
247
+ run: |
248
+ cat reports/tests_onnx_cuda_stats.txt
249
+ cat reports/tests_onnx_cuda_failures_short.txt
250
+
251
+ - name: Test suite reports artifacts
252
+ if: ${{ always() }}
253
+ uses: actions/upload-artifact@v4
254
+ with:
255
+ name: onnx_cuda_test_reports
256
+ path: reports
257
+
258
+ run_torch_compile_tests:
259
+ name: PyTorch Compile CUDA tests
260
+
261
+ runs-on:
262
+ group: aws-g4dn-2xlarge
263
+
264
+ container:
265
+ image: diffusers/diffusers-pytorch-compile-cuda
266
+ options: --gpus 0 --shm-size "16gb" --ipc host
267
+
268
+ steps:
269
+ - name: Checkout diffusers
270
+ uses: actions/checkout@v3
271
+ with:
272
+ fetch-depth: 2
273
+
274
+ - name: NVIDIA-SMI
275
+ run: |
276
+ nvidia-smi
277
+ - name: Install dependencies
278
+ run: |
279
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
280
+ python -m uv pip install -e [quality,test,training]
281
+ - name: Environment
282
+ run: |
283
+ python utils/print_env.py
284
+ - name: Run example tests on GPU
285
+ env:
286
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
287
+ RUN_COMPILE: yes
288
+ run: |
289
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile -s -v -k "compile" --make-reports=tests_torch_compile_cuda tests/
290
+ - name: Failure short reports
291
+ if: ${{ failure() }}
292
+ run: cat reports/tests_torch_compile_cuda_failures_short.txt
293
+
294
+ - name: Test suite reports artifacts
295
+ if: ${{ always() }}
296
+ uses: actions/upload-artifact@v4
297
+ with:
298
+ name: torch_compile_test_reports
299
+ path: reports
300
+
301
+ run_xformers_tests:
302
+ name: PyTorch xformers CUDA tests
303
+
304
+ runs-on:
305
+ group: aws-g4dn-2xlarge
306
+
307
+ container:
308
+ image: diffusers/diffusers-pytorch-xformers-cuda
309
+ options: --gpus 0 --shm-size "16gb" --ipc host
310
+
311
+ steps:
312
+ - name: Checkout diffusers
313
+ uses: actions/checkout@v3
314
+ with:
315
+ fetch-depth: 2
316
+
317
+ - name: NVIDIA-SMI
318
+ run: |
319
+ nvidia-smi
320
+ - name: Install dependencies
321
+ run: |
322
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
323
+ python -m uv pip install -e [quality,test,training]
324
+ - name: Environment
325
+ run: |
326
+ python utils/print_env.py
327
+ - name: Run example tests on GPU
328
+ env:
329
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
330
+ run: |
331
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile -s -v -k "xformers" --make-reports=tests_torch_xformers_cuda tests/
332
+ - name: Failure short reports
333
+ if: ${{ failure() }}
334
+ run: cat reports/tests_torch_xformers_cuda_failures_short.txt
335
+
336
+ - name: Test suite reports artifacts
337
+ if: ${{ always() }}
338
+ uses: actions/upload-artifact@v4
339
+ with:
340
+ name: torch_xformers_test_reports
341
+ path: reports
342
+
343
+ run_examples_tests:
344
+ name: Examples PyTorch CUDA tests on Ubuntu
345
+
346
+ runs-on:
347
+ group: aws-g4dn-2xlarge
348
+
349
+ container:
350
+ image: diffusers/diffusers-pytorch-cuda
351
+ options: --gpus 0 --shm-size "16gb" --ipc host
352
+ steps:
353
+ - name: Checkout diffusers
354
+ uses: actions/checkout@v3
355
+ with:
356
+ fetch-depth: 2
357
+
358
+ - name: NVIDIA-SMI
359
+ run: |
360
+ nvidia-smi
361
+ - name: Install dependencies
362
+ run: |
363
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
364
+ python -m uv pip install -e [quality,test,training]
365
+
366
+ - name: Environment
367
+ run: |
368
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
369
+ python utils/print_env.py
370
+
371
+ - name: Run example tests on GPU
372
+ env:
373
+ HF_TOKEN: ${{ secrets.DIFFUSERS_HF_HUB_READ_TOKEN }}
374
+ run: |
375
+ python -m venv /opt/venv && export PATH="/opt/venv/bin:$PATH"
376
+ python -m uv pip install timm
377
+ python -m pytest -n 1 --max-worker-restart=0 --dist=loadfile -s -v --make-reports=examples_torch_cuda examples/
378
+
379
+ - name: Failure short reports
380
+ if: ${{ failure() }}
381
+ run: |
382
+ cat reports/examples_torch_cuda_stats.txt
383
+ cat reports/examples_torch_cuda_failures_short.txt
384
+
385
+ - name: Test suite reports artifacts
386
+ if: ${{ always() }}
387
+ uses: actions/upload-artifact@v4
388
+ with:
389
+ name: examples_test_reports
390
+ path: reports