mlx-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.
Files changed (52) hide show
  1. mlx_teacache-0.1.0/.gitignore +17 -0
  2. mlx_teacache-0.1.0/CHANGELOG.md +34 -0
  3. mlx_teacache-0.1.0/LICENSE +201 -0
  4. mlx_teacache-0.1.0/NOTICE +53 -0
  5. mlx_teacache-0.1.0/PKG-INFO +172 -0
  6. mlx_teacache-0.1.0/README.md +145 -0
  7. mlx_teacache-0.1.0/docs/m3-plus-tradeoff.md +46 -0
  8. mlx_teacache-0.1.0/docs/manual-verification.md +41 -0
  9. mlx_teacache-0.1.0/docs/release-setup.md +17 -0
  10. mlx_teacache-0.1.0/pyproject.toml +115 -0
  11. mlx_teacache-0.1.0/scripts/_calibration_flux2_klein.json +35 -0
  12. mlx_teacache-0.1.0/scripts/calibrate_flux2_klein.py +216 -0
  13. mlx_teacache-0.1.0/src/mlx_teacache/__init__.py +62 -0
  14. mlx_teacache-0.1.0/src/mlx_teacache/_version.py +24 -0
  15. mlx_teacache-0.1.0/src/mlx_teacache/api.py +259 -0
  16. mlx_teacache-0.1.0/src/mlx_teacache/cache.py +33 -0
  17. mlx_teacache-0.1.0/src/mlx_teacache/coefficients.py +144 -0
  18. mlx_teacache-0.1.0/src/mlx_teacache/errors.py +97 -0
  19. mlx_teacache-0.1.0/src/mlx_teacache/gate.py +116 -0
  20. mlx_teacache-0.1.0/src/mlx_teacache/integrations/__init__.py +5 -0
  21. mlx_teacache-0.1.0/src/mlx_teacache/integrations/mflux/__init__.py +4 -0
  22. mlx_teacache-0.1.0/src/mlx_teacache/integrations/mflux/detect.py +77 -0
  23. mlx_teacache-0.1.0/src/mlx_teacache/integrations/mflux/flux1.py +73 -0
  24. mlx_teacache-0.1.0/src/mlx_teacache/integrations/mflux/flux2.py +127 -0
  25. mlx_teacache-0.1.0/src/mlx_teacache/integrations/mflux/forward.py +446 -0
  26. mlx_teacache-0.1.0/src/mlx_teacache/integrations/mflux/lifecycle.py +188 -0
  27. mlx_teacache-0.1.0/src/mlx_teacache/py.typed +0 -0
  28. mlx_teacache-0.1.0/src/mlx_teacache/stats.py +163 -0
  29. mlx_teacache-0.1.0/tests/__init__.py +0 -0
  30. mlx_teacache-0.1.0/tests/conftest.py +35 -0
  31. mlx_teacache-0.1.0/tests/fixtures.toml +50 -0
  32. mlx_teacache-0.1.0/tests/generate_references.py +138 -0
  33. mlx_teacache-0.1.0/tests/hf_revisions.toml +26 -0
  34. mlx_teacache-0.1.0/tests/test_api.py +153 -0
  35. mlx_teacache-0.1.0/tests/test_cache.py +43 -0
  36. mlx_teacache-0.1.0/tests/test_coefficients.py +71 -0
  37. mlx_teacache-0.1.0/tests/test_detect.py +77 -0
  38. mlx_teacache-0.1.0/tests/test_errors.py +89 -0
  39. mlx_teacache-0.1.0/tests/test_fixtures_integrity.py +42 -0
  40. mlx_teacache-0.1.0/tests/test_flux1_proxy.py +86 -0
  41. mlx_teacache-0.1.0/tests/test_flux2_predict.py +107 -0
  42. mlx_teacache-0.1.0/tests/test_forward_flux1.py +184 -0
  43. mlx_teacache-0.1.0/tests/test_forward_flux2.py +199 -0
  44. mlx_teacache-0.1.0/tests/test_gate.py +167 -0
  45. mlx_teacache-0.1.0/tests/test_gate_hypothesis.py +47 -0
  46. mlx_teacache-0.1.0/tests/test_hf_revisions.py +44 -0
  47. mlx_teacache-0.1.0/tests/test_image_quality_flux1.py +188 -0
  48. mlx_teacache-0.1.0/tests/test_image_quality_flux2.py +162 -0
  49. mlx_teacache-0.1.0/tests/test_lifecycle.py +215 -0
  50. mlx_teacache-0.1.0/tests/test_parity_flux1.py +443 -0
  51. mlx_teacache-0.1.0/tests/test_parity_flux2.py +285 -0
  52. mlx_teacache-0.1.0/tests/test_stats.py +143 -0
@@ -0,0 +1,17 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ .DS_Store
5
+ .venv/
6
+ .hypothesis/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ .mypy_cache/
10
+ dist/
11
+ build/
12
+ *.egg-info/
13
+ .coverage
14
+ htmlcov/
15
+ tests/converted/*.safetensors
16
+ tests/_artifacts/
17
+ src/mlx_teacache/_version.py
@@ -0,0 +1,34 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here.
4
+
5
+ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
+ Project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.1.0] — 2026-05-15 (planned)
11
+
12
+ ### Added
13
+ - Initial public release.
14
+ - `apply_teacache(flux, *, rel_l1_thresh=0.20, ...)` for FLUX.1 dev/schnell and FLUX.2 Klein 4b.
15
+ - Context-manager-compatible `TeaCacheHandle` with live `.stats`, `.provenance`, `.restore()`.
16
+ - Built-in polynomial coefficients vendored from ali-vilab/TeaCache (FLUX.1) and derived in-repo (FLUX.2 Klein 4b).
17
+ - Custom-coefficient override path.
18
+ - Auto-disable on FLUX.2 CFG (`guidance > 1.0`); bit-exact vanilla fallback.
19
+ - img2img rejection with `Img2ImgNotSupportedError`.
20
+ - Threshold-zero fast path: at `rel_l1_thresh <= 0` the wrapper skips building cache tensors entirely (cheap no-op).
21
+ - Five-tier test pyramid: shape/dtype unit tests, paired same-process latent parity (bit-exact for FLUX.1, cosine ≥ 0.97 for FLUX.2), image-level SSIM gates on VAE-decoded outputs.
22
+ - Trusted-Publishing release pipeline.
23
+
24
+ ### Calibration notes (2026-05-15)
25
+ - Default `rel_l1_thresh` chosen by visual comparison + SSIM measurement: at 0.25 some text/synthetic prompts changed rendering style; at 0.20 outputs are indistinguishable from vanilla while still skipping ~25% of steps.
26
+ - FLUX.1-dev / 25 steps / M1 Max: measured 1.48× speedup at default threshold, SSIM ≥ 0.80 on a 5-prompt suite.
27
+ - FLUX.1 polynomial coefficients corrected from a transcription error in an earlier revision (`c0..c3` were ~10× too large); now match ali-vilab upstream exactly.
28
+
29
+ ### Known limitations
30
+ - v0.1 supports txt2img only.
31
+ - FLUX.2 Klein variants other than `flux2-klein-4b` are not in v0.1.
32
+ - Distilled-step schedules (FLUX.1 schnell 4-step, Klein 4-step) see no measurable speedup.
33
+ - M3+ users lose mflux's `mx.compile` of `_predict`; net behavior unmeasured in v0.1 (M1 Max benchmarks only).
34
+ - FLUX.2 parity is numerical, not bit-exact: vanilla-compiled vs wrapper-eager Metal kernel dispatch differs by ~1 ULP per element. Cosine similarity ≥ 0.99 measured; image-level SSIM is the user-facing guarantee. CFG-fallback path remains bit-exact.
@@ -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,53 @@
1
+ mlx-teacache
2
+ Copyright 2026 Denis Ineshin
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 ali-vilab/TeaCache
15
+ (https://github.com/ali-vilab/TeaCache), licensed under Apache License 2.0:
16
+ Copyright 2024-2025 the TeaCache authors.
17
+
18
+ The polynomial coefficients in src/mlx_teacache/coefficients.py for the
19
+ FLUX architecture (flux1-dev, flux1-schnell) are vendored verbatim from
20
+ ali-vilab/TeaCache/TeaCache4FLUX/teacache_flux.py.
21
+
22
+ ------------------------------------------------------------------------------
23
+
24
+ This product includes software derived from filipstrand/mflux
25
+ (https://github.com/filipstrand/mflux), licensed under MIT License:
26
+
27
+ MIT License
28
+
29
+ Copyright (c) 2024-2026 Filip Strand
30
+
31
+ Permission is hereby granted, free of charge, to any person obtaining a copy
32
+ of this software and associated documentation files (the "Software"), to deal
33
+ in the Software without restriction, including without limitation the rights
34
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
35
+ copies of the Software, and to permit persons to whom the Software is
36
+ furnished to do so, subject to the following conditions:
37
+
38
+ The above copyright notice and this permission notice shall be included in all
39
+ copies or substantial portions of the Software.
40
+
41
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
42
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
43
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
44
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
45
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
46
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
47
+ SOFTWARE.
48
+
49
+ mlx-teacache/src/mlx_teacache/integrations/mflux/forward.py reimplements the
50
+ transformer forward passes from mflux's Flux1.Transformer and
51
+ Flux2Klein.Flux2Transformer for the purpose of inserting TeaCache gating
52
+ between body and tail. The reimplementation closely follows mflux's
53
+ internal structure as of 0.17.5.
@@ -0,0 +1,172 @@
1
+ Metadata-Version: 2.4
2
+ Name: mlx-teacache
3
+ Version: 0.1.0
4
+ Summary: TeaCache step-skipping for FLUX diffusion on Apple Silicon, in pure MLX
5
+ Project-URL: Homepage, https://github.com/IonDen/mlx-teacache
6
+ Project-URL: Issues, https://github.com/IonDen/mlx-teacache/issues
7
+ Author-email: Denis Ineshin <denis.ineshin@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Keywords: apple-silicon,diffusion,flux,mlx,teacache
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: MacOS :: MacOS X
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: mlx>=0.31
23
+ Requires-Dist: numpy
24
+ Provides-Extra: mflux
25
+ Requires-Dist: mflux<0.18,>=0.17; extra == 'mflux'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # mlx-teacache
29
+
30
+ [![PyPI version](https://img.shields.io/pypi/v/mlx-teacache.svg)](https://pypi.org/project/mlx-teacache/)
31
+ [![Python versions](https://img.shields.io/pypi/pyversions/mlx-teacache.svg)](https://pypi.org/project/mlx-teacache/)
32
+ [![License: Apache 2.0](https://img.shields.io/pypi/l/mlx-teacache.svg)](https://github.com/IonDen/mlx-teacache/blob/main/LICENSE)
33
+ [![CI](https://github.com/IonDen/mlx-teacache/actions/workflows/ci.yml/badge.svg)](https://github.com/IonDen/mlx-teacache/actions/workflows/ci.yml)
34
+
35
+ **TeaCache step-skipping for FLUX diffusion on Apple Silicon, in pure MLX.**
36
+
37
+ `mlx-teacache` is the first MLX port of TeaCache — a training-free inference optimization that skips ~20-50% of denoising steps in FLUX-family diffusion models by predicting which steps contribute little to the final image. Measured ~1.48× wall-clock speedup at the default threshold on FLUX.1-dev / 25 steps with visually-equivalent output (SSIM ≥ 0.80 on a 5-prompt suite).
38
+
39
+ ## What it does
40
+
41
+ Diffusion models run the same big transformer 20-50 times in a loop. Between consecutive steps the output changes very little; TeaCache uses a tiny polynomial fit to predict which steps can reuse the previous step's output. On M1 Max FLUX.1-dev @ 25 steps the default threshold (`rel_l1_thresh=0.20`) skips 6 of 25 steps for a ~1.48× speedup.
42
+
43
+ ```python
44
+ from mflux.models.flux2.variants.txt2img.flux2_klein import Flux2Klein
45
+ from mflux.models.common.config.model_config import ModelConfig
46
+ from mlx_teacache import apply_teacache
47
+
48
+ flux = Flux2Klein(quantize=4, model_config=ModelConfig.flux2_klein_4b())
49
+ with apply_teacache(flux): # default rel_l1_thresh=0.20
50
+ flux.generate_image(prompt="a red apple", seed=42, num_inference_steps=25)
51
+ ```
52
+
53
+ ## Install
54
+
55
+ ```bash
56
+ pip install "mlx-teacache[mflux]"
57
+ # or with uv:
58
+ uv add "mlx-teacache[mflux]"
59
+ ```
60
+
61
+ Requires Python ≥ 3.11 and Apple Silicon. The `[mflux]` extra pulls in `mflux>=0.17,<0.18`.
62
+
63
+ ```bash
64
+ pip install "mlx-teacache==0.1.0[mflux]" # pin for reproducibility
65
+ ```
66
+
67
+ ## Quick start
68
+
69
+ FLUX.1 dev:
70
+
71
+ ```python
72
+ from mflux.models.flux.variants.txt2img.flux import Flux1
73
+ from mlx_teacache import apply_teacache
74
+
75
+ flux = Flux1.from_name("dev", quantize=4)
76
+ with apply_teacache(flux) as handle: # default rel_l1_thresh=0.20
77
+ flux.generate_image(prompt="...", seed=42, num_inference_steps=25, guidance=3.5)
78
+ print(f"Speedup: {handle.stats.speedup_estimate:.2f}×")
79
+ ```
80
+
81
+ ## Threshold guide
82
+
83
+ Measured on M1 Max 32GB, FLUX.1-dev @ 25 steps, bf16, `seed=42`, `guidance=3.5`, red-apple prompt:
84
+
85
+ | `rel_l1_thresh` | Skipped steps | Speedup | SSIM vs vanilla | Recommended use |
86
+ |---|---|---|---|---|
87
+ | 0.10 | 0 / 25 | 1.07× | 1.0000 | Cache never engages |
88
+ | 0.15 | 0 / 25 | 1.13× | 1.0000 | Cache never engages |
89
+ | **0.20 (default)** | **6 / 25** | **1.48×** | **≥ 0.80 (5-prompt suite)** | **Visually-lossless sweet spot** |
90
+ | 0.25 | 11 / 25 | 1.96× | 0.57-0.93 | Visible style changes on text/synthetic prompts |
91
+
92
+ The 0.20 default was chosen after side-by-side visual comparison: at 0.25 a text prompt that vanilla renders as neon tubes can come out as dot-matrix; at 0.20 the output is indistinguishable from vanilla while still skipping ~25% of steps. SSIM is a conservative metric on high-frequency-detail prompts (text, synthetic patterns).
93
+
94
+ ## Supported models
95
+
96
+ | Variant id | mflux class + config | Coefficient source |
97
+ |---|---|---|
98
+ | `flux1-dev` | `Flux1(model_config=ModelConfig.dev())` | upstream ali-vilab/TeaCache |
99
+ | `flux1-schnell` | `Flux1(model_config=ModelConfig.schnell())` | upstream (shared with dev) |
100
+ | `flux2-klein-4b` | `Flux2Klein(model_config=ModelConfig.flux2_klein_4b())` | in-repo (see `docs/calibration.md`) |
101
+
102
+ ## Combining with mlx-taef
103
+
104
+ ```python
105
+ from mlx_taef.integrations.mflux import LivePreviewCallback
106
+ from mlx_teacache import apply_teacache
107
+
108
+ preview = LivePreviewCallback(variant="taef2", every=5, save_to="preview.png",
109
+ latent_height=32, latent_width=32)
110
+ flux.callbacks.register(preview)
111
+
112
+ with apply_teacache(flux): # default rel_l1_thresh=0.20
113
+ flux.generate_image(prompt="...", seed=42, num_inference_steps=25)
114
+ ```
115
+
116
+ ## Inspecting stats
117
+
118
+ ```python
119
+ handle = apply_teacache(flux)
120
+ flux.generate_image(prompt="apple", seed=42, num_inference_steps=25)
121
+ print(handle.stats.computed_count, handle.stats.skipped_count)
122
+ print(handle.stats.last_generation.decisions[5]) # per-step record
123
+ ```
124
+
125
+ ## Custom coefficients
126
+
127
+ ```python
128
+ custom = [...] # length 5, all finite
129
+ apply_teacache(flux, coefficients=custom)
130
+ ```
131
+
132
+ ## How it works
133
+
134
+ TeaCache observes that in diffusion denoising, consecutive transformer outputs change very little between most pairs of adjacent steps. The expensive transformer body (all the joint + single attention blocks) produces a residual that's added to the input — and that residual stays roughly stable for stretches of the denoising trajectory.
135
+
136
+ TeaCache trains a tiny polynomial that predicts how much the output will change given how much the input has changed (measured as relative L1 distance of the modulated block-0 input). When the predicted accumulated change since the last actual compute step is small, TeaCache reuses the cached residual instead of running the full transformer body — only the cheap prelude (embeddings) and tail (norm + projection) still run.
137
+
138
+ mlx-teacache implements this for mflux on Apple Silicon. We replace `flux.transformer` with a per-instance proxy for FLUX.1, and `flux._predict` with an instance-level closure for FLUX.2 (to keep gating live even when `mx.compile` is normally used). The polynomial coefficients for FLUX.1 are vendored from upstream; the FLUX.2 Klein 4b coefficients are derived in-repo via `scripts/calibrate.py`. See the TeaCache paper at https://liewfeng.github.io/TeaCache/ and `docs/superpowers/spikes/2026-05-14-mlx-teacache-phase-0-spike.md` for the Apple-Silicon-specific design notes.
139
+
140
+ ## Benchmarks
141
+
142
+ M1 Max 32GB, default threshold (`rel_l1_thresh=0.20`):
143
+
144
+ | Model | Steps | Vanilla | With TeaCache | Speedup | SSIM (PR-gate prompt) |
145
+ |---|---|---|---|---|---|
146
+ | FLUX.1-dev @ 512² | 25 | ~5:18 | ~3:35 | 1.48× | ≥ 0.90 |
147
+ | FLUX.2 Klein 4b @ 512² | 8 | ~37s | ~30s | ~1.2× | ≥ 0.85 |
148
+
149
+ FLUX.2's smaller speedup at 8 steps reflects the short non-distilled denoising trajectory at Klein's recommended step count. Longer schedules (`num_inference_steps>=15`) give larger gains.
150
+
151
+ ## Limitations
152
+
153
+ - **v0.1 is txt2img only.** img2img inputs raise `Img2ImgNotSupportedError`. v0.2 planned.
154
+ - **FLUX.2 CFG (`guidance > 1.0`) auto-falls-back to vanilla mflux.** Output is bit-exact. v0.2 will add per-branch caching.
155
+ - **Distilled schedules see no speedup.** FLUX.1 schnell 4-step and Klein 4-step defaults have too few non-forced steps. Use `num_inference_steps >= 10` for benefit.
156
+ - **Klein variants other than `flux2-klein-4b` are not supported in v0.1.** 9b and base configs planned for v0.2.
157
+ - **M3+ users lose mflux's `mx.compile` of `_predict`.** v0.1 provides a manual benchmark recipe (`docs/m3-plus-tradeoff.md`) and does not claim a measured M3+ speedup.
158
+ - **FLUX.2 parity is numerical, not bit-exact.** Because the wrapper replaces a function mflux wraps in `mx.compile`, vanilla-compiled vs wrapper-eager differ by ~1 ULP per element from Metal kernel-dispatch noise (compounds across steps; cosine similarity stays ≥ 0.99). The CFG-fallback path remains bit-exact. End-to-end image quality (SSIM ≥ 0.85 on Klein 4b) is the user-facing guarantee.
159
+ - **mflux pin is strict (`>=0.17,<0.18`).** Bumping requires a deliberate release.
160
+ - **Parent-level `flux.parameters()` may miss transformer parameters while patched.** Use `flux.transformer.parameters()` directly, or `handle.restore()` first.
161
+
162
+ ## Contributing
163
+
164
+ Open an issue at https://github.com/IonDen/mlx-teacache/issues.
165
+
166
+ ## License + acknowledgements
167
+
168
+ Apache-2.0. See `LICENSE` and `NOTICE`.
169
+
170
+ - [ali-vilab/TeaCache](https://github.com/ali-vilab/TeaCache) — upstream method and FLUX.1 coefficients.
171
+ - [filipstrand/mflux](https://github.com/filipstrand/mflux) — MLX FLUX runner this library integrates with.
172
+ - [Apple ML Explore](https://github.com/ml-explore/mlx) — MLX.
@@ -0,0 +1,145 @@
1
+ # mlx-teacache
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/mlx-teacache.svg)](https://pypi.org/project/mlx-teacache/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/mlx-teacache.svg)](https://pypi.org/project/mlx-teacache/)
5
+ [![License: Apache 2.0](https://img.shields.io/pypi/l/mlx-teacache.svg)](https://github.com/IonDen/mlx-teacache/blob/main/LICENSE)
6
+ [![CI](https://github.com/IonDen/mlx-teacache/actions/workflows/ci.yml/badge.svg)](https://github.com/IonDen/mlx-teacache/actions/workflows/ci.yml)
7
+
8
+ **TeaCache step-skipping for FLUX diffusion on Apple Silicon, in pure MLX.**
9
+
10
+ `mlx-teacache` is the first MLX port of TeaCache — a training-free inference optimization that skips ~20-50% of denoising steps in FLUX-family diffusion models by predicting which steps contribute little to the final image. Measured ~1.48× wall-clock speedup at the default threshold on FLUX.1-dev / 25 steps with visually-equivalent output (SSIM ≥ 0.80 on a 5-prompt suite).
11
+
12
+ ## What it does
13
+
14
+ Diffusion models run the same big transformer 20-50 times in a loop. Between consecutive steps the output changes very little; TeaCache uses a tiny polynomial fit to predict which steps can reuse the previous step's output. On M1 Max FLUX.1-dev @ 25 steps the default threshold (`rel_l1_thresh=0.20`) skips 6 of 25 steps for a ~1.48× speedup.
15
+
16
+ ```python
17
+ from mflux.models.flux2.variants.txt2img.flux2_klein import Flux2Klein
18
+ from mflux.models.common.config.model_config import ModelConfig
19
+ from mlx_teacache import apply_teacache
20
+
21
+ flux = Flux2Klein(quantize=4, model_config=ModelConfig.flux2_klein_4b())
22
+ with apply_teacache(flux): # default rel_l1_thresh=0.20
23
+ flux.generate_image(prompt="a red apple", seed=42, num_inference_steps=25)
24
+ ```
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install "mlx-teacache[mflux]"
30
+ # or with uv:
31
+ uv add "mlx-teacache[mflux]"
32
+ ```
33
+
34
+ Requires Python ≥ 3.11 and Apple Silicon. The `[mflux]` extra pulls in `mflux>=0.17,<0.18`.
35
+
36
+ ```bash
37
+ pip install "mlx-teacache==0.1.0[mflux]" # pin for reproducibility
38
+ ```
39
+
40
+ ## Quick start
41
+
42
+ FLUX.1 dev:
43
+
44
+ ```python
45
+ from mflux.models.flux.variants.txt2img.flux import Flux1
46
+ from mlx_teacache import apply_teacache
47
+
48
+ flux = Flux1.from_name("dev", quantize=4)
49
+ with apply_teacache(flux) as handle: # default rel_l1_thresh=0.20
50
+ flux.generate_image(prompt="...", seed=42, num_inference_steps=25, guidance=3.5)
51
+ print(f"Speedup: {handle.stats.speedup_estimate:.2f}×")
52
+ ```
53
+
54
+ ## Threshold guide
55
+
56
+ Measured on M1 Max 32GB, FLUX.1-dev @ 25 steps, bf16, `seed=42`, `guidance=3.5`, red-apple prompt:
57
+
58
+ | `rel_l1_thresh` | Skipped steps | Speedup | SSIM vs vanilla | Recommended use |
59
+ |---|---|---|---|---|
60
+ | 0.10 | 0 / 25 | 1.07× | 1.0000 | Cache never engages |
61
+ | 0.15 | 0 / 25 | 1.13× | 1.0000 | Cache never engages |
62
+ | **0.20 (default)** | **6 / 25** | **1.48×** | **≥ 0.80 (5-prompt suite)** | **Visually-lossless sweet spot** |
63
+ | 0.25 | 11 / 25 | 1.96× | 0.57-0.93 | Visible style changes on text/synthetic prompts |
64
+
65
+ The 0.20 default was chosen after side-by-side visual comparison: at 0.25 a text prompt that vanilla renders as neon tubes can come out as dot-matrix; at 0.20 the output is indistinguishable from vanilla while still skipping ~25% of steps. SSIM is a conservative metric on high-frequency-detail prompts (text, synthetic patterns).
66
+
67
+ ## Supported models
68
+
69
+ | Variant id | mflux class + config | Coefficient source |
70
+ |---|---|---|
71
+ | `flux1-dev` | `Flux1(model_config=ModelConfig.dev())` | upstream ali-vilab/TeaCache |
72
+ | `flux1-schnell` | `Flux1(model_config=ModelConfig.schnell())` | upstream (shared with dev) |
73
+ | `flux2-klein-4b` | `Flux2Klein(model_config=ModelConfig.flux2_klein_4b())` | in-repo (see `docs/calibration.md`) |
74
+
75
+ ## Combining with mlx-taef
76
+
77
+ ```python
78
+ from mlx_taef.integrations.mflux import LivePreviewCallback
79
+ from mlx_teacache import apply_teacache
80
+
81
+ preview = LivePreviewCallback(variant="taef2", every=5, save_to="preview.png",
82
+ latent_height=32, latent_width=32)
83
+ flux.callbacks.register(preview)
84
+
85
+ with apply_teacache(flux): # default rel_l1_thresh=0.20
86
+ flux.generate_image(prompt="...", seed=42, num_inference_steps=25)
87
+ ```
88
+
89
+ ## Inspecting stats
90
+
91
+ ```python
92
+ handle = apply_teacache(flux)
93
+ flux.generate_image(prompt="apple", seed=42, num_inference_steps=25)
94
+ print(handle.stats.computed_count, handle.stats.skipped_count)
95
+ print(handle.stats.last_generation.decisions[5]) # per-step record
96
+ ```
97
+
98
+ ## Custom coefficients
99
+
100
+ ```python
101
+ custom = [...] # length 5, all finite
102
+ apply_teacache(flux, coefficients=custom)
103
+ ```
104
+
105
+ ## How it works
106
+
107
+ TeaCache observes that in diffusion denoising, consecutive transformer outputs change very little between most pairs of adjacent steps. The expensive transformer body (all the joint + single attention blocks) produces a residual that's added to the input — and that residual stays roughly stable for stretches of the denoising trajectory.
108
+
109
+ TeaCache trains a tiny polynomial that predicts how much the output will change given how much the input has changed (measured as relative L1 distance of the modulated block-0 input). When the predicted accumulated change since the last actual compute step is small, TeaCache reuses the cached residual instead of running the full transformer body — only the cheap prelude (embeddings) and tail (norm + projection) still run.
110
+
111
+ mlx-teacache implements this for mflux on Apple Silicon. We replace `flux.transformer` with a per-instance proxy for FLUX.1, and `flux._predict` with an instance-level closure for FLUX.2 (to keep gating live even when `mx.compile` is normally used). The polynomial coefficients for FLUX.1 are vendored from upstream; the FLUX.2 Klein 4b coefficients are derived in-repo via `scripts/calibrate.py`. See the TeaCache paper at https://liewfeng.github.io/TeaCache/ and `docs/superpowers/spikes/2026-05-14-mlx-teacache-phase-0-spike.md` for the Apple-Silicon-specific design notes.
112
+
113
+ ## Benchmarks
114
+
115
+ M1 Max 32GB, default threshold (`rel_l1_thresh=0.20`):
116
+
117
+ | Model | Steps | Vanilla | With TeaCache | Speedup | SSIM (PR-gate prompt) |
118
+ |---|---|---|---|---|---|
119
+ | FLUX.1-dev @ 512² | 25 | ~5:18 | ~3:35 | 1.48× | ≥ 0.90 |
120
+ | FLUX.2 Klein 4b @ 512² | 8 | ~37s | ~30s | ~1.2× | ≥ 0.85 |
121
+
122
+ FLUX.2's smaller speedup at 8 steps reflects the short non-distilled denoising trajectory at Klein's recommended step count. Longer schedules (`num_inference_steps>=15`) give larger gains.
123
+
124
+ ## Limitations
125
+
126
+ - **v0.1 is txt2img only.** img2img inputs raise `Img2ImgNotSupportedError`. v0.2 planned.
127
+ - **FLUX.2 CFG (`guidance > 1.0`) auto-falls-back to vanilla mflux.** Output is bit-exact. v0.2 will add per-branch caching.
128
+ - **Distilled schedules see no speedup.** FLUX.1 schnell 4-step and Klein 4-step defaults have too few non-forced steps. Use `num_inference_steps >= 10` for benefit.
129
+ - **Klein variants other than `flux2-klein-4b` are not supported in v0.1.** 9b and base configs planned for v0.2.
130
+ - **M3+ users lose mflux's `mx.compile` of `_predict`.** v0.1 provides a manual benchmark recipe (`docs/m3-plus-tradeoff.md`) and does not claim a measured M3+ speedup.
131
+ - **FLUX.2 parity is numerical, not bit-exact.** Because the wrapper replaces a function mflux wraps in `mx.compile`, vanilla-compiled vs wrapper-eager differ by ~1 ULP per element from Metal kernel-dispatch noise (compounds across steps; cosine similarity stays ≥ 0.99). The CFG-fallback path remains bit-exact. End-to-end image quality (SSIM ≥ 0.85 on Klein 4b) is the user-facing guarantee.
132
+ - **mflux pin is strict (`>=0.17,<0.18`).** Bumping requires a deliberate release.
133
+ - **Parent-level `flux.parameters()` may miss transformer parameters while patched.** Use `flux.transformer.parameters()` directly, or `handle.restore()` first.
134
+
135
+ ## Contributing
136
+
137
+ Open an issue at https://github.com/IonDen/mlx-teacache/issues.
138
+
139
+ ## License + acknowledgements
140
+
141
+ Apache-2.0. See `LICENSE` and `NOTICE`.
142
+
143
+ - [ali-vilab/TeaCache](https://github.com/ali-vilab/TeaCache) — upstream method and FLUX.1 coefficients.
144
+ - [filipstrand/mflux](https://github.com/filipstrand/mflux) — MLX FLUX runner this library integrates with.
145
+ - [Apple ML Explore](https://github.com/ml-explore/mlx) — MLX.