mflux-teacache 0.1.0__tar.gz
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.
- mflux_teacache-0.1.0/LICENSE +201 -0
- mflux_teacache-0.1.0/NOTICE +41 -0
- mflux_teacache-0.1.0/PKG-INFO +158 -0
- mflux_teacache-0.1.0/README.md +130 -0
- mflux_teacache-0.1.0/pyproject.toml +101 -0
- mflux_teacache-0.1.0/src/mflux/extras/teacache/__init__.py +8 -0
- mflux_teacache-0.1.0/src/mflux/extras/teacache/_core.py +261 -0
- mflux_teacache-0.1.0/src/mflux/extras/teacache/z_image.py +78 -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 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 type. We 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 2026 Denis Ineshin
|
|
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.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
mflux-teacache
|
|
2
|
+
Copyright 2026 Denis Ineshin and the mflux-teacache contributors
|
|
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
|
+
------------------------------------------------------------------------------
|
|
11
|
+
Third-party attributions
|
|
12
|
+
------------------------------------------------------------------------------
|
|
13
|
+
|
|
14
|
+
This product includes software derived from mflux
|
|
15
|
+
(https://github.com/mflux-community/mflux), licensed under MIT License:
|
|
16
|
+
|
|
17
|
+
MIT License
|
|
18
|
+
|
|
19
|
+
Copyright (c) 2026 Filip Strand
|
|
20
|
+
|
|
21
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
22
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
23
|
+
in the Software without restriction, including without limitation the rights
|
|
24
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
25
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
26
|
+
furnished to do so, subject to the following conditions:
|
|
27
|
+
|
|
28
|
+
The above copyright notice and this permission notice shall be included in all
|
|
29
|
+
copies or substantial portions of the Software.
|
|
30
|
+
|
|
31
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
32
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
33
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
34
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
35
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
36
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
37
|
+
SOFTWARE.
|
|
38
|
+
|
|
39
|
+
src/mflux/extras/teacache/z_image.py (warn_ineffective_options) copies a
|
|
40
|
+
block of statements from main() in mflux's
|
|
41
|
+
src/mflux/models/z_image/cli/z_image_generate.py.
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mflux-teacache
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: TeaCache step skipping for mflux's command line, powered by mlx-teacache.
|
|
5
|
+
Keywords: mflux,mlx,teacache,apple-silicon,diffusion,z-image
|
|
6
|
+
Author: Denis Ineshin
|
|
7
|
+
Author-email: Denis Ineshin <denis.ineshin@gmail.com>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
License-File: NOTICE
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: MacOS
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Requires-Dist: mlx-teacache[mflux]>=0.13.2
|
|
19
|
+
Requires-Dist: mflux>=0.22
|
|
20
|
+
Maintainer: Denis Ineshin
|
|
21
|
+
Maintainer-email: Denis Ineshin <denis.ineshin@gmail.com>
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Project-URL: Homepage, https://github.com/mflux-community/mflux-plugins/tree/main/teacache
|
|
24
|
+
Project-URL: Repository, https://github.com/mflux-community/mflux-plugins
|
|
25
|
+
Project-URL: Issues, https://github.com/mflux-community/mflux-plugins/issues
|
|
26
|
+
Project-URL: Documentation, https://github.com/mflux-community/mflux-plugins/tree/main/teacache#readme
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# mflux-teacache
|
|
30
|
+
|
|
31
|
+
Adds the command `mflux-generate-z-image-teacache` to [mflux](https://github.com/mflux-community/mflux). It takes
|
|
32
|
+
every option of `mflux-generate-z-image` and runs mflux's own loading and generation steps, with TeaCache step
|
|
33
|
+
skipping from [mlx-teacache](https://github.com/IonDen/mlx-teacache) turned on in between.
|
|
34
|
+
|
|
35
|
+
TeaCache skips transformer steps when the result would barely change, and reuses an earlier result. The image is
|
|
36
|
+
close to the plain command's output but not identical. For a supported model, run `mflux-generate-z-image-teacache`
|
|
37
|
+
wherever you would run `mflux-generate-z-image`; the other options stay the same.
|
|
38
|
+
|
|
39
|
+
mflux-teacache lives in the `teacache/` folder of
|
|
40
|
+
[mflux-plugins](https://github.com/mflux-community/mflux-plugins), the plugin repository of the mflux-community
|
|
41
|
+
organization. Denis Ineshin maintains it. The step skipping itself is in
|
|
42
|
+
[mlx-teacache](https://github.com/IonDen/mlx-teacache), a separate Python library by the same author; this package
|
|
43
|
+
connects it to mflux's command line.
|
|
44
|
+
[Versions](https://github.com/mflux-community/mflux-plugins/tree/main/teacache#versions) lists the mflux releases it
|
|
45
|
+
installs with.
|
|
46
|
+
|
|
47
|
+
## Install
|
|
48
|
+
|
|
49
|
+
The recommended setup puts mflux and this package in one tool environment:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
uv tool install mflux --with-executables-from mflux-teacache
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
You get mflux's commands and `mflux-generate-z-image-teacache` side by side, and `mflux-capabilities` lists all of
|
|
56
|
+
them. In a virtual environment that already has mflux:
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install mflux-teacache
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`uv tool install mflux-teacache` on its own works too, but it builds a second mflux environment and puts only this
|
|
63
|
+
package's command on your path.
|
|
64
|
+
|
|
65
|
+
## Usage
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
mflux-generate-z-image-teacache --prompt "a lighthouse on a cliff at dusk" --steps 50 --seed 42 -q 8
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Every `mflux-generate-z-image` option works the same way. After each image the command prints a line such as
|
|
72
|
+
`TeaCache: skipped <k> of <n> steps (threshold 0.12)`.
|
|
73
|
+
|
|
74
|
+
`--teacache-threshold VALUE` replaces the model's calibrated threshold. It must be greater than 0 and at most 1.
|
|
75
|
+
A higher value skips more steps and moves the image further from a plain mflux run.
|
|
76
|
+
|
|
77
|
+
mflux also has a `--step-cache-ratio` flag (alias `--teacache-ratio`), on the Qwen-Image 2.1 command. It is a
|
|
78
|
+
different feature: a fixed share of steps reused by mflux's own step cache. That step cache is not an option on the
|
|
79
|
+
Z-Image command.
|
|
80
|
+
|
|
81
|
+
`--compute-precision` is accepted with a warning: in mflux 0.22 the only value is `float16`, and TeaCache's skip
|
|
82
|
+
decisions and image quality have not been measured with it. It changes only mflux's attention and feed-forward math;
|
|
83
|
+
TeaCache's cached results keep the model's own precision.
|
|
84
|
+
|
|
85
|
+
The command checks your request before it loads any weights. When TeaCache can't run it, the command stops with
|
|
86
|
+
exit code 2 and a message that points to the plain mflux command. That happens for:
|
|
87
|
+
|
|
88
|
+
- a model TeaCache doesn't support on this command, such as `--model z-image-turbo` (the message lists the
|
|
89
|
+
supported models);
|
|
90
|
+
- a distilled few-step model, where there is nothing to skip;
|
|
91
|
+
- a threshold outside 0 to 1;
|
|
92
|
+
- mflux's step cache. This command has no step-cache option; a later command for a model that has one refuses it,
|
|
93
|
+
also when `-C` restores it;
|
|
94
|
+
- too few steps. The first and last steps always run. 2 or fewer active steps are refused. With 3, the run is accepted
|
|
95
|
+
but skips nothing, and TeaCache prints a warning saying so. An image-to-image run counts only the steps it actually
|
|
96
|
+
runs, so a high strength in `--image PATH STRENGTH` can leave too few (strength 1.0 leaves none).
|
|
97
|
+
|
|
98
|
+
A checkpoint other than the one TeaCache was calibrated on (a finetune, a third-party repo) runs with a warning,
|
|
99
|
+
because the skips may not suit it.
|
|
100
|
+
|
|
101
|
+
If something fails after the model has loaded, the command prints the error's traceback and exits with code 1.
|
|
102
|
+
|
|
103
|
+
## Supported models
|
|
104
|
+
|
|
105
|
+
| Command | `--model` | Default threshold |
|
|
106
|
+
|---|---|---|
|
|
107
|
+
| `mflux-generate-z-image-teacache` | `z-image` (the default) | 0.12 |
|
|
108
|
+
|
|
109
|
+
Z-Image Turbo is not supported: the command refuses it as an unsupported model. Other model families get a
|
|
110
|
+
command once their mflux command has the same load-and-generate steps.
|
|
111
|
+
|
|
112
|
+
## What it changes
|
|
113
|
+
|
|
114
|
+
The command patches the loaded model in memory. For Z-Image it replaces the model's prediction step with
|
|
115
|
+
mlx-teacache's gated version. Nothing on disk changes, and mflux's own commands behave exactly as before. mflux's
|
|
116
|
+
shell completions list only mflux's own commands.
|
|
117
|
+
|
|
118
|
+
Each image records what TeaCache did, next to mflux's usual metadata: `teacache_threshold`,
|
|
119
|
+
`teacache_skipped_steps`, `teacache_active_steps`, `teacache_variant` and `teacache_version` (the mlx-teacache
|
|
120
|
+
version). Replaying a TeaCache image with plain mflux and `-C` produces the plain run, without TeaCache. Replaying
|
|
121
|
+
it with this command uses the model's default threshold unless you pass `--teacache-threshold` again, because the
|
|
122
|
+
`teacache_*` keys are not read back.
|
|
123
|
+
|
|
124
|
+
For measured speedups and image comparisons, see the
|
|
125
|
+
[mlx-teacache README](https://github.com/IonDen/mlx-teacache#readme).
|
|
126
|
+
|
|
127
|
+
## Versions
|
|
128
|
+
|
|
129
|
+
- Python 3.10 or newer, on Apple Silicon.
|
|
130
|
+
- mflux 0.22 or newer. The upper limit comes from mlx-teacache: its `[mflux]` extra allows mflux below 0.25. A newer
|
|
131
|
+
mflux needs a newer mlx-teacache first; until then the installer keeps or picks an older mflux. mflux 0.21 and
|
|
132
|
+
earlier set the Z-Image scheduler default outside the parser this command reuses, so the command would not get it.
|
|
133
|
+
- mlx-teacache 0.13.2 or newer, the first release that lists mflux 0.22 as checked. This package adds no upper limit
|
|
134
|
+
of its own. On an mflux newer than the newest one mlx-teacache was checked against, the command runs and prints a
|
|
135
|
+
warning.
|
|
136
|
+
|
|
137
|
+
mflux's other options, `--float32` included, pass through unchanged.
|
|
138
|
+
|
|
139
|
+
What changed in each release is in
|
|
140
|
+
[CHANGELOG.md](https://github.com/mflux-community/mflux-plugins/blob/main/teacache/CHANGELOG.md).
|
|
141
|
+
|
|
142
|
+
## Development
|
|
143
|
+
|
|
144
|
+
From the `teacache/` folder of an mflux-plugins checkout:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
uv sync --locked
|
|
148
|
+
uv run pytest
|
|
149
|
+
uv run ruff check . && uv run ruff format --check .
|
|
150
|
+
uv run ty check src
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The tests use stand-ins for the model and never download weights. `AGENTS.md` describes the package layout and its
|
|
154
|
+
rules.
|
|
155
|
+
|
|
156
|
+
## License
|
|
157
|
+
|
|
158
|
+
Apache-2.0. `NOTICE` lists the code this package copies from mflux, which is MIT-licensed.
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# mflux-teacache
|
|
2
|
+
|
|
3
|
+
Adds the command `mflux-generate-z-image-teacache` to [mflux](https://github.com/mflux-community/mflux). It takes
|
|
4
|
+
every option of `mflux-generate-z-image` and runs mflux's own loading and generation steps, with TeaCache step
|
|
5
|
+
skipping from [mlx-teacache](https://github.com/IonDen/mlx-teacache) turned on in between.
|
|
6
|
+
|
|
7
|
+
TeaCache skips transformer steps when the result would barely change, and reuses an earlier result. The image is
|
|
8
|
+
close to the plain command's output but not identical. For a supported model, run `mflux-generate-z-image-teacache`
|
|
9
|
+
wherever you would run `mflux-generate-z-image`; the other options stay the same.
|
|
10
|
+
|
|
11
|
+
mflux-teacache lives in the `teacache/` folder of
|
|
12
|
+
[mflux-plugins](https://github.com/mflux-community/mflux-plugins), the plugin repository of the mflux-community
|
|
13
|
+
organization. Denis Ineshin maintains it. The step skipping itself is in
|
|
14
|
+
[mlx-teacache](https://github.com/IonDen/mlx-teacache), a separate Python library by the same author; this package
|
|
15
|
+
connects it to mflux's command line.
|
|
16
|
+
[Versions](https://github.com/mflux-community/mflux-plugins/tree/main/teacache#versions) lists the mflux releases it
|
|
17
|
+
installs with.
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
The recommended setup puts mflux and this package in one tool environment:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
uv tool install mflux --with-executables-from mflux-teacache
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
You get mflux's commands and `mflux-generate-z-image-teacache` side by side, and `mflux-capabilities` lists all of
|
|
28
|
+
them. In a virtual environment that already has mflux:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install mflux-teacache
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`uv tool install mflux-teacache` on its own works too, but it builds a second mflux environment and puts only this
|
|
35
|
+
package's command on your path.
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
mflux-generate-z-image-teacache --prompt "a lighthouse on a cliff at dusk" --steps 50 --seed 42 -q 8
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Every `mflux-generate-z-image` option works the same way. After each image the command prints a line such as
|
|
44
|
+
`TeaCache: skipped <k> of <n> steps (threshold 0.12)`.
|
|
45
|
+
|
|
46
|
+
`--teacache-threshold VALUE` replaces the model's calibrated threshold. It must be greater than 0 and at most 1.
|
|
47
|
+
A higher value skips more steps and moves the image further from a plain mflux run.
|
|
48
|
+
|
|
49
|
+
mflux also has a `--step-cache-ratio` flag (alias `--teacache-ratio`), on the Qwen-Image 2.1 command. It is a
|
|
50
|
+
different feature: a fixed share of steps reused by mflux's own step cache. That step cache is not an option on the
|
|
51
|
+
Z-Image command.
|
|
52
|
+
|
|
53
|
+
`--compute-precision` is accepted with a warning: in mflux 0.22 the only value is `float16`, and TeaCache's skip
|
|
54
|
+
decisions and image quality have not been measured with it. It changes only mflux's attention and feed-forward math;
|
|
55
|
+
TeaCache's cached results keep the model's own precision.
|
|
56
|
+
|
|
57
|
+
The command checks your request before it loads any weights. When TeaCache can't run it, the command stops with
|
|
58
|
+
exit code 2 and a message that points to the plain mflux command. That happens for:
|
|
59
|
+
|
|
60
|
+
- a model TeaCache doesn't support on this command, such as `--model z-image-turbo` (the message lists the
|
|
61
|
+
supported models);
|
|
62
|
+
- a distilled few-step model, where there is nothing to skip;
|
|
63
|
+
- a threshold outside 0 to 1;
|
|
64
|
+
- mflux's step cache. This command has no step-cache option; a later command for a model that has one refuses it,
|
|
65
|
+
also when `-C` restores it;
|
|
66
|
+
- too few steps. The first and last steps always run. 2 or fewer active steps are refused. With 3, the run is accepted
|
|
67
|
+
but skips nothing, and TeaCache prints a warning saying so. An image-to-image run counts only the steps it actually
|
|
68
|
+
runs, so a high strength in `--image PATH STRENGTH` can leave too few (strength 1.0 leaves none).
|
|
69
|
+
|
|
70
|
+
A checkpoint other than the one TeaCache was calibrated on (a finetune, a third-party repo) runs with a warning,
|
|
71
|
+
because the skips may not suit it.
|
|
72
|
+
|
|
73
|
+
If something fails after the model has loaded, the command prints the error's traceback and exits with code 1.
|
|
74
|
+
|
|
75
|
+
## Supported models
|
|
76
|
+
|
|
77
|
+
| Command | `--model` | Default threshold |
|
|
78
|
+
|---|---|---|
|
|
79
|
+
| `mflux-generate-z-image-teacache` | `z-image` (the default) | 0.12 |
|
|
80
|
+
|
|
81
|
+
Z-Image Turbo is not supported: the command refuses it as an unsupported model. Other model families get a
|
|
82
|
+
command once their mflux command has the same load-and-generate steps.
|
|
83
|
+
|
|
84
|
+
## What it changes
|
|
85
|
+
|
|
86
|
+
The command patches the loaded model in memory. For Z-Image it replaces the model's prediction step with
|
|
87
|
+
mlx-teacache's gated version. Nothing on disk changes, and mflux's own commands behave exactly as before. mflux's
|
|
88
|
+
shell completions list only mflux's own commands.
|
|
89
|
+
|
|
90
|
+
Each image records what TeaCache did, next to mflux's usual metadata: `teacache_threshold`,
|
|
91
|
+
`teacache_skipped_steps`, `teacache_active_steps`, `teacache_variant` and `teacache_version` (the mlx-teacache
|
|
92
|
+
version). Replaying a TeaCache image with plain mflux and `-C` produces the plain run, without TeaCache. Replaying
|
|
93
|
+
it with this command uses the model's default threshold unless you pass `--teacache-threshold` again, because the
|
|
94
|
+
`teacache_*` keys are not read back.
|
|
95
|
+
|
|
96
|
+
For measured speedups and image comparisons, see the
|
|
97
|
+
[mlx-teacache README](https://github.com/IonDen/mlx-teacache#readme).
|
|
98
|
+
|
|
99
|
+
## Versions
|
|
100
|
+
|
|
101
|
+
- Python 3.10 or newer, on Apple Silicon.
|
|
102
|
+
- mflux 0.22 or newer. The upper limit comes from mlx-teacache: its `[mflux]` extra allows mflux below 0.25. A newer
|
|
103
|
+
mflux needs a newer mlx-teacache first; until then the installer keeps or picks an older mflux. mflux 0.21 and
|
|
104
|
+
earlier set the Z-Image scheduler default outside the parser this command reuses, so the command would not get it.
|
|
105
|
+
- mlx-teacache 0.13.2 or newer, the first release that lists mflux 0.22 as checked. This package adds no upper limit
|
|
106
|
+
of its own. On an mflux newer than the newest one mlx-teacache was checked against, the command runs and prints a
|
|
107
|
+
warning.
|
|
108
|
+
|
|
109
|
+
mflux's other options, `--float32` included, pass through unchanged.
|
|
110
|
+
|
|
111
|
+
What changed in each release is in
|
|
112
|
+
[CHANGELOG.md](https://github.com/mflux-community/mflux-plugins/blob/main/teacache/CHANGELOG.md).
|
|
113
|
+
|
|
114
|
+
## Development
|
|
115
|
+
|
|
116
|
+
From the `teacache/` folder of an mflux-plugins checkout:
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
uv sync --locked
|
|
120
|
+
uv run pytest
|
|
121
|
+
uv run ruff check . && uv run ruff format --check .
|
|
122
|
+
uv run ty check src
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
The tests use stand-ins for the model and never download weights. `AGENTS.md` describes the package layout and its
|
|
126
|
+
rules.
|
|
127
|
+
|
|
128
|
+
## License
|
|
129
|
+
|
|
130
|
+
Apache-2.0. `NOTICE` lists the code this package copies from mflux, which is MIT-licensed.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
# The backend this package is built and tested with: uv 0.11.2 (CI pins it) builds with its own uv_build 0.11.2.
|
|
3
|
+
requires = ["uv_build>=0.11.2,<0.12"]
|
|
4
|
+
build-backend = "uv_build"
|
|
5
|
+
|
|
6
|
+
[tool.uv.build-backend]
|
|
7
|
+
default-excludes = true
|
|
8
|
+
# mflux PR #776 namespace contract: this distribution ships only mflux/extras/teacache/.
|
|
9
|
+
# Never ship src/mflux/__init__.py (mflux core owns it) or src/mflux/extras/__init__.py
|
|
10
|
+
# (mflux.extras must stay an implicit namespace package that every extras package shares).
|
|
11
|
+
# The dotted module name already marks a namespace package, so no `namespace = true`.
|
|
12
|
+
module-name = "mflux.extras.teacache"
|
|
13
|
+
|
|
14
|
+
[project]
|
|
15
|
+
name = "mflux-teacache"
|
|
16
|
+
version = "0.1.0"
|
|
17
|
+
description = "TeaCache step skipping for mflux's command line, powered by mlx-teacache."
|
|
18
|
+
readme = "README.md"
|
|
19
|
+
license = "Apache-2.0"
|
|
20
|
+
license-files = ["LICENSE", "NOTICE"]
|
|
21
|
+
authors = [{ name = "Denis Ineshin", email = "denis.ineshin@gmail.com" }]
|
|
22
|
+
maintainers = [{ name = "Denis Ineshin", email = "denis.ineshin@gmail.com" }]
|
|
23
|
+
requires-python = ">=3.10"
|
|
24
|
+
keywords = ["mflux", "mlx", "teacache", "apple-silicon", "diffusion", "z-image"]
|
|
25
|
+
classifiers = [
|
|
26
|
+
"Intended Audience :: Developers",
|
|
27
|
+
"Operating System :: MacOS",
|
|
28
|
+
"Programming Language :: Python :: 3",
|
|
29
|
+
"Programming Language :: Python :: 3.10",
|
|
30
|
+
"Programming Language :: Python :: 3.11",
|
|
31
|
+
"Programming Language :: Python :: 3.12",
|
|
32
|
+
"Programming Language :: Python :: 3.13",
|
|
33
|
+
]
|
|
34
|
+
dependencies = [
|
|
35
|
+
# The supported mflux range comes from mlx-teacache's [mflux] extra, which lists the
|
|
36
|
+
# mflux versions mlx-teacache has checked. This package adds no mflux upper bound.
|
|
37
|
+
# 0.13.2 is the first release that records mflux 0.22 as checked (it follows 0.22's bfloat16 Z-Image
|
|
38
|
+
# stream and does not warn on it).
|
|
39
|
+
"mlx-teacache[mflux]>=0.13.2",
|
|
40
|
+
# A floor only: 0.22 is the first mflux whose Z-Image parser sets the scheduler default.
|
|
41
|
+
"mflux>=0.22",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
[project.urls]
|
|
45
|
+
Homepage = "https://github.com/mflux-community/mflux-plugins/tree/main/teacache"
|
|
46
|
+
Repository = "https://github.com/mflux-community/mflux-plugins"
|
|
47
|
+
Issues = "https://github.com/mflux-community/mflux-plugins/issues"
|
|
48
|
+
Documentation = "https://github.com/mflux-community/mflux-plugins/tree/main/teacache#readme"
|
|
49
|
+
|
|
50
|
+
[project.scripts]
|
|
51
|
+
mflux-generate-z-image-teacache = "mflux.extras.teacache.z_image:main"
|
|
52
|
+
|
|
53
|
+
[dependency-groups]
|
|
54
|
+
dev = [
|
|
55
|
+
"pytest>=9.1,<10.0",
|
|
56
|
+
# Pinned exactly, matching mflux core.
|
|
57
|
+
"ruff==0.16.3",
|
|
58
|
+
"ty==0.0.72",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
[tool.ruff]
|
|
62
|
+
line-length = 120
|
|
63
|
+
indent-width = 4
|
|
64
|
+
target-version = "py310"
|
|
65
|
+
respect-gitignore = true
|
|
66
|
+
|
|
67
|
+
[tool.ruff.lint]
|
|
68
|
+
select = ["BLE", "E4", "E7", "E9", "F", "I", "ICN", "LOG", "PERF", "W"]
|
|
69
|
+
|
|
70
|
+
[tool.ruff.lint.per-file-ignores]
|
|
71
|
+
# conftest.py sets HF_HUB_OFFLINE / HF_HOME before importing anything that reads them.
|
|
72
|
+
"tests/conftest.py" = ["E402"]
|
|
73
|
+
|
|
74
|
+
[tool.ruff.lint.isort]
|
|
75
|
+
case-sensitive = false
|
|
76
|
+
combine-as-imports = true
|
|
77
|
+
known-first-party = ["mflux.extras.teacache"]
|
|
78
|
+
|
|
79
|
+
[tool.ruff.format]
|
|
80
|
+
quote-style = "double"
|
|
81
|
+
indent-style = "space"
|
|
82
|
+
|
|
83
|
+
[tool.ty.environment]
|
|
84
|
+
python-version = "3.10"
|
|
85
|
+
|
|
86
|
+
[tool.ty.analysis]
|
|
87
|
+
# ty cannot model mflux core's pkgutil.extend_path merge: core is a regular package in
|
|
88
|
+
# site-packages and this distribution adds mflux/extras/teacache/ from src/, so a static
|
|
89
|
+
# resolver reports absolute mflux.extras.* imports as unresolved. The package uses relative
|
|
90
|
+
# imports internally; tests/test_namespace.py checks the real import at runtime.
|
|
91
|
+
allowed-unresolved-imports = ["mflux.extras.**"]
|
|
92
|
+
|
|
93
|
+
[tool.pytest.ini_options]
|
|
94
|
+
testpaths = ["tests"]
|
|
95
|
+
addopts = "-ra --strict-markers"
|
|
96
|
+
filterwarnings = [
|
|
97
|
+
"error",
|
|
98
|
+
"ignore:builtin type SwigPyPacked has no __module__ attribute:DeprecationWarning",
|
|
99
|
+
"ignore:builtin type SwigPyObject has no __module__ attribute:DeprecationWarning",
|
|
100
|
+
"ignore:builtin type swigvarlink has no __module__ attribute:DeprecationWarning",
|
|
101
|
+
]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""TeaCache step skipping for mflux's command line, powered by mlx-teacache."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("mflux-teacache")
|
|
7
|
+
except PackageNotFoundError: # imported from a source tree that was never installed
|
|
8
|
+
__version__ = "0+unknown"
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""The command flow every mflux-teacache command shares.
|
|
2
|
+
|
|
3
|
+
Each model family has a small adapter module (z_image.py) that names mflux's own command steps.
|
|
4
|
+
run() parses with mflux's parser, refuses anything TeaCache can't run before any weights load, then
|
|
5
|
+
loads with mflux, applies TeaCache, and generates, records and saves the way the plain mflux command
|
|
6
|
+
does."""
|
|
7
|
+
|
|
8
|
+
import sys
|
|
9
|
+
import traceback
|
|
10
|
+
import warnings
|
|
11
|
+
from argparse import Namespace
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from mflux.callbacks.callback_manager import CallbackManager
|
|
17
|
+
from mflux.cli.parser.parsers import CommandLineParser
|
|
18
|
+
from mflux.models.common.config.config import Config
|
|
19
|
+
from mflux.models.common.config.model_config import AVAILABLE_MODELS, ModelConfig
|
|
20
|
+
from mflux.utils.exceptions import ModelConfigError, PromptFileReadError, StopImageGenerationException
|
|
21
|
+
from mflux.utils.generated_image import GeneratedImage
|
|
22
|
+
from mflux.utils.prompt_util import PromptUtil
|
|
23
|
+
from mlx_teacache import (
|
|
24
|
+
InvalidStepWindowError,
|
|
25
|
+
TeaCacheHandle,
|
|
26
|
+
TeaCacheUncalibratedCheckpointWarning,
|
|
27
|
+
TeaCacheValueError,
|
|
28
|
+
VariantInfo,
|
|
29
|
+
__version__ as mlx_teacache_version,
|
|
30
|
+
apply_teacache,
|
|
31
|
+
check_step_window,
|
|
32
|
+
match_variant,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
THRESHOLD_FLAG = "--teacache-threshold"
|
|
36
|
+
# mflux 0.22's --compute-precision (float16 today): any non-default value is allowed for now, with this one
|
|
37
|
+
# warning. Kept in one place so a later switch to a refusal is a small change.
|
|
38
|
+
COMPUTE_PRECISION_WARNING = (
|
|
39
|
+
"TeaCache's skip decisions and image quality have not been measured with --compute-precision {value}; "
|
|
40
|
+
"the run uses it as asked."
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class Adapter:
|
|
46
|
+
"""One mflux command as run() needs it.
|
|
47
|
+
|
|
48
|
+
The required fields are mflux's own command steps. The hooks are optional, so an adapter names
|
|
49
|
+
only what its mirrored command does around them:
|
|
50
|
+
- before_validate(args): right after parsing and the threshold check, before validate (no current
|
|
51
|
+
adapter uses it).
|
|
52
|
+
- after_checks(args, model_config): after TeaCache's refusals, before load (Z-Image: mflux's
|
|
53
|
+
guidance and negative-prompt warnings), so a refused run prints one message.
|
|
54
|
+
- active_steps(args, model_config): the denoising steps mflux will run; None uses
|
|
55
|
+
default_active_steps (mflux's own Config.init_time_step).
|
|
56
|
+
- library_checks_checkpoint: True when mlx-teacache's VariantInfo.calibrated already tells a
|
|
57
|
+
custom checkpoint apart (Qwen-Image); it switches off this package's model-path warning so
|
|
58
|
+
the user sees one warning, not two."""
|
|
59
|
+
|
|
60
|
+
command: str
|
|
61
|
+
plain_command: str
|
|
62
|
+
pipeline: type
|
|
63
|
+
family_keys: tuple[str, ...]
|
|
64
|
+
build_parser: Callable[[], CommandLineParser]
|
|
65
|
+
validate: Callable[[Namespace], ModelConfig]
|
|
66
|
+
load: Callable[[Namespace], Any]
|
|
67
|
+
generate: Callable[[Any, Namespace, int, str], GeneratedImage]
|
|
68
|
+
latent_creator: type
|
|
69
|
+
before_validate: Callable[[Namespace], None] | None = None
|
|
70
|
+
after_checks: Callable[[Namespace, ModelConfig], None] | None = None
|
|
71
|
+
active_steps: Callable[[Namespace, ModelConfig], int] | None = None
|
|
72
|
+
library_checks_checkpoint: bool = False
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def add_teacache_arguments(parser: CommandLineParser) -> None:
|
|
76
|
+
group = parser.add_argument_group("TeaCache")
|
|
77
|
+
group.add_argument(
|
|
78
|
+
THRESHOLD_FLAG,
|
|
79
|
+
dest="teacache_threshold",
|
|
80
|
+
type=float,
|
|
81
|
+
default=None,
|
|
82
|
+
metavar="VALUE",
|
|
83
|
+
help=(
|
|
84
|
+
"How much change TeaCache tolerates before it computes a step again: greater than 0, at most 1. "
|
|
85
|
+
"Higher skips more steps and changes the image more. Default: the model's calibrated value."
|
|
86
|
+
),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def default_active_steps(args: Namespace, model_config: ModelConfig) -> int:
|
|
91
|
+
"""The denoising steps mflux will run: --steps minus mflux's own init_time_step (an image-to-image
|
|
92
|
+
run starts later; strength 1.0 leaves none). Loads no weights and opens no image: width and height
|
|
93
|
+
keep Config's defaults."""
|
|
94
|
+
init_time_step = Config(
|
|
95
|
+
model_config=model_config,
|
|
96
|
+
num_inference_steps=args.steps,
|
|
97
|
+
image_path=getattr(args, "image_path", None),
|
|
98
|
+
image_strength=getattr(args, "image_strength", None),
|
|
99
|
+
).init_time_step
|
|
100
|
+
return args.steps - init_time_step
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def supported_model_names(adapter: Adapter) -> tuple[str, ...]:
|
|
104
|
+
"""The --model names this command can run under TeaCache, from mlx-teacache's own registry."""
|
|
105
|
+
names: list[str] = []
|
|
106
|
+
for key in adapter.family_keys:
|
|
107
|
+
variant = match_variant(AVAILABLE_MODELS[key], adapter.pipeline)
|
|
108
|
+
if variant is not None:
|
|
109
|
+
names.extend(name for name in variant.model_names if name not in names)
|
|
110
|
+
return tuple(names)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def teacache_metadata(handle: TeaCacheHandle, committed_before: int) -> dict[str, float | int | str] | None:
|
|
114
|
+
"""The image's TeaCache record, or None when this generation was not committed (interrupted, or
|
|
115
|
+
the handle was restored mid-run). Flat keys and JSON primitives, like mflux's own step-cache key,
|
|
116
|
+
because mflux writes them into the PNG and the JSON sidecar as they are."""
|
|
117
|
+
stats = handle.stats
|
|
118
|
+
last = stats.last_generation
|
|
119
|
+
if stats.generations <= committed_before or last is None:
|
|
120
|
+
return None
|
|
121
|
+
return {
|
|
122
|
+
"teacache_threshold": float(handle.rel_l1_thresh),
|
|
123
|
+
"teacache_skipped_steps": sum(1 for step in last.decisions if step.decision == "skipped"),
|
|
124
|
+
"teacache_active_steps": int(last.num_steps),
|
|
125
|
+
"teacache_variant": str(getattr(handle, "variant_id", "unknown")),
|
|
126
|
+
"teacache_version": str(mlx_teacache_version),
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _record_teacache(image: GeneratedImage, handle: TeaCacheHandle, committed_before: int) -> None:
|
|
131
|
+
recorded = teacache_metadata(handle, committed_before)
|
|
132
|
+
if recorded is None:
|
|
133
|
+
return
|
|
134
|
+
# Merged into what mflux recorded there (Z-Image: float32, compute_precision, which -C replays), and a new
|
|
135
|
+
# dict: never mutate one the image may share (GeneratedImage.get_right_half shares it). A later family's image may
|
|
136
|
+
# carry None there.
|
|
137
|
+
image.generation_parameters = {**(image.generation_parameters or {}), **recorded}
|
|
138
|
+
print(
|
|
139
|
+
f"TeaCache: skipped {recorded['teacache_skipped_steps']} of {recorded['teacache_active_steps']} steps "
|
|
140
|
+
f"(threshold {recorded['teacache_threshold']:g})"
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _checked_threshold(parser: CommandLineParser, adapter: Adapter, value: float | None) -> float | None:
|
|
145
|
+
if value is not None and not 0.0 < value <= 1.0: # NaN fails both comparisons and is refused
|
|
146
|
+
parser.error(
|
|
147
|
+
f"{THRESHOLD_FLAG} must be greater than 0 and at most 1, got {value}. "
|
|
148
|
+
f"Run {adapter.plain_command} to generate without TeaCache."
|
|
149
|
+
)
|
|
150
|
+
return value
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _refuse_what_teacache_cannot_run(
|
|
154
|
+
parser: CommandLineParser, adapter: Adapter, args: Namespace, model_config: ModelConfig
|
|
155
|
+
) -> VariantInfo:
|
|
156
|
+
variant = match_variant(model_config, adapter.pipeline)
|
|
157
|
+
if variant is None:
|
|
158
|
+
shown = args.model or model_config.model_name
|
|
159
|
+
names = ", ".join(supported_model_names(adapter)) or "none"
|
|
160
|
+
parser.error(
|
|
161
|
+
f"TeaCache doesn't support {shown} yet. Supported on this command: {names}. "
|
|
162
|
+
f"Run {adapter.plain_command} to generate without TeaCache."
|
|
163
|
+
)
|
|
164
|
+
if variant.default_thresh is None:
|
|
165
|
+
parser.error(
|
|
166
|
+
f"{variant.display_name} is a distilled few-step model: TeaCache has no steps to skip there. "
|
|
167
|
+
f"Run {adapter.plain_command} instead."
|
|
168
|
+
)
|
|
169
|
+
if getattr(args, "step_cache_ratio", None) is not None:
|
|
170
|
+
parser.error(
|
|
171
|
+
"--step-cache-ratio (given on the command line or restored by --config-from-conf) also skips steps, "
|
|
172
|
+
"and mflux's step cache and TeaCache can't run together. "
|
|
173
|
+
"Remove --step-cache-ratio (or --teacache-ratio) from the command line, or the step_cache_ratio key "
|
|
174
|
+
f"from the -C file; or run {adapter.plain_command} to use mflux's step cache."
|
|
175
|
+
)
|
|
176
|
+
active_steps = (adapter.active_steps or default_active_steps)(args, model_config)
|
|
177
|
+
try:
|
|
178
|
+
check_step_window(active_num_steps=active_steps, nominal_num_inference_steps=args.steps)
|
|
179
|
+
# TeaCacheValueError: a negative count (--steps -1, or --steps 0 with --image); mflux's --steps has no range check.
|
|
180
|
+
except (InvalidStepWindowError, TeaCacheValueError) as exc:
|
|
181
|
+
# The library's texts end with or without a period; print exactly one before the hint.
|
|
182
|
+
parser.error(
|
|
183
|
+
f"{str(exc).rstrip('.')}. Use more --steps (or a lower --image strength), "
|
|
184
|
+
f"or run {adapter.plain_command} without TeaCache."
|
|
185
|
+
)
|
|
186
|
+
return variant
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _warn_unverified_checkpoint(
|
|
190
|
+
adapter: Adapter, args: Namespace, model_config: ModelConfig, variant: VariantInfo
|
|
191
|
+
) -> None:
|
|
192
|
+
"""One warning, never a refusal, when the coefficients were not fitted on the checkpoint this run loads."""
|
|
193
|
+
model_path = getattr(args, "model_path", None)
|
|
194
|
+
if not variant.calibrated:
|
|
195
|
+
shown = model_path or args.model or model_config.model_name
|
|
196
|
+
warnings.warn(
|
|
197
|
+
TeaCacheUncalibratedCheckpointWarning(
|
|
198
|
+
f"{shown} is not the checkpoint {variant.display_name}'s TeaCache coefficients were calibrated "
|
|
199
|
+
"on; skip counts and image quality on it are unchecked. TeaCache still runs."
|
|
200
|
+
),
|
|
201
|
+
stacklevel=3,
|
|
202
|
+
)
|
|
203
|
+
return
|
|
204
|
+
if adapter.library_checks_checkpoint or model_path is None or model_path == model_config.model_name:
|
|
205
|
+
return
|
|
206
|
+
warnings.warn(
|
|
207
|
+
TeaCacheUncalibratedCheckpointWarning(
|
|
208
|
+
f"{model_path} is not {model_config.model_name}, the checkpoint TeaCache's coefficients were "
|
|
209
|
+
"calibrated on; skip counts and image quality on it are unchecked."
|
|
210
|
+
),
|
|
211
|
+
stacklevel=3,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _warn_unmeasured_compute_precision(args: Namespace) -> None:
|
|
216
|
+
"""Reads the parsed value, so a -C sidecar that recorded a compute precision warns too."""
|
|
217
|
+
value = getattr(args, "compute_precision", None)
|
|
218
|
+
if value is not None:
|
|
219
|
+
warnings.warn(COMPUTE_PRECISION_WARNING.format(value=value), UserWarning, stacklevel=3)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def run(adapter: Adapter) -> None:
|
|
223
|
+
parser = adapter.build_parser()
|
|
224
|
+
args = parser.parse_args()
|
|
225
|
+
threshold = _checked_threshold(parser, adapter, args.teacache_threshold)
|
|
226
|
+
if adapter.before_validate is not None:
|
|
227
|
+
adapter.before_validate(args)
|
|
228
|
+
try:
|
|
229
|
+
model_config = adapter.validate(args)
|
|
230
|
+
except ModelConfigError as exc:
|
|
231
|
+
parser.error(str(exc))
|
|
232
|
+
# TeaCache's refusals come before mflux's option warnings: a refused run prints one message.
|
|
233
|
+
variant = _refuse_what_teacache_cannot_run(parser, adapter, args, model_config)
|
|
234
|
+
if adapter.after_checks is not None:
|
|
235
|
+
adapter.after_checks(args, model_config)
|
|
236
|
+
_warn_unverified_checkpoint(adapter, args, model_config, variant)
|
|
237
|
+
_warn_unmeasured_compute_precision(args)
|
|
238
|
+
|
|
239
|
+
model = adapter.load(args)
|
|
240
|
+
memory_saver = None
|
|
241
|
+
try:
|
|
242
|
+
handle = apply_teacache(model, rel_l1_thresh=threshold)
|
|
243
|
+
memory_saver = CallbackManager.register_callbacks(args=args, model=model, latent_creator=adapter.latent_creator)
|
|
244
|
+
for seed in args.seed:
|
|
245
|
+
committed_before = handle.stats.generations
|
|
246
|
+
image = adapter.generate(model, args, seed, PromptUtil.read_prompt(args))
|
|
247
|
+
_record_teacache(image, handle, committed_before)
|
|
248
|
+
image.save(path=args.output.format(seed=seed), export_json_metadata=args.metadata)
|
|
249
|
+
except (StopImageGenerationException, PromptFileReadError) as exc:
|
|
250
|
+
print(exc)
|
|
251
|
+
except Exception: # noqa: BLE001 -- any failure after load: keep the traceback for a report, exit 1
|
|
252
|
+
traceback.print_exc()
|
|
253
|
+
print(
|
|
254
|
+
f"{adapter.command}: error: the run failed (traceback above). "
|
|
255
|
+
f"Run {adapter.plain_command} to generate without TeaCache.",
|
|
256
|
+
file=sys.stderr,
|
|
257
|
+
)
|
|
258
|
+
raise SystemExit(1) from None
|
|
259
|
+
finally:
|
|
260
|
+
if memory_saver:
|
|
261
|
+
print(memory_saver.memory_stats())
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""mflux-generate-z-image-teacache: mflux's Z-Image command with TeaCache step skipping."""
|
|
2
|
+
|
|
3
|
+
import warnings
|
|
4
|
+
from argparse import Namespace
|
|
5
|
+
|
|
6
|
+
from mflux.cli.parser.parsers import CommandLineParser
|
|
7
|
+
from mflux.models.common.config.model_config import ModelConfig
|
|
8
|
+
from mflux.models.z_image.cli import z_image_generate
|
|
9
|
+
from mflux.models.z_image.cli.z_image_generate import CONDITIONAL_OPTIONS, ZImageCommand
|
|
10
|
+
from mflux.models.z_image.variants.z_image import ZImage
|
|
11
|
+
|
|
12
|
+
from ._core import Adapter, add_teacache_arguments, run
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"ADAPTER",
|
|
16
|
+
"CONDITIONAL_OPTIONS",
|
|
17
|
+
"DESCRIPTION",
|
|
18
|
+
"PIPELINE",
|
|
19
|
+
"build_parser",
|
|
20
|
+
"main",
|
|
21
|
+
"warn_ineffective_options",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
# The class ZImageCommand.load() returns; mlx-teacache's match_variant is asked about it.
|
|
25
|
+
PIPELINE = ZImage
|
|
26
|
+
DESCRIPTION = "Generate an image using Z-Image with TeaCache step skipping."
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def build_parser() -> CommandLineParser:
|
|
30
|
+
parser = z_image_generate.build_parser()
|
|
31
|
+
parser.description = DESCRIPTION
|
|
32
|
+
add_teacache_arguments(parser)
|
|
33
|
+
return parser
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# The function below is copied statement for statement from mflux's z_image_generate.main(),
|
|
37
|
+
# which runs it before load(). tests/test_mflux_drift.py fails when it stops matching. It goes
|
|
38
|
+
# away once mflux's Z-Image command has a Command.prepare(args) step the plugin can call.
|
|
39
|
+
def warn_ineffective_options(args: Namespace, model_config: ModelConfig) -> None:
|
|
40
|
+
# Warn on the EFFECTIVE behavior, not the flag value: --model may resolve to a
|
|
41
|
+
# guidance-distilled variant (guidance forced to 0.0 regardless of the flag), and on
|
|
42
|
+
# CFG-capable models the negative prompt is only encoded at guidance > 1.0, where an
|
|
43
|
+
# omitted --guidance defaults to 0.0.
|
|
44
|
+
if not model_config.supports_guidance:
|
|
45
|
+
CommandLineParser.warn_ignored_options(
|
|
46
|
+
{
|
|
47
|
+
"--guidance": CONDITIONAL_OPTIONS["--guidance"]["reason"],
|
|
48
|
+
"--negative-prompt": CONDITIONAL_OPTIONS["--negative-prompt"]["reason"],
|
|
49
|
+
}
|
|
50
|
+
)
|
|
51
|
+
elif CommandLineParser._option_was_provided("--negative-prompt") and (
|
|
52
|
+
args.guidance is None or args.guidance <= 1.0
|
|
53
|
+
):
|
|
54
|
+
warnings.warn(
|
|
55
|
+
f"--negative-prompt has no effect: {CONDITIONAL_OPTIONS['--negative-prompt']['reason']}"
|
|
56
|
+
" Pass --guidance above 1.0 to enable it.",
|
|
57
|
+
stacklevel=1,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# Z-Image needs one optional hook (after_checks); active_steps keeps the Config-based default, and
|
|
62
|
+
# mlx-teacache has no checkpoint check for Z-Image, so this package's own model-path warning applies.
|
|
63
|
+
ADAPTER = Adapter(
|
|
64
|
+
command="mflux-generate-z-image-teacache",
|
|
65
|
+
plain_command="mflux-generate-z-image",
|
|
66
|
+
pipeline=PIPELINE,
|
|
67
|
+
family_keys=(z_image_generate.DEFAULT_MODEL, *z_image_generate.FAMILY_MODELS),
|
|
68
|
+
build_parser=build_parser,
|
|
69
|
+
validate=ZImageCommand.validate,
|
|
70
|
+
load=ZImageCommand.load,
|
|
71
|
+
generate=ZImageCommand.generate,
|
|
72
|
+
latent_creator=ZImageCommand.latent_creator,
|
|
73
|
+
after_checks=warn_ineffective_options,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def main() -> None:
|
|
78
|
+
run(ADAPTER)
|