Nekochu commited on
Commit
dadc4db
·
verified ·
1 Parent(s): b976281

ONNX export of dflow_2b + 4-step eDMD/LADD LoRA for WebGPU (4-bit)

Browse files
.gitattributes CHANGED
@@ -33,3 +33,10 @@ saved_model/**/* 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
 
 
 
 
 
 
 
 
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
36
+ dit_a/dit_a.onnx.data filter=lfs diff=lfs merge=lfs -text
37
+ dit_b/dit_b.onnx.data filter=lfs diff=lfs merge=lfs -text
38
+ dit_c/dit_c.onnx.data filter=lfs diff=lfs merge=lfs -text
39
+ dit_d/dit_d.onnx.data filter=lfs diff=lfs merge=lfs -text
40
+ text/text.onnx.data filter=lfs diff=lfs merge=lfs -text
41
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
42
+ vae_dec/vae_dec.onnx.data filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ModelGo Attribution-NonCommercial License
2
+ Version 2.0, May 2025
3
+
4
+ By exercising the rights granted in Section 2.1, You acknowledge and agree that You have
5
+ read, understood, and agree to be bound by the terms and conditions of this License. If You
6
+ do not agree to any terms and/or conditions of this License, then the Licensor grants You no
7
+ rights under this License.
8
+
9
+ 1. DEFINITIONS
10
+
11
+ "Complementary Materials" means the source code and scripts used to define, run, load,
12
+ benchmark and/or evaluate the Model, and prepare data for the purpose of training, pretraining,
13
+ fine-tuning and/or evaluation of the Model, and any tutorials, operating manuals, user guides
14
+ and/or documentation that guide users in using, operating, implementing and/or customising
15
+ the Model.
16
+
17
+ "Derivative Materials" means all improvements, modifications or derivative works to the
18
+ Licensed Material or any part thereof, which are created or developed by You (either by
19
+ Yourself or jointly with other third parties), including any derivative model developed by
20
+ transferring patterns of weights, parameters, activations and/or Output from the Model, such as
21
+ through distillation methods or synthetic data generation techniques, in order to replicate,
22
+ approximate, or otherwise achieve functional behavior that is similar to the Model.
23
+
24
+ "Distribution" (or "Distribute") means any transmission, publication, public performance,
25
+ sharing, or other methods of making the Licensed Materials, Derivative Materials and/or Output
26
+ available to a third party, including providing the Licensed Materials or any part thereof as a
27
+ hosted service or remotely accessible service, such as API-based access or web access.
28
+
29
+ "Licensor" means the rights owner that is granting the License.
30
+
31
+ "Licensed Materials" means the Model and Complementary Materials that are Distributed by
32
+ the Licensor under this License. The Licensed Materials do not include any datasets used for
33
+ pretraining, training, adapting, or evaluating the Model, which may or may not be made
34
+ available under a separate license.
35
+
36
+ "Model" means the machine-learning constructs and/or assemblies licensed by the Licensor
37
+ under this License, including any checkpoints, learned weights, parameters (including optimizer
38
+ states) and the model architecture.
39
+
40
+ "NonCommercial" means not primarily intended for or directed towards commercial advantage
41
+ or monetary compensation.
42
+
43
+ "Output" means any information, data, and/or content, including but not limited to images, text,
44
+ text effects, audio files, and/or video files, generated through operation of the Model, or through
45
+ operation of any new model developed by transferring patterns from the Model.
46
+
47
+ "You" (or "Your") means you, or any other person or entity you are entering into this license on
48
+ behalf of, provided you have the legal authority to bind such person or entity.
49
+
50
+ 2. LICENSE RIGHTS
51
+
52
+ 2.1 Grant of Rights
53
+
54
+ (a) Subject to the conditions in Section 2.2 of this License, the Licensor hereby grants to
55
+ You a non-exclusive, non-sublicensable, revocable, royalty-free, worldwide license under
56
+ the relevant copyrights, patent rights, database rights, and any other intellectual property
57
+ rights to:
58
+
59
+ (i) make, have made, use, reproduce and Distribute the Licensed Materials;
60
+
61
+ (ii) use the Licensed Materials to create Derivative Materials; and
62
+
63
+ (iii) make, have made, use, reproduce and Distribute Derivative Materials;
64
+
65
+ for NonCommercial purposes only.
66
+
67
+ 2.2 Conditions
68
+
69
+ (a) If You Distribute any of the Licensed Materials or Derivative Materials, You shall:
70
+
71
+ (i) provide a copy of this License with the Licensed Material or Derivative Materials;
72
+
73
+ (ii) in the case of Distributing Derivative Materials, provide as part of the Distribution,
74
+ prominent notices stating that You have modified the Licensed Materials and the
75
+ relevant date of such modification;
76
+
77
+ (iii) retain as part of the Distribution any existing copyright notice, attribution notice,
78
+ and/or any notice identifying the authors of the Licensed Materials and any
79
+ Derivative Materials.
80
+
81
+ (b) If You Distribute a collection of Output as a dataset generated wholly or partially using
82
+ the Licensed Materials and/or Derivative Materials, You shall provide a prominent notice
83
+ in the Distribution stating that the dataset is generated using the Licensed Materials
84
+ and/or Derivative Materials provided under this License.
85
+
86
+ 2.3 Reservation of Rights
87
+
88
+ You shall not refer to the Licensor or use the Licensor's trademarks, trade names, and service
89
+ marks, for any publicity, advertising or marketing purposes, without the Licensor's prior written
90
+ consent.
91
+
92
+ 3. DISCLAIMER
93
+
94
+ To the maximum extent permissible under applicable law, the Licensed Materials are provided
95
+ on an "as is" and "as available" basis without any representation or warranty of any kind
96
+ (whether express, implied, statutory or otherwise), including of merchantability, satisfactory
97
+ quality, fitness for a particular purpose, title, accuracy, correctness, absence of error, reliability,
98
+ timeliness, non-infringement of or compliance with any laws, regulations and/or third-party
99
+ rights, all of which are expressly disclaimed by the Licensor.
100
+
101
+ 4. LIMITATION OF LIABILITY
102
+
103
+ To the maximum extent permissible under applicable law, the Licensor shall not be liable for
104
+ any claims, damages, or any other liabilities, in any way arising out of or in connection with the
105
+ Licensed Materials, Derivative Materials, and/or Output, whether on an action or claim in
106
+ contract, tort (including negligence), breach of statutory duty or otherwise, even if the Licensor
107
+ has been advised of the possibility of such damages.
108
+
109
+ 5. TERMINATION
110
+
111
+ This License shall terminate immediately if You breach any material term and/or condition of
112
+ this License, or if You initiate any legal action against the Licensor alleging that the Licensed
113
+ Materials and/or Derivative Materials infringe any patent worldwide. Sections 3, 4 and 6 shall
114
+ survive the termination of this License.
115
+
116
+ 6. MODIFICATION OF THIS LICENSE
117
+
118
+ This License is Copyright © 2024 National University of Singapore. Permission is granted to
119
+ copy, distribute, or communicate this License without modification. Nothing in this License
120
+ permits You to modify this License as applied to the Licensed Materials. However, You may
121
+ modify the text of this License and copy, distribute or communicate Your modified version and
122
+ apply it to other original works of authorship, provided that You do not use the name "ModelGo"
123
+ for your version of the license and furnish a readable notice describing Your modifications to
124
+ this License.
README.md ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: mg-by-nc-2.0
4
+ license_link: LICENSE
5
+ base_model:
6
+ - data-archetype/dflow_2b
7
+ - lvladikov/DFlow2-Distill-4steps-eDMD-LADD-LoRA
8
+ base_model_relation: quantized
9
+ pipeline_tag: text-to-image
10
+ library_name: onnxruntime
11
+ tags:
12
+ - onnx
13
+ - webgpu
14
+ - onnxruntime-web
15
+ - text-to-image
16
+ - dflow
17
+ - few-step
18
+ ---
19
+
20
+ # DFlow2 4-step, ONNX for WebGPU
21
+
22
+ [dflow_2b](https://huggingface.co/data-archetype/dflow_2b) (v0.215) with the 4-step
23
+ [eDMD + LADD LoRA](https://huggingface.co/lvladikov/DFlow2-Distill-4steps-eDMD-LADD-LoRA) (`chk00003000`)
24
+ merged in, converted to ONNX so it runs in a web browser on the visitor's own GPU with
25
+ [ONNX Runtime Web](https://onnxruntime.ai/docs/tutorials/web/). No server, no Python.
26
+
27
+ **Try it:** [WeReCooking2/DFlow2-WebGPU](https://huggingface.co/spaces/WeReCooking2/DFlow2-WebGPU)
28
+
29
+ ## Files
30
+
31
+ | part | runs on | weights | what it does |
32
+ |---|---|---|---|
33
+ | `text/` | WASM (CPU) | 8-bit | T5Gemma 2 encoder layers 1 to 12, the three tap projections, the learned suffix tokens and the 2 text-refiner blocks |
34
+ | `dit_a/` | WebGPU | 4-bit, AdaLN 8-bit | latent embed, time embed, 6 prefix blocks |
35
+ | `dit_b/`, `dit_c/` | WebGPU | 4-bit, AdaLN 8-bit | the 18 middle blocks, 9 each |
36
+ | `dit_d/` | WebGPU | 4-bit, AdaLN 8-bit | tail join, 6 suffix blocks, velocity head |
37
+ | `vae_dec/` | WebGPU | 8-bit | [dinac3_96](https://huggingface.co/data-archetype/dinac3_96) decoder, de-whitening, output in [0, 1] |
38
+ | `embed_bf16.bin` | | bf16, raw | token embeddings `[262144, 640]`, read row by row with HTTP Range (a prompt needs a few KB of it) |
39
+ | `tokenizer.json` | | | the T5Gemma 2 tokenizer |
40
+ | `manifest.json` | | | part sizes for download progress |
41
+
42
+ About 1.7 GB to download in total; the page stores it in the browser after the first visit.
43
+
44
+ Weights are `MatMulNBits` (block 32, asymmetric) with fp32 activations, so they run on any WebGPU device,
45
+ including ones without `shader-f16`. The text graph stays on WASM because Gemma's hidden states have
46
+ channels far outside fp16 range.
47
+
48
+ All RoPE tables are graph inputs computed by the page, so every graph takes any image size (multiple
49
+ of 16) and any prompt length up to 256 tokens with no fixed shape baked in.
50
+
51
+ ## Sampling
52
+
53
+ 4 Euler steps, CFG and path-drop guidance off, the `beta_1_25` schedule with the training resolution
54
+ shift `s = min(0, -0.25 - ln(W·H / 256²))`, self-attention gain -0.03 up to about 1 MP (closer to 0
55
+ above), as the LoRA was trained. The JS port of the schedule reproduces the LoRA's own recorded grids
56
+ (`[1.0, 0.920527, 0.816588, 0.631176, 0.0]` at 832×1216) exactly.
57
+
58
+ ## How it was checked
59
+
60
+ Against a float32 PyTorch reference of the release code on CPU, same noise:
61
+
62
+ | stage | fp32 ONNX | this repo (4-bit) |
63
+ |---|---|---|
64
+ | refined text tokens, cosine | 1.000000 | 0.99997 |
65
+ | velocity at step 1, cosine | 1.000000 | 0.99914 |
66
+ | worst step, reference input fed at each step | 1.000000 | 0.9937 |
67
+ | final image PSNR vs fp32, 512×512 | 125 dB | 27 dB (same scene and layout) |
68
+
69
+ The browser pipeline (JS tokenizer, RoPE, schedule, Euler loop, ORT Web WebGPU) was then run in
70
+ Chromium and matched ONNX Runtime on CPU to a cosine of 0.99999999 on the final image. The JS tokenizer
71
+ reproduces dflow's prompt rules (`<bos>` frame, quoted text split into single characters) and matched
72
+ the Python token ids on every test prompt.
73
+
74
+ 8-bit everywhere scores 0.99995 on the worst step but is 2.2 GB for the denoiser; 4-bit is 1.27 GB.
75
+ `scripts/` holds the export, quantization and verification code.
76
+
77
+ ## Licences
78
+
79
+ Different parts come under different terms; all of them allow redistribution with the notices below.
80
+
81
+ - **dflow_2b weights and the LoRA:** ModelGo Attribution-NonCommercial License 2.0 (MG-BY-NC-2.0),
82
+ [`LICENSE`](LICENSE). Non-commercial use only.
83
+
84
+ This project uses dflow_2b by Data Archetype.
85
+ https://huggingface.co/data-archetype/dflow_2b
86
+
87
+ The LoRA is by lvladikov,
88
+ https://huggingface.co/lvladikov/DFlow2-Distill-4steps-eDMD-LADD-LoRA, under the same licence
89
+ ([`licenses/LICENSE-LoRA-MG-BY-NC-2.0`](licenses/LICENSE-LoRA-MG-BY-NC-2.0)).
90
+
91
+ - **Text encoder (`text/`, `embed_bf16.bin`, `tokenizer.json`):** Gemma is provided under and subject to the
92
+ Gemma Terms of Use found at gemma.ai/resources/terms. A copy is in
93
+ [`licenses/LICENSE-GEMMA.md`](licenses/LICENSE-GEMMA.md); use is subject to the restrictions in its
94
+ Section 3.2, including the Gemma Prohibited Use Policy at gemma.ai/resources/prohibited_use_policy.
95
+ Modification notice: these files derive from Data Archetype's modified copy of part of
96
+ google/t5gemma-2-270m-270m (tokenizer, token embeddings, encoder layers 1 to 12). In November 2026 they
97
+ were further converted to ONNX, with the encoder layers quantized to 8 bits and the embeddings stored as
98
+ a raw bfloat16 table.
99
+
100
+ - **Decoder (`vae_dec/`):** from data-archetype/dinac3_96, Apache-2.0
101
+ ([`licenses/LICENSE-dinac3_96-Apache-2.0`](licenses/LICENSE-dinac3_96-Apache-2.0)), with the DINOv3
102
+ License Agreement it ships ([`licenses/LICENSE-DINOV3.md`](licenses/LICENSE-DINOV3.md)). Converted to
103
+ ONNX and quantized to 8 bits.
104
+
105
+ Third-party material is listed in `licenses/ATTRIBUTION-*.md`.
dit_a/dit_a.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d073d4d0443cf105d50a2803dc4b59f4a6c7bf28f68e5b54fbae4c8c0fd7ecb6
3
+ size 259121
dit_a/dit_a.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20b13bbc09291a1ab0ed501d2fa522977d8341ad9ae61adb42190d0c826d5bb1
3
+ size 263442432
dit_b/dit_b.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dee01a511a604fea5f9a626161979ee2510a4f52ac895b33ae8cf36de23dd36f
3
+ size 358898
dit_b/dit_b.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6430288eaef19c9268401cb329bfc0e703cc37cb2553fd2dd8084c5d3403e217
3
+ size 392905728
dit_c/dit_c.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b6de768fb0a5df8e127a49fcac599a37d63d0edcd8ed2ff4c13e274e9ae90d3
3
+ size 358898
dit_c/dit_c.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:99e2d9ae68f4f04b6d8ee290acd58145e2b48e30034fa437cc28e7f513448f87
3
+ size 392905728
dit_d/dit_d.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c9cf9d4b6216267dc9e6640a095b74c7a9714928911db96a7cad77237f5a0ed
3
+ size 265008
dit_d/dit_d.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd638f989df2c3963c486394eb18ebc1a994bc4160c5b2e74bd0987765df670c
3
+ size 277137792
embed_bf16.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b63533df50fdd66185fbf4a0e6c4ef4f473ab41783ad1e0d17ed6af240edc75
3
+ size 335544320
licenses/ATTRIBUTION-dflow_2b.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Attribution
2
+
3
+ ## T5Gemma 2 text encoder
4
+
5
+ The `text_encoder/` folder is derived from
6
+ [`google/t5gemma-2-270m-270m`](https://huggingface.co/google/t5gemma-2-270m-270m),
7
+ published by Google, at revision `7c38f16641f455ef0685b18431faf1b17722d5a1`.
8
+
9
+ > Zhang et al., "T5Gemma 2: Seeing, Reading, and Understanding Longer," 2025.
10
+ > [arXiv:2512.14856](https://arxiv.org/abs/2512.14856)
11
+
12
+ The folder is a modified copy of the original. It contains only what dflow_2b
13
+ uses for prompt conditioning:
14
+
15
+ - the tokenizer files, unchanged;
16
+ - the token embeddings;
17
+ - encoder layers 1 to 12.
18
+
19
+ The remaining encoder layers and the whole decoder are not included. The kept
20
+ weights are stored in bfloat16 with their values unchanged and with shortened
21
+ tensor names. Data Archetype made these modifications in November 2026.
22
+
23
+ Gemma is provided under and subject to the Gemma Terms of Use found at
24
+ [gemma.ai/resources/terms](https://gemma.ai/resources/terms). A copy of the
25
+ terms is in `text_encoder/LICENSE-GEMMA.md`. Use of the text encoder is subject
26
+ to the use restrictions in Section 3.2 of those terms, which include the
27
+ [Gemma Prohibited Use Policy](https://gemma.ai/resources/prohibited_use_policy).
28
+ The bundled files are not relicensed under MG-BY-NC-2.0.
29
+
30
+ ## dinac3_96 autoencoder
31
+
32
+ dflow_2b generates latents for the separately published
33
+ [`data-archetype/dinac3_96`](https://huggingface.co/data-archetype/dinac3_96)
34
+ autoencoder. The loader downloads it at the pinned commit
35
+ `d0ca36daa3e429a510ba465a5f7f8139c66d2f82`. It is not part of this repository,
36
+ and its own repository is the authority for its code, model card and licence.
37
+
38
+ ## dflow_2b
39
+
40
+ The model weights, the `dflow` package, the documentation and the gallery
41
+ images are distributed under the ModelGo Attribution-NonCommercial License 2.0
42
+ (`MG-BY-NC-2.0`). See `LICENSE`, and retain `NOTICE` in any distribution.
43
+
44
+ The ComfyUI nodes in `comfyui/` and the root `__init__.py` are distributed
45
+ under GPL-3.0. See `comfyui/LICENSE`.
licenses/ATTRIBUTION-dinac3_96.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Attribution
2
+
3
+ Licensing (code and weights) is stated once, in the License section of the model
4
+ card (README.md).
5
+
6
+ - **DINOv3 pretrained encoder:** Meta,
7
+ [official repository](https://github.com/facebookresearch/dinov3),
8
+ [paper](https://arxiv.org/abs/2508.10104),
9
+ [timm model](https://huggingface.co/timm/vit_base_patch16_dinov3.lvd_1689m).
10
+ The transformer blocks are used frozen; the input patch embedding is adapted
11
+ for this autoencoder. The weights are therefore distributed under the included
12
+ [DINOv3 License](LICENSE-DINOV3.md); see the model card's License section.
13
+ - **Encoder implementation:** provided by the separately installed
14
+ [timm](https://github.com/huggingface/pytorch-image-models) dependency, pinned
15
+ to `timm==1.0.26`.
16
+ - **semantic_vae** ([well9472/semantic_vae](https://huggingface.co/well9472/semantic_vae)):
17
+ the design follows its key ideas. These are a pretrained DINO encoder adapted
18
+ at its edges and a latent split into a reconstruction part and a DINO-derived
19
+ part. Its encoder has two DINOv2-B branches: one with a trainable patch
20
+ embedding, whose last six blocks are each LayerNormed and projected to 32
21
+ channels, and one fully frozen, whose final block is projected to 32 channels.
22
+ We also follow it in training the decoder mainly with a DINO feature loss and
23
+ in using VISReg as the latent regularizer.¹ No code or weights from it are included.
24
+ - **Decoder up-path:** the VQGAN f16 decoder layout of Esser, Rombach and Ommer,
25
+ [Taming Transformers for High-Resolution Image Synthesis](https://arxiv.org/abs/2012.09841),
26
+ slightly modernized (per-position RMSNorm, folded upsampling) and behind a ViT
27
+ trunk.
28
+ - **Earlier decoder head (not in the release):** a pixel-level head after
29
+ [PixelDiT](https://arxiv.org/abs/2511.20645)
30
+ ([NVlabs/PixelDiT](https://github.com/NVlabs/PixelDiT)), with the FCDM block of
31
+ Kwon et al.,
32
+ [Reviving ConvNeXt for Efficient Convolutional Diffusion Models](https://arxiv.org/abs/2603.09408),
33
+ as its token mixer. The released encoder and decoder trunk were trained with it
34
+ before the convolutional head replaced it.
35
+ - **Latent regularizer:** [VISReg](https://arxiv.org/abs/2606.02572)
36
+ ([project page](https://haiyuwu.github.io/visreg/)), used during training only.
37
+ - **Optimizer (training only, not a runtime dependency):**
38
+ [dionw](https://github.com/JTriggerFish/dionw), a single-GPU implementation of
39
+ [Dion](https://arxiv.org/abs/2504.05295) /
40
+ [Dion3](https://arxiv.org/abs/2608.11612) with
41
+ [NorMuon](https://arxiv.org/abs/2510.05491) normalization, using kernels from
42
+ [microsoft/dion](https://github.com/microsoft/dion) and
43
+ [Dao-AILab/gram-newton-schulz](https://github.com/Dao-AILab/gram-newton-schulz).
44
+ - **Training data:** about 14 million images from a mix of public and licensed
45
+ or curated datasets: mostly photographs, plus book covers, a few text-heavy
46
+ datasets and 1% synthetic rendered text. No training images are redistributed.
47
+
48
+ ¹ semantic_vae's public model card names SIGReg (from LeJEPA) at 1e-3 as its
49
+ regularizer. We verified in its released training code that the regularizer is
50
+ VISReg, at 1e-3.
licenses/LICENSE-DINOV3.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DINOv3 License
2
+
3
+ *Last Updated: August 19, 2025*
4
+
5
+ **“Agreement”** means the terms and conditions for use, reproduction, distribution and modification of the DINO Materials set forth herein.
6
+
7
+ **“DINO Materials”** means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement.
8
+
9
+ **“Documentation”** means the specifications, manuals and documentation accompanying
10
+ DINO Materials distributed by Meta.
11
+
12
+ **“Licensee”** or **“you”** means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
13
+
14
+ **“Meta”** or **“we”** means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
15
+
16
+ **“Sanctions”** means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom.
17
+
18
+ **“Trade Controls”** means any of the following: Sanctions and applicable export and import controls.
19
+
20
+ By clicking “I Accept” below or by using or distributing any portion or element of the DINO Materials, you agree to be bound by this Agreement.
21
+
22
+ ## 1. License Rights and Redistribution.
23
+
24
+ a. <ins>Grant of Rights</ins>. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the DINO Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the DINO Materials.
25
+
26
+ b. <ins>Redistribution and Use</ins>.
27
+
28
+ i. Distribution of DINO Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the DINO Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such DINO Materials.
29
+
30
+ ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with DINO Materials, you must acknowledge the use of DINO Materials in your publication.
31
+
32
+ iii. Your use of the DINO Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws.
33
+
34
+ iv. Your use of the DINO Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the DINO Materials.
35
+
36
+ v. You are not the target of Trade Controls and your use of DINO Materials must comply with Trade Controls. You agree not to use, or permit others to use, DINO Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons.
37
+
38
+ ## 2. User Support.
39
+
40
+ Your use of the DINO Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the DINO Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
41
+
42
+ ## 3. Disclaimer of Warranty.
43
+
44
+ UNLESS REQUIRED BY APPLICABLE LAW, THE DINO MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE DINO MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE DINO MATERIALS AND ANY OUTPUT AND RESULTS.
45
+
46
+ ## 4. Limitation of Liability.
47
+
48
+ IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
49
+
50
+ ## 5. Intellectual Property.
51
+
52
+ a. Subject to Meta’s ownership of DINO Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the DINO Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications.
53
+
54
+ b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the DINO Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the DINO Materials.
55
+
56
+ ## 6. Term and Termination.
57
+
58
+ The term of this Agreement will commence upon your acceptance of this Agreement or access to the DINO Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the DINO Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement.
59
+
60
+ ## 7. Governing Law and Jurisdiction.
61
+
62
+ This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
63
+
64
+ ## 8. Modifications and Amendments.
65
+
66
+ Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the DINO Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta.
licenses/LICENSE-GEMMA.md ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Gemma Terms of Use for the bundled text encoder
2
+
3
+ Gemma is provided under and subject to the Gemma Terms of Use found at
4
+ gemma.ai/resources/terms
5
+
6
+ The same terms were previously published at ai.google.dev/gemma/terms, which
7
+ now redirects to the address above. Earlier versions of the terms worded this
8
+ notice as: "Gemma is provided under and subject to the Gemma Terms of Use found
9
+ at ai.google.dev/gemma/terms".
10
+
11
+ ## Modification notice
12
+
13
+ **The files in this folder have been modified from the original.** They are
14
+ derived from
15
+ [`google/t5gemma-2-270m-270m`](https://huggingface.co/google/t5gemma-2-270m-270m)
16
+ at revision `7c38f16641f455ef0685b18431faf1b17722d5a1`. Data Archetype made the
17
+ following changes in November 2026:
18
+
19
+ - `model.safetensors` is a trimmed copy of the original weights. It keeps the
20
+ token embeddings and encoder layers 1 to 12. The remaining encoder layers and
21
+ the whole decoder were removed. The kept weights are stored in bfloat16 with
22
+ shortened tensor names.
23
+ - `config.json` was rewritten to describe the trimmed encoder and to record the
24
+ source repository and revision.
25
+ - The tokenizer files are unchanged.
26
+
27
+ ## Use restrictions
28
+
29
+ Use of these files is subject to the use restrictions in Section 3.2 of the
30
+ Gemma Terms of Use below. You must not use them:
31
+
32
+ - for the restricted uses set forth in the Gemma Prohibited Use Policy at
33
+ [gemma.ai/resources/prohibited_use_policy](https://gemma.ai/resources/prohibited_use_policy),
34
+ which the terms incorporate by reference; or
35
+ - in violation of applicable laws and regulations.
36
+
37
+ If you distribute these files or a model derived from them, the Gemma Terms of
38
+ Use require you to pass on the same restrictions, a copy of the terms, the
39
+ notice at the top of this file and a notice of any modifications you make. See
40
+ Section 3.1 below.
41
+
42
+ ## Gemma Terms of Use
43
+
44
+ The text below is a copy of the terms as published at
45
+ [gemma.ai/resources/terms](https://gemma.ai/resources/terms), retrieved on
46
+ 18 November 2026. The published page is the authoritative version.
47
+
48
+ ---
49
+
50
+ Last modified: April 1, 2026
51
+
52
+ By using, reproducing, modifying, distributing, performing or displaying any portion or element of Gemma, Model Derivatives including via any Hosted Service, (each as defined below) (collectively, the "Gemma Services") or otherwise accepting the terms of this Agreement, you agree to be bound by this Agreement.
53
+
54
+ ### Section 1: DEFINITIONS
55
+
56
+ #### 1.1 Definitions
57
+
58
+ (a) "Agreement" or "Gemma Terms of Use" means these terms and conditions that govern the use, reproduction, Distribution or modification of the Gemma Services and any terms and conditions incorporated by reference.
59
+
60
+ (b) "Distribution" or "Distribute" means any transmission, publication, or other sharing of Gemma or Model Derivatives to a third party, including by providing or making Gemma or its functionality available as a hosted service via API, web access, or any other electronic or remote means ("Hosted Service").
61
+
62
+ (c) "Gemma" means the set of machine learning language models, trained model weights and parameters identified in the Appendix, regardless of the source that you obtained it from.
63
+
64
+ (d) "Google" means Google LLC.
65
+
66
+ (e) "Model Derivatives" means all (i) modifications to Gemma, (ii) works based on Gemma, or (iii) any other machine learning model which is created by transfer of patterns of the weights, parameters, operations, or Output of Gemma, to that model in order to cause that model to perform similarly to Gemma, including distillation methods that use intermediate data representations or methods based on the generation of synthetic data Outputs by Gemma for training that model. For clarity, Outputs are not deemed Model Derivatives.
67
+
68
+ (f) "Output" means the information content output of Gemma or a Model Derivative that results from operating or otherwise using Gemma or the Model Derivative, including via a Hosted Service.
69
+
70
+ #### 1.2
71
+
72
+ As used in this Agreement, "including" means "including without limitation".
73
+
74
+ ### Section 2: ELIGIBILITY AND USAGE
75
+
76
+ #### 2.1 Eligibility
77
+
78
+ You represent and warrant that you have the legal capacity to enter into this Agreement (including being of sufficient age of consent). If you are accessing or using any of the Gemma Services for or on behalf of a legal entity, (a) you are entering into this Agreement on behalf of yourself and that legal entity, (b) you represent and warrant that you have the authority to act on behalf of and bind that entity to this Agreement and (c) references to "you" or "your" in the remainder of this Agreement refers to both you (as an individual) and that entity.
79
+
80
+ #### 2.2 Use
81
+
82
+ You may use, reproduce, modify, Distribute, perform or display any of the Gemma Services only in accordance with the terms of this Agreement, and must not violate (or encourage or permit anyone else to violate) any term of this Agreement.
83
+
84
+ ### Section 3: DISTRIBUTION AND RESTRICTIONS
85
+
86
+ #### 3.1 Distribution and Redistribution
87
+
88
+ You may reproduce or Distribute copies of Gemma or Model Derivatives if you meet all of the following conditions:
89
+
90
+ 1. You must include the use restrictions referenced in Section 3.2 as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Gemma or Model Derivatives and you must provide notice to subsequent users you Distribute to that Gemma or Model Derivatives are subject to the use restrictions in Section 3.2.
91
+ 2. You must provide all third party recipients of Gemma or Model Derivatives a copy of this Agreement.
92
+ 3. You must cause any modified files to carry prominent notices stating that you modified the files.
93
+ 4. All Distributions (other than through a Hosted Service) must be accompanied by a "Notice" text file that contains the following notice: "Gemma is provided under and subject to the Gemma Terms of Use found at gemma.ai/resources/terms".
94
+
95
+ You may add your own intellectual property statement to your modifications and, except as set forth in this Section, may provide additional or different terms and conditions for use, reproduction, or Distribution of your modifications, or for any such Model Derivatives as a whole, provided your use, reproduction, modification, Distribution, performance, and display of Gemma otherwise complies with the terms and conditions of this Agreement. Any additional or different terms and conditions you impose must not conflict with the terms of this Agreement.
96
+
97
+ #### 3.2 Use Restrictions
98
+
99
+ You must not use any of the Gemma Services:
100
+
101
+ 1. for the restricted uses set forth in the Gemma Prohibited Use Policy at gemma.ai/resources/prohibited_use_policy ("Prohibited Use Policy"), which is hereby incorporated by reference into this Agreement; or
102
+ 2. in violation of applicable laws and regulations.
103
+
104
+ To the maximum extent permitted by law, Google reserves the right to restrict (remotely or otherwise) usage of any of the Gemma Services that Google reasonably believes are in violation of this Agreement.
105
+
106
+ #### 3.3 Generated Output
107
+
108
+ Google claims no rights in Outputs you generate using Gemma. You and your users are solely responsible for Outputs and their subsequent uses.
109
+
110
+ ### Section 4: ADDITIONAL PROVISIONS
111
+
112
+ #### 4.1 Updates
113
+
114
+ Google may update Gemma from time to time.
115
+
116
+ #### 4.2 Trademarks
117
+
118
+ Nothing in this Agreement grants you any rights to use Google's trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between you and Google. Google reserves any rights not expressly granted herein.
119
+
120
+ #### 4.3 DISCLAIMER OF WARRANTY
121
+
122
+ UNLESS REQUIRED BY APPLICABLE LAW, THE GEMMA SERVICES, AND OUTPUTS, ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING, REPRODUCING, MODIFYING, PERFORMING, DISPLAYING OR DISTRIBUTING ANY OF THE GEMMA SERVICES OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR USE OR DISTRIBUTION OF ANY OF THE GEMMA SERVICES OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND PERMISSIONS UNDER THIS AGREEMENT.
123
+
124
+ #### 4.4 LIMITATION OF LIABILITY
125
+
126
+ TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), PRODUCT LIABILITY, CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW, SHALL GOOGLE OR ITS AFFILIATES BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR LOST PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO, ANY OF THE GEMMA SERVICES OR OUTPUTS EVEN IF GOOGLE OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
127
+
128
+ #### 4.5 Term, Termination, and Survival
129
+
130
+ The term of this Agreement will commence upon your acceptance of this Agreement (including acceptance by your use, modification, or Distribution, reproduction, performance or display of any portion or element of the Gemma Services) and will continue in full force and effect until terminated in accordance with the terms of this Agreement. Google may terminate this Agreement if you are in breach of any term of this Agreement. Upon termination of this Agreement, you must delete and cease use and Distribution of all copies of Gemma and Model Derivatives in your possession or control. Sections 1, 2.1, 3.3, 4.2 to 4.9 shall survive the termination of this Agreement.
131
+
132
+ #### 4.6 Governing Law and Jurisdiction
133
+
134
+ This Agreement will be governed by the laws of the State of California without regard to choice of law principles. The UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The state and federal courts of Santa Clara County, California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
135
+
136
+ #### 4.7 Severability
137
+
138
+ If any provision of this Agreement is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
139
+
140
+ #### 4.8 Entire Agreement
141
+
142
+ This Agreement states all the terms agreed between the parties and supersedes all other agreements between the parties as of the date of acceptance relating to its subject matter.
143
+
144
+ #### 4.9 No Waiver
145
+
146
+ Google will not be treated as having waived any rights by not exercising (or delaying the exercise of) any rights under this Agreement.
147
+
148
+ ### Appendix
149
+
150
+ - Gemma 1
151
+ - Gemma 1.1
152
+ - Gemma 2
153
+ - Gemma 3
154
+ - Gemma 3n
155
+ - FunctionGemma
156
+ - EmbeddingGemma
157
+ - PaliGemma
158
+ - PaliGemma 2
159
+ - ShieldGemma
160
+ - ShieldGemma 2
161
+ - CodeGemma
162
+ - CodeGemma 1.1
163
+ - Gemma 2 JPN
164
+ - DataGemma RIG
165
+ - DataGemma RAG
166
+ - RecurrentGemma
167
+ - Gemma Scope
168
+ - Gemma-APS
169
+ - T5Gemma
170
+ - VaultGemma
171
+ - FunctionGemma
172
+ - T5Gemma 2
173
+ - TranslateGemma
licenses/LICENSE-LoRA-MG-BY-NC-2.0 ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ModelGo Attribution-NonCommercial License
2
+ Version 2.0, May 2025
3
+
4
+ By exercising the rights granted in Section 2.1, You acknowledge and agree that You have
5
+ read, understood, and agree to be bound by the terms and conditions of this License. If You
6
+ do not agree to any terms and/or conditions of this License, then the Licensor grants You no
7
+ rights under this License.
8
+
9
+ 1. DEFINITIONS
10
+
11
+ "Complementary Materials" means the source code and scripts used to define, run, load,
12
+ benchmark and/or evaluate the Model, and prepare data for the purpose of training, pretraining,
13
+ fine-tuning and/or evaluation of the Model, and any tutorials, operating manuals, user guides
14
+ and/or documentation that guide users in using, operating, implementing and/or customising
15
+ the Model.
16
+
17
+ "Derivative Materials" means all improvements, modifications or derivative works to the
18
+ Licensed Material or any part thereof, which are created or developed by You (either by
19
+ Yourself or jointly with other third parties), including any derivative model developed by
20
+ transferring patterns of weights, parameters, activations and/or Output from the Model, such as
21
+ through distillation methods or synthetic data generation techniques, in order to replicate,
22
+ approximate, or otherwise achieve functional behavior that is similar to the Model.
23
+
24
+ "Distribution" (or "Distribute") means any transmission, publication, public performance,
25
+ sharing, or other methods of making the Licensed Materials, Derivative Materials and/or Output
26
+ available to a third party, including providing the Licensed Materials or any part thereof as a
27
+ hosted service or remotely accessible service, such as API-based access or web access.
28
+
29
+ "Licensor" means the rights owner that is granting the License.
30
+
31
+ "Licensed Materials" means the Model and Complementary Materials that are Distributed by
32
+ the Licensor under this License. The Licensed Materials do not include any datasets used for
33
+ pretraining, training, adapting, or evaluating the Model, which may or may not be made
34
+ available under a separate license.
35
+
36
+ "Model" means the machine-learning constructs and/or assemblies licensed by the Licensor
37
+ under this License, including any checkpoints, learned weights, parameters (including optimizer
38
+ states) and the model architecture.
39
+
40
+ "NonCommercial" means not primarily intended for or directed towards commercial advantage
41
+ or monetary compensation.
42
+
43
+ "Output" means any information, data, and/or content, including but not limited to images, text,
44
+ text effects, audio files, and/or video files, generated through operation of the Model, or through
45
+ operation of any new model developed by transferring patterns from the Model.
46
+
47
+ "You" (or "Your") means you, or any other person or entity you are entering into this license on
48
+ behalf of, provided you have the legal authority to bind such person or entity.
49
+
50
+ 2. LICENSE RIGHTS
51
+
52
+ 2.1 Grant of Rights
53
+
54
+ (a) Subject to the conditions in Section 2.2 of this License, the Licensor hereby grants to
55
+ You a non-exclusive, non-sublicensable, revocable, royalty-free, worldwide license under
56
+ the relevant copyrights, patent rights, database rights, and any other intellectual property
57
+ rights to:
58
+
59
+ (i) make, have made, use, reproduce and Distribute the Licensed Materials;
60
+
61
+ (ii) use the Licensed Materials to create Derivative Materials; and
62
+
63
+ (iii) make, have made, use, reproduce and Distribute Derivative Materials;
64
+
65
+ for NonCommercial purposes only.
66
+
67
+ 2.2 Conditions
68
+
69
+ (a) If You Distribute any of the Licensed Materials or Derivative Materials, You shall:
70
+
71
+ (i) provide a copy of this License with the Licensed Material or Derivative Materials;
72
+
73
+ (ii) in the case of Distributing Derivative Materials, provide as part of the Distribution,
74
+ prominent notices stating that You have modified the Licensed Materials and the
75
+ relevant date of such modification;
76
+
77
+ (iii) retain as part of the Distribution any existing copyright notice, attribution notice,
78
+ and/or any notice identifying the authors of the Licensed Materials and any
79
+ Derivative Materials.
80
+
81
+ (b) If You Distribute a collection of Output as a dataset generated wholly or partially using
82
+ the Licensed Materials and/or Derivative Materials, You shall provide a prominent notice
83
+ in the Distribution stating that the dataset is generated using the Licensed Materials
84
+ and/or Derivative Materials provided under this License.
85
+
86
+ 2.3 Reservation of Rights
87
+
88
+ You shall not refer to the Licensor or use the Licensor's trademarks, trade names, and service
89
+ marks, for any publicity, advertising or marketing purposes, without the Licensor's prior written
90
+ consent.
91
+
92
+ 3. DISCLAIMER
93
+
94
+ To the maximum extent permissible under applicable law, the Licensed Materials are provided
95
+ on an "as is" and "as available" basis without any representation or warranty of any kind
96
+ (whether express, implied, statutory or otherwise), including of merchantability, satisfactory
97
+ quality, fitness for a particular purpose, title, accuracy, correctness, absence of error, reliability,
98
+ timeliness, non-infringement of or compliance with any laws, regulations and/or third-party
99
+ rights, all of which are expressly disclaimed by the Licensor.
100
+
101
+ 4. LIMITATION OF LIABILITY
102
+
103
+ To the maximum extent permissible under applicable law, the Licensor shall not be liable for
104
+ any claims, damages, or any other liabilities, in any way arising out of or in connection with the
105
+ Licensed Materials, Derivative Materials, and/or Output, whether on an action or claim in
106
+ contract, tort (including negligence), breach of statutory duty or otherwise, even if the Licensor
107
+ has been advised of the possibility of such damages.
108
+
109
+ 5. TERMINATION
110
+
111
+ This License shall terminate immediately if You breach any material term and/or condition of
112
+ this License, or if You initiate any legal action against the Licensor alleging that the Licensed
113
+ Materials and/or Derivative Materials infringe any patent worldwide. Sections 3, 4 and 6 shall
114
+ survive the termination of this License.
115
+
116
+ 6. MODIFICATION OF THIS LICENSE
117
+
118
+ This License is Copyright © 2024 National University of Singapore. Permission is granted to
119
+ copy, distribute, or communicate this License without modification. Nothing in this License
120
+ permits You to modify this License as applied to the Licensed Materials. However, You may
121
+ modify the text of this License and copy, distribute or communicate Your modified version and
122
+ apply it to other original works of authorship, provided that You do not use the name "ModelGo"
123
+ for your version of the license and furnish a readable notice describing Your modifications to
124
+ this License.
licenses/LICENSE-dinac3_96-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.
manifest.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "dflow2-web-v1",
3
+ "parts": {
4
+ "text": 230535705,
5
+ "dit_a": 263701553,
6
+ "dit_b": 393264626,
7
+ "dit_c": 393264626,
8
+ "dit_d": 277402800,
9
+ "vae_dec": 142138666
10
+ },
11
+ "total": 1733692364,
12
+ "embeddings": {
13
+ "file": "embed_bf16.bin",
14
+ "dtype": "bfloat16",
15
+ "rows": 262144,
16
+ "dim": 640
17
+ }
18
+ }
scripts/dfl.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU fp32 loader for dflow_2b + the 4-step LoRA + dinac3_96 decoder.
2
+
3
+ The release refuses non-CUDA devices, so this drives its own modules directly.
4
+ Autocast is disabled by pointing the packages' compute dtypes at float32
5
+ (CPU autocast rejects float32 and turns itself off).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import sys
11
+ import warnings
12
+ from pathlib import Path
13
+
14
+ import torch
15
+
16
+ SP = Path("/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad")
17
+ REL = SP / "repos/dflow_2b"
18
+ VAE_DIR = SP / "repos/dinac3_96"
19
+ TE_DIR = REL / "text_encoder"
20
+ DIT = SP / "w/dit.safetensors"
21
+ LORA = SP / "w/lora.safetensors"
22
+
23
+ sys.path.insert(0, str(REL))
24
+ sys.path.insert(0, str(VAE_DIR))
25
+ warnings.filterwarnings("ignore", message=".*CPU autocast.*")
26
+ warnings.filterwarnings("ignore", message=".*autocast.*not supported.*")
27
+
28
+ import dflow.modeling as mdl # noqa: E402
29
+ import dflow.text_conditioning as tc_mod # noqa: E402
30
+ import dflow.text_encoder as te_mod # noqa: E402
31
+ from safetensors import safe_open # noqa: E402
32
+
33
+ te_mod.COMPUTE_DTYPE = torch.float32
34
+ tc_mod.COMPUTE_DTYPE = torch.float32
35
+ mdl.AUTOCAST_DTYPE = torch.float32
36
+
37
+ from dflow.configuration import DFLOW_2B_CONFIG # noqa: E402
38
+ from dflow.modeling import DFlowModel # noqa: E402
39
+ from dflow.schedules import ( # noqa: E402
40
+ ScheduleKind,
41
+ TimeSchedule,
42
+ build_timesteps,
43
+ resolution_log_snr_shift,
44
+ )
45
+ from dflow.text_conditioning import TextAdapter # noqa: E402
46
+ from dflow.text_encoder import T5Gemma2Encoder # noqa: E402
47
+ from dflow.tokenization import PromptTokenizer # noqa: E402
48
+ from dflow.types import DFlowPath, TextConditioning # noqa: E402
49
+
50
+ CPU = torch.device("cpu")
51
+ GROUPS = ("prefix_layers", "middle_layers", "suffix_layers")
52
+ PROJ = ("attn.qkv", "attn.proj_out", "mlp.up", "mlp.down")
53
+
54
+
55
+ def _f32(module: torch.nn.Module) -> None:
56
+ for t in (*module.parameters(), *module.buffers()):
57
+ t.data = t.data.float()
58
+
59
+
60
+ def load_denoiser(*, lora: bool = True, prefixes: tuple[str, ...] | None = None
61
+ ) -> tuple[DFlowModel, TextAdapter]:
62
+ """fp32 denoiser (LoRA merged in fp32) and the text adapter.
63
+
64
+ ``prefixes`` loads only denoiser tensors whose names start with one of them
65
+ (the rest stay on the meta device), to keep export processes small.
66
+ """
67
+ den: dict[str, torch.Tensor] = {}
68
+ ada: dict[str, torch.Tensor] = {}
69
+ with safe_open(str(DIT), framework="pt") as f:
70
+ for k in f.keys():
71
+ if k.startswith("denoiser."):
72
+ name = k.removeprefix("denoiser.")
73
+ if prefixes is not None and not name.startswith(prefixes):
74
+ continue
75
+ den[name] = f.get_tensor(k).float()
76
+ continue
77
+ t = f.get_tensor(k).float()
78
+ if k.startswith("denoiser."):
79
+ den[k.removeprefix("denoiser.")] = t
80
+ elif k.startswith("text_adapter."):
81
+ ada[k.removeprefix("text_adapter.")] = t
82
+ else:
83
+ raise KeyError(k)
84
+ if lora:
85
+ merged = 0
86
+ with safe_open(str(LORA), framework="pt") as f:
87
+ keys = set(f.keys())
88
+ for grp in GROUPS:
89
+ depth = getattr(DFLOW_2B_CONFIG, grp.replace("_layers", "_depth"))
90
+ for i in range(depth):
91
+ for proj in PROJ:
92
+ base = None
93
+ for cand in (f"denoiser.{grp}.{i}.{proj}", f"{grp}.{i}.{proj}"):
94
+ if f"{cand}.lora_down.weight" in keys:
95
+ base = cand
96
+ if base is None:
97
+ continue
98
+ down = f.get_tensor(f"{base}.lora_down.weight").double()
99
+ up = f.get_tensor(f"{base}.lora_up.weight").double()
100
+ rank = down.shape[0]
101
+ alpha = (float(f.get_tensor(f"{base}.alpha"))
102
+ if f"{base}.alpha" in keys else float(rank))
103
+ if f"{grp}.{i}.{proj}.weight" not in den:
104
+ merged += 1
105
+ continue
106
+ w = den[f"{grp}.{i}.{proj}.weight"]
107
+ den[f"{grp}.{i}.{proj}.weight"] = (
108
+ w.double() + (alpha / rank) * (up @ down)).float()
109
+ merged += 1
110
+ assert merged == 30 * 4, merged
111
+ with torch.device("meta"):
112
+ model = DFlowModel(DFLOW_2B_CONFIG)
113
+ model.load_state_dict(den, strict=prefixes is None, assign=True)
114
+ model.eval().requires_grad_(False)
115
+ adapter = TextAdapter()
116
+ adapter.load_state_dict(ada, strict=True)
117
+ adapter.float().eval().requires_grad_(False)
118
+ return model, adapter
119
+
120
+
121
+ def load_text_encoder() -> tuple[PromptTokenizer, T5Gemma2Encoder]:
122
+ tok = PromptTokenizer.from_directory(TE_DIR)
123
+ enc = T5Gemma2Encoder.from_directory(TE_DIR, device=CPU)
124
+ _f32(enc)
125
+ return tok, enc.eval().requires_grad_(False)
126
+
127
+
128
+ def load_vae():
129
+ from dinac3 import Dinac3
130
+ from dinac3.config import Dinac3Config
131
+ from safetensors.torch import load_file
132
+
133
+ cfg = Dinac3Config.load(VAE_DIR / "config.json")
134
+ with torch.device("meta"):
135
+ vae = Dinac3(cfg)
136
+ vae.load_state_dict(load_file(str(VAE_DIR / "model.safetensors")), strict=True, assign=True)
137
+ for t in (*vae.parameters(), *vae.buffers()):
138
+ t.data = t.data.float()
139
+ vae.compute_dtype = torch.float32
140
+ vae.eval().requires_grad_(False)
141
+ vae.decoder.conv_up_head.fold_kernels()
142
+ vae._encode_call = vae.encoder.forward
143
+ vae._decode_call = vae.decoder.forward
144
+ return vae
145
+
146
+
147
+ def gain_for(width: int, height: int) -> float:
148
+ area = float(width) * float(height)
149
+ if area <= 1.05e6:
150
+ return -0.03
151
+ frac = math.log(area / 1.05e6) / math.log(2.5e6 / 1.05e6)
152
+ return -0.03 * max(0.0, 1.0 - frac)
153
+
154
+
155
+ def timesteps(width: int, height: int, steps: int = 4) -> torch.Tensor:
156
+ return build_timesteps(
157
+ TimeSchedule(kind=ScheduleKind.BETA_1_25, steps=steps),
158
+ log_snr_shift=resolution_log_snr_shift(width, height),
159
+ finite_noisy_endpoint=False,
160
+ device=CPU,
161
+ )
162
+
163
+
164
+ def text_conditioning(tok, enc, adapter, prompt: str) -> tuple[list[int], torch.Tensor]:
165
+ ids = list(tok.tokenize(prompt).ids)
166
+ taps = enc(torch.tensor([ids], dtype=torch.int64), weighting=None)
167
+ return ids, adapter.conditioning_tokens(taps)
168
+
169
+
170
+ __all__ = [
171
+ "DFlowPath", "TextConditioning", "load_denoiser", "load_text_encoder", "load_vae",
172
+ "gain_for", "timesteps", "text_conditioning", "SP",
173
+ ]
scripts/export.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export one part of the browser pipeline to fp32 ONNX.
2
+
3
+ usage: export.py {text,dit_a,dit_b,dit_c,dit_d,vae}
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from torch import nn
14
+
15
+ import dfl
16
+ from dflow import modeling as mdl
17
+ from dflow.text_encoder import EncoderTaps, LayerKind
18
+
19
+ def _rms_norm(x, normalized_shape, weight=None, eps=None):
20
+ """Explicit RMSNorm (aten::rms_norm has no ONNX mapping below opset 23)."""
21
+ dims = tuple(range(-len(normalized_shape), 0))
22
+ eps = torch.finfo(x.dtype).eps if eps is None else eps
23
+ y = x * torch.rsqrt(x.pow(2).mean(dims, keepdim=True) + eps)
24
+ return y if weight is None else y * weight
25
+
26
+
27
+ F.rms_norm = _rms_norm
28
+ torch.rms_norm = _rms_norm
29
+
30
+ OUT = dfl.SP / "onnx_fp32"
31
+ OUT.mkdir(exist_ok=True)
32
+ torch.set_num_threads(4)
33
+
34
+
35
+ def _stream(tact, rsin, rcos, qs):
36
+ return mdl._StreamInputs(rope_sin=rsin, rope_cos=rcos, query_scale=qs,
37
+ key_bias=None, value_scale=None, time_act=tact)
38
+
39
+
40
+ def _run(x, blocks, adaln, stream):
41
+ for blk, proj in zip(blocks, adaln):
42
+ x = blk(x, rope_sin=stream.rope_sin, rope_cos=stream.rope_cos,
43
+ modulation=proj(stream.time_act).to(torch.float32), query_scale=stream.query_scale,
44
+ key_bias=None, value_scale=None)
45
+ return x
46
+
47
+
48
+ class TextPart(nn.Module):
49
+ """Scaled token embeddings [1, L, 640] -> refined text tokens [1, L+3, 2304]."""
50
+
51
+ def __init__(self, enc, adapter, model):
52
+ super().__init__()
53
+ self.layers = enc.layers
54
+ self.adapter = adapter
55
+ self.refiner = model.text_refiner_layers
56
+
57
+ def forward(self, emb, g_cos_s, g_sin_s, g_cos_f, g_sin_f, r_sin, r_cos):
58
+ values = emb
59
+ taps = []
60
+ for index, layer in enumerate(self.layers, start=1):
61
+ full = layer.kind == LayerKind.FULL
62
+ values = layer._forward_impl(values, cos=g_cos_f if full else g_cos_s,
63
+ sin=g_sin_f if full else g_sin_s,
64
+ attn_bias=None, value_scale=None)
65
+ if index in (2, 6, 12):
66
+ taps.append(values)
67
+ x = self.adapter.conditioning_tokens(EncoderTaps(*taps))
68
+ for blk in self.refiner:
69
+ x = blk(x, rope_sin=r_sin, rope_cos=r_cos, modulation=None, query_scale=None,
70
+ key_bias=None, value_scale=None)
71
+ return x
72
+
73
+
74
+ class DitA(nn.Module):
75
+ """Latent tokens + text -> stream after the 6 prefix blocks, and SiLU(time)."""
76
+
77
+ def __init__(self, m):
78
+ super().__init__()
79
+ self.patch_embed, self.time_embed = m.patch_embed, m.time_embed
80
+ self.prefix_layers, self.prefix_adaln = m.prefix_layers, m.prefix_adaln
81
+
82
+ def forward(self, lat, t, text, rope_sin, rope_cos, qscale):
83
+ m = self
84
+ image = F.linear(lat, m.patch_embed.weight.flatten(1), m.patch_embed.bias)
85
+ x = torch.cat([image, text], dim=1)
86
+ tact = F.silu(m.time_embed(t))
87
+ x = _run(x, m.prefix_layers, m.prefix_adaln, _stream(tact, rope_sin, rope_cos, qscale))
88
+ return x, tact
89
+
90
+
91
+ class DitMid(nn.Module):
92
+ def __init__(self, m, lo, hi):
93
+ super().__init__()
94
+ self.blocks = m.middle_layers[lo:hi]
95
+ self.adaln = m.middle_adaln[lo:hi]
96
+
97
+ def forward(self, x, tact, rope_sin, rope_cos, qscale):
98
+ return _run(x, self.blocks, self.adaln, _stream(tact, rope_sin, rope_cos, qscale))
99
+
100
+
101
+ class DitD(nn.Module):
102
+ """Tail join + 6 suffix blocks + velocity head on every row: [1, S, 96]."""
103
+
104
+ def __init__(self, m):
105
+ super().__init__()
106
+ self.tail_join, self.final_norm = m.tail_join, m.final_norm
107
+ self.suffix_layers, self.suffix_adaln = m.suffix_layers, m.suffix_adaln
108
+ self.final_modulation, self.velocity_head = m.final_modulation, m.velocity_head
109
+
110
+ def forward(self, prefix, middle, tact, rope_sin, rope_cos, qscale):
111
+ m = self
112
+ x = m.tail_join(prefix, middle, None, tact)
113
+ x = _run(x, m.suffix_layers, m.suffix_adaln, _stream(tact, rope_sin, rope_cos, qscale))
114
+ normed = m.final_norm(x)
115
+ shift, scale = m.final_modulation(tact).to(torch.float32).chunk(2, dim=-1)
116
+ out = normed * (1.0 + scale.unsqueeze(1)) + shift.unsqueeze(1)
117
+ return F.linear(out, m.velocity_head.weight, m.velocity_head.bias)
118
+
119
+
120
+ class VaePart(nn.Module):
121
+ """Whitened latents [1, 96, h, w] -> RGB [1, 3, 16h, 16w] in [0, 1]."""
122
+
123
+ def __init__(self, vae):
124
+ super().__init__()
125
+ self.dec = vae.decoder
126
+ mean, std = vae._latent_stats()
127
+ self.register_buffer("mean", mean.clone())
128
+ self.register_buffer("std", std.clone())
129
+
130
+ def forward(self, z, v_sin, v_cos):
131
+ z = z * self.std + self.mean
132
+ x = self.dec.latent_up(z)
133
+ b, c, h, w = x.shape
134
+ tokens = x.permute(0, 2, 3, 1).reshape(b, h * w, c)
135
+ for block in self.dec.trunk:
136
+ tokens = block(tokens, v_sin, v_cos)
137
+ feats = tokens.transpose(1, 2).reshape(b, c, h, w)
138
+ rgb = self.dec.conv_up_head(feats)
139
+ return ((rgb.clamp(-1.0, 1.0) + 1.0) * 0.5)
140
+
141
+
142
+ def export(module, args, names, outs, dyn, path: Path):
143
+ t0 = time.time()
144
+ path = path.parent / path.stem / path.name
145
+ path.parent.mkdir(exist_ok=True)
146
+ torch.onnx.export(module, args, str(path), dynamo=False, opset_version=18,
147
+ input_names=names, output_names=outs, dynamic_axes=dyn,
148
+ do_constant_folding=True)
149
+ print(f"exported {path.name} in {time.time()-t0:.0f}s", flush=True)
150
+
151
+
152
+ def main(part: str) -> None:
153
+ n, lt = 12, 9 # image tokens (3x4 grid), text tokens incl. suffix
154
+ s = n + lt
155
+ seq = {1: "s"}
156
+ if part == "text":
157
+ tok, enc = dfl.load_text_encoder()
158
+ model, adapter = dfl.load_denoiser(lora=False, prefixes=("text_refiner_layers.",))
159
+ L = 6
160
+ args = (torch.randn(1, L, 640) * 3, torch.randn(L, 1, 256), torch.randn(L, 1, 256),
161
+ torch.randn(L, 1, 256), torch.randn(L, 1, 256),
162
+ torch.randn(1, L + 3, 128), torch.randn(1, L + 3, 128))
163
+ names = ["emb", "g_cos_s", "g_sin_s", "g_cos_f", "g_sin_f", "r_sin", "r_cos"]
164
+ dyn = {"emb": {1: "l"}, "g_cos_s": {0: "l"}, "g_sin_s": {0: "l"}, "g_cos_f": {0: "l"},
165
+ "g_sin_f": {0: "l"}, "r_sin": {1: "l3"}, "r_cos": {1: "l3"}, "text": {1: "l3"}}
166
+ export(TextPart(enc, adapter, model).eval(), args, names, ["text"], dyn, OUT / "text.onnx")
167
+ return
168
+ if part == "vae":
169
+ vae = dfl.load_vae()
170
+ args = (torch.randn(1, 96, 3, 4), torch.randn(12, 64), torch.randn(12, 64))
171
+ dyn = {"z": {2: "h", 3: "w"}, "v_sin": {0: "hw"}, "v_cos": {0: "hw"},
172
+ "rgb": {2: "H", 3: "W"}}
173
+ export(VaePart(vae).eval(), args, ["z", "v_sin", "v_cos"], ["rgb"], dyn, OUT / "vae_dec.onnx")
174
+ return
175
+ rope = (torch.randn(1, s, 128), torch.randn(1, s, 128), torch.tensor(0.97, dtype=torch.float32))
176
+ if part == "dit_a":
177
+ model, _ = dfl.load_denoiser(prefixes=("patch_embed.", "time_embed.", "prefix_layers.",
178
+ "prefix_adaln."))
179
+ args = (torch.randn(1, n, 96), torch.tensor([0.9]), torch.randn(1, lt, 2304), *rope)
180
+ dyn = {"lat": {1: "n"}, "text": {1: "lt"}, "rope_sin": seq, "rope_cos": seq, "x": seq}
181
+ export(DitA(model).eval(), args, ["lat", "t", "text", "rope_sin", "rope_cos", "qscale"],
182
+ ["x", "tact"], dyn, OUT / "dit_a.onnx")
183
+ elif part in ("dit_b", "dit_c"):
184
+ lo, hi = (0, 9) if part == "dit_b" else (9, 18)
185
+ pref = tuple(f"middle_{k}.{i}." for k in ("layers", "adaln") for i in range(lo, hi))
186
+ model, _ = dfl.load_denoiser(prefixes=pref)
187
+ args = (torch.randn(1, s, 2304), torch.randn(1, 256), *rope)
188
+ dyn = {"x": seq, "rope_sin": seq, "rope_cos": seq, "y": seq}
189
+ export(DitMid(model, lo, hi).eval(), args, ["x", "tact", "rope_sin", "rope_cos", "qscale"],
190
+ ["y"], dyn, OUT / f"{part}.onnx")
191
+ elif part == "dit_d":
192
+ model, _ = dfl.load_denoiser(prefixes=("tail_join.", "suffix_layers.", "suffix_adaln.",
193
+ "final_norm.", "final_modulation.", "velocity_head."))
194
+ args = (torch.randn(1, s, 2304), torch.randn(1, s, 2304), torch.randn(1, 256), *rope)
195
+ dyn = {"prefix": seq, "middle": seq, "rope_sin": seq, "rope_cos": seq, "vel": seq}
196
+ export(DitD(model).eval(), args, ["prefix", "middle", "tact", "rope_sin", "rope_cos", "qscale"],
197
+ ["vel"], dyn, OUT / "dit_d.onnx")
198
+ else:
199
+ raise SystemExit(f"unknown part {part}")
200
+
201
+
202
+ if __name__ == "__main__":
203
+ with torch.no_grad():
204
+ main(sys.argv[1])
scripts/qall.sh ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # qall.sh OUT_DIR BITS BLOCK [extra quant.py args]
3
+ OUT=$1; shift
4
+ run(){ ../venv/bin/python quant.py "$@" 2>&1 | grep -vE "Warning|^\s*$|INFO" | tail -1; }
5
+ run dit_a $OUT "$@" & run dit_d $OUT "$@" & wait
6
+ run dit_b $OUT "$@" & run dit_c $OUT "$@" & wait
7
+ for p in text vae_dec; do [ -e $OUT/$p ] || ln -s $(realpath ../onnx_q4b32/$p) $OUT/$p; done
8
+ du -sh $OUT/dit_* | awk '{s=s" "$2":"$1} END{print s}'
scripts/quant.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Weight-only MatMulNBits quantization of one exported part.
2
+
3
+ usage: quant.py PART OUT_DIR BITS BLOCK [--sym] [--hi REGEX] [--hi-bits 8]
4
+ Constant-weight Gemm nodes are rewritten as MatMul + Add first (the quantizer
5
+ only handles MatMul). Nodes whose weight name matches --hi get --hi-bits
6
+ (default 8); the rest get BITS. Writes OUT_DIR/PART/PART.onnx + PART.onnx.data.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import logging
12
+ import re
13
+ import time
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import onnx
18
+ from onnx import helper, numpy_helper
19
+ from onnxruntime.quantization.matmul_nbits_quantizer import (
20
+ DefaultWeightOnlyQuantConfig,
21
+ MatMulNBitsQuantizer,
22
+ )
23
+
24
+ logging.basicConfig(level=logging.WARNING)
25
+ SP = Path("/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad")
26
+ ap = argparse.ArgumentParser()
27
+ ap.add_argument("part")
28
+ ap.add_argument("out_dir", type=Path)
29
+ ap.add_argument("bits", type=int)
30
+ ap.add_argument("block", type=int)
31
+ ap.add_argument("--sym", action="store_true")
32
+ ap.add_argument("--hi", default=r"Gemm_mm")
33
+ ap.add_argument("--hi-bits", type=int, default=8)
34
+ ap.add_argument("--hi-block", type=int, default=32)
35
+ a = ap.parse_args()
36
+
37
+ src = SP / "onnx_fp32" / a.part / f"{a.part}.onnx"
38
+ dst = a.out_dir / a.part / f"{a.part}.onnx"
39
+ dst.parent.mkdir(parents=True, exist_ok=True)
40
+ t0 = time.time()
41
+ model = onnx.load(str(src))
42
+ g = model.graph
43
+ inits = {i.name: i for i in g.initializer}
44
+
45
+ # Gemm(A, B, C) with constant B -> MatMul(A, B') + C
46
+ new_nodes = []
47
+ for node in g.node:
48
+ if node.op_type != "Gemm" or node.input[1] not in inits:
49
+ new_nodes.append(node)
50
+ continue
51
+ attrs = {x.name: helper.get_attribute_value(x) for x in node.attribute}
52
+ assert attrs.get("alpha", 1.0) == 1.0 and attrs.get("beta", 1.0) == 1.0 and not attrs.get("transA", 0)
53
+ w = numpy_helper.to_array(inits[node.input[1]])
54
+ if attrs.get("transB", 0):
55
+ w = w.T
56
+ wname = f"gemm_w_{len(new_nodes)}"
57
+ g.initializer.append(numpy_helper.from_array(np.ascontiguousarray(w), wname))
58
+ mm_out = node.output[0] + "_mm"
59
+ new_nodes.append(helper.make_node("MatMul", [node.input[0], wname],
60
+ [mm_out if len(node.input) > 2 else node.output[0]],
61
+ name=f"{node.name}_mm"))
62
+ if len(node.input) > 2:
63
+ new_nodes.append(helper.make_node("Add", [mm_out, node.input[2]], [node.output[0]],
64
+ name=f"{node.name}_add"))
65
+ del g.node[:]
66
+ g.node.extend(new_nodes)
67
+ used = {i for n in g.node for i in n.input}
68
+ keep = [i for i in g.initializer if i.name in used]
69
+ del g.initializer[:]
70
+ g.initializer.extend(keep)
71
+
72
+ hi_re = re.compile(a.hi)
73
+ const = {i.name for i in g.initializer}
74
+ mm = [n for n in g.node if n.op_type == "MatMul" and n.input[1] in const]
75
+ hi_nodes = [n.name for n in mm if hi_re.search(n.name)]
76
+ lo_nodes = [n.name for n in mm if not hi_re.search(n.name)]
77
+
78
+
79
+ def run(m, bits, block, include):
80
+ # nodes_to_include is additive in this ORT version, so select by exclusion
81
+ if not include:
82
+ return m
83
+ exclude = [n.name for n in m.graph.node if n.op_type == "MatMul" and n.name not in set(include)]
84
+ cfg = DefaultWeightOnlyQuantConfig(block_size=block, is_symmetric=a.sym, bits=bits)
85
+ q = MatMulNBitsQuantizer(m, bits=bits, block_size=block, is_symmetric=a.sym,
86
+ nodes_to_exclude=exclude, algo_config=cfg)
87
+ q.process()
88
+ return q.model.model
89
+
90
+
91
+ model = run(model, a.hi_bits, a.hi_block, hi_nodes)
92
+ model = run(model, a.bits, a.block, lo_nodes)
93
+ for f in dst.parent.glob("*"):
94
+ f.unlink()
95
+ onnx.save_model(model, str(dst), save_as_external_data=True, all_tensors_to_one_file=True,
96
+ location=f"{a.part}.onnx.data", size_threshold=1024)
97
+ ops: dict[str, int] = {}
98
+ for node in model.graph.node:
99
+ ops[node.op_type] = ops.get(node.op_type, 0) + 1
100
+ size = sum(f.stat().st_size for f in dst.parent.glob("*")) / 1e6
101
+ print(f"{a.part} q{a.bits} b{a.block}{' sym' if a.sym else ''} hi={len(hi_nodes)}@q{a.hi_bits}: "
102
+ f"{size:.0f} MB, MatMulNBits={ops.get('MatMulNBits', 0)} MatMul left={ops.get('MatMul', 0)} "
103
+ f"Gemm left={ops.get('Gemm', 0)} in {time.time()-t0:.0f}s", flush=True)
scripts/ref.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """fp32 CPU reference: prompt -> 4-step LoRA sample -> image, saving every stage."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import time
6
+
7
+ import numpy as np
8
+ import torch
9
+ from PIL import Image
10
+
11
+ import dfl
12
+
13
+ p = argparse.ArgumentParser()
14
+ p.add_argument("--prompt", default="A snow leopard walking along a rocky ridge in falling snow, "
15
+ "telephoto wildlife photograph, natural light")
16
+ p.add_argument("--width", type=int, default=512)
17
+ p.add_argument("--height", type=int, default=512)
18
+ p.add_argument("--seed", type=int, default=7)
19
+ p.add_argument("--out", default="ref_512")
20
+ p.add_argument("--no-lora", action="store_true")
21
+ a = p.parse_args()
22
+
23
+ torch.set_num_threads(4)
24
+ out = dfl.SP / "work" / a.out
25
+ t0 = time.time()
26
+ tok, enc = dfl.load_text_encoder()
27
+ model, adapter = dfl.load_denoiser(lora=not a.no_lora)
28
+ vae = dfl.load_vae()
29
+ print(f"loaded in {time.time()-t0:.0f}s", flush=True)
30
+
31
+ with torch.no_grad():
32
+ ids, cond = dfl.text_conditioning(tok, enc, adapter, a.prompt)
33
+ prepared = model.prepare_text(dfl.TextConditioning(tokens=cond, key_bias=None, value_scale=None))
34
+ gh, gw = a.height // 16, a.width // 16
35
+ noise = torch.randn((1, 96, gh, gw), generator=torch.Generator("cpu").manual_seed(a.seed),
36
+ dtype=torch.float32)
37
+ ts = dfl.timesteps(a.width, a.height)
38
+ gain = torch.tensor(dfl.gain_for(a.width, a.height), dtype=torch.float32)
39
+ print("ids", len(ids), "times", ts.tolist(), "gain", float(gain), flush=True)
40
+ x = noise.clone()
41
+ vels = []
42
+ for i in range(len(ts) - 1):
43
+ t1 = time.time()
44
+ v = model(x, ts[i].expand(1), prepared, path=dfl.DFlowPath.FULL,
45
+ self_attention_gain=gain, suffix_caption_bias=0.0, generator=None)
46
+ vels.append(v.numpy().copy())
47
+ x = x + float(ts[i + 1] - ts[i]) * v
48
+ print(f"step {i} t={float(ts[i]):.4f} {time.time()-t1:.1f}s |v|={v.std():.3f}", flush=True)
49
+ t1 = time.time()
50
+ rgb = vae.decode(x, a.height, a.width).clamp(-1, 1)
51
+ print(f"decode {time.time()-t1:.1f}s", flush=True)
52
+
53
+ img = ((rgb[0].permute(1, 2, 0).numpy() + 1) * 127.5).round().clip(0, 255).astype(np.uint8)
54
+ Image.fromarray(img).save(f"{out}.png")
55
+ np.savez(f"{out}.npz", ids=np.array(ids, np.int64), cond=cond.numpy(),
56
+ refined=prepared.tokens.numpy(), noise=noise.numpy(), times=ts.numpy(),
57
+ gain=np.float32(gain), vels=np.stack(vels), latent=x.numpy(), rgb=rgb.numpy())
58
+ print("saved", out, f"total {time.time()-t0:.0f}s")
scripts/ropes.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RoPE tables fed to the ONNX graphs. The browser computes the same values in JS.
2
+
3
+ All angles: float64 product, rounded to float32, then sin/cos rounded to float32.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import numpy as np
8
+
9
+ F32 = np.float32
10
+
11
+
12
+ def _axis_freqs(dim: int, theta: float) -> np.ndarray:
13
+ return 1.0 / (theta ** (np.arange(0, dim, 2, dtype=np.float64) / float(dim)))
14
+
15
+
16
+ def dflow_rows(pos: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
17
+ """``pos`` [N, 3] float64 -> (sin, cos) [N, 128] float32, adjacent-pair layout."""
18
+ sins, coses = [], []
19
+ for axis, dim in enumerate((32, 48, 48)):
20
+ ang = np.outer(pos[:, axis], _axis_freqs(dim, 10000.0)).astype(F32)
21
+ sins.append(np.repeat(np.sin(ang), 2, axis=1))
22
+ coses.append(np.repeat(np.cos(ang), 2, axis=1))
23
+ return np.concatenate(sins, 1).astype(F32), np.concatenate(coses, 1).astype(F32)
24
+
25
+
26
+ def text_positions(length: int) -> np.ndarray:
27
+ p = np.zeros((length, 3), np.float64)
28
+ p[:, 0] = np.arange(1, length + 1)
29
+ return p
30
+
31
+
32
+ def joint_positions(text_length: int, gh: int, gw: int) -> np.ndarray:
33
+ idx = np.arange(gh * gw)
34
+ row, col = idx // gw, idx % gw
35
+ img = np.stack([np.full(gh * gw, text_length + 1.0), row - (gh - 1) / 2, col - (gw - 1) / 2], 1)
36
+ return np.concatenate([img.astype(np.float64), text_positions(text_length)], 0)
37
+
38
+
39
+ def gemma_tables(length: int) -> dict[str, np.ndarray]:
40
+ """Gemma encoder RoPE, [L, 1, 256] cos/sin for sliding and full layers."""
41
+ out = {}
42
+ exps = np.arange(0, 256, 2, dtype=np.int64).astype(F32)
43
+ for name, theta, factor in (("s", 10000.0, 1.0), ("f", 1_000_000.0, 8.0)):
44
+ inv = (F32(1.0) / (F32(theta) ** (exps / F32(256.0)))).astype(F32) / F32(factor)
45
+ freqs = np.arange(length, dtype=F32)[:, None] * inv[None, :]
46
+ emb = np.concatenate([freqs, freqs], 1).astype(F32)
47
+ out[f"g_cos_{name}"] = np.cos(emb)[:, None, :].astype(F32)
48
+ out[f"g_sin_{name}"] = np.sin(emb)[:, None, :].astype(F32)
49
+ return out
50
+
51
+
52
+ def vae_tables(gh: int, gw: int) -> tuple[np.ndarray, np.ndarray]:
53
+ """dinac3 decoder axial RoPE (head_dim 64): (sin, cos) [gh*gw, 64]."""
54
+ periods = (F32(10000.0) ** (F32(2.0) * np.arange(16, dtype=F32) / F32(32))).astype(F32)
55
+ rr, cc = np.meshgrid(np.arange(gh, dtype=F32), np.arange(gw, dtype=F32), indexing="ij")
56
+ coords = np.stack([rr, cc], -1).reshape(-1, 2)
57
+ ang = (coords[:, :, None] / periods[None, None, :]).astype(F32)
58
+ ang = np.repeat(ang, 2, axis=-1).reshape(gh * gw, 64)
59
+ return np.sin(ang).astype(F32), np.cos(ang).astype(F32)
scripts/verify.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the ONNX chain on ORT CPU against the fp32 PyTorch reference.
2
+
3
+ usage: verify.py ONNX_DIR REF_NPZ [--full]
4
+ Reports cosine per stage; with --full it also runs all 4 steps and the decoder.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ import sys
10
+ import time
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ import onnxruntime as ort
15
+ from PIL import Image
16
+ from safetensors import safe_open
17
+
18
+ import ropes
19
+
20
+ SP = Path("/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad")
21
+ root = Path(sys.argv[1])
22
+ ref = np.load(sys.argv[2])
23
+ full = "--full" in sys.argv
24
+ tag = root.name
25
+
26
+
27
+ def cos(a, b):
28
+ a, b = a.astype(np.float64).ravel(), b.astype(np.float64).ravel()
29
+ return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-30))
30
+
31
+
32
+ def rel(a, b):
33
+ return float(np.linalg.norm(a - b) / (np.linalg.norm(b) + 1e-30))
34
+
35
+
36
+ def sess(name, threads=4):
37
+ so = ort.SessionOptions()
38
+ so.intra_op_num_threads = threads
39
+ p = next((root / name).glob("*.onnx"))
40
+ t0 = time.time()
41
+ s = ort.InferenceSession(str(p), so, providers=["CPUExecutionProvider"])
42
+ print(f" load {name}: {time.time()-t0:.1f}s", flush=True)
43
+ return s
44
+
45
+
46
+ def embeddings(ids):
47
+ emb_file = SP / "emb" / "embed_int8.npy"
48
+ if (root / "EMB_INT8").exists() and emb_file.exists():
49
+ q = np.load(emb_file, mmap_mode="r")
50
+ sc = np.load(SP / "emb" / "embed_scale.npy")
51
+ e = q[ids].astype(np.float32) * sc[ids][:, None]
52
+ else:
53
+ with safe_open(str(SP / "w/te.safetensors"), "pt") as f:
54
+ w = f.get_tensor("embed_tokens.weight").float().numpy()
55
+ e = w[ids]
56
+ return (e * np.float32(math.sqrt(640.0))).astype(np.float32)[None]
57
+
58
+
59
+ ids = ref["ids"].astype(np.int64)
60
+ L = len(ids)
61
+ feeds = {"emb": embeddings(ids), **ropes.gemma_tables(L)}
62
+ rs, rc = ropes.dflow_rows(ropes.text_positions(L + 3))
63
+ feeds["r_sin"], feeds["r_cos"] = rs[None], rc[None]
64
+ t0 = time.time()
65
+ text = sess("text").run(None, feeds)[0]
66
+ print(f"text cos={cos(text, ref['refined']):.6f} rel={rel(text, ref['refined']):.2e} {time.time()-t0:.1f}s")
67
+
68
+ lat0 = ref["noise"]
69
+ _, C, gh, gw = lat0.shape
70
+ n = gh * gw
71
+ lt = text.shape[1]
72
+ js, jc = ropes.dflow_rows(ropes.joint_positions(lt, gh, gw))
73
+ rope = {"rope_sin": js[None], "rope_cos": jc[None],
74
+ "qscale": np.array(math.exp(float(ref["gain"])), dtype=np.float32)}
75
+ A, B, Cc, D = (sess(k) for k in ("dit_a", "dit_b", "dit_c", "dit_d"))
76
+
77
+
78
+ def velocity(x, t):
79
+ lat = x.reshape(1, C, n).transpose(0, 2, 1).copy()
80
+ p, tact = A.run(None, {"lat": lat, "t": np.array([t], np.float32), "text": text, **rope})
81
+ m = B.run(None, {"x": p, "tact": tact, **rope})[0]
82
+ m = Cc.run(None, {"x": m, "tact": tact, **rope})[0]
83
+ v = D.run(None, {"prefix": p, "middle": m, "tact": tact, **rope})[0]
84
+ return v[:, :n].transpose(0, 2, 1).reshape(1, C, gh, gw)
85
+
86
+
87
+ times = ref["times"]
88
+ t0 = time.time()
89
+ v0 = velocity(lat0, float(times[0]))
90
+ print(f"vel[0] cos={cos(v0, ref['vels'][0]):.6f} rel={rel(v0, ref['vels'][0]):.2e} {time.time()-t0:.1f}s/step")
91
+ xs = [lat0]
92
+ for i in range(len(times) - 2):
93
+ xs.append(xs[-1] + np.float32(times[i + 1] - times[i]) * ref["vels"][i])
94
+ tf = [cos(v0, ref["vels"][0])] + [cos(velocity(xs[i], float(times[i])), ref["vels"][i])
95
+ for i in range(1, len(times) - 1)]
96
+ print("teacher-forced vel cos:", " ".join(f"{c:.5f}" for c in tf), f"min={min(tf):.5f}")
97
+ if not full:
98
+ sys.exit()
99
+ x = lat0.copy()
100
+ for i in range(len(times) - 1):
101
+ v = v0 if i == 0 else velocity(x, float(times[i]))
102
+ if i:
103
+ print(f"vel[{i}] cos={cos(v, ref['vels'][i]):.6f}")
104
+ x = x + np.float32(times[i + 1] - times[i]) * v
105
+ print(f"latent cos={cos(x, ref['latent']):.6f} rel={rel(x, ref['latent']):.2e}")
106
+ vs, vc = ropes.vae_tables(gh, gw)
107
+ t0 = time.time()
108
+ rgb = sess("vae_dec").run(None, {"z": x.astype(np.float32), "v_sin": vs, "v_cos": vc})[0]
109
+ want = (ref["rgb"] + 1) * 0.5
110
+ print(f"rgb cos={cos(rgb, want):.6f} maxabs={np.abs(rgb-want).max():.3f} "
111
+ f"psnr={10*math.log10(1/np.mean((rgb-want)**2)):.1f}dB {time.time()-t0:.1f}s")
112
+ img = (rgb[0].transpose(1, 2, 0) * 255).round().clip(0, 255).astype(np.uint8)
113
+ out = SP / "work" / f"onnx_{tag}.png"
114
+ Image.fromarray(img).save(out)
115
+ print("saved", out)
116
+ if "--dump" in sys.argv:
117
+ d = SP / "web" / "test_data"
118
+ d.mkdir(exist_ok=True)
119
+ for k, v in {"noise": lat0, "ref_text": ref["refined"], "ort_text": text, "ort_v0": v0,
120
+ "ref_v0": ref["vels"][0], "ort_latent": x, "ref_latent": ref["latent"],
121
+ "ort_rgb": rgb, "ref_rgb": (ref["rgb"] + 1) * 0.5}.items():
122
+ np.ascontiguousarray(v, dtype=np.float32).tofile(d / f"{k}.f32")
123
+ import json
124
+ json.dump({"ids": ids.tolist(), "times": [float(t) for t in times], "gh": gh, "gw": gw,
125
+ "gain": float(ref["gain"])}, open(d / "meta.json", "w"))
126
+ print("dumped", d)
text/text.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f10d7de1953edb97a9b5d09c0d20e43d438867709ac818578c6c86c72d4f4ce5
3
+ size 464409
text/text.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a43b7f15434012b590ce9462b271855e81f422acc8014e2257932f17d903014e
3
+ size 230071296
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c76318660cc87c3029535cc1596717df67132d231ce4ecf088ba2a8ec07c098
3
+ size 33384388
tokenizer_config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "additional_special_tokens": null,
5
+ "backend": "tokenizers",
6
+ "boi_token": "<start_of_image>",
7
+ "bos_token": "<bos>",
8
+ "clean_up_tokenization_spaces": false,
9
+ "eoi_token": "<end_of_image>",
10
+ "eos_token": "<eos>",
11
+ "image_token": "<image_soft_token>",
12
+ "is_local": true,
13
+ "mask_token": "<mask>",
14
+ "model_max_length": 1000000000000000019884624838656,
15
+ "model_specific_special_tokens": {
16
+ "boi_token": "<start_of_image>",
17
+ "eoi_token": "<end_of_image>",
18
+ "image_token": "<image_soft_token>"
19
+ },
20
+ "pad_token": "<pad>",
21
+ "padding_side": "right",
22
+ "processor_class": "Gemma3Processor",
23
+ "sp_model_kwargs": null,
24
+ "spaces_between_special_tokens": false,
25
+ "tokenizer_class": "GemmaTokenizer",
26
+ "unk_token": "<unk>",
27
+ "use_default_system_prompt": false
28
+ }
vae_dec/vae_dec.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c3af48e76e304ceacd67d386333a1366e136db1d268d8b7843b3c656055f937
3
+ size 26456362
vae_dec/vae_dec.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a63eafe6f1c29b58ace1793f3a39f78fdea9c45efd46ee42cf92df88452637f0
3
+ size 115682304