finaltv971 commited on
Commit
b36071f
·
0 Parent(s):

Release experimental FastFrames-L MLX inference port

Browse files
Files changed (10) hide show
  1. .gitattributes +35 -0
  2. .gitignore +7 -0
  3. LICENSE +88 -0
  4. LICENSE-APACHE-2.0 +201 -0
  5. LICENSE-APPLE-SAMPLE-CODE +38 -0
  6. README.md +110 -0
  7. fastframes_attention.metal +281 -0
  8. generate.py +341 -0
  9. quantize.py +65 -0
  10. requirements.txt +6 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ .venv/
2
+ __pycache__/
3
+ dependencies/
4
+ weights/
5
+ output/
6
+ *.mp4
7
+ *.safetensors
LICENSE ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Disclaimer: IMPORTANT: This Apple Machine Learning Research Model is
2
+ specifically developed and released by Apple Inc. ("Apple") for the sole purpose
3
+ of scientific research of artificial intelligence and machine-learning
4
+ technology. “Apple Machine Learning Research Model” means the model, including
5
+ but not limited to algorithms, formulas, trained model weights, parameters,
6
+ configurations, checkpoints, and any related materials (including
7
+ documentation).
8
+
9
+ This Apple Machine Learning Research Model is provided to You by
10
+ Apple in consideration of your agreement to the following terms, and your use,
11
+ modification, creation of Model Derivatives, and or redistribution of the Apple
12
+ Machine Learning Research Model constitutes acceptance of this Agreement. If You
13
+ do not agree with these terms, please do not use, modify, create Model
14
+ Derivatives of, or distribute this Apple Machine Learning Research Model or
15
+ Model Derivatives.
16
+
17
+ * License Scope: In consideration of your agreement to abide by the following
18
+ terms, and subject to these terms, Apple hereby grants you a personal,
19
+ non-exclusive, worldwide, non-transferable, royalty-free, revocable, and
20
+ limited license, to use, copy, modify, distribute, and create Model
21
+ Derivatives (defined below) of the Apple Machine Learning Research Model
22
+ exclusively for Research Purposes. You agree that any Model Derivatives You
23
+ may create or that may be created for You will be limited to Research Purposes
24
+ as well. “Research Purposes” means non-commercial scientific research and
25
+ academic development activities, such as experimentation, analysis, testing
26
+ conducted by You with the sole intent to advance scientific knowledge and
27
+ research. “Research Purposes” does not include any commercial exploitation,
28
+ product development or use in any commercial product or service.
29
+
30
+ * Distribution of Apple Machine Learning Research Model and Model Derivatives:
31
+ If you choose to redistribute Apple Machine Learning Research Model or its
32
+ Model Derivatives, you must provide a copy of this Agreement to such third
33
+ party, and ensure that the following attribution notice be provided: “Apple
34
+ Machine Learning Research Model is licensed under the Apple Machine Learning
35
+ Research Model License Agreement.” Additionally, all Model Derivatives must
36
+ clearly be identified as such, including disclosure of modifications and
37
+ changes made to the Apple Machine Learning Research Model. The name,
38
+ trademarks, service marks or logos of Apple may not be used to endorse or
39
+ promote Model Derivatives or the relationship between You and Apple. “Model
40
+ Derivatives” means any models or any other artifacts created by modifications,
41
+ improvements, adaptations, alterations to the architecture, algorithm or
42
+ training processes of the Apple Machine Learning Research Model, or by any
43
+ retraining, fine-tuning of the Apple Machine Learning Research Model.
44
+
45
+ * No Other License: Except as expressly stated in this notice, no other rights
46
+ or licenses, express or implied, are granted by Apple herein, including but
47
+ not limited to any patent, trademark, and similar intellectual property rights
48
+ worldwide that may be infringed by the Apple Machine Learning Research Model,
49
+ the Model Derivatives or by other works in which the Apple Machine Learning
50
+ Research Model may be incorporated.
51
+
52
+ * Compliance with Laws: Your use of Apple Machine Learning Research Model must
53
+ be in compliance with all applicable laws and regulations.
54
+
55
+ * Term and Termination: The term of this Agreement will begin upon your
56
+ acceptance of this Agreement or use of the Apple Machine Learning Research
57
+ Model and will continue until terminated in accordance with the following
58
+ terms. Apple may terminate this Agreement at any time if You are in breach of
59
+ any term or condition of this Agreement. Upon termination of this Agreement,
60
+ You must cease to use all Apple Machine Learning Research Models and Model
61
+ Derivatives and permanently delete any copy thereof. Sections 3, 6 and 7 will
62
+ survive termination.
63
+
64
+ * Disclaimer and Limitation of Liability: This Apple Machine Learning Research
65
+ Model and any outputs generated by the Apple Machine Learning Research Model
66
+ are provided on an “AS IS” basis. APPLE MAKES NO WARRANTIES, EXPRESS OR
67
+ IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
68
+ NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE,
69
+ REGARDING THE APPLE MACHINE LEARNING RESEARCH MODEL OR OUTPUTS GENERATED BY
70
+ THE APPLE MACHINE LEARNING RESEARCH MODEL. You are solely responsible for
71
+ determining the appropriateness of using or redistributing the Apple Machine
72
+ Learning Research Model and any outputs of the Apple Machine Learning Research
73
+ Model and assume any risks associated with Your use of the Apple Machine
74
+ Learning Research Model and any output and results. IN NO EVENT SHALL APPLE BE
75
+ LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
76
+ IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF
77
+ THE APPLE MACHINE LEARNING RESEARCH MODEL AND ANY OUTPUTS OF THE APPLE MACHINE
78
+ LEARNING RESEARCH MODEL, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT,
79
+ TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS
80
+ BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
81
+
82
+ * Governing Law: This Agreement will be governed by and construed under the laws
83
+ of the State of California without regard to its choice of law principles. The
84
+ Convention on Contracts for the International Sale of Goods shall not apply to
85
+ the Agreement except that the arbitration clause and any arbitration hereunder
86
+ shall be governed by the Federal Arbitration Act, Chapters 1 and 2. 
87
+
88
+ Copyright (C) 2026 Apple Inc. All Rights Reserved.
LICENSE-APACHE-2.0 ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
LICENSE-APPLE-SAMPLE-CODE ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (C) 2026 Apple Inc. All Rights Reserved.
2
+
3
+ Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of
4
+ your agreement to the following terms, and your use, installation, modification or redistribution of this Apple
5
+ software constitutes acceptance of these terms. If you do not agree with these terms, please do not use,
6
+ install, modify or redistribute this Apple software.
7
+
8
+ In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants
9
+ you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple
10
+ Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in
11
+ source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without
12
+ modifications, you must retain this notice and the following text and disclaimers in all such redistributions of
13
+ the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to
14
+ endorse or promote products derived from the Apple Software without specific prior written permission from
15
+ Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by
16
+ Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or
17
+ by other works in which the Apple Software may be incorporated.
18
+
19
+ The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR
20
+ IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
21
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS
22
+ USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
23
+
24
+ IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
26
+ OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
27
+ REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
28
+ AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
29
+ OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ -------------------------------------------------------------------------------
32
+ SOFTWARE DISTRIBUTED WITH FASTFRAMES:
33
+
34
+ The FastFrames software includes a number of subcomponents with separate
35
+ copyright notices and license terms - please see the file ACKNOWLEDGEMENTS.
36
+ LingBot-World v2 code and weights follow their upstream license - please see
37
+ the file LICENSE_LINGBOT.
38
+ -------------------------------------------------------------------------------
README.md ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: apple-amlr
4
+ license_link: https://huggingface.co/finaltv971/fastframes-l-mlx/blob/main/LICENSE
5
+ library_name: mlx
6
+ pipeline_tag: text-to-video
7
+ base_model: apple/FastFrames-L
8
+ tags:
9
+ - mlx
10
+ - apple-silicon
11
+ - fastframes
12
+ - video-generation
13
+ - research
14
+ ---
15
+
16
+ # FastFrames-L on MLX
17
+
18
+ An unofficial, experimental Apple Silicon inference port of Apple's [FastFrames-L 14B](https://huggingface.co/apple/FastFrames-L). It generates 832 × 480 H.264 video at 16 fps from a text prompt. The repository provides the inference and quantization code. Setup downloads the required checkpoints from their original repositories.
19
+
20
+ **For non-commercial scientific research and academic development under the [Apple Machine Learning Research Model License Agreement](LICENSE).**
21
+
22
+ Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement.
23
+
24
+ ## Tested setup
25
+
26
+ Mac Studio M5 Max with 64 GiB of unified memory, Python 3.13, MLX 0.32.2 and FFmpeg with `libx264`. The standard MLX attention path is the default. The optional Metal/NAX path was tested on the M5 Max.
27
+
28
+ Clone or download this repository, then run these commands from its root.
29
+
30
+ ```sh
31
+ python3.13 -m venv .venv
32
+ . .venv/bin/activate
33
+ python -m pip install -r requirements.txt
34
+ python - <<'PY'
35
+ from huggingface_hub import snapshot_download
36
+
37
+ snapshot_download(
38
+ "apple/FastFrames-L",
39
+ revision="d18ec5f054bb03f6b8e561a63d52af3142b5b81d",
40
+ local_dir="weights",
41
+ allow_patterns=[
42
+ "fastframes-l/dit.safetensors",
43
+ "fastframes-l/kv_refiner.safetensors",
44
+ "fastframes-l/pixel_decoder.safetensors",
45
+ ],
46
+ )
47
+ snapshot_download(
48
+ "mlx-community/FastFrames-S-bf16-mlx",
49
+ revision="08b95d8bd4b77d09b56d732f998d000b0c6b8835",
50
+ local_dir="dependencies/FastFrames-S",
51
+ allow_patterns=["ff_ref.py", "umt5_xxl.safetensors"],
52
+ )
53
+ snapshot_download(
54
+ "Wan-AI/Wan2.1-T2V-1.3B",
55
+ revision="37ec512624d61f7aa208f7ea8140a131f93afc9a",
56
+ local_dir="dependencies/Wan2.1-T2V-1.3B",
57
+ allow_patterns=["google/umt5-xxl/*"],
58
+ )
59
+ PY
60
+ mkdir -p output
61
+ ```
62
+
63
+ Allow about 42 GB for the source weights and a further 15.4 GB to keep the optional Q8 checkpoint alongside them.
64
+
65
+ ### Generate a short BF16 clip
66
+
67
+ ```sh
68
+ python generate.py "A red wooden sailboat glides across a calm pond at golden hour." \
69
+ output/sailboat-bf16.mp4 --seed 42 --latent-frames 5
70
+ ```
71
+
72
+ ### Generate a five-second Q8 clip
73
+
74
+ Run the quantizer once to build `weights/fastframes-l/dit-q8.safetensors`.
75
+
76
+ ```sh
77
+ python quantize.py
78
+ python generate.py "A red wooden sailboat glides across a calm pond at golden hour." \
79
+ output/sailboat-q8.mp4 --seed 42 --latent-frames 21 --dit q8 --eval-every 4 --compile-ffn
80
+ ```
81
+
82
+ Add `--attention nax` to use the experimental Metal kernel on the tested M5 Max configuration. Generation writes an MP4 and an adjacent JSON file containing timings and peak MLX allocations. Five latent frames produce 17 video frames. Twenty-one latent frames produce 81.
83
+
84
+ ## What this port changes
85
+
86
+ - Uses MLX for the frame-causal 40-layer FastFrames-L generator and KV refiner, with the released L-specific denoising schedule and 5120-to-1536 pixel decoder bridge.
87
+ - Reuses the FastFrames-S MLX reference implementation and Wan umT5-XXL text encoder. The L generator, KV refiner and decoder use Apple's FastFrames-L checkpoints.
88
+ - Optionally packs 400 generator projection matrices with 8-bit affine quantization in groups of 64. Other generator parameters, activations, KV cache, refiner and decoder remain in floating point. The generator checkpoint shrinks from 28.58 GB to 15.40 GB.
89
+ - Supports grouping evaluations across layers, compiling the Q8 feed-forward function and using an optional NAX self-attention kernel.
90
+
91
+ ## Local measurements
92
+
93
+ The table reports the elapsed time from Python startup through MP4 export, with source weights already on local storage. Peak memory is the MLX allocation reported during generation.
94
+
95
+ | Configuration | Frames | Elapsed | Peak MLX |
96
+ |---|---:|---:|---:|
97
+ | BF16, standard MLX | 17 | 24.1 s | 40.2 GiB |
98
+ | BF16, standard MLX | 41 | 51.9 s | 47.4 GiB |
99
+ | Q8, NAX, 4-layer evaluation, compiled FFN | 81 | 75.5 s | 47.2 GiB |
100
+
101
+ The last row is the mean of two local runs on one sailboat prompt. A matched pair of runs with the feed-forward compiler disabled averaged 80.6 s, with the same peak MLX allocation. All four decoded Q8 clips matched pixel for pixel on that prompt. This is a small reproducibility check. CUDA output parity, other Mac models and broad quality evaluation remain unverified.
102
+
103
+ The release was also tested in a fresh environment. The BF16 sailboat clip (17 frames) and the Q8 Metal sailboat clip (81 frames) matched the earlier decoded frames exactly. The standard MLX Q8 path generated an 81-frame fox clip in 77.8 s with a peak MLX allocation of 47.2 GiB. All three H.264 files decoded at 832 × 480 and 16 fps.
104
+
105
+ ## Attribution
106
+
107
+ - [Apple FastFrames-L checkpoints](https://huggingface.co/apple/FastFrames-L) and [FastFrames reference implementation](https://github.com/apple-aiml-research/ml-fastframes).
108
+ - [MLX Community FastFrames-S port](https://huggingface.co/mlx-community/FastFrames-S-bf16-mlx) at the revision pinned above.
109
+ - [Wan2.1](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B) for its text tokenizer and encoder.
110
+ - [Apple MLX](https://github.com/ml-explore/mlx). The optional Metal kernel retains its upstream MIT notice.
fastframes_attention.metal ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Adapted from Apple MLX steel_attention_nax.h, copyright 2024–25 Apple Inc.
3
+ MIT License
4
+
5
+ Copyright © 2023 Apple Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+ */
25
+ using namespace mlx::steel;
26
+ struct MaxOp {
27
+ template <typename T> METAL_FUNC static constexpr T apply(T x, T y) {
28
+ return metal::max(x, y);
29
+ }
30
+ };
31
+
32
+ struct SumOp {
33
+ template <typename T> METAL_FUNC static constexpr T apply(T x, T y) {
34
+ return x + y;
35
+ }
36
+ };
37
+
38
+ struct MulOp {
39
+ template <typename T> METAL_FUNC static constexpr T apply(T x, T y) {
40
+ return x * y;
41
+ }
42
+ };
43
+
44
+ struct ExpSubOp {
45
+ template <typename T> METAL_FUNC static constexpr T apply(T x, T y) {
46
+ return fast::exp2(x - y);
47
+ }
48
+ };
49
+
50
+ // Kernel body
51
+ const int active_keys = range_end[0];
52
+ using T = bfloat;
53
+ using AccumType = float;
54
+ constexpr int BQ = 32, BK = 32, BD = 128, WM = 2, WN = 1;
55
+ constexpr bool align_Q = false, align_K = KEY_ALIGNED;
56
+ auto tid = threadgroup_position_in_grid;
57
+ auto simd_group_id = simdgroup_index_in_threadgroup;
58
+ // Keep the head and query-block offsets in 64-bit arithmetic on the M5 NAX path.
59
+ auto Q = query + (ulong(tid.y) * 1600 + ulong(tid.x) * BQ) * BD;
60
+ auto K = keys + ulong(tid.y) * CACHE_ROWS * BD;
61
+ auto V = values + ulong(tid.y) * CACHE_ROWS * BD;
62
+ auto O = result + (ulong(tid.y) * 1560 + ulong(tid.x) * BQ) * BD;
63
+ const metal::uniform<float> scale2 =
64
+ make_uniform(0.08838834764831845f) * make_uniform(1.44269504089f);
65
+
66
+ // Prepare MMA tiles
67
+ constexpr short kU = 16;
68
+
69
+ constexpr int kNWarps = WM * WN;
70
+ static_assert(
71
+ BQ >= (kNWarps * kU) && BQ % (kNWarps * kU) == 0,
72
+ "Each simdgroup must host at least 1 simdgroup matrix along Q sequence.");
73
+
74
+ // Q seq frags per warp
75
+ constexpr int TQ = BQ / (kNWarps * kU);
76
+ // HeadDim frags (all warps load the same frags)
77
+ constexpr int TD = BD / kU;
78
+ // KV seq frags per warp
79
+ constexpr short TK = BK / kU;
80
+
81
+ static_assert(TQ == 1, "Check TQ");
82
+ using otile_t = NAXTile<AccumType, TQ, TD>;
83
+ otile_t Otile;
84
+
85
+ Otile.clear();
86
+
87
+ // Prepare mma tile offsets
88
+ const short tm = kU * TQ * simd_group_id;
89
+ Q += tm * BD;
90
+
91
+ const short2 simd_coord = otile_t::NAXFrag_t::get_coord();
92
+ const short sn = simd_coord.x;
93
+
94
+ // Init row reduction variables
95
+ constexpr short kRowsPT = otile_t::kRowsPerThread;
96
+
97
+ metal::vec<AccumType, kRowsPT> max_score;
98
+ metal::vec<AccumType, kRowsPT> sum_score{0};
99
+
100
+ // Match the finite minimum used by the MLX kernel.
101
+ STEEL_PRAGMA_UNROLL
102
+ for (short i = 0; i < kRowsPT; ++i) {
103
+ max_score[i] = (-FLT_MAX);
104
+ }
105
+
106
+ const int kb_lim = (active_keys + BK - 1) / BK;
107
+
108
+ const bool is_last_q = int(tid.x) == 1560 / BQ;
109
+
110
+ const short lim_rows_q = (1560 % BQ) - tm;
111
+ const short lim_rows_k = (active_keys % BK);
112
+
113
+ NAXTile<T, 1, 1> cached_query[TD];
114
+ STEEL_PRAGMA_UNROLL
115
+ for (short id = 0; id < TD; ++id) {
116
+ const int Q_load_off = id * kU;
117
+ if (!align_Q && is_last_q) {
118
+ cached_query[id].load_rows(Q + Q_load_off, BD, lim_rows_q);
119
+ } else {
120
+ cached_query[id].load(Q + Q_load_off, BD);
121
+ }
122
+ }
123
+ // Loop over KV seq length
124
+ for (int kb = 0; kb < kb_lim; kb++) {
125
+ const int is_last_k = kb == active_keys / BK;
126
+
127
+ // Do S = Q @ K.T
128
+ using stile_t = NAXTile<AccumType, TQ, TK>;
129
+ stile_t Stile;
130
+
131
+ Stile.clear();
132
+
133
+ STEEL_PRAGMA_UNROLL
134
+ for (short iq = 0; iq < TQ; iq++) {
135
+ STEEL_PRAGMA_UNROLL
136
+ for (short ik = 0; ik < TK; ik += 2) {
137
+ #pragma clang loop unroll_count(8)
138
+ for (short id = 0; id < TD; id++) {
139
+
140
+ NAXTile<T, 2, 1> Ktile;
141
+
142
+ const int K_load_off = ik * kU * BD + id * kU;
143
+
144
+ if (!align_K && is_last_k) {
145
+ Ktile.load_rows(K + K_load_off, BD, lim_rows_k - ik * kU);
146
+ } else {
147
+ Ktile.load(K + K_load_off, BD);
148
+ }
149
+
150
+ stile_t::NAXFrag_t::mma(
151
+ Stile.frag_at(iq, ik), Stile.frag_at(iq, ik + 1),
152
+ cached_query[id].frag_at(0, 0), metal::false_type{},
153
+ Ktile.frag_at(0, 0), Ktile.frag_at(1, 0), metal::true_type{});
154
+ }
155
+ }
156
+ }
157
+
158
+ // Scale S
159
+ STEEL_PRAGMA_UNROLL
160
+ for (short ii = 0; ii < stile_t::kElemsPerTile; ii++) {
161
+ Stile.elems()[ii] *= float(scale2);
162
+ }
163
+
164
+ // Mask out length sequence
165
+ if (!align_K && is_last_k) {
166
+ constexpr auto neg_inf = (-FLT_MAX);
167
+
168
+ STEEL_PRAGMA_UNROLL
169
+ for (short iq = 0; iq < TQ; iq++) {
170
+ STEEL_PRAGMA_UNROLL
171
+ for (short ik = 0; ik < TK; ik++) {
172
+ const short col_pos = ik * kU + sn;
173
+
174
+ thread auto &fg = Stile.frag_at(iq, ik);
175
+
176
+ STEEL_PRAGMA_UNROLL
177
+ for (short ii = 0; ii < stile_t::kFragThrRows; ii++) {
178
+ STEEL_PRAGMA_UNROLL
179
+ for (short jj = 0; jj < stile_t::kFragThrCols; jj++) {
180
+ const auto loc = ii * stile_t::kFragThrCols + jj;
181
+ fg[loc] =
182
+ ((col_pos + jj) < (active_keys % BK)) ? fg[loc] : neg_inf;
183
+ }
184
+ }
185
+ }
186
+ }
187
+ }
188
+
189
+ // Update the running softmax over KV tiles.
190
+ metal::vec<AccumType, kRowsPT> new_max;
191
+ metal::vec<AccumType, kRowsPT> factor;
192
+ STEEL_PRAGMA_UNROLL
193
+ for (short i = 0; i < kRowsPT; ++i) {
194
+ new_max[i] = max_score[i];
195
+ }
196
+
197
+ // Row max
198
+ Stile.template row_reduce<MaxOp>(new_max);
199
+
200
+ // exp(Si - rowmax(Si))
201
+ Stile.template row_bin_op<ExpSubOp>(new_max);
202
+
203
+ // Factor exp(rowmax(Si) - rowmax(Si-1))
204
+ STEEL_PRAGMA_UNROLL
205
+ for (short i = 0; i < kRowsPT; ++i) {
206
+ factor[i] = fast::exp2(max_score[i] - new_max[i]);
207
+ max_score[i] = new_max[i];
208
+ }
209
+
210
+ // Row Sum
211
+ STEEL_PRAGMA_UNROLL
212
+ for (short i = 0; i < kRowsPT; ++i) {
213
+ sum_score[i] = sum_score[i] * factor[i];
214
+ }
215
+
216
+ Stile.template row_reduce<SumOp>(sum_score);
217
+
218
+ // Update O
219
+ Otile.template row_bin_op<MulOp>(factor);
220
+
221
+ simdgroup_barrier(mem_flags::mem_none);
222
+
223
+ // Do O = P @ V
224
+ STEEL_PRAGMA_UNROLL
225
+ for (short iq = 0; iq < TQ; iq++) {
226
+ STEEL_PRAGMA_UNROLL
227
+ for (short id = 0; id < TD; id += 2) {
228
+ if constexpr (BD == 128) {
229
+ if (id == 4) {
230
+ threadgroup_barrier(mem_flags::mem_none);
231
+ }
232
+ }
233
+
234
+ STEEL_PRAGMA_UNROLL
235
+ for (short ik = 0; ik < TK; ik++) {
236
+ NAXTile<T, 1, 2> Vtile;
237
+
238
+ const int V_load_off = ik * kU * BD + id * kU;
239
+
240
+ if (!align_K && is_last_k) {
241
+ Vtile.load_rows(V + V_load_off, BD, lim_rows_k - ik * kU);
242
+ } else {
243
+ Vtile.load(V + V_load_off, BD);
244
+ }
245
+
246
+ otile_t::NAXFrag_t::mma(
247
+ Otile.frag_at(iq, id), Otile.frag_at(iq, id + 1),
248
+ Stile.frag_at(iq, ik), metal::false_type{}, Vtile.frag_at(0, 0),
249
+ Vtile.frag_at(0, 1), metal::false_type{});
250
+ }
251
+ }
252
+ }
253
+
254
+ // Prepare for next iteration
255
+ K += BK * BD;
256
+ V += BK * BD;
257
+ }
258
+
259
+ // Normalize output
260
+
261
+ threadgroup_barrier(mem_flags::mem_none);
262
+
263
+ metal::vec<AccumType, kRowsPT> rcp;
264
+ STEEL_PRAGMA_UNROLL
265
+ for (short i = 0; i < kRowsPT; ++i) {
266
+ rcp[i] = 1.f / sum_score[i];
267
+ }
268
+
269
+ Otile.template row_bin_op<MulOp>(rcp);
270
+
271
+ // Store results
272
+ O += tm * BD;
273
+
274
+ if (!align_Q && is_last_q) {
275
+ if (lim_rows_q <= 0)
276
+ return;
277
+
278
+ Otile.store_rows(O, BD, lim_rows_q);
279
+ } else {
280
+ Otile.store(O, BD);
281
+ }
generate.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate FastFrames-L video with MLX using an existing FastFrames-S port."""
3
+
4
+ import argparse
5
+ from functools import cache
6
+ import gc
7
+ import html
8
+ import importlib.util
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ import re
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ from tempfile import NamedTemporaryFile
17
+ from time import perf_counter
18
+
19
+ import mlx.core as mx
20
+ import numpy as np
21
+
22
+ from quantize import BITS, GROUP_SIZE, METADATA
23
+
24
+
25
+ PROJECT_ROOT = Path(__file__).resolve().parent
26
+ DEFAULT_S_MODEL = PROJECT_ROOT / "dependencies/FastFrames-S"
27
+ DEFAULT_TOKENIZER = PROJECT_ROOT / "dependencies/Wan2.1-T2V-1.3B/google/umt5-xxl"
28
+ FIRST_FRAME_STEPS = (1000.0, 937.0, 833.0, 625.0)
29
+ FOLLOWING_STEPS = (1000.0, 833.0)
30
+ LAYERS, HEADS, WIDTH, FFN = 40, 40, 5120, 13824
31
+ GIB = 1024**3
32
+
33
+
34
+ def q8_projection(x, weight, scales, offsets):
35
+ return mx.quantized_matmul(
36
+ x, weight, scales, offsets,
37
+ transpose=True, group_size=GROUP_SIZE, bits=BITS,
38
+ )
39
+
40
+
41
+ def load_large_backbone(port_path):
42
+ # Load a private module so the S text encoder and 1536-wide pixel head
43
+ # can keep using their original dimensions in the normal import.
44
+ spec = importlib.util.spec_from_file_location("_fastframes_l_backbone", port_path / "ff_ref.py")
45
+ backbone = importlib.util.module_from_spec(spec)
46
+ spec.loader.exec_module(backbone)
47
+ backbone.DIM = WIDTH
48
+ backbone.HEADS = HEADS
49
+ backbone.LAYERS = LAYERS
50
+ backbone.FFN = FFN
51
+ backbone.REFINE_T = FOLLOWING_STEPS[-1]
52
+ dense_linear = backbone.lin
53
+
54
+ def linear(x, weights, name, bias=True):
55
+ weight = weights[name + ".weight"]
56
+ if weight.dtype != mx.uint32:
57
+ return dense_linear(x, weights, name, bias)
58
+ y = q8_projection(x, weight, weights[name + ".scales"], weights[name + ".biases"])
59
+ return y + weights[name + ".bias"] if bias else y
60
+
61
+ backbone.lin = linear
62
+ return backbone
63
+
64
+
65
+ def load_nax_attention():
66
+ steel = Path(mx.__file__).parent / "include/mlx/backend/metal/kernels/steel"
67
+ fragments = []
68
+ for filename in ("defines.h", "utils/integral_constant.h", "utils/type_traits.h", "attn/nax.h"):
69
+ lines = (steel / filename).read_text().splitlines()
70
+ fragments.extend(line for line in lines if not line.startswith(("#pragma once", '#include "mlx/')))
71
+ operations, body = (PROJECT_ROOT / "fastframes_attention.metal").read_text().split("// Kernel body")
72
+ kernel = mx.fast.metal_kernel(
73
+ name="fastframes_register_attention",
74
+ input_names=["query", "keys", "values", "range_end"], output_names=["result"],
75
+ header="\n".join(fragments) + "\n" + operations, source=body,
76
+ )
77
+
78
+ @cache
79
+ def range_end(end):
80
+ return mx.array([end], dtype=mx.int32)
81
+
82
+ def attend(query, keys, values, end):
83
+ # The Metal source uses strides of 1,600 query and 1,560 output rows.
84
+ query = mx.pad(query, [(0, 0), (0, 0), (0, 40), (0, 0)])
85
+ return kernel(
86
+ inputs=[query, keys, values, range_end(end)],
87
+ template=[("CACHE_ROWS", keys.shape[2]), ("KEY_ALIGNED", end % 32 == 0)],
88
+ grid=(49 * 64, HEADS, 1), threadgroup=(64, 1, 1),
89
+ output_shapes=[(1, HEADS, 1560, 128)], output_dtypes=[mx.bfloat16],
90
+ )[0]
91
+
92
+ return attend
93
+
94
+
95
+ def make_model(
96
+ backbone, dit_weights, refiner_weights, frame_count, eval_every=1, nax_attention=None,
97
+ compile_ffn=False,
98
+ ):
99
+ gelu = backbone.gelu_tanh
100
+
101
+ def q8_ffn(h, residual, gate, up, down):
102
+ hidden = gelu(q8_projection(h, *up[:3]) + up[3])
103
+ return residual + gate * (q8_projection(hidden, *down[:3]) + down[3])
104
+
105
+ compiled_ffn = mx.compile(q8_ffn) if compile_ffn else None
106
+
107
+ class BoundedWanDiT(backbone.WanDiT):
108
+ def __init__(self, weights, frames):
109
+ super().__init__(weights, frames)
110
+ if compiled_ffn is not None:
111
+ self.ffn_parameters = [
112
+ tuple(
113
+ tuple(weights[f"blocks.{i}.ffn.{layer}.{field}"]
114
+ for field in ("weight", "scales", "biases", "bias"))
115
+ for layer in (0, 2)
116
+ )
117
+ for i in range(LAYERS)
118
+ ]
119
+
120
+ def forward_frame(self, latent, t_cond, text_cache, kv_cache, frame):
121
+ weights = self.W
122
+ e0, e_head = t_cond
123
+ x = self.patch_embed(latent)
124
+ tokens, head_dim = backbone.FRAME_TOKENS, backbone.HD
125
+ start, end = frame * tokens, (frame + 1) * tokens
126
+ lin, norm, rms = backbone.lin, backbone.layer_norm, backbone.rms_norm
127
+ pending = []
128
+
129
+ for index, cache in enumerate(kv_cache):
130
+ block = f"blocks.{index}"
131
+ modulation = weights[block + ".modulation"] + e0
132
+ sh1, sc1, g1, sh2, sc2, g2 = mx.split(modulation, 6, axis=1)
133
+ h = norm(x, 1e-6) * (1 + sc1) + sh1
134
+ attn = block + ".self_attn"
135
+ q = rms(lin(h, weights, attn + ".q"), weights[attn + ".norm_q.weight"], 1e-6)
136
+ k = rms(lin(h, weights, attn + ".k"), weights[attn + ".norm_k.weight"], 1e-6)
137
+ v = lin(h, weights, attn + ".v")
138
+ q = backbone.rope(q.reshape(tokens, HEADS, head_dim), self.rope[frame])
139
+ k = backbone.rope(k.reshape(tokens, HEADS, head_dim), self.rope[frame])
140
+ cache["k"][:, :, start:end] = k.transpose(1, 0, 2)[None]
141
+ cache["v"][:, :, start:end] = v.reshape(tokens, HEADS, head_dim).transpose(1, 0, 2)[None]
142
+ q = q.transpose(1, 0, 2)[None]
143
+ if nax_attention is None:
144
+ attended = backbone.sdpa(q, cache["k"][:, :, :end], cache["v"][:, :, :end])
145
+ else:
146
+ attended = nax_attention(q, cache["k"], cache["v"], end)
147
+ x = x + g1 * lin(attended.transpose(0, 2, 1, 3).reshape(1, tokens, WIDTH), weights, attn + ".o")
148
+
149
+ attn = block + ".cross_attn"
150
+ h = norm(x, 1e-6, weights[block + ".norm3.weight"], weights[block + ".norm3.bias"])
151
+ q = rms(lin(h, weights, attn + ".q"), weights[attn + ".norm_q.weight"], 1e-6)
152
+ q = q.reshape(1, tokens, HEADS, head_dim).transpose(0, 2, 1, 3)
153
+ attended = backbone.sdpa(q, *text_cache[index])
154
+ x = x + lin(attended.transpose(0, 2, 1, 3).reshape(1, tokens, WIDTH), weights, attn + ".o")
155
+ h = norm(x, 1e-6) * (1 + sc2) + sh2
156
+ if compiled_ffn is None:
157
+ x = x + g2 * lin(gelu(lin(h, weights, block + ".ffn.0")), weights, block + ".ffn.2")
158
+ else:
159
+ x = compiled_ffn(h, x, g2, *self.ffn_parameters[index])
160
+ pending.extend((cache["k"], cache["v"]))
161
+ if (index + 1) % eval_every == 0 or index + 1 == len(kv_cache):
162
+ mx.eval(x, pending)
163
+ pending.clear()
164
+
165
+ shift, scale = mx.split(weights["head.modulation"] + e_head, 2, axis=1)
166
+ flow = lin(norm(x, 1e-6) * (1 + scale) + shift, weights, "head.head")
167
+ flow = flow.reshape(backbone.GH, backbone.GW, 2, 2, backbone.Z)
168
+ return flow.transpose(4, 0, 2, 1, 3).reshape(latent.shape), x
169
+
170
+ class FastFramesL(backbone.FastFramesS):
171
+ def __init__(self):
172
+ self.dit = BoundedWanDiT(dit_weights, frame_count)
173
+ self.refiner = backbone.KVRefiner(refiner_weights)
174
+ self.sched = backbone.FlowMatch()
175
+ self._tc = {}
176
+ self._ref_e = None
177
+
178
+ def rollout(self, embedding, seed):
179
+ shape = (frame_count, backbone.Z, backbone.LAT_H, backbone.LAT_W)
180
+ mx.random.seed(seed)
181
+ noise = mx.random.normal(shape, dtype=mx.bfloat16)
182
+ transitions = mx.random.normal((3, *shape), dtype=mx.bfloat16)
183
+ text_cache = self.dit.text_cache(embedding)
184
+ kv_cache = self.dit.new_kv_cache()
185
+ mx.eval(noise, transitions, text_cache, kv_cache)
186
+ features, modulations = [], []
187
+ started = perf_counter()
188
+ for frame in range(frame_count):
189
+ schedule = FIRST_FRAME_STEPS if frame == 0 else FOLLOWING_STEPS
190
+ latent = noise[frame]
191
+ for step, timestep in enumerate(schedule):
192
+ clean, feature, mod = self.predict(latent, timestep, frame, text_cache, kv_cache)
193
+ if step + 1 < len(schedule):
194
+ sigma = self.sched.sigma(schedule[step + 1])
195
+ latent = ((1 - sigma) * clean.astype(mx.float32)
196
+ + sigma * transitions[step, frame].astype(mx.float32)).astype(mx.bfloat16)
197
+ mx.eval(clean, feature, mod, latent)
198
+ print(f"Latent {frame + 1}/{frame_count}, étape {step + 1}/{len(schedule)}", flush=True)
199
+ features.append(feature[0])
200
+ modulations.append(mod[0])
201
+ if frame == 0:
202
+ self.predict(clean, 0.0, frame, text_cache, kv_cache)
203
+ elif frame + 1 < frame_count:
204
+ self.refine(clean, frame, kv_cache)
205
+ mx.eval(kv_cache, features[-1], modulations[-1])
206
+ print(f"Latent {frame + 1}/{frame_count} terminé à {perf_counter() - started:.1f} s", flush=True)
207
+ return mx.stack(features), mx.stack(modulations)
208
+
209
+ return FastFramesL()
210
+
211
+
212
+ def encode_prompt(prompt, tokenizer_dir, model_dir, encoder_type):
213
+ from transformers import AutoTokenizer
214
+
215
+ tokenizer = AutoTokenizer.from_pretrained(str(tokenizer_dir), local_files_only=True)
216
+ cleaned = re.sub(r"\s+", " ", html.unescape(html.unescape(prompt)).strip()).strip()
217
+ tokens = tokenizer(
218
+ [cleaned], padding="max_length", truncation=True, max_length=512,
219
+ add_special_tokens=True, return_tensors="np",
220
+ )
221
+ encoder = encoder_type(mx.load(str(model_dir / "umt5_xxl.safetensors")))
222
+ embedding = encoder(mx.array(tokens["input_ids"][0]), mx.array(tokens["attention_mask"][0]))
223
+ mx.eval(embedding)
224
+ return embedding, mx.get_peak_memory() / GIB
225
+
226
+
227
+ def write_mp4(pixels, output, fps):
228
+ ffmpeg = shutil.which("ffmpeg")
229
+ if ffmpeg is None:
230
+ raise RuntimeError("FFmpeg est requis pour exporter la vidéo.")
231
+ _, height, width, _ = pixels.shape
232
+ with NamedTemporaryFile(dir=output.parent, suffix=".mp4", delete=False) as temp:
233
+ pending = Path(temp.name)
234
+ try:
235
+ subprocess.run(
236
+ [ffmpeg, "-y", "-v", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
237
+ "-s", f"{width}x{height}", "-r", str(fps), "-i", "-", "-c:v", "libx264",
238
+ "-pix_fmt", "yuv420p", "-crf", "18", "-movflags", "+faststart", str(pending)],
239
+ input=pixels.tobytes(), check=True,
240
+ )
241
+ os.link(pending, output)
242
+ finally:
243
+ pending.unlink()
244
+
245
+
246
+ def main():
247
+ parser = argparse.ArgumentParser(description=__doc__)
248
+ parser.add_argument("prompt")
249
+ parser.add_argument("output", type=Path)
250
+ parser.add_argument("--weights", type=Path, default=PROJECT_ROOT / "weights/fastframes-l")
251
+ parser.add_argument("--s-model", type=Path, default=DEFAULT_S_MODEL)
252
+ parser.add_argument("--tokenizer", type=Path, default=DEFAULT_TOKENIZER)
253
+ parser.add_argument("--seed", type=int, default=42)
254
+ parser.add_argument("--latent-frames", type=int, choices=range(2, 22), default=5, metavar="2–21")
255
+ parser.add_argument("--dit", choices=("bf16", "q8"), default="bf16")
256
+ parser.add_argument("--eval-every", type=int, choices=(1, 2, 4), default=1)
257
+ parser.add_argument("--attention", choices=("mlx", "nax"), default="mlx")
258
+ parser.add_argument("--compile-ffn", action="store_true", help="compile the Q8 feed-forward block")
259
+ args = parser.parse_args()
260
+
261
+ if args.compile_ffn and args.dit != "q8":
262
+ parser.error("--compile-ffn nécessite --dit q8")
263
+ dit_name = "dit-q8" if args.dit == "q8" else "dit"
264
+ for name in (dit_name, "kv_refiner", "pixel_decoder"):
265
+ if not (args.weights / f"{name}.safetensors").is_file():
266
+ parser.error(f"Poids manquants : {args.weights / (name + '.safetensors')}")
267
+ if not all((args.s_model / filename).is_file() for filename in ("ff_ref.py", "umt5_xxl.safetensors")):
268
+ parser.error(f"Code ou encodeur FastFrames-S introuvable dans {args.s_model}")
269
+ if not (args.tokenizer / "spiece.model").is_file():
270
+ parser.error(f"Tokenizer Wan introuvable dans {args.tokenizer}")
271
+ if args.output.suffix.lower() != ".mp4" or not args.output.parent.is_dir():
272
+ parser.error("La sortie doit être un fichier .mp4 dans un dossier existant.")
273
+ if args.output.exists() or args.output.with_suffix(".json").exists():
274
+ parser.error(f"Sortie déjà existante : {args.output}")
275
+ sys.path.insert(0, str(args.s_model))
276
+ import ff_ref
277
+
278
+ mx.set_default_device(mx.gpu)
279
+ mx.set_cache_limit(2 * GIB)
280
+ mx.reset_peak_memory()
281
+ started = perf_counter()
282
+ embedding, text_peak = encode_prompt(args.prompt, args.tokenizer, args.s_model, ff_ref.UMT5Encoder)
283
+ gc.collect()
284
+ mx.clear_cache()
285
+ stats = {"model": "apple/FastFrames-L", "prompt": args.prompt, "seed": args.seed,
286
+ "dit_precision": args.dit, "eval_every": args.eval_every, "attention": args.attention,
287
+ "compiled_ffn": args.compile_ffn,
288
+ "text_s": perf_counter() - started, "text_peak_gib": text_peak}
289
+ print(f"Texte encodé en {stats['text_s']:.1f} s", flush=True)
290
+ mx.reset_peak_memory()
291
+
292
+ started = perf_counter()
293
+ backbone = load_large_backbone(args.s_model)
294
+ dit_weights, metadata = mx.load(str(args.weights / f"{dit_name}.safetensors"), return_metadata=True)
295
+ if args.dit == "q8" and metadata != METADATA:
296
+ raise ValueError(f"Métadonnées Q8 incompatibles : {metadata}")
297
+ refiner_weights = mx.load(str(args.weights / "kv_refiner.safetensors"))
298
+ if dit_weights["patch_embedding.weight"].shape != (WIDTH, 16, 1, 2, 2):
299
+ raise ValueError("Le checkpoint ne correspond pas au générateur FastFrames-L.")
300
+ attention = load_nax_attention() if args.attention == "nax" else None
301
+ model = make_model(
302
+ backbone, dit_weights, refiner_weights, args.latent_frames,
303
+ eval_every=args.eval_every, nax_attention=attention, compile_ffn=args.compile_ffn,
304
+ )
305
+ mx.eval(dit_weights, refiner_weights)
306
+ stats["load_s"] = perf_counter() - started
307
+ print(f"Générateur chargé en {stats['load_s']:.1f} s", flush=True)
308
+ started = perf_counter()
309
+ features, modulations = model.rollout(embedding, args.seed)
310
+ mx.eval(features, modulations)
311
+ stats["rollout_s"] = perf_counter() - started
312
+ stats["rollout_peak_gib"] = mx.get_peak_memory() / GIB
313
+ del model, dit_weights, refiner_weights
314
+ gc.collect()
315
+ mx.clear_cache()
316
+
317
+ started = perf_counter()
318
+ weights = mx.load(str(args.weights / "pixel_decoder.safetensors"))
319
+ bridge = weights["bridge.weight"].astype(mx.bfloat16)
320
+ decoder_weights = {
321
+ name.removeprefix("pixel_head."): weight
322
+ for name, weight in weights.items() if name.startswith("pixel_head.")
323
+ }
324
+ decoder = ff_ref.PixelDecoder(decoder_weights, dtype=mx.bfloat16)
325
+ pixels = decoder(features.astype(mx.bfloat16) @ bridge.T, modulations.astype(mx.bfloat16) @ bridge.T)
326
+ frame_count = 4 * args.latent_frames - 3
327
+ # Wan convention: the first latent supplies one RGB frame, then four per latent.
328
+ pixels = pixels[-frame_count:].astype(mx.float32)
329
+ if not mx.all(mx.isfinite(pixels)).item():
330
+ raise RuntimeError("Pixels non finis dans la sortie du décodeur.")
331
+ pixels = np.asarray(mx.round((mx.clip(pixels, -1, 1) + 1) * 127.5).astype(mx.uint8))
332
+ stats["decode_s"] = perf_counter() - started
333
+ stats["frames"] = list(pixels.shape)
334
+ stats["fps"] = 16
335
+ write_mp4(pixels, args.output, fps=stats["fps"])
336
+ args.output.with_suffix(".json").write_text(json.dumps(stats, indent=2) + "\n")
337
+ print(json.dumps(stats, indent=2), flush=True)
338
+
339
+
340
+ if __name__ == "__main__":
341
+ main()
quantize.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Pack FastFrames-L transformer projections as groupwise affine Q8."""
3
+
4
+ import argparse
5
+ import os
6
+ from pathlib import Path
7
+ from tempfile import NamedTemporaryFile
8
+ from time import perf_counter
9
+
10
+ import mlx.core as mx
11
+
12
+
13
+ GROUP_SIZE = 64
14
+ BITS = 8
15
+ METADATA = {"format": "fastframes-l-affine", "bits": str(BITS), "group_size": str(GROUP_SIZE)}
16
+
17
+
18
+ def pack(source, destination):
19
+ if destination.exists() or destination.is_symlink():
20
+ raise FileExistsError(destination)
21
+ mx.set_default_device(mx.gpu)
22
+ mx.set_cache_limit(2 * 1024**3)
23
+ started = perf_counter()
24
+ weights = mx.load(str(source))
25
+ if weights["patch_embedding.weight"].shape != (5120, 16, 1, 2, 2):
26
+ raise ValueError("Le checkpoint ne correspond pas à FastFrames-L.")
27
+ total = 0
28
+ packed = {}
29
+ for name in tuple(weights):
30
+ tensor = weights.pop(name)
31
+ if name.startswith("blocks.") and name.endswith(".weight") and tensor.ndim == 2:
32
+ if tensor.dtype != mx.bfloat16 or tensor.shape[-1] % GROUP_SIZE:
33
+ raise ValueError(f"Projection incompatible : {name}")
34
+ quantized, scales, biases = mx.quantize(tensor, group_size=GROUP_SIZE, bits=BITS)
35
+ mx.eval(quantized, scales, biases)
36
+ prefix = name.removesuffix(".weight")
37
+ packed.update({name: quantized, f"{prefix}.scales": scales, f"{prefix}.biases": biases})
38
+ total += 1
39
+ if total % 100 == 0:
40
+ print(f"{total} matrices quantifiées", flush=True)
41
+ else:
42
+ packed[name] = tensor
43
+ if total != 400:
44
+ raise ValueError(f"Nombre de projections inattendu : {total}")
45
+
46
+ with NamedTemporaryFile(dir=destination.parent, suffix=".safetensors", delete=False) as temp:
47
+ pending = Path(temp.name)
48
+ try:
49
+ mx.save_safetensors(pending, packed, metadata=METADATA)
50
+ os.link(pending, destination)
51
+ finally:
52
+ pending.unlink()
53
+ print(f"{total} matrices · {destination.stat().st_size / 1e9:.2f} Go · "
54
+ f"{perf_counter() - started:.1f} s", flush=True)
55
+
56
+
57
+ def main():
58
+ parser = argparse.ArgumentParser(description=__doc__)
59
+ parser.add_argument("--weights", type=Path, default=Path(__file__).parent / "weights/fastframes-l")
60
+ args = parser.parse_args()
61
+ pack(args.weights / "dit.safetensors", args.weights / "dit-q8.safetensors")
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ mlx==0.32.2
2
+ mlx-metal==0.32.2
3
+ numpy==2.4.2
4
+ transformers==5.9.0
5
+ huggingface-hub[hf_xet]==1.16.1
6
+ sentencepiece==0.2.3