moss-image-mlx 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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,14 @@
1
+ moss-image-mlx
2
+ Copyright 2026 Felix Brener. Licensed under the Apache License, Version 2.0.
3
+
4
+ This project is an independent MLX implementation of MOSS-Image. It is not affiliated with or endorsed by OpenMOSS.
5
+
6
+ It reproduces the inference behaviour of software and models released by others:
7
+ - MOSS-Image (model weights and pipeline_moss_image.py), Copyright OpenMOSS, Apache License 2.0.
8
+ https://github.com/OpenMOSS/MOSS-Image
9
+ - Qwen3.5-9B (the text encoder weights MOSS-Image ships), Copyright Alibaba Cloud (Qwen team), Apache License 2.0.
10
+ - FLUX.2 VAE with the FLUX.2 small decoder (the autoencoder MOSS-Image ships), Copyright Black Forest Labs,
11
+ Apache License 2.0. https://huggingface.co/black-forest-labs/FLUX.2-small-decoder
12
+ - mlx-lm (used as a dependency for the Qwen3.5 backbone), Copyright Apple Inc., MIT License.
13
+
14
+ torch_randn.py and the strip-decoding VAE are adapted from felix-ab/flux3-mlx (Apache License 2.0).
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.4
2
+ Name: moss-image-mlx
3
+ Version: 0.1.0
4
+ Summary: MOSS-Image (OpenMOSS's 5B bilingual text-rendering DiT) on Apple Silicon with MLX: exact port, 9 GB peak
5
+ Author: Felix Brener
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/felix-ab/moss-image-mlx
8
+ Project-URL: Weights, https://huggingface.co/VisualInference/MOSS-Image-SFT-MLX-8bit
9
+ Project-URL: Upstream, https://github.com/OpenMOSS/MOSS-Image
10
+ Keywords: mlx,apple-silicon,text-to-image,diffusion,moss-image,text-rendering,layout
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: MacOS
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ License-File: NOTICE
19
+ Requires-Dist: mlx>=0.32.4
20
+ Requires-Dist: mlx-lm>=0.32.2
21
+ Requires-Dist: numpy
22
+ Requires-Dist: pillow
23
+ Requires-Dist: transformers>=5.3
24
+ Requires-Dist: huggingface_hub
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest>=8; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # moss-image-mlx
30
+
31
+ **MOSS-Image on Apple Silicon.** This is a pure-MLX port of OpenMOSS's 5B text-to-image DiT, the open model built for long bilingual (English and Chinese) text rendering and JSON layout control. The port is verified against the official PyTorch pipeline, reproduces the official sample gallery from its seeds, and runs a 1024² image in **9.3 GB** (8-bit tier) or **7.4 GB** (compact tier).
32
+
33
+ ![Six renders from the 8-bit tier: a bakery sign, a Chinese poster, a layout-JSON jazz poster, a coffee infographic, a handwritten Chinese note, a typed paragraph](docs/showcase.jpg)
34
+
35
+ *All six renders come from the 8-bit tier at 1024², 50 steps, CFG 3, seed 42.*
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install git+https://github.com/felix-ab/moss-image-mlx
41
+ ```
42
+
43
+ macOS on Apple Silicon, Python ≥ 3.11. PyTorch is not needed. (Not on PyPI yet; this installs straight from the GitHub repo.)
44
+
45
+ ## Use
46
+
47
+ ```bash
48
+ moss-mlx "A minimalist book cover with a deep green background. Title at the top in large white letters: \"THE QUIET ORBIT\"." -o cover.png
49
+ ```
50
+
51
+ ![Two road-sign snapshots generated with the 8bit tier: street signs reading HELLO AVE and MLX LN, and a highway LED sign at sunset reading REMINDER: HELLO MLX IT RUNS LOCALLY NOW](docs/hello_mlx.jpg)
52
+
53
+ *8bit tier, official defaults, about 12 minutes each on an M4 Pro. Reproduce both, same seeds: `moss-mlx --batch examples/hello_mlx.jsonl`.*
54
+
55
+ **Which tier you get:**
56
+ - The first run downloads a pre-quantized tier from Hugging Face and caches it:
57
+ - **8bit** on Macs with ≥ 24 GB of memory;
58
+ - **compact** below that.
59
+ - Pick explicitly with `--model 8bit`, `--model compact`, any Hugging Face repo id, or a local directory.
60
+ - The official bf16 checkpoints also work: `--model OpenMOSS-Team/MOSS-Image-SFT`.
61
+
62
+ ```python
63
+ from moss_image_mlx import MOSSImagePipeline, Request, save
64
+ from moss_image_mlx.cli import resolve_model
65
+
66
+ pipe = MOSSImagePipeline(resolve_model("8bit"))
67
+ req = Request(prompt="A neon sign that reads \"OPEN LATE\" above a ramen bar", width=1024, height=1024, seed=7)
68
+ save(pipe(req), req, "ramen.png")
69
+ ```
70
+
71
+ **Options:**
72
+ - **Several seeds or prompts, one model load:** `--seeds 1,2,3,4`, or `--batch jobs.jsonl` with one JSON object per line (any `Request` field, or `{"parameters": "path/to/parameters.json"}`).
73
+ - **Official examples:** `--parameters path/to/parameters.json` renders an OpenMOSS gallery example with its exact settings and seed.
74
+ - **Prompt cache:** prompts are cached, so re-rendering one with a new seed, size or step count skips the 9B text encoder. Disable with `--no-cache`.
75
+ - **Defaults** follow upstream: 50 steps, CFG 3, shift 5, block 22 skipped in the negative branch. Every PNG gets an upstream-style `.json` with its parameters next to it.
76
+
77
+ ## Tiers
78
+
79
+ Measured on a Mac mini M4 Pro (48 GB), 1024², official defaults:
80
+
81
+ | Tier | Transformer + text encoder | Download | Peak memory | Text and layout vs bf16 (14-image eval) |
82
+ |---|---|---|---|---|
83
+ | [`8bit`](https://huggingface.co/VisualInference/MOSS-Image-SFT-MLX-8bit) | 8-bit + 8-bit | 14.1 GB | **9.3 GB** | **identical OCR on every prompt**, same layout boxes, 30.8 dB |
84
+ | [`compact`](https://huggingface.co/VisualInference/MOSS-Image-SFT-MLX-compact) | 8-bit + 6-bit | 12.1 GB | **7.4 GB** | all text still correct, 27.5 dB |
85
+ | [`Base 8bit`](https://huggingface.co/VisualInference/MOSS-Image-Base-MLX-8bit) | 8-bit + 8-bit (Base checkpoint) | 14.1 GB | 9.3–10.2 GB | reproduces the official sample gallery (Base) |
86
+ | official bf16 (`--model OpenMOSS-Team/MOSS-Image-SFT`) | bf16 + bf16 | 27.2 GB | 16.6 GB | reference (fastest: ~11½ min per image) |
87
+
88
+ **Memory:**
89
+ - Peaks are for a short prompt; a 650-token prompt adds about 1 GB.
90
+ - Stages load and free in turn, and the VAE decodes in seamless strips, so the peak is the largest single stage rather than their sum.
91
+ - Batch mode (`--seeds`, `--batch`) keeps the transformer loaded between images: the 8bit tier then peaks at about 10.8 GB.
92
+
93
+ **Speed:** a 1024² image at the official 50 steps with CFG takes about 12½ minutes on an M4 Pro. The model is compute-bound, so quantization saves memory, not time. Few-step turbo support is next.
94
+
95
+ **Rejected tiers:**
96
+ - *4-bit text encoder:* it reflowed a multi-line paragraph out of order in one of two runs, and saved no peak memory.
97
+ - *6-bit and smaller transformers:* too much error at the low-noise steps that settle fine detail.
98
+
99
+ ## Why this port
100
+
101
+ | | moss-image-mlx | mlx-vlm `main` (2026-10-17) |
102
+ |---|---|---|
103
+ | Peak memory, one 1024² image | **9.3 GB** (8bit) / **7.4 GB** (compact) | 38.7 GB |
104
+ | Download | 14.1 / 12.1 GB | 27.2 GB |
105
+ | Official seeds reproduce official images | **yes** (torch CPU-generator noise, training-grid schedule) | no (MLX RNG) |
106
+ | Quantized tiers with text-fidelity evidence | **yes** | bf16 only |
107
+ | Prompt cache, batch/resident mode, layout checker | yes | no |
108
+ | Time per 1024² image (M4 Pro, 50 steps) | ~12½ min (quantized tiers), ~11½ min (bf16) | ~11¾ min (bf16) |
109
+
110
+ *mlx-vlm figures were measured on the same machine with its default pipeline. Its peak comes from an uncapped fp32 VAE decode.*
111
+
112
+ ## How it was verified
113
+
114
+ All checks compare against the official `pipeline_moss_image.py` running in PyTorch 2.14 on the CPU.
115
+
116
+ | Check | Result |
117
+ |---|---|
118
+ | Sampling schedule (sigmas snapped to the training grid) | **bit-identical**, including torch's fused-multiply-add `linspace` |
119
+ | Starting noise for a seed | matches torch's CPU generator to 2e-6 |
120
+ | VAE decode | max error 1.5e-5 |
121
+ | Text encoder | identical tokens; per-token cosine 0.9997–0.9999 |
122
+ | Transformer velocities | at the bf16 noise floor at every timestep; agrees with mlx-vlm's independent implementation |
123
+ | **End to end in fp32** | **69.7 dB vs torch fp32**: the implementation is exact; bf16 differences are rounding |
124
+ | Official gallery, 6 samples, official seeds | **all six reproduce the official composition**; five also match in detail at 20.8–28.6 dB. With this model, bf16 rounding alone moves an image about 23 dB (measured) |
125
+
126
+ ![Official CUDA renders (left) vs this port (right) from the official seeds and settings](docs/gallery_parity.jpg)
127
+
128
+ ## Layout prompts
129
+
130
+ MOSS-Image takes a JSON layout as the prompt. Boxes are `[y_min, x_min, y_max, x_max]` in pixels, with the canvas centre as the origin. Check a layout against the size you will render, and preview its boxes, before spending minutes on an image:
131
+
132
+ ```bash
133
+ moss-mlx-layout check poster.json --size 1024x1024 --preview boxes.png
134
+ moss-mlx "$(cat poster.json)" --width 1024 --height 1024 -o poster.png
135
+ ```
136
+
137
+ `moss_image_mlx.layout.from_top_left()` and `from_normalized_1000()` convert the usual box conventions.
138
+
139
+ ## Exporting your own tier
140
+
141
+ ```bash
142
+ moss-mlx-export --model path/to/MOSS-Image-SFT --dit-quant 8 --te-quant 8 --out MOSS-Image-SFT-MLX-8bit
143
+ ```
144
+
145
+ Quantization runs on the CPU, one module at a time; an export takes about 30 s.
146
+
147
+ ## Limitations
148
+
149
+ - Dense, very small text can still garble, as it does in the original model.
150
+ - The SFT checkpoint shows faint vertical banding on some skies and walls. That is the upstream checkpoint, not the port; a fix is planned.
151
+ - Speed: see above. A turbo (few-step) path is the next release.
152
+ - "Runs on 16 GB Macs" is an expectation from the measured peaks, not yet tested on a 16 GB machine. Reports welcome.
153
+
154
+ ## License
155
+
156
+ Apache-2.0. MOSS-Image is © OpenMOSS (Apache-2.0); the text encoder is Qwen3.5-9B (Apache-2.0); the VAE is FLUX.2 with the FLUX.2 small decoder (Apache-2.0). See [NOTICE](NOTICE). This is an independent port, not affiliated with OpenMOSS.
@@ -0,0 +1,128 @@
1
+ # moss-image-mlx
2
+
3
+ **MOSS-Image on Apple Silicon.** This is a pure-MLX port of OpenMOSS's 5B text-to-image DiT, the open model built for long bilingual (English and Chinese) text rendering and JSON layout control. The port is verified against the official PyTorch pipeline, reproduces the official sample gallery from its seeds, and runs a 1024² image in **9.3 GB** (8-bit tier) or **7.4 GB** (compact tier).
4
+
5
+ ![Six renders from the 8-bit tier: a bakery sign, a Chinese poster, a layout-JSON jazz poster, a coffee infographic, a handwritten Chinese note, a typed paragraph](docs/showcase.jpg)
6
+
7
+ *All six renders come from the 8-bit tier at 1024², 50 steps, CFG 3, seed 42.*
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install git+https://github.com/felix-ab/moss-image-mlx
13
+ ```
14
+
15
+ macOS on Apple Silicon, Python ≥ 3.11. PyTorch is not needed. (Not on PyPI yet; this installs straight from the GitHub repo.)
16
+
17
+ ## Use
18
+
19
+ ```bash
20
+ moss-mlx "A minimalist book cover with a deep green background. Title at the top in large white letters: \"THE QUIET ORBIT\"." -o cover.png
21
+ ```
22
+
23
+ ![Two road-sign snapshots generated with the 8bit tier: street signs reading HELLO AVE and MLX LN, and a highway LED sign at sunset reading REMINDER: HELLO MLX IT RUNS LOCALLY NOW](docs/hello_mlx.jpg)
24
+
25
+ *8bit tier, official defaults, about 12 minutes each on an M4 Pro. Reproduce both, same seeds: `moss-mlx --batch examples/hello_mlx.jsonl`.*
26
+
27
+ **Which tier you get:**
28
+ - The first run downloads a pre-quantized tier from Hugging Face and caches it:
29
+ - **8bit** on Macs with ≥ 24 GB of memory;
30
+ - **compact** below that.
31
+ - Pick explicitly with `--model 8bit`, `--model compact`, any Hugging Face repo id, or a local directory.
32
+ - The official bf16 checkpoints also work: `--model OpenMOSS-Team/MOSS-Image-SFT`.
33
+
34
+ ```python
35
+ from moss_image_mlx import MOSSImagePipeline, Request, save
36
+ from moss_image_mlx.cli import resolve_model
37
+
38
+ pipe = MOSSImagePipeline(resolve_model("8bit"))
39
+ req = Request(prompt="A neon sign that reads \"OPEN LATE\" above a ramen bar", width=1024, height=1024, seed=7)
40
+ save(pipe(req), req, "ramen.png")
41
+ ```
42
+
43
+ **Options:**
44
+ - **Several seeds or prompts, one model load:** `--seeds 1,2,3,4`, or `--batch jobs.jsonl` with one JSON object per line (any `Request` field, or `{"parameters": "path/to/parameters.json"}`).
45
+ - **Official examples:** `--parameters path/to/parameters.json` renders an OpenMOSS gallery example with its exact settings and seed.
46
+ - **Prompt cache:** prompts are cached, so re-rendering one with a new seed, size or step count skips the 9B text encoder. Disable with `--no-cache`.
47
+ - **Defaults** follow upstream: 50 steps, CFG 3, shift 5, block 22 skipped in the negative branch. Every PNG gets an upstream-style `.json` with its parameters next to it.
48
+
49
+ ## Tiers
50
+
51
+ Measured on a Mac mini M4 Pro (48 GB), 1024², official defaults:
52
+
53
+ | Tier | Transformer + text encoder | Download | Peak memory | Text and layout vs bf16 (14-image eval) |
54
+ |---|---|---|---|---|
55
+ | [`8bit`](https://huggingface.co/VisualInference/MOSS-Image-SFT-MLX-8bit) | 8-bit + 8-bit | 14.1 GB | **9.3 GB** | **identical OCR on every prompt**, same layout boxes, 30.8 dB |
56
+ | [`compact`](https://huggingface.co/VisualInference/MOSS-Image-SFT-MLX-compact) | 8-bit + 6-bit | 12.1 GB | **7.4 GB** | all text still correct, 27.5 dB |
57
+ | [`Base 8bit`](https://huggingface.co/VisualInference/MOSS-Image-Base-MLX-8bit) | 8-bit + 8-bit (Base checkpoint) | 14.1 GB | 9.3–10.2 GB | reproduces the official sample gallery (Base) |
58
+ | official bf16 (`--model OpenMOSS-Team/MOSS-Image-SFT`) | bf16 + bf16 | 27.2 GB | 16.6 GB | reference (fastest: ~11½ min per image) |
59
+
60
+ **Memory:**
61
+ - Peaks are for a short prompt; a 650-token prompt adds about 1 GB.
62
+ - Stages load and free in turn, and the VAE decodes in seamless strips, so the peak is the largest single stage rather than their sum.
63
+ - Batch mode (`--seeds`, `--batch`) keeps the transformer loaded between images: the 8bit tier then peaks at about 10.8 GB.
64
+
65
+ **Speed:** a 1024² image at the official 50 steps with CFG takes about 12½ minutes on an M4 Pro. The model is compute-bound, so quantization saves memory, not time. Few-step turbo support is next.
66
+
67
+ **Rejected tiers:**
68
+ - *4-bit text encoder:* it reflowed a multi-line paragraph out of order in one of two runs, and saved no peak memory.
69
+ - *6-bit and smaller transformers:* too much error at the low-noise steps that settle fine detail.
70
+
71
+ ## Why this port
72
+
73
+ | | moss-image-mlx | mlx-vlm `main` (2026-10-17) |
74
+ |---|---|---|
75
+ | Peak memory, one 1024² image | **9.3 GB** (8bit) / **7.4 GB** (compact) | 38.7 GB |
76
+ | Download | 14.1 / 12.1 GB | 27.2 GB |
77
+ | Official seeds reproduce official images | **yes** (torch CPU-generator noise, training-grid schedule) | no (MLX RNG) |
78
+ | Quantized tiers with text-fidelity evidence | **yes** | bf16 only |
79
+ | Prompt cache, batch/resident mode, layout checker | yes | no |
80
+ | Time per 1024² image (M4 Pro, 50 steps) | ~12½ min (quantized tiers), ~11½ min (bf16) | ~11¾ min (bf16) |
81
+
82
+ *mlx-vlm figures were measured on the same machine with its default pipeline. Its peak comes from an uncapped fp32 VAE decode.*
83
+
84
+ ## How it was verified
85
+
86
+ All checks compare against the official `pipeline_moss_image.py` running in PyTorch 2.14 on the CPU.
87
+
88
+ | Check | Result |
89
+ |---|---|
90
+ | Sampling schedule (sigmas snapped to the training grid) | **bit-identical**, including torch's fused-multiply-add `linspace` |
91
+ | Starting noise for a seed | matches torch's CPU generator to 2e-6 |
92
+ | VAE decode | max error 1.5e-5 |
93
+ | Text encoder | identical tokens; per-token cosine 0.9997–0.9999 |
94
+ | Transformer velocities | at the bf16 noise floor at every timestep; agrees with mlx-vlm's independent implementation |
95
+ | **End to end in fp32** | **69.7 dB vs torch fp32**: the implementation is exact; bf16 differences are rounding |
96
+ | Official gallery, 6 samples, official seeds | **all six reproduce the official composition**; five also match in detail at 20.8–28.6 dB. With this model, bf16 rounding alone moves an image about 23 dB (measured) |
97
+
98
+ ![Official CUDA renders (left) vs this port (right) from the official seeds and settings](docs/gallery_parity.jpg)
99
+
100
+ ## Layout prompts
101
+
102
+ MOSS-Image takes a JSON layout as the prompt. Boxes are `[y_min, x_min, y_max, x_max]` in pixels, with the canvas centre as the origin. Check a layout against the size you will render, and preview its boxes, before spending minutes on an image:
103
+
104
+ ```bash
105
+ moss-mlx-layout check poster.json --size 1024x1024 --preview boxes.png
106
+ moss-mlx "$(cat poster.json)" --width 1024 --height 1024 -o poster.png
107
+ ```
108
+
109
+ `moss_image_mlx.layout.from_top_left()` and `from_normalized_1000()` convert the usual box conventions.
110
+
111
+ ## Exporting your own tier
112
+
113
+ ```bash
114
+ moss-mlx-export --model path/to/MOSS-Image-SFT --dit-quant 8 --te-quant 8 --out MOSS-Image-SFT-MLX-8bit
115
+ ```
116
+
117
+ Quantization runs on the CPU, one module at a time; an export takes about 30 s.
118
+
119
+ ## Limitations
120
+
121
+ - Dense, very small text can still garble, as it does in the original model.
122
+ - The SFT checkpoint shows faint vertical banding on some skies and walls. That is the upstream checkpoint, not the port; a fix is planned.
123
+ - Speed: see above. A turbo (few-step) path is the next release.
124
+ - "Runs on 16 GB Macs" is an expectation from the measured peaks, not yet tested on a 16 GB machine. Reports welcome.
125
+
126
+ ## License
127
+
128
+ Apache-2.0. MOSS-Image is © OpenMOSS (Apache-2.0); the text encoder is Qwen3.5-9B (Apache-2.0); the VAE is FLUX.2 with the FLUX.2 small decoder (Apache-2.0). See [NOTICE](NOTICE). This is an independent port, not affiliated with OpenMOSS.
@@ -0,0 +1,6 @@
1
+ """MOSS-Image on Apple Silicon (MLX)."""
2
+
3
+ from .pipeline import MOSSImagePipeline, Request, save
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["MOSSImagePipeline", "Request", "save", "__version__"]
@@ -0,0 +1,57 @@
1
+ """On-disk cache of prompt embeddings.
2
+
3
+ Re-rendering a prompt (new seed, steps, size or guidance) then skips the 9B text encoder entirely: no ~16 GB (bf16)
4
+ load and no encode. Entries are keyed by the encoder's identity (config, weight files, quantization, the
5
+ implementation's numerics version), the token limit and the exact prompt text.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+
15
+ import mlx.core as mx
16
+
17
+ # Bump when the encoder numerics change, so stale embeddings are never reused.
18
+ ENCODER_NUMERICS_VERSION = "transformers-faithful-1"
19
+
20
+
21
+ def default_cache_dir() -> Path:
22
+ return Path(os.environ.get("MOSS_MLX_CACHE", Path.home() / ".cache" / "moss-image-mlx")) / "prompt-embeds"
23
+
24
+
25
+ def encoder_id(text_encoder_dir: str | Path) -> str:
26
+ d = Path(text_encoder_dir)
27
+ h = hashlib.sha256(ENCODER_NUMERICS_VERSION.encode())
28
+ h.update((d / "config.json").read_bytes())
29
+ for f in sorted(d.glob("*.safetensors")):
30
+ h.update(f"{f.name}:{f.stat().st_size}".encode())
31
+ return h.hexdigest()[:16]
32
+
33
+
34
+ class PromptCache:
35
+ def __init__(self, text_encoder_dir: str | Path, root: str | Path | None = None, tag: str = "bf16"):
36
+ """tag distinguishes encoder variants built from the same files (e.g. quantized at load)."""
37
+ self.dir = Path(root or default_cache_dir()) / f"{encoder_id(text_encoder_dir)}-{tag}"
38
+
39
+ def _path(self, prompt: str, max_tokens: int) -> Path:
40
+ key = hashlib.sha256(json.dumps([prompt, max_tokens], ensure_ascii=False).encode()).hexdigest()
41
+ return self.dir / f"{key}.safetensors"
42
+
43
+ def get(self, prompt: str, max_tokens: int) -> mx.array | None:
44
+ path = self._path(prompt, max_tokens)
45
+ if not path.exists():
46
+ return None
47
+ try:
48
+ return mx.load(str(path))["hidden"]
49
+ except Exception:
50
+ return None
51
+
52
+ def put(self, prompt: str, max_tokens: int, hidden: mx.array):
53
+ self.dir.mkdir(parents=True, exist_ok=True)
54
+ path = self._path(prompt, max_tokens)
55
+ tmp = path.with_suffix(".tmp.safetensors")
56
+ mx.save_safetensors(str(tmp), {"hidden": hidden})
57
+ tmp.replace(path)