diffusers-workflow 0.4.0a3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. diffusers_workflow-0.4.0a3.dist-info/METADATA +310 -0
  2. diffusers_workflow-0.4.0a3.dist-info/RECORD +171 -0
  3. diffusers_workflow-0.4.0a3.dist-info/WHEEL +5 -0
  4. diffusers_workflow-0.4.0a3.dist-info/entry_points.txt +6 -0
  5. diffusers_workflow-0.4.0a3.dist-info/licenses/LICENSE +201 -0
  6. diffusers_workflow-0.4.0a3.dist-info/top_level.txt +1 -0
  7. dw/__init__.py +353 -0
  8. dw/arguments.py +906 -0
  9. dw/cache_blocks.json +16 -0
  10. dw/cache_blocks.py +145 -0
  11. dw/community_pipelines/pipeline_flux_rf_inversion.py +1184 -0
  12. dw/events.py +78 -0
  13. dw/hub_cache.py +289 -0
  14. dw/introspection.py +458 -0
  15. dw/log_setup.py +45 -0
  16. dw/pipeline_processors/chain.py +750 -0
  17. dw/pipeline_processors/config_objects.py +235 -0
  18. dw/pipeline_processors/pipeline.py +1687 -0
  19. dw/pipeline_processors/remote.py +18 -0
  20. dw/previous_results.py +259 -0
  21. dw/prompt_weighting.py +378 -0
  22. dw/repl.py +298 -0
  23. dw/repl_commands.py +808 -0
  24. dw/repl_worker.py +129 -0
  25. dw/result.py +850 -0
  26. dw/run.py +92 -0
  27. dw/schema.py +24 -0
  28. dw/security.py +379 -0
  29. dw/serve.py +70 -0
  30. dw/server/__init__.py +2 -0
  31. dw/server/app.py +588 -0
  32. dw/server/jobs.py +547 -0
  33. dw/server/ui/assets/abap-08VXUWAP.js +1 -0
  34. dw/server/ui/assets/apex-BWPQTe0t.js +1 -0
  35. dw/server/ui/assets/azcli-Bc_sGQ0U.js +1 -0
  36. dw/server/ui/assets/bat-i0X4ZdIN.js +1 -0
  37. dw/server/ui/assets/bicep-B5-_aFwp.js +2 -0
  38. dw/server/ui/assets/cameligo-DMUM7wLl.js +1 -0
  39. dw/server/ui/assets/clojure-Cm7r79vr.js +1 -0
  40. dw/server/ui/assets/codicon-Brq4_Ui5.ttf +0 -0
  41. dw/server/ui/assets/coffee-Ba7i2nA0.js +1 -0
  42. dw/server/ui/assets/cpp-C7h46wYY.js +1 -0
  43. dw/server/ui/assets/csharp-BKxtCVv1.js +1 -0
  44. dw/server/ui/assets/csp-bTuwJoIa.js +1 -0
  45. dw/server/ui/assets/css-DIMkf-bt.js +3 -0
  46. dw/server/ui/assets/css.worker-B3ciXF_0.js +93 -0
  47. dw/server/ui/assets/cssMode-CEh6hWi2.js +1 -0
  48. dw/server/ui/assets/cypher-CVaqCwHa.js +1 -0
  49. dw/server/ui/assets/dart-onAF5SnQ.js +1 -0
  50. dw/server/ui/assets/dockerfile-DZFCIeNp.js +1 -0
  51. dw/server/ui/assets/ecl-D05T4iGw.js +1 -0
  52. dw/server/ui/assets/editor-jjEx9u7D.css +1 -0
  53. dw/server/ui/assets/editor.api-CExg3_mM.js +847 -0
  54. dw/server/ui/assets/editor.worker-q-txB4vs.js +30 -0
  55. dw/server/ui/assets/elixir-6RTg0lbw.js +1 -0
  56. dw/server/ui/assets/flow9-C5_-GSwl.js +1 -0
  57. dw/server/ui/assets/freemarker2-DH6orYh2.js +3 -0
  58. dw/server/ui/assets/fsharp-C8Ef5oNN.js +1 -0
  59. dw/server/ui/assets/go-C-y9NEjX.js +1 -0
  60. dw/server/ui/assets/graphql-fmXr3nnJ.js +1 -0
  61. dw/server/ui/assets/handlebars-CbrMVW4Q.js +1 -0
  62. dw/server/ui/assets/hcl-CpzslTdj.js +1 -0
  63. dw/server/ui/assets/html-YDNPZw2M.js +1 -0
  64. dw/server/ui/assets/html.worker-C93Ht9o9.js +506 -0
  65. dw/server/ui/assets/htmlMode-B_zSGWO2.js +1 -0
  66. dw/server/ui/assets/index-B7-VcYS-.css +1 -0
  67. dw/server/ui/assets/index-D_EiPU3b.js +13 -0
  68. dw/server/ui/assets/ini-sBoK_t0W.js +1 -0
  69. dw/server/ui/assets/java-BEtHBSE6.js +1 -0
  70. dw/server/ui/assets/javascript-dYuBvioq.js +1 -0
  71. dw/server/ui/assets/json.worker-B2V3pomh.js +62 -0
  72. dw/server/ui/assets/jsonMode-CUqLM39V.js +7 -0
  73. dw/server/ui/assets/julia-Bri6UV-V.js +1 -0
  74. dw/server/ui/assets/kotlin-BOotOW0E.js +1 -0
  75. dw/server/ui/assets/less-B9JPFI3C.js +2 -0
  76. dw/server/ui/assets/lexon-CfSJPG6W.js +1 -0
  77. dw/server/ui/assets/liquid-D6vxBzMv.js +1 -0
  78. dw/server/ui/assets/lspLanguageFeatures-1WJ2palX.js +4 -0
  79. dw/server/ui/assets/lua-CsQS60Ue.js +1 -0
  80. dw/server/ui/assets/m3-D-oSqn_W.js +1 -0
  81. dw/server/ui/assets/markdown-Cimd5fb3.js +1 -0
  82. dw/server/ui/assets/mdx-SHQb6vmD.js +1 -0
  83. dw/server/ui/assets/mips-CIPQ_RoX.js +1 -0
  84. dw/server/ui/assets/monaco--ixms01u.css +1 -0
  85. dw/server/ui/assets/monaco-CP-s5rcP.js +56 -0
  86. dw/server/ui/assets/msdax-DauUninz.js +1 -0
  87. dw/server/ui/assets/mysql-SOo6toE5.js +1 -0
  88. dw/server/ui/assets/objective-c-FvmIjYaQ.js +1 -0
  89. dw/server/ui/assets/pascal-DrH0SRf2.js +1 -0
  90. dw/server/ui/assets/pascaligo-D-ptJ9y-.js +1 -0
  91. dw/server/ui/assets/perl-oz_6vUea.js +1 -0
  92. dw/server/ui/assets/pgsql-DTj74zXo.js +1 -0
  93. dw/server/ui/assets/php-nr791fC2.js +1 -0
  94. dw/server/ui/assets/pla-CopQ2nXW.js +1 -0
  95. dw/server/ui/assets/postiats-43DmfD33.js +1 -0
  96. dw/server/ui/assets/powerquery-D3hlyOfw.js +1 -0
  97. dw/server/ui/assets/powershell-DmHpPYUd.js +1 -0
  98. dw/server/ui/assets/protobuf-C531GsRP.js +2 -0
  99. dw/server/ui/assets/pug-Z5eAx3Zn.js +1 -0
  100. dw/server/ui/assets/python-x0_EGHq9.js +1 -0
  101. dw/server/ui/assets/qsharp-DkqhCAOL.js +1 -0
  102. dw/server/ui/assets/r-BwWrilGY.js +1 -0
  103. dw/server/ui/assets/razor-BZC4LQDP.js +1 -0
  104. dw/server/ui/assets/redis-ClamHrr6.js +1 -0
  105. dw/server/ui/assets/redshift-DT7zqm-g.js +1 -0
  106. dw/server/ui/assets/restructuredtext-BYgofb2h.js +1 -0
  107. dw/server/ui/assets/ruby-DezsRK8O.js +1 -0
  108. dw/server/ui/assets/rust-DdL9SqIa.js +1 -0
  109. dw/server/ui/assets/sb-CcwsVR0C.js +1 -0
  110. dw/server/ui/assets/scala-DHpiXF5c.js +1 -0
  111. dw/server/ui/assets/scheme-BeGwcela.js +1 -0
  112. dw/server/ui/assets/scss-gp-XZpBa.js +3 -0
  113. dw/server/ui/assets/shell-CC2rA5mh.js +1 -0
  114. dw/server/ui/assets/solidity-BEEn4gHE.js +1 -0
  115. dw/server/ui/assets/sophia-CRfGWb83.js +1 -0
  116. dw/server/ui/assets/sparql-D_Lu-MrJ.js +1 -0
  117. dw/server/ui/assets/sql-NEE52Syq.js +1 -0
  118. dw/server/ui/assets/st-DbInun42.js +1 -0
  119. dw/server/ui/assets/swift-Bxkupp3x.js +1 -0
  120. dw/server/ui/assets/systemverilog-Bz4Y3fRF.js +1 -0
  121. dw/server/ui/assets/tcl-DISqw1ZD.js +1 -0
  122. dw/server/ui/assets/ts.worker-D7T1-Ig5.js +67738 -0
  123. dw/server/ui/assets/tsMode-BTfA6SbD.js +11 -0
  124. dw/server/ui/assets/twig-De2hgUGE.js +1 -0
  125. dw/server/ui/assets/typescript-CWA4MsNk.js +1 -0
  126. dw/server/ui/assets/typespec-B8J7ngcE.js +1 -0
  127. dw/server/ui/assets/vb-DV3o63ZY.js +1 -0
  128. dw/server/ui/assets/wgsl-DpFanUEy.js +298 -0
  129. dw/server/ui/assets/workers-CWU0uvj5.js +1 -0
  130. dw/server/ui/assets/xml-KmfTm3rg.js +1 -0
  131. dw/server/ui/assets/yaml-nFO_dDS6.js +1 -0
  132. dw/server/ui/index.html +17 -0
  133. dw/settings.py +77 -0
  134. dw/step.py +132 -0
  135. dw/tasks/audio_utils.py +266 -0
  136. dw/tasks/background_remover.py +43 -0
  137. dw/tasks/borders.py +113 -0
  138. dw/tasks/concat_videos.py +80 -0
  139. dw/tasks/depth_estimator.py +54 -0
  140. dw/tasks/diffusion_upscale.py +109 -0
  141. dw/tasks/format_messages.py +24 -0
  142. dw/tasks/gather.py +139 -0
  143. dw/tasks/image_to_text.py +43 -0
  144. dw/tasks/image_utils.py +661 -0
  145. dw/tasks/interpolate_frames.py +227 -0
  146. dw/tasks/model_cache.py +39 -0
  147. dw/tasks/pair_audio.py +58 -0
  148. dw/tasks/qr_code.py +19 -0
  149. dw/tasks/restore_faces.py +175 -0
  150. dw/tasks/rife_model.py +192 -0
  151. dw/tasks/segment.py +121 -0
  152. dw/tasks/task.py +474 -0
  153. dw/tasks/tensor_image.py +57 -0
  154. dw/tasks/text_generation.py +168 -0
  155. dw/tasks/text_sections.py +80 -0
  156. dw/tasks/upscale.py +203 -0
  157. dw/tasks/video_utils.py +154 -0
  158. dw/tasks/zoe_depth.py +71 -0
  159. dw/teacache.py +376 -0
  160. dw/teacache_models.json +99 -0
  161. dw/test.py +29 -0
  162. dw/type_helpers.py +68 -0
  163. dw/validate.py +43 -0
  164. dw/variables.py +153 -0
  165. dw/worker.py +517 -0
  166. dw/workflow.py +553 -0
  167. dw/workflow_schema.json +1157 -0
  168. dw/workflows/augment_prompt.json +65 -0
  169. dw/workflows/describe_image.json +58 -0
  170. dw/workflows/h3_context_ir.json +57 -0
  171. dw/workflows/test.json +31 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
dw/__init__.py ADDED
@@ -0,0 +1,353 @@
1
+ from .settings import resolve_path, load_settings
2
+ from .log_setup import setup_logging
3
+ import os
4
+ import re
5
+ import logging
6
+ import warnings
7
+ from dotenv import load_dotenv
8
+
9
+ load_dotenv() # Loads .env from current directory
10
+
11
+ # Allow MPS to use all available unified memory by default
12
+ # This prevents "MPS backend out of memory" errors with large models
13
+ # Users can override by setting these env vars before import
14
+ if "PYTORCH_MPS_HIGH_WATERMARK_RATIO" not in os.environ:
15
+ os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] = "0.0"
16
+
17
+ # Let the CUDA allocator grow segments instead of fragmenting fixed-size ones.
18
+ # Multi-step workflows churn differently-shaped allocations (generate, upscale,
19
+ # interpolate), and fragmentation is what OOMs a card that nominally has room
20
+ if "PYTORCH_CUDA_ALLOC_CONF" not in os.environ:
21
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
22
+
23
+ # Load sharded checkpoints in parallel - a pure cold-start win
24
+ if "HF_ENABLE_PARALLEL_LOADING" not in os.environ:
25
+ os.environ["HF_ENABLE_PARALLEL_LOADING"] = "true"
26
+
27
+ # Suppress all common library warnings before any imports
28
+ warnings.filterwarnings("ignore", category=FutureWarning)
29
+ warnings.filterwarnings("ignore", category=UserWarning)
30
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
31
+
32
+ # Lazy import torch to avoid import errors when torch isn't available
33
+ # (e.g., when using system Python instead of venv)
34
+ try:
35
+ import torch
36
+ import diffusers
37
+ from packaging import version
38
+
39
+ _TORCH_AVAILABLE = True
40
+ except ImportError as e:
41
+ _TORCH_AVAILABLE = False
42
+ _TORCH_IMPORT_ERROR = e
43
+ # Create dummy objects to prevent AttributeError
44
+ torch = None
45
+ diffusers = None
46
+ version = None
47
+
48
+
49
+ def _read_version():
50
+ # Single-sourced from pyproject.toml. Read as text rather than TOML:
51
+ # tomllib is 3.11+ and this project supports 3.10. In a wheel install
52
+ # there is no pyproject on disk - the package metadata carries it.
53
+ try:
54
+ pyproject = os.path.join(os.path.dirname(__file__), "..", "pyproject.toml")
55
+ with open(pyproject, encoding="utf-8") as f:
56
+ match = re.search(r'^version = "([^"]+)"$', f.read(), re.MULTILINE)
57
+ if match:
58
+ return match.group(1)
59
+ except OSError:
60
+ pass
61
+ try:
62
+ from importlib.metadata import version
63
+
64
+ return version("diffusers-workflow")
65
+ except Exception:
66
+ return "unknown"
67
+
68
+
69
+ __version__ = _read_version()
70
+
71
+ settings = load_settings()
72
+
73
+
74
+ def detect_device():
75
+ """
76
+ Detect the best device available on this machine.
77
+ Priority: CUDA > MPS > CPU
78
+
79
+ Returns:
80
+ str: Device identifier ('cuda', 'mps', or 'cpu')
81
+ """
82
+ if not _TORCH_AVAILABLE:
83
+ return "cpu"
84
+
85
+ if torch.cuda.is_available():
86
+ return "cuda"
87
+
88
+ if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
89
+ return "mps"
90
+
91
+ return "cpu"
92
+
93
+
94
+ def get_device():
95
+ """
96
+ Get the device to run on.
97
+
98
+ An explicit choice wins over detection - the DW_DEVICE environment variable for a
99
+ single run, or the 'device' setting for a standing one. Either can name a specific
100
+ accelerator ('cuda:1'), force a CPU run to rule out a GPU-specific problem, or pin
101
+ a machine that has both to one backend.
102
+
103
+ Returns:
104
+ str: Device identifier ('cuda', 'cuda:1', 'mps', 'cpu', ...)
105
+ """
106
+ if not _TORCH_AVAILABLE:
107
+ return "cpu"
108
+
109
+ configured_device = os.environ.get("DW_DEVICE") or settings.device
110
+ if configured_device:
111
+ try:
112
+ # Only checks that torch understands the name - whether the machine has
113
+ # that device surfaces when a model is loaded onto it
114
+ torch.device(configured_device)
115
+ return configured_device
116
+ except (RuntimeError, TypeError, ValueError) as e:
117
+ logging.warning(f"Ignoring invalid configured device: {e}")
118
+
119
+ return detect_device()
120
+
121
+
122
+ def get_device_type(device=None):
123
+ """
124
+ Get the backend a device belongs to - 'cuda' for 'cuda:1', 'mps' for 'mps'.
125
+
126
+ A device identifier can carry an index, so comparisons against a backend name have
127
+ to be made on the type alone or a device like 'cuda:1' matches nothing.
128
+
129
+ Args:
130
+ device: Device identifier, or None to use the device dw is running on
131
+
132
+ Returns:
133
+ str: Backend name ('cuda', 'mps', 'xpu', 'cpu', ...)
134
+ """
135
+ if not _TORCH_AVAILABLE:
136
+ return "cpu"
137
+
138
+ return torch.device(device if device is not None else get_device()).type
139
+
140
+
141
+ def get_autocast_device_type():
142
+ """
143
+ Get the device type to use for torch.autocast.
144
+ MPS doesn't support autocast, so use 'cpu' for MPS devices.
145
+
146
+ Returns:
147
+ str: Device type for autocast ('cuda' or 'cpu')
148
+ """
149
+ if get_device_type() == "cuda":
150
+ return "cuda"
151
+
152
+ # MPS and CPU both use 'cpu' for autocast
153
+ return "cpu"
154
+
155
+
156
+ def preferred_task_dtype(device=None):
157
+ """
158
+ Get the preferred torch dtype for a lightweight inference task (captioning,
159
+ text generation, diffusion upscaling, depth estimation).
160
+
161
+ fp16 produces NaN values on MPS and is unsupported by many CPU operations,
162
+ so only CUDA gets it - everything else runs in fp32.
163
+
164
+ Args:
165
+ device: Device identifier, or None to use the device dw is running on
166
+
167
+ Returns:
168
+ torch.dtype: torch.float16 on CUDA, torch.float32 otherwise (or None
169
+ if torch isn't available)
170
+ """
171
+ if not _TORCH_AVAILABLE:
172
+ return None
173
+
174
+ return torch.float16 if get_device_type(device) == "cuda" else torch.float32
175
+
176
+
177
+ def empty_device_cache(synchronize=False):
178
+ """
179
+ Empty the allocator cache of the device dw is configured for, if its
180
+ backend has one. A no-op on CPU.
181
+
182
+ Dispatch honors the DW_DEVICE/settings override (via get_device_type())
183
+ but also checks the backend's own availability before calling into it,
184
+ matching the belt-and-suspenders checks the call sites used to do
185
+ individually.
186
+
187
+ Args:
188
+ synchronize: Also block until pending device work completes before
189
+ returning. Skipped by default - it's expensive and callers on a
190
+ hot path (e.g. between-run cleanup) don't need it.
191
+ """
192
+ if not _TORCH_AVAILABLE:
193
+ return
194
+
195
+ device_type = get_device_type()
196
+ if device_type == "cuda" and torch.cuda.is_available():
197
+ torch.cuda.empty_cache()
198
+ if synchronize:
199
+ torch.cuda.synchronize()
200
+ elif (
201
+ device_type == "mps"
202
+ and hasattr(torch.backends, "mps")
203
+ and torch.backends.mps.is_available()
204
+ ):
205
+ if hasattr(torch.mps, "empty_cache"):
206
+ torch.mps.empty_cache()
207
+ if synchronize and hasattr(torch.mps, "synchronize"):
208
+ torch.mps.synchronize()
209
+
210
+
211
+ def device_memory_stats():
212
+ """
213
+ Snapshot of allocator memory usage for the device dw is configured for.
214
+
215
+ Only CUDA exposes free/total figures (via torch.cuda.mem_get_info); MPS
216
+ has no equivalent API, so its snapshot reports zeroed, "known" values
217
+ instead. CPU, or a CUDA/MPS backend that isn't actually available despite
218
+ being the configured device type, results in an "unavailable" snapshot.
219
+
220
+ Returns:
221
+ dict with keys:
222
+ available (bool): whether the backend could be queried
223
+ device_name (str or None)
224
+ allocated_mb (float)
225
+ reserved_mb (float)
226
+ free_mb (float or None): None only when CUDA's mem_get_info call
227
+ itself fails
228
+ total_mb (float or None): None only when CUDA's mem_get_info call
229
+ itself fails
230
+ """
231
+ stats = {
232
+ "available": False,
233
+ "device_name": None,
234
+ "allocated_mb": 0.0,
235
+ "reserved_mb": 0.0,
236
+ "free_mb": None,
237
+ "total_mb": None,
238
+ }
239
+
240
+ if not _TORCH_AVAILABLE:
241
+ return stats
242
+
243
+ device_type = get_device_type()
244
+ if device_type == "cuda" and torch.cuda.is_available():
245
+ stats["available"] = True
246
+ stats["device_name"] = torch.cuda.get_device_name(0)
247
+ stats["allocated_mb"] = torch.cuda.memory_allocated() / 1024 / 1024
248
+ stats["reserved_mb"] = torch.cuda.memory_reserved() / 1024 / 1024
249
+ try:
250
+ free, total = torch.cuda.mem_get_info()
251
+ stats["free_mb"] = free / 1024 / 1024
252
+ stats["total_mb"] = total / 1024 / 1024
253
+ except (RuntimeError, AttributeError):
254
+ pass
255
+ elif (
256
+ device_type == "mps"
257
+ and hasattr(torch.backends, "mps")
258
+ and torch.backends.mps.is_available()
259
+ ):
260
+ # MPS doesn't provide detailed memory stats like CUDA
261
+ stats["available"] = True
262
+ stats["device_name"] = "Apple Silicon (MPS)"
263
+ stats["free_mb"] = 0.0
264
+ stats["total_mb"] = 0.0
265
+
266
+ return stats
267
+
268
+
269
+ def startup(log_level=None):
270
+ if not _TORCH_AVAILABLE:
271
+ raise ImportError(
272
+ f"PyTorch is not available. {_TORCH_IMPORT_ERROR}\n"
273
+ "Please ensure you're using the virtual environment where torch is installed.\n"
274
+ "Activate the venv: source venv/bin/activate"
275
+ )
276
+
277
+ # The default torch device is deliberately left alone. Diffusers loads weights into
278
+ # system memory and then places them - moving them to the device, or hooking them
279
+ # for offloading. A default device of 'cuda' pre-empts that by building every module
280
+ # directly in VRAM, which runs a large pipeline out of memory before its offload
281
+ # hooks are ever installed. Device placement is explicit throughout dw instead.
282
+ device = get_device()
283
+ device_type = get_device_type(device)
284
+
285
+ # MPS-specific configuration (Apple Silicon)
286
+ if device_type == "mps":
287
+ # Suppress autocast warnings (MPS doesn't support autocast,
288
+ # and libraries may try to use it with 'cuda' device_type)
289
+ warnings.filterwarnings(
290
+ "ignore",
291
+ message=".*User provided device_type of 'cuda'.*",
292
+ category=UserWarning,
293
+ module="torch.amp.autocast_mode",
294
+ )
295
+
296
+ logging.info(
297
+ f"MPS backend - watermark ratio: "
298
+ f"{os.environ.get('PYTORCH_MPS_HIGH_WATERMARK_RATIO', 'default')}"
299
+ )
300
+
301
+ # Check if we have a GPU backend (CUDA or MPS)
302
+ if device_type == "cpu":
303
+ logging.warning(
304
+ "No GPU backend available (CUDA or MPS). Running on CPU may be slow."
305
+ )
306
+
307
+ if version.parse(torch.__version__) < version.parse("2.0.0"):
308
+ raise Exception(
309
+ f"Pytorch must be 2.0 or greater (found {torch.__version__}). Run install script. Quitting."
310
+ )
311
+
312
+ if log_level is not None:
313
+ settings.log_level = log_level
314
+
315
+ setup_logging(
316
+ resolve_path(settings.log_filename),
317
+ settings.log_level,
318
+ log_to_console=settings.log_to_console,
319
+ )
320
+
321
+ logging.info(f"Version {__version__}")
322
+ logging.debug(f"Torch version {torch.__version__}")
323
+ logging.info(f"Using device: {device}")
324
+
325
+ diffusers.logging.set_verbosity_error()
326
+
327
+ # TF32 optimization (Ampere+ GPUs: RTX 30/40 series, A100, H100)
328
+ # Provides ~2x speedup for matmul operations with minimal precision loss
329
+ if settings.enable_tf32:
330
+ torch.set_float32_matmul_precision("high")
331
+ if device_type == "cuda":
332
+ torch.backends.cuda.matmul.allow_tf32 = True
333
+ logging.debug("TF32 precision enabled for faster matmul operations")
334
+ else:
335
+ logging.debug("TF32 precision disabled (full FP32 precision)")
336
+
337
+ # CUDA-specific optimizations
338
+ if device_type == "cuda":
339
+ # cuDNN autotuner - benchmarks algorithms and selects fastest
340
+ # Best for fixed input sizes, may slow down variable-size workflows
341
+ torch.backends.cudnn.benchmark = settings.cudnn_benchmark
342
+
343
+ # Always enable cuDNN (default anyway)
344
+ torch.backends.cudnn.enabled = True
345
+
346
+ # Deterministic mode - set True for reproducibility (same seed = same output)
347
+ # False prioritizes performance over strict reproducibility
348
+ torch.backends.cudnn.deterministic = settings.cudnn_deterministic
349
+
350
+ logging.debug(
351
+ f"CUDA optimizations - benchmark: {settings.cudnn_benchmark}, "
352
+ f"deterministic: {settings.cudnn_deterministic}"
353
+ )