BenchmarkXPRTAdmin captainspock commited on
Commit
5fab480
·
0 Parent(s):

Duplicate from webnn/Z-Image-Turbo

Browse files

Co-authored-by: Spock <captainspock@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ onnx/safety_checker_model_f16.onnx_data filter=lfs diff=lfs merge=lfs -text
37
+ onnx/text_encoder_model_q4f16.onnx_data filter=lfs diff=lfs merge=lfs -text
38
+ onnx/text_encoder_model_q4f16.onnx_data_1 filter=lfs diff=lfs merge=lfs -text
39
+ onnx/transformer_model_q4f16.onnx_data filter=lfs diff=lfs merge=lfs -text
40
+ onnx/transformer_model_q4f16.onnx_data_1 filter=lfs diff=lfs merge=lfs -text
41
+ tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ tags:
4
+ - onnx
5
+ - webnn
6
+ - webgpu
7
+ - text-to-image
8
+ - z-image-turbo
9
+ ---
10
+
11
+ # Z-Image-Turbo
12
+
13
+ This repository provides an optimized ONNX version of **[Tongyi-MAI/Z-Image-Turbo](https://huggingface.co/Tongyi-MAI/Z-Image-Turbo)**, specifically tailored for efficient browser execution via **WebNN** and **WebGPU** using ONNX Runtime Web.
14
+
15
+ ## 🔄 Runtime Pipeline
16
+
17
+ The end-to-end inference flow runs sequentially across the ONNX sub-models under `onnx/` per image generation:
18
+
19
+ ### Inference Flow
20
+
21
+ <div align="center">
22
+ <img src="https://cdn-uploads.huggingface.co/production/uploads/65ee995fc7b0ce53e4a91edb/2ckM0sTl3VVrRzJ-5recK.jpeg" style="max-width: 100%; height: auto;" alt="Z Image Turbo Pipeline">
23
+ </div>
24
+
25
+ ### 🧩 Sub-model Components
26
+
27
+ | Stage | ONNX Model Artifact | Precision | Key Role |
28
+ |---|---|---|---|
29
+ | **1. Text Encoding** | `text_encoder_model_q4f16.onnx` | Q4F16 | Encodes text prompts into conditional embeddings |
30
+ | **2. Denoising** | `transformer_model_q4f16.onnx` | Q4F16 | Predicts noise latents across diffusion iterations |
31
+ | | `scheduler_step_model_f16.onnx` | FP16 | Computes denoised latents per step |
32
+ | **3. Decoding** | `vae_pre_process_model_f16.onnx` | FP16 | Scales and shifts latents for decoding |
33
+ | | `vae_decoder_model_f16.onnx` | FP16 | Reconstructs pixel-space RGB image from latents |
34
+ | **4. Safety** | `sc_prep_model_f16.onnx` | FP16 | Normalizes and pre-processes the image for the safety checker |
35
+ | | `safety_checker_model_f16.onnx` | FP16 | Inspects processed image features to ensure content safety |
36
+
37
+ ## 🛠️ Export & Reproduction
38
+
39
+ Instructions and scripts for exporting and optimizing the ONNX models from the original PyTorch weights can be found in the [model_exporter/README.md](model_exporter/README.md).
40
+
41
+ ## 🌐 Live Demo
42
+
43
+ Experience the model running in the browser:
44
+ * **Interactive Demo**: [WebNN Developer Preview - Z-Image-Turbo](https://microsoft.github.io/webnn-developer-preview/demos/z-image-turbo/)
45
+
46
+ ## 📑 Credits
47
+
48
+ * **Original PyTorch Model**: [Tongyi-MAI/Z-Image-Turbo](https://huggingface.co/Tongyi-MAI/Z-Image-Turbo)
49
+ * **Web Runtime**: [ONNX Runtime Web](https://github.com/microsoft/onnxruntime) / [WebNN Developer Preview](https://github.com/microsoft/webnn-developer-preview)
model_exporter/README.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Z-Image-Turbo ONNX Exporters
2
+
3
+ Export the [Z-Image-Turbo](https://huggingface.co/Tongyi-MAI/Z-Image-Turbo) text-to-image pipeline to ONNX models.
4
+
5
+ `export_models.py` serves as the primary entry point for converting all pipeline components.
6
+
7
+ ## Supported Components
8
+
9
+ The export script covers all essential parts of the Z-Image-Turbo pipeline:
10
+
11
+ * **Tokenizer:** Essential JSON and text configurations for prompt processing.
12
+ * **Text encoder (Qwen3):** Processes text prompts into embeddings.
13
+ * **Transformer trunk:** The core image generation model.
14
+ * **VAE decoder:** Converts latent representations back into pixel-space images.
15
+ * **Helper models:** Includes `scheduler_step`, `vae_pre_process`, and `sc_prep`.
16
+ * **Safety checker:** *(Optional)* Filters out unsafe content. Requires a separate checkpoint (see Usage below).
17
+
18
+ *Note: Running `export_models.py` builds the full pipeline into a single, self-contained bundle directory.*
19
+
20
+ ---
21
+
22
+ ## Installation
23
+
24
+ Python 3.13 is recommended.
25
+
26
+ ```bash
27
+ pip install -r requirements.txt
28
+ ```
29
+
30
+ ---
31
+
32
+ ## Usage
33
+
34
+ ### 1. Download Checkpoints
35
+ Download the model checkpoints locally before exporting. You can do this quickly using the `huggingface_hub` Python library:
36
+
37
+ ```python
38
+ from huggingface_hub import snapshot_download
39
+
40
+ # Download the core Z-Image-Turbo checkpoint
41
+ snapshot_download("Tongyi-MAI/Z-Image-Turbo", local_dir="checkpoints/z-image-turbo")
42
+
43
+ # Optional: Download the Safety Checker checkpoint
44
+ snapshot_download("CompVis/stable-diffusion-safety-checker", local_dir="checkpoints/safety-checker")
45
+ ```
46
+
47
+ ### 2. Export the Pipeline
48
+ By default, the script exports all components to a `z-image-turbo-onnx/` directory.
49
+
50
+ **Export everything at once:**
51
+ ```bash
52
+ python export_models.py checkpoints/z-image-turbo
53
+ ```
54
+
55
+ **Export with the Safety Checker:**
56
+ Because the safety checker uses a separate CompVis model, it requires the `--safety_checker_checkpoint` flag. If this flag is provided, the standard full export automatically includes it. If omitted, the safety checker is safely skipped.
57
+ ```bash
58
+ python export_models.py checkpoints/z-image-turbo --safety_checker_checkpoint checkpoints/safety-checker
59
+ ```
60
+
61
+ ---
62
+
63
+ ## Output Structure
64
+
65
+ All generated `.onnx` models and their associated external data are written to `<output_dir>/onnx/`. To ensure the output bundle is fully self-contained, `export_models.py` automatically copies the required tokenizer files from the source checkpoint into `<output_dir>/tokenizer/`.
66
+
67
+ The final output directory (`z-image-turbo-onnx/` by default) will look like this:
68
+
69
+ ```text
70
+ z-image-turbo-onnx/
71
+ ├── onnx/
72
+ │ ├── sc_prep_model_f16.onnx
73
+ │ ├── scheduler_step_model_f16.onnx
74
+ │ ├── text_encoder_model_q4f16.onnx
75
+ │ ├── text_encoder_model_q4f16.onnx_data
76
+ │ ├── text_encoder_model_q4f16.onnx_data_1
77
+ │ ├── transformer_model_q4f16.onnx
78
+ │ ├── transformer_model_q4f16.onnx_data
79
+ │ ├── transformer_model_q4f16.onnx_data_1
80
+ │ ├── vae_decoder_model_f16.onnx
81
+ │ └── vae_pre_process_model_f16.onnx
82
+ └── tokenizer/
83
+ ├── merges.txt
84
+ ├── tokenizer.json
85
+ ├── tokenizer_config.json
86
+ └── vocab.json
87
+ ```
model_exporter/build_helper_models.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ # Modifications Copyright (C) 2026 Intel Corporation. All rights reserved.
7
+ # --------------------------------------------------------------------------
8
+ """Build the scheduler_step / vae_pre_process / sc_prep helper ONNX graphs for the self-built
9
+ Z-Image-Turbo pipeline, in either float16 or float32.
10
+ """
11
+
12
+ import argparse
13
+ import os
14
+
15
+ import numpy as np
16
+ import onnx
17
+ import onnxruntime as ort
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ LATENT_CHANNELS = 16
23
+
24
+ VAE_SCALING_FACTOR = 0.3611
25
+ VAE_SHIFT_FACTOR = 0.1159
26
+
27
+ # Standard OpenAI CLIP preprocessing constants.
28
+ CLIP_MEAN = (0.48145466, 0.4578275, 0.40821073)
29
+ CLIP_STD = (0.26862954, 0.26130258, 0.27577711)
30
+
31
+ PRECISION_CONFIGS = {"f16": {}, "f32": {}}
32
+
33
+ DEFAULT_OUTPUT_DIR = "z-image-turbo-onnx"
34
+
35
+
36
+ def parse_extra_options(pairs):
37
+ """Parse `key=value` strings (as passed via `--extra_options`) into a dict."""
38
+ extra_options = {}
39
+ for kv_str in pairs or []:
40
+ key, _, value = kv_str.partition("=")
41
+ extra_options[key.strip()] = value.strip()
42
+ return extra_options
43
+
44
+
45
+ # ======================================================================
46
+ # Model 1 - Scheduler Step (one flow-matching Euler step + sigma calc)
47
+ # ======================================================================
48
+ class SchedulerStepModel(nn.Module):
49
+ """Inputs: noise_pred [1,16,H,W], latents [1,16,H,W], step_info [2]. Output: latents_out."""
50
+
51
+ def __init__(self):
52
+ super().__init__()
53
+ timesteps = torch.linspace(1, 1000, 1000, dtype=torch.float32).flip(0)
54
+ s = timesteps / 1000.0
55
+ shift = 3.0
56
+ sigmas = (shift * s) / (1.0 + (shift - 1.0) * s)
57
+ self.register_buffer("sigma_max", sigmas[0])
58
+ self.register_buffer("sigma_min", sigmas[-1])
59
+ self.register_buffer("shift", torch.tensor(shift, dtype=torch.float32))
60
+
61
+ def forward(self, noise_pred, latents, step_info):
62
+ step, num_steps = step_info[0], step_info[1]
63
+
64
+ t_start = self.sigma_max * 1000.0
65
+ t_end = self.sigma_min * 1000.0
66
+ denom = num_steps - 1.0
67
+ denom = torch.where(denom == 0.0, torch.tensor(1.0), denom)
68
+ step_delta = (t_end - t_start) / denom
69
+
70
+ t_curr = t_start + step * step_delta
71
+ t_next = t_start + (step + 1.0) * step_delta
72
+
73
+ s_curr = t_curr / 1000.0
74
+ s_next = t_next / 1000.0
75
+ sigma_curr = (self.shift * s_curr) / (1.0 + (self.shift - 1.0) * s_curr)
76
+ sigma_next_raw = (self.shift * s_next) / (1.0 + (self.shift - 1.0) * s_next)
77
+
78
+ is_last = step >= (num_steps - 1.0)
79
+ sigma_next = torch.where(is_last, torch.tensor(0.0), sigma_next_raw)
80
+
81
+ dt = sigma_next - sigma_curr
82
+ return latents - dt * noise_pred
83
+
84
+
85
+ def numpy_scheduler_step(noise_pred, latents, step, num_steps):
86
+ timesteps = np.linspace(1, 1000, 1000, dtype=np.float32)[::-1]
87
+ s = timesteps / 1000.0
88
+ shift = 3.0
89
+ sigmas = (shift * s) / (1.0 + (shift - 1.0) * s)
90
+ sigma_max, sigma_min = sigmas[0], sigmas[-1]
91
+ t_start, t_end = sigma_max * 1000.0, sigma_min * 1000.0
92
+ denom = max(num_steps - 1.0, 1.0)
93
+ step_delta = (t_end - t_start) / denom
94
+ t_curr = t_start + step * step_delta
95
+ t_next = t_start + (step + 1) * step_delta
96
+ s_curr, s_next = t_curr / 1000.0, t_next / 1000.0
97
+ sigma_curr = (shift * s_curr) / (1.0 + (shift - 1.0) * s_curr)
98
+ if step >= num_steps - 1:
99
+ sigma_next = 0.0
100
+ else:
101
+ sigma_next = (shift * s_next) / (1.0 + (shift - 1.0) * s_next)
102
+ dt = sigma_next - sigma_curr
103
+ return latents - dt * noise_pred
104
+
105
+
106
+ # ======================================================================
107
+ # Model 2 - VAE Pre-Process (scale/shift, no frame-axis squeeze)
108
+ # ======================================================================
109
+ class VaePreProcessModel(nn.Module):
110
+ """Input: latents [1,16,H,W]. Output: scaled_latents [1,16,H,W]."""
111
+
112
+ def __init__(self):
113
+ super().__init__()
114
+ self.register_buffer("scaling_factor", torch.tensor(VAE_SCALING_FACTOR, dtype=torch.float32))
115
+ self.register_buffer("shift_factor", torch.tensor(VAE_SHIFT_FACTOR, dtype=torch.float32))
116
+
117
+ def forward(self, latents):
118
+ return latents / self.scaling_factor + self.shift_factor
119
+
120
+
121
+ # ======================================================================
122
+ # Model 3 - sc_prep (resize + CLIP normalize, for the safety checker)
123
+ # ======================================================================
124
+ class ScPrepModel(nn.Module):
125
+ """Input: sample [1,3,H,W] (VAE output, [-1,1] range). Output: clip_input [1,3,224,224]."""
126
+
127
+ def __init__(self):
128
+ super().__init__()
129
+ std = torch.tensor(CLIP_STD, dtype=torch.float32).view(1, 3, 1, 1)
130
+ mean = torch.tensor(CLIP_MEAN, dtype=torch.float32).view(1, 3, 1, 1)
131
+ self.register_buffer("scale", 0.5 / std)
132
+ self.register_buffer("offset", (0.5 - mean) / std)
133
+
134
+ def forward(self, sample):
135
+ resized = F.interpolate(sample, size=(224, 224), mode="bilinear", align_corners=False)
136
+ return resized * self.scale + self.offset
137
+
138
+
139
+ def numpy_resize_asymmetric_bilinear(img, out_h, out_w):
140
+ """img: [C, H, W] float32. "asymmetric" == in_coord = out_coord * (in/out), no half-pixel centering."""
141
+ c, h, w = img.shape
142
+ scale_h, scale_w = h / out_h, w / out_w
143
+ ys = np.arange(out_h) * scale_h
144
+ xs = np.arange(out_w) * scale_w
145
+ y0 = np.clip(np.floor(ys).astype(np.int64), 0, h - 1)
146
+ y1 = np.clip(y0 + 1, 0, h - 1)
147
+ wy = (ys - y0).astype(np.float32)
148
+ x0 = np.clip(np.floor(xs).astype(np.int64), 0, w - 1)
149
+ x1 = np.clip(x0 + 1, 0, w - 1)
150
+ wx = (xs - x0).astype(np.float32)
151
+
152
+ top = img[:, y0][:, :, x0] * (1 - wx)[None, None, :] + img[:, y0][:, :, x1] * wx[None, None, :]
153
+ bot = img[:, y1][:, :, x0] * (1 - wx)[None, None, :] + img[:, y1][:, :, x1] * wx[None, None, :]
154
+ return (top * (1 - wy)[None, :, None] + bot * wy[None, :, None]).astype(np.float32)
155
+
156
+
157
+ def numpy_sc_prep(sample):
158
+ """sample: [1, 3, H, W] float32."""
159
+ resized = numpy_resize_asymmetric_bilinear(sample[0], 224, 224)[None, ...]
160
+ std = np.array(CLIP_STD, dtype=np.float32).reshape(1, 3, 1, 1)
161
+ mean = np.array(CLIP_MEAN, dtype=np.float32).reshape(1, 3, 1, 1)
162
+ return resized * (0.5 / std) + (0.5 - mean) / std
163
+
164
+
165
+ # ======================================================================
166
+ # Export helpers
167
+ # ======================================================================
168
+ def _force_dynamic_dim_names(onnx_model, dynamic_axes):
169
+ tensors = {t.name: t for t in list(onnx_model.graph.input) + list(onnx_model.graph.output)}
170
+ for name, axes in dynamic_axes.items():
171
+ tensor = tensors.get(name)
172
+ if tensor is None:
173
+ continue
174
+ dims = tensor.type.tensor_type.shape.dim
175
+ for axis, dim_name in axes.items():
176
+ if axis < len(dims):
177
+ dims[axis].dim_param = dim_name
178
+ if dims[axis].HasField("dim_value"):
179
+ dims[axis].ClearField("dim_value")
180
+
181
+
182
+ def _force_resize_asymmetric(onnx_model):
183
+ # torch exports bilinear interpolate as pytorch_half_pixel; must be asymmetric here instead.
184
+ for node in onnx_model.graph.node:
185
+ if node.op_type != "Resize":
186
+ continue
187
+ for attr in node.attribute:
188
+ if attr.name == "coordinate_transformation_mode":
189
+ attr.s = b"asymmetric"
190
+ break
191
+ else:
192
+ node.attribute.append(onnx.helper.make_attribute("coordinate_transformation_mode", "asymmetric"))
193
+
194
+
195
+ def export_model(model, dummy_inputs, input_names, output_names, dynamic_axes, f32_path, opset=17):
196
+ os.makedirs(os.path.dirname(f32_path) or ".", exist_ok=True)
197
+ torch.onnx.export(
198
+ model,
199
+ dummy_inputs,
200
+ f32_path,
201
+ input_names=input_names,
202
+ output_names=output_names,
203
+ dynamic_axes=dynamic_axes,
204
+ opset_version=opset,
205
+ do_constant_folding=True,
206
+ dynamo=False,
207
+ )
208
+
209
+ onnx_model = onnx.load(f32_path)
210
+ _force_dynamic_dim_names(onnx_model, dynamic_axes)
211
+ _force_resize_asymmetric(onnx_model)
212
+ onnx.save(onnx_model, f32_path)
213
+ print(f" wrote {f32_path} ({os.path.getsize(f32_path) / 1024:.1f} KB)")
214
+
215
+
216
+ def _fix_cast_node_types(onnx_model):
217
+ # Patches a Cast node's `to` attribute to match its (possibly f16-converted) declared output type.
218
+ vi = {v.name: v for v in onnx_model.graph.value_info}
219
+ for node in onnx_model.graph.node:
220
+ if node.op_type != "Cast":
221
+ continue
222
+ for attr in node.attribute:
223
+ if attr.name == "to" and attr.i == onnx.TensorProto.FLOAT:
224
+ out_type = vi.get(node.output[0])
225
+ if out_type and out_type.type.tensor_type.elem_type == onnx.TensorProto.FLOAT16:
226
+ attr.i = onnx.TensorProto.FLOAT16
227
+
228
+
229
+ def convert_to_f16(f32_path, f16_path):
230
+ from onnxconverter_common import float16
231
+
232
+ onnx_model = onnx.load(f32_path)
233
+ # Un-block Resize to get a genuinely all-fp16 graph instead of wrapped Casts.
234
+ op_block_list = [op for op in float16.DEFAULT_OP_BLOCK_LIST if op != "Resize"]
235
+ onnx_model_f16 = float16.convert_float_to_float16(
236
+ onnx_model, keep_io_types=False, op_block_list=op_block_list
237
+ )
238
+ _fix_cast_node_types(onnx_model_f16)
239
+ onnx.save(onnx_model_f16, f16_path)
240
+ print(f" wrote {f16_path} ({os.path.getsize(f16_path) / 1024:.1f} KB)")
241
+
242
+
243
+ def verify_model(path, feed_dict, label):
244
+ sess = ort.InferenceSession(path, providers=["CPUExecutionProvider"])
245
+ outputs = sess.run(None, feed_dict)
246
+ for meta, arr in zip(sess.get_outputs(), outputs):
247
+ print(
248
+ f" [{label}] output '{meta.name}': shape={arr.shape}, dtype={arr.dtype}, "
249
+ f"min={float(arr.min()):.4f}, max={float(arr.max()):.4f}, mean={float(arr.mean()):.4f}"
250
+ )
251
+ return outputs
252
+
253
+
254
+ def build_one(name, model, dummy_inputs, input_names, output_names, dynamic_axes, out_dir, precision, verify_fn):
255
+ f32_path = os.path.join(out_dir, f"{name}_f32.onnx")
256
+ export_model(model, dummy_inputs, input_names, output_names, dynamic_axes, f32_path)
257
+ if precision == "f32":
258
+ verify_fn(f32_path, "f32")
259
+ return
260
+
261
+ f16_path = os.path.join(out_dir, f"{name}_f16.onnx")
262
+ convert_to_f16(f32_path, f16_path)
263
+ verify_fn(f16_path, "f16")
264
+ os.remove(f32_path)
265
+ print(f" (removed intermediate {f32_path}; only f16 was requested)")
266
+
267
+
268
+ # ======================================================================
269
+ # Standalone build driver
270
+ # ======================================================================
271
+ def build(input_path, output_dir, precision="f16", extra_options=None):
272
+ """Build scheduler_step_model / vae_pre_process_model / sc_prep_model into `output_dir`/onnx.
273
+
274
+ `input_path` is unused (kept so export_models.py can dispatch to every build() uniformly).
275
+ """
276
+ del input_path
277
+ if precision not in PRECISION_CONFIGS:
278
+ raise ValueError(f"Unknown precision '{precision}'; choose from {sorted(PRECISION_CONFIGS)}")
279
+
280
+ extra_options = dict(extra_options or {})
281
+ height = int(extra_options.get("height", 512))
282
+ width = int(extra_options.get("width", 512))
283
+ num_inference_steps = int(extra_options.get("num_inference_steps", 8))
284
+
285
+ onnx_dir = os.path.join(output_dir, "onnx")
286
+ os.makedirs(onnx_dir, exist_ok=True)
287
+ latent_h, latent_w = height // 8, width // 8
288
+
289
+ print("=" * 60)
290
+ print("Generating Z-Image-Turbo helper models (self-built shape convention)")
291
+ print(f"output_dir={onnx_dir} precision={precision}")
292
+ print("=" * 60)
293
+
294
+ # ── 1. scheduler_step ────────────────────────────────────────────────
295
+ print("\n[1/3] scheduler_step_model")
296
+ np_noise = np.random.randn(1, LATENT_CHANNELS, 24, 32).astype(np.float32)
297
+ np_lat = np.random.randn(1, LATENT_CHANNELS, 24, 32).astype(np.float32)
298
+ step_val, num_steps_val = 2, num_inference_steps
299
+
300
+ def verify_scheduler_step(path, label):
301
+ outputs = verify_model(
302
+ path,
303
+ {
304
+ "noise_pred": np_noise.astype(np.float16 if label == "f16" else np.float32),
305
+ "latents": np_lat.astype(np.float16 if label == "f16" else np.float32),
306
+ "step_info": np.array([step_val, num_steps_val], dtype=np.float16 if label == "f16" else np.float32),
307
+ },
308
+ label,
309
+ )
310
+ ref = numpy_scheduler_step(np_noise, np_lat, step_val, num_steps_val)
311
+ diff = np.max(np.abs(outputs[0].astype(np.float32) - ref))
312
+ print(f" [{label}] max abs diff vs numpy reference: {diff:.6e}")
313
+
314
+ build_one(
315
+ "scheduler_step_model",
316
+ SchedulerStepModel().eval(),
317
+ (
318
+ torch.randn(1, LATENT_CHANNELS, latent_h, latent_w),
319
+ torch.randn(1, LATENT_CHANNELS, latent_h, latent_w),
320
+ torch.tensor([0.0, float(num_inference_steps)], dtype=torch.float32),
321
+ ),
322
+ ["noise_pred", "latents", "step_info"],
323
+ ["latents_out"],
324
+ {
325
+ "noise_pred": {2: "height", 3: "width"},
326
+ "latents": {2: "height", 3: "width"},
327
+ "step_info": {},
328
+ "latents_out": {2: "height", 3: "width"},
329
+ },
330
+ onnx_dir, precision, verify_scheduler_step,
331
+ )
332
+
333
+ # ── 2. vae_pre_process ───────────────────────────────────────────────
334
+ print("\n[2/3] vae_pre_process_model")
335
+ np_vae_lat = np.random.randn(1, LATENT_CHANNELS, 24, 32).astype(np.float32)
336
+
337
+ def verify_vae_pre_process(path, label):
338
+ outputs = verify_model(
339
+ path, {"latents": np_vae_lat.astype(np.float16 if label == "f16" else np.float32)}, label,
340
+ )
341
+ ref = np_vae_lat / VAE_SCALING_FACTOR + VAE_SHIFT_FACTOR
342
+ diff = np.max(np.abs(outputs[0].astype(np.float32) - ref))
343
+ print(f" [{label}] max abs diff vs numpy reference: {diff:.6e}")
344
+
345
+ build_one(
346
+ "vae_pre_process_model",
347
+ VaePreProcessModel().eval(),
348
+ (torch.randn(1, LATENT_CHANNELS, latent_h, latent_w),),
349
+ ["latents"], ["scaled_latents"],
350
+ {
351
+ "latents": {2: "height", 3: "width"},
352
+ "scaled_latents": {2: "height", 3: "width"},
353
+ },
354
+ onnx_dir, precision, verify_vae_pre_process,
355
+ )
356
+
357
+ # ── 3. sc_prep ───────────────────────────────────────────────────────
358
+ print("\n[3/3] sc_prep_model")
359
+ np_sample = np.random.uniform(-1.0, 1.0, size=(1, 3, 48, 64)).astype(np.float32)
360
+
361
+ def verify_sc_prep(path, label):
362
+ outputs = verify_model(
363
+ path, {"sample": np_sample.astype(np.float16 if label == "f16" else np.float32)}, label,
364
+ )
365
+ assert outputs[0].shape == (1, 3, 224, 224), f"unexpected sc_prep output shape {outputs[0].shape}"
366
+ ref = numpy_sc_prep(np_sample)
367
+ diff = np.max(np.abs(outputs[0].astype(np.float32) - ref))
368
+ print(f" [{label}] max abs diff vs numpy reference: {diff:.6e}")
369
+
370
+ build_one(
371
+ "sc_prep_model",
372
+ ScPrepModel().eval(),
373
+ (torch.randn(1, 3, height, width),),
374
+ ["sample"], ["clip_input"],
375
+ {
376
+ "sample": {2: "height", 3: "width"},
377
+ "clip_input": {},
378
+ },
379
+ onnx_dir, precision, verify_sc_prep,
380
+ )
381
+
382
+ print("\n" + "=" * 60)
383
+ print(f"Done! Models saved to {os.path.abspath(onnx_dir)}/")
384
+ print("=" * 60)
385
+ return onnx_dir
386
+
387
+
388
+ def get_args():
389
+ parser = argparse.ArgumentParser(description="Export the Z-Image-Turbo helper models to ONNX.")
390
+ parser.add_argument(
391
+ "-o", "--output_dir", default=DEFAULT_OUTPUT_DIR,
392
+ help=f"Directory to write the ONNX models to (under an `onnx/` subdir). Default: {DEFAULT_OUTPUT_DIR}",
393
+ )
394
+ parser.add_argument(
395
+ "-p", "--precision", default="f16", choices=sorted(PRECISION_CONFIGS),
396
+ help="Output precision. Default: f16.",
397
+ )
398
+ parser.add_argument(
399
+ "--extra_options", nargs="*", default=[],
400
+ help="Extra key=value options, e.g. height=512 width=512 num_inference_steps=8.",
401
+ )
402
+ return parser.parse_args()
403
+
404
+
405
+ def main():
406
+ args = get_args()
407
+ onnx_dir = build(None, args.output_dir, args.precision, parse_extra_options(args.extra_options))
408
+ print(f"\nSuccess: helper_models exported to {onnx_dir}")
409
+
410
+
411
+ if __name__ == "__main__":
412
+ main()
model_exporter/build_safety_checker.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ # Modifications Copyright (C) 2026 Intel Corporation. All rights reserved.
7
+ # --------------------------------------------------------------------------
8
+ """Standalone exporter for the Z-Image-Turbo NSFW safety checker."""
9
+
10
+ import argparse
11
+ import os
12
+
13
+ import numpy as np
14
+ import onnx
15
+ import onnx_ir as ir
16
+ import onnxruntime as ort
17
+ import torch
18
+ import torch.nn as nn
19
+ from diffusers.pipelines.stable_diffusion.safety_checker import (
20
+ StableDiffusionSafetyChecker,
21
+ cosine_distance,
22
+ )
23
+
24
+ from build_helper_models import convert_to_f16
25
+ from external_data_utils import (
26
+ INLINE_SIZE_THRESHOLD_BYTES,
27
+ MAX_SHARD_SIZE_BYTES,
28
+ save_ir_model_sharded,
29
+ )
30
+
31
+ DEFAULT_OUTPUT_DIR = "z-image-turbo-onnx"
32
+
33
+ PRECISION_CONFIGS = {"f16": {}, "f32": {}}
34
+
35
+
36
+ def parse_extra_options(pairs):
37
+ """Parse `key=value` strings (as passed via `--extra_options`) into a dict."""
38
+ extra_options = {}
39
+ for kv_str in pairs or []:
40
+ key, _, value = kv_str.partition("=")
41
+ extra_options[key.strip()] = value.strip()
42
+ return extra_options
43
+
44
+
45
+ def optimize_onnx_graph(onnx_path):
46
+ """Run ORT's EP-neutral (BASIC-level) graph optimizations on `onnx_path`, in place."""
47
+ tmp_path = onnx_path + ".opt.tmp"
48
+ sess_options = ort.SessionOptions()
49
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
50
+ sess_options.optimized_model_filepath = tmp_path
51
+ ort.InferenceSession(onnx_path, sess_options, providers=["CPUExecutionProvider"])
52
+ os.replace(tmp_path, onnx_path)
53
+ print(f" optimized {onnx_path} ({os.path.getsize(onnx_path) / (1024 * 1024):.1f} MB)")
54
+
55
+
56
+ class SafetyCheckerOnnxWrapper(nn.Module):
57
+ """`StableDiffusionSafetyChecker.forward_onnx` minus the `images` masking I/O."""
58
+
59
+ def __init__(self, safety_checker):
60
+ super().__init__()
61
+ self.vision_model = safety_checker.vision_model
62
+ self.visual_projection = safety_checker.visual_projection
63
+ self.concept_embeds = safety_checker.concept_embeds
64
+ self.special_care_embeds = safety_checker.special_care_embeds
65
+ self.concept_embeds_weights = safety_checker.concept_embeds_weights
66
+ self.special_care_embeds_weights = safety_checker.special_care_embeds_weights
67
+
68
+ def forward(self, clip_input):
69
+ pooled_output = self.vision_model(clip_input)[1] # pooled_output
70
+ image_embeds = self.visual_projection(pooled_output)
71
+
72
+ special_cos_dist = cosine_distance(image_embeds, self.special_care_embeds)
73
+ cos_dist = cosine_distance(image_embeds, self.concept_embeds)
74
+
75
+ special_scores = special_cos_dist - self.special_care_embeds_weights
76
+ special_care = torch.any(special_scores > 0, dim=1)
77
+ special_adjustment = special_care * 0.01
78
+ special_adjustment = special_adjustment.unsqueeze(1).expand(-1, cos_dist.shape[1])
79
+
80
+ concept_scores = (cos_dist - self.concept_embeds_weights) + special_adjustment
81
+ has_nsfw_concepts = torch.any(concept_scores > 0, dim=1)
82
+
83
+ return has_nsfw_concepts
84
+
85
+
86
+ def build(input_path, output_dir, precision="f16", extra_options=None, opset=17):
87
+ if precision not in PRECISION_CONFIGS:
88
+ raise ValueError(f"Unknown precision '{precision}'; choose from {sorted(PRECISION_CONFIGS)}")
89
+
90
+ onnx_dir = os.path.join(output_dir, "onnx")
91
+ os.makedirs(onnx_dir, exist_ok=True)
92
+
93
+ print(f"Loading safety checker checkpoint from {input_path}")
94
+ safety_checker = StableDiffusionSafetyChecker.from_pretrained(input_path)
95
+ safety_checker.eval()
96
+ wrapper = SafetyCheckerOnnxWrapper(safety_checker).eval()
97
+
98
+ f32_path = os.path.join(onnx_dir, "safety_checker_model_f32.onnx")
99
+ dummy_clip_input = torch.randn(1, 3, 224, 224)
100
+ torch.onnx.export(
101
+ wrapper,
102
+ (dummy_clip_input,),
103
+ f32_path,
104
+ input_names=["clip_input"],
105
+ output_names=["has_nsfw_concepts"],
106
+ dynamic_axes={},
107
+ opset_version=opset,
108
+ do_constant_folding=True,
109
+ dynamo=False,
110
+ )
111
+ print(f" wrote {f32_path} ({os.path.getsize(f32_path) / (1024 * 1024):.1f} MB)")
112
+
113
+ optimize_onnx_graph(f32_path)
114
+
115
+ if precision == "f32":
116
+ final_name = "safety_checker_model_f32.onnx"
117
+ proto = onnx.load(f32_path)
118
+ else:
119
+ final_name = "safety_checker_model_f16.onnx"
120
+ f16_tmp = os.path.join(onnx_dir, "safety_checker_model_f16_tmp.onnx")
121
+ convert_to_f16(f32_path, f16_tmp)
122
+ proto = onnx.load(f16_tmp)
123
+ os.remove(f16_tmp)
124
+ os.remove(f32_path)
125
+
126
+ save_ir_model_sharded(
127
+ ir.from_proto(proto), onnx_dir, final_name,
128
+ size_threshold_bytes=INLINE_SIZE_THRESHOLD_BYTES,
129
+ max_shard_size_bytes=MAX_SHARD_SIZE_BYTES,
130
+ )
131
+ final_path = os.path.join(onnx_dir, final_name)
132
+ print(f" wrote {final_path} (+ sharded external data)")
133
+
134
+ sess = ort.InferenceSession(final_path, providers=["CPUExecutionProvider"])
135
+ for i in sess.get_inputs():
136
+ print(f"input: {i}")
137
+ for o in sess.get_outputs():
138
+ print(f"output: {o}")
139
+
140
+ dtype = np.float16 if precision == "f16" else np.float32
141
+ sample = np.random.randn(1, 3, 224, 224).astype(dtype)
142
+ outputs = sess.run(None, {"clip_input": sample})
143
+ print(
144
+ f" sanity run output 'has_nsfw_concepts': shape={outputs[0].shape}, "
145
+ f"dtype={outputs[0].dtype}, values={outputs[0]}"
146
+ )
147
+
148
+ return onnx_dir
149
+
150
+
151
+ def get_args():
152
+ parser = argparse.ArgumentParser(description="Export the Z-Image-Turbo NSFW safety checker to ONNX.")
153
+ parser.add_argument(
154
+ "input_path",
155
+ help="Path to a local CompVis/stable-diffusion-safety-checker-compatible checkpoint "
156
+ "(config.json + weights), e.g. via huggingface_hub.snapshot_download('CompVis/"
157
+ "stable-diffusion-safety-checker', local_dir=...).",
158
+ )
159
+ parser.add_argument(
160
+ "-o", "--output_dir", default=DEFAULT_OUTPUT_DIR,
161
+ help=f"Directory to write the ONNX model to (under an `onnx/` subdir). Default: {DEFAULT_OUTPUT_DIR}",
162
+ )
163
+ parser.add_argument(
164
+ "-p", "--precision", default="f16", choices=sorted(PRECISION_CONFIGS),
165
+ help="Output precision. Default: f16.",
166
+ )
167
+ parser.add_argument(
168
+ "--extra_options", nargs="*", default=[],
169
+ help="Extra key=value options (currently unused; kept for CLI consistency with the "
170
+ "other build_*.py scripts).",
171
+ )
172
+ return parser.parse_args()
173
+
174
+
175
+ def main():
176
+ args = get_args()
177
+ onnx_dir = build(args.input_path, args.output_dir, args.precision, parse_extra_options(args.extra_options))
178
+ print(f"\nSuccess: safety_checker exported to {onnx_dir}")
179
+
180
+
181
+ if __name__ == "__main__":
182
+ main()
model_exporter/build_text_encoder.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ # Modifications Copyright (C) 2026 Intel Corporation. All rights reserved.
7
+ # --------------------------------------------------------------------------
8
+ """Build the Z-Image-Turbo text encoder ONNX graph directly from a Qwen3 HF checkpoint."""
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+
14
+ import numpy as np
15
+ import onnx
16
+ import onnx_ir as ir
17
+ import torch
18
+ from onnx import TensorProto, helper, numpy_helper
19
+ from onnxruntime.quantization.matmul_nbits_quantizer import MatMulNBitsQuantizer, QuantFormat
20
+ from transformers import AutoModelForCausalLM
21
+
22
+ from external_data_utils import (
23
+ INLINE_SIZE_THRESHOLD_BYTES,
24
+ MAX_SHARD_SIZE_BYTES,
25
+ save_ir_model_sharded,
26
+ )
27
+
28
+ DEFAULT_OUTPUT_DIR = "z-image-turbo-onnx"
29
+
30
+ PRECISION_CONFIGS = {
31
+ "f16": {"dtype": "f16", "quantize": False, "suffix": "f16"},
32
+ "f32": {"dtype": "f32", "quantize": False, "suffix": "f32"},
33
+ "f16_int4_quant": {"dtype": "f16", "quantize": True, "suffix": "q4f16"},
34
+ "f32_int4_quant": {"dtype": "f32", "quantize": True, "suffix": "q4f32"},
35
+ }
36
+
37
+
38
+ def parse_extra_options(pairs):
39
+ """Parse `key=value` strings (as passed via `--extra_options`) into a dict."""
40
+ extra_options = {}
41
+ for kv_str in pairs or []:
42
+ key, _, value = kv_str.partition("=")
43
+ extra_options[key.strip()] = value.strip()
44
+ return extra_options
45
+
46
+
47
+ def _read_qwen3_config(text_encoder_dir):
48
+ with open(os.path.join(text_encoder_dir, "config.json"), encoding="utf-8") as f:
49
+ cfg = json.load(f)
50
+ return {
51
+ "num_layers": cfg["num_hidden_layers"],
52
+ "hidden_size": cfg["hidden_size"],
53
+ "num_attn_heads": cfg["num_attention_heads"],
54
+ "num_kv_heads": cfg["num_key_value_heads"],
55
+ "head_size": cfg["head_dim"],
56
+ "rope_theta": float(cfg["rope_theta"]),
57
+ "rms_norm_eps": float(cfg["rms_norm_eps"]),
58
+ "max_position_embeddings": cfg["max_position_embeddings"],
59
+ }
60
+
61
+
62
+ _TORCH_DTYPES = {"f16": torch.float16, "f32": torch.float32}
63
+ _ONNX_DTYPES = {"f16": TensorProto.FLOAT16, "f32": TensorProto.FLOAT}
64
+ _NP_DTYPES = {"f16": np.float16, "f32": np.float32}
65
+
66
+
67
+ def _rotary_cos_sin_tables(head_size, rope_theta, max_position_embeddings, np_dtype):
68
+ dim = head_size
69
+ inv_freq = 1.0 / (rope_theta ** (np.arange(0, dim, 2, dtype=np.int64).astype(np.float64) / dim))
70
+ t = np.arange(max_position_embeddings, dtype=np.float64)
71
+ freqs = np.outer(t, inv_freq)
72
+ emb = np.concatenate([freqs, freqs], axis=-1)
73
+ # com.microsoft.RotaryEmbedding expects cos/sin caches of shape [max_seq_len, head_size/2]
74
+ cos_cache = np.cos(emb)[:, : dim // 2].astype(np_dtype)
75
+ sin_cache = np.sin(emb)[:, : dim // 2].astype(np_dtype)
76
+ return cos_cache, sin_cache
77
+
78
+
79
+ class _GraphBuilder:
80
+ """Accumulates onnx NodeProtos and initializers for the encoder graph."""
81
+
82
+ def __init__(self):
83
+ self.nodes = []
84
+ self.initializers = []
85
+
86
+ def initializer(self, name, array):
87
+ array = np.asarray(array)
88
+ # Keep true scalars 0-d (np.ascontiguousarray would promote to shape (1,)).
89
+ if array.ndim:
90
+ array = np.ascontiguousarray(array)
91
+ self.initializers.append(numpy_helper.from_array(array, name=name))
92
+ return name
93
+
94
+ def const_i64(self, name, values):
95
+ return self.initializer(name, np.array(values, dtype=np.int64))
96
+
97
+ def node(self, op_type, inputs, outputs, name, domain="", **attrs):
98
+ self.nodes.append(helper.make_node(op_type, inputs, outputs, name=name, domain=domain, **attrs))
99
+ return outputs[0]
100
+
101
+
102
+ def _attention_mask_reformat(gb, attention_mask_name, enable_webgpu_graph=False):
103
+ """Derive GroupQueryAttention's seqlens_k/total_seq_len from the 2D attention_mask."""
104
+ if enable_webgpu_graph:
105
+ mask_i32 = gb.node("Cast", [attention_mask_name], ["attn_mask_reformat/mask_i32"],
106
+ "attn_mask_reformat/Cast", to=TensorProto.INT32)
107
+ axis1 = gb.const_i64("attn_mask_reformat/axis1", [1])
108
+ mask_sum = gb.node("ReduceSum", [mask_i32, axis1], ["attn_mask_reformat/mask_sum"],
109
+ "attn_mask_reformat/ReduceSum", keepdims=0)
110
+ one_i32 = gb.initializer("attn_mask_reformat/one_i32", np.array([1], dtype=np.int32))
111
+ seqlens_k = gb.node("Sub", [mask_sum, one_i32], ["attn_mask_reformat/seqlens_k"],
112
+ "attn_mask_reformat/Sub")
113
+ total_seq_len = gb.node("ReduceMax", [mask_sum], ["attn_mask_reformat/total_seq_len"],
114
+ "attn_mask_reformat/ReduceMax", keepdims=0)
115
+ return seqlens_k, total_seq_len
116
+
117
+ axis1 = gb.const_i64("attn_mask_reformat/axis1", [1])
118
+ mask_sum = gb.node("ReduceSum", [attention_mask_name, axis1], ["attn_mask_reformat/mask_sum"],
119
+ "attn_mask_reformat/ReduceSum", keepdims=0)
120
+ one_i64 = gb.const_i64("attn_mask_reformat/one_i64", [1])
121
+ sub = gb.node("Sub", [mask_sum, one_i64], ["attn_mask_reformat/sub"], "attn_mask_reformat/Sub")
122
+ seqlens_k = gb.node("Cast", [sub], ["attn_mask_reformat/seqlens_k"],
123
+ "attn_mask_reformat/Sub/Cast", to=TensorProto.INT32)
124
+
125
+ shape = gb.node("Shape", [attention_mask_name], ["attn_mask_reformat/shape"], "attn_mask_reformat/Shape")
126
+ idx1 = gb.const_i64("attn_mask_reformat/idx1", 1)
127
+ gathered = gb.node("Gather", [shape, idx1], ["attn_mask_reformat/gathered"],
128
+ "attn_mask_reformat/Gather", axis=0)
129
+ total_seq_len = gb.node("Cast", [gathered], ["attn_mask_reformat/total_seq_len"],
130
+ "attn_mask_reformat/Gather/Cast", to=TensorProto.INT32)
131
+ return seqlens_k, total_seq_len
132
+
133
+
134
+ def _simplified_layernorm(gb, x, weight_name, eps, name_prefix, skip=None, need_sum=False, sum_output_name=None):
135
+ """skip=None: plain norm. skip=<name>: SkipSimplifiedLayerNormalization."""
136
+ inputs = [x, weight_name] if skip is None else [x, skip, weight_name]
137
+ op_type = ("Skip" if skip is not None else "") + "SimplifiedLayerNormalization"
138
+ domain = "com.microsoft" if skip is not None else ""
139
+ y = f"{name_prefix}/Y"
140
+ sum_name = sum_output_name or f"{name_prefix}/sum"
141
+ outputs = [y] if skip is None else [y, "", "", (sum_name if need_sum else "")]
142
+ attrs = {"epsilon": eps}
143
+ if skip is None:
144
+ attrs.update(axis=-1, stash_type=1)
145
+ gb.node(op_type, inputs, outputs, name_prefix, domain=domain, **attrs)
146
+ return y, (outputs[3] if skip is not None else None)
147
+
148
+
149
+ def _qk_head_norm(gb, x, weight_name, num_heads, head_size, eps, name_prefix):
150
+ # BxSxD -> Bx(S*N)xH -> SimplifiedLayerNormalization -> BxSxD
151
+ shape1 = gb.const_i64(f"{name_prefix}/shape1", [0, -1, head_size])
152
+ r1 = gb.node("Reshape", [x, shape1], [f"{name_prefix}/Reshape_1/out"], f"{name_prefix}/Reshape_1")
153
+ normed, _ = _simplified_layernorm(gb, r1, weight_name, eps, f"{name_prefix}/SimplifiedLayerNormalization")
154
+ shape2 = gb.const_i64(f"{name_prefix}/shape2", [0, -1, num_heads * head_size])
155
+ return gb.node("Reshape", [normed, shape2], [f"{name_prefix}/Reshape_2/out"], f"{name_prefix}/Reshape_2")
156
+
157
+
158
+ def _matmul(gb, x, weight_param, name_prefix, torch_dtype):
159
+ # weight_param: nn.Linear weight [out_features, in_features]; MatMul needs it transposed. No bias anywhere in Qwen3.
160
+ weight = weight_param.detach().to(torch_dtype).numpy().T
161
+ weight_name = gb.initializer(f"{name_prefix}.weight", weight)
162
+ return gb.node("MatMul", [x, weight_name], [f"{name_prefix}/out"], f"{name_prefix}/MatMul")
163
+
164
+
165
+ def _build_decoder_layer(gb, layer_id, layer, root_residual, input_ln_skip, dims,
166
+ seqlens_k_name, total_seq_len_name, cos_cache_name, sin_cache_name, torch_dtype):
167
+ """Emits one full Qwen3 decoder layer (attention + MLP). Returns (resid_before_mlp, mlp_output)."""
168
+ num_attn_heads, num_kv_heads = dims["num_attn_heads"], dims["num_kv_heads"]
169
+ head_size, eps = dims["head_size"], dims["rms_norm_eps"]
170
+
171
+ ln1_w = gb.initializer(
172
+ f"model.layers.{layer_id}.input_layernorm.weight",
173
+ layer.input_layernorm.weight.detach().to(torch_dtype).numpy(),
174
+ )
175
+ normed, resid_before_attn = _simplified_layernorm(
176
+ gb, root_residual, ln1_w, eps, f"layer{layer_id}/input_layernorm",
177
+ skip=input_ln_skip, need_sum=(input_ln_skip is not None),
178
+ )
179
+ if input_ln_skip is None:
180
+ resid_before_attn = root_residual
181
+
182
+ attn = layer.self_attn
183
+ q = _matmul(gb, normed, attn.q_proj.weight, f"layer{layer_id}/attn/q_proj", torch_dtype)
184
+ k = _matmul(gb, normed, attn.k_proj.weight, f"layer{layer_id}/attn/k_proj", torch_dtype)
185
+ v = _matmul(gb, normed, attn.v_proj.weight, f"layer{layer_id}/attn/v_proj", torch_dtype)
186
+
187
+ qn_w = gb.initializer(f"model.layers.{layer_id}.attn.q_norm.weight",
188
+ attn.q_norm.weight.detach().to(torch_dtype).numpy())
189
+ kn_w = gb.initializer(f"model.layers.{layer_id}.attn.k_norm.weight",
190
+ attn.k_norm.weight.detach().to(torch_dtype).numpy())
191
+ q = _qk_head_norm(gb, q, qn_w, num_attn_heads, head_size, eps, f"layer{layer_id}/attn/q_norm")
192
+ k = _qk_head_norm(gb, k, kn_w, num_kv_heads, head_size, eps, f"layer{layer_id}/attn/k_norm")
193
+
194
+ scale = float(1.0 / np.sqrt(head_size))
195
+ attn_out = gb.node(
196
+ "GroupQueryAttention",
197
+ [q, k, v, "", "", seqlens_k_name, total_seq_len_name, cos_cache_name, sin_cache_name, "", "", ""],
198
+ [f"layer{layer_id}/attn/gqa_out", f"layer{layer_id}/attn/present_k", f"layer{layer_id}/attn/present_v"],
199
+ f"layer{layer_id}/attn/GQA", domain="com.microsoft",
200
+ num_heads=num_attn_heads, kv_num_heads=num_kv_heads, scale=scale,
201
+ local_window_size=-1, do_rotary=1, rotary_interleaved=0,
202
+ )
203
+ o = _matmul(gb, attn_out, attn.o_proj.weight, f"layer{layer_id}/attn/o_proj", torch_dtype)
204
+
205
+ post_ln_w = gb.initializer(
206
+ f"model.layers.{layer_id}.post_attention_layernorm.weight",
207
+ layer.post_attention_layernorm.weight.detach().to(torch_dtype).numpy(),
208
+ )
209
+ mlp_in, resid_before_mlp = _simplified_layernorm(
210
+ gb, resid_before_attn, post_ln_w, eps, f"layer{layer_id}/post_attention_layernorm",
211
+ skip=o, need_sum=True,
212
+ )
213
+
214
+ mlp = layer.mlp
215
+ gate = _matmul(gb, mlp_in, mlp.gate_proj.weight, f"layer{layer_id}/mlp/gate_proj", torch_dtype)
216
+ up = _matmul(gb, mlp_in, mlp.up_proj.weight, f"layer{layer_id}/mlp/up_proj", torch_dtype)
217
+ sig = gb.node("Sigmoid", [gate], [f"layer{layer_id}/mlp/sigmoid"], f"layer{layer_id}/mlp/Sigmoid")
218
+ silu = gb.node("Mul", [gate, sig], [f"layer{layer_id}/mlp/silu"], f"layer{layer_id}/mlp/Mul_silu")
219
+ gated = gb.node("Mul", [silu, up], [f"layer{layer_id}/mlp/gated"], f"layer{layer_id}/mlp/Mul_gated")
220
+ down = _matmul(gb, gated, mlp.down_proj.weight, f"layer{layer_id}/mlp/down_proj", torch_dtype)
221
+
222
+ return resid_before_mlp, down
223
+
224
+
225
+ def _quantize_int4(onnx_model):
226
+ """Quantize the encoder graph to int4 using MatMulNBitsQuantizer.
227
+
228
+ Applies int4 weight-only quantization to MatMul and Gather ops:
229
+ - MatMul -> MatMulNBits
230
+ - Gather (embedding) -> GatherBlockQuantized
231
+ """
232
+ quantizer = MatMulNBitsQuantizer(
233
+ model=onnx_model,
234
+ bits=4,
235
+ block_size=32,
236
+ is_symmetric=True,
237
+ accuracy_level=4,
238
+ quant_format=QuantFormat.QOperator,
239
+ op_types_to_quantize=("MatMul", "Gather"),
240
+ )
241
+ quantizer.process()
242
+ quantized = quantizer.model.model
243
+ quantized.ir_version = 10 # required for opset 21 (int4), which the quantizer bumps to
244
+ return quantized
245
+
246
+
247
+ def _build_encoder_graph(checkpoint_dir, dtype="f16", enable_webgpu_graph=False):
248
+ torch_dtype = _TORCH_DTYPES[dtype]
249
+ onnx_dtype = _ONNX_DTYPES[dtype]
250
+ np_dtype = _NP_DTYPES[dtype]
251
+
252
+ dims = _read_qwen3_config(checkpoint_dir)
253
+ num_layers = dims["num_layers"]
254
+
255
+ model = AutoModelForCausalLM.from_pretrained(checkpoint_dir, torch_dtype=torch_dtype, low_cpu_mem_usage=True)
256
+ model.eval()
257
+ layers = model.model.layers
258
+
259
+ gb = _GraphBuilder()
260
+ input_ids_name, attn_mask_name = "input_ids", "attention_mask"
261
+
262
+ cos_cache, sin_cache = _rotary_cos_sin_tables(
263
+ dims["head_size"], dims["rope_theta"], dims["max_position_embeddings"], np_dtype
264
+ )
265
+ cos_cache_name = gb.initializer("cos_cache", cos_cache)
266
+ sin_cache_name = gb.initializer("sin_cache", sin_cache)
267
+
268
+ embed_w = gb.initializer("model.embed_tokens.weight",
269
+ model.model.embed_tokens.weight.detach().to(torch_dtype).numpy())
270
+ embeddings = gb.node("Gather", [embed_w, input_ids_name], ["embeddings"], "embed/Gather", axis=0)
271
+
272
+ seqlens_k_name, total_seq_len_name = _attention_mask_reformat(gb, attn_mask_name, enable_webgpu_graph)
273
+
274
+ root_residual, input_ln_skip = embeddings, None
275
+ for layer_id in range(num_layers - 1):
276
+ resid_before_mlp, mlp_out = _build_decoder_layer(
277
+ gb, layer_id, layers[layer_id], root_residual, input_ln_skip, dims,
278
+ seqlens_k_name, total_seq_len_name, cos_cache_name, sin_cache_name, torch_dtype,
279
+ )
280
+ root_residual, input_ln_skip = resid_before_mlp, mlp_out
281
+
282
+ # Tap the last layer's input_layernorm sum output only; its attention is never run.
283
+ tap_id = num_layers - 1
284
+ tap_ln_w = gb.initializer(
285
+ f"model.layers.{tap_id}.input_layernorm.weight",
286
+ layers[tap_id].input_layernorm.weight.detach().to(torch_dtype).numpy(),
287
+ )
288
+ _, encoder_hidden_states = _simplified_layernorm(
289
+ gb, root_residual, tap_ln_w, dims["rms_norm_eps"], f"layer{tap_id}/input_layernorm",
290
+ skip=input_ln_skip, need_sum=True, sum_output_name="encoder_hidden_states",
291
+ )
292
+ assert encoder_hidden_states is not None # guaranteed by need_sum=True with a non-None skip
293
+
294
+ graph_inputs = [
295
+ helper.make_tensor_value_info(input_ids_name, TensorProto.INT64, [1, "sequence_length"]),
296
+ helper.make_tensor_value_info(attn_mask_name, TensorProto.INT64, [1, "total_sequence_length"]),
297
+ ]
298
+ graph_output = helper.make_tensor_value_info(
299
+ encoder_hidden_states, onnx_dtype, [1, "sequence_length", dims["hidden_size"]]
300
+ )
301
+ graph = helper.make_graph(gb.nodes, "zimage_text_encoder", graph_inputs, [graph_output], initializer=gb.initializers)
302
+ onnx_model = helper.make_model(
303
+ graph, opset_imports=[helper.make_opsetid("", 17), helper.make_opsetid("com.microsoft", 1)]
304
+ )
305
+ onnx_model.ir_version = 9
306
+ return onnx_model
307
+
308
+
309
+ def export_qwen3_text_encoder(checkpoint_dir, output_onnx_path, quantize, dtype="f16", enable_webgpu_graph=False):
310
+ onnx_model = _build_encoder_graph(checkpoint_dir, dtype=dtype, enable_webgpu_graph=enable_webgpu_graph)
311
+ if quantize:
312
+ onnx_model = _quantize_int4(onnx_model)
313
+
314
+ out_dir = os.path.dirname(os.path.abspath(output_onnx_path)) or "."
315
+ os.makedirs(out_dir, exist_ok=True)
316
+ save_ir_model_sharded(
317
+ ir.from_proto(onnx_model), out_dir, os.path.basename(output_onnx_path),
318
+ size_threshold_bytes=INLINE_SIZE_THRESHOLD_BYTES,
319
+ max_shard_size_bytes=MAX_SHARD_SIZE_BYTES,
320
+ )
321
+ print(f"Saved text encoder: {output_onnx_path}")
322
+ return output_onnx_path
323
+
324
+
325
+ def build(input_path, output_dir, precision="f16_int4_quant", extra_options=None):
326
+ if precision not in PRECISION_CONFIGS:
327
+ raise ValueError(f"Unknown precision '{precision}'; choose from {sorted(PRECISION_CONFIGS)}")
328
+ config = PRECISION_CONFIGS[precision]
329
+
330
+ extra_options = extra_options or {}
331
+ enable_webgpu_graph = str(extra_options.get("enable_webgpu_graph", "false")).lower() not in ("false", "0", "")
332
+
333
+ onnx_dir = os.path.join(output_dir, "onnx")
334
+ os.makedirs(onnx_dir, exist_ok=True)
335
+
336
+ suffix = config["suffix"]
337
+ output_onnx = os.path.join(onnx_dir, f"text_encoder_model_{suffix}.onnx")
338
+ export_qwen3_text_encoder(
339
+ input_path, output_onnx, quantize=config["quantize"], dtype=config["dtype"],
340
+ enable_webgpu_graph=enable_webgpu_graph,
341
+ )
342
+ return onnx_dir
343
+
344
+
345
+ def get_args():
346
+ parser = argparse.ArgumentParser(description="Export the Z-Image-Turbo text encoder (Qwen3) to ONNX.")
347
+ parser.add_argument("input_path", help="Path to the Z-Image-Turbo `text_encoder/` folder (or its parent).")
348
+ parser.add_argument(
349
+ "-o", "--output_dir", default=DEFAULT_OUTPUT_DIR,
350
+ help=f"Directory to write the ONNX model to (under an `onnx/` subdir). Default: {DEFAULT_OUTPUT_DIR}",
351
+ )
352
+ parser.add_argument(
353
+ "-p", "--precision", default="f16_int4_quant", choices=sorted(PRECISION_CONFIGS),
354
+ help="Output precision. Default: f16_int4_quant.",
355
+ )
356
+ parser.add_argument(
357
+ "--extra_options", nargs="*", default=[],
358
+ help="Extra key=value options. Supported: enable_webgpu_graph=true|false (default false). "
359
+ "true emits the GPU-only graph-capture attention-mask reformat (WebGPU graph capture); "
360
+ "false emits the standard Shape-based form preferred by WebNN EP.",
361
+ )
362
+ return parser.parse_args()
363
+
364
+
365
+ def main():
366
+ args = get_args()
367
+ input_path = args.input_path
368
+ if os.path.isdir(os.path.join(input_path, "text_encoder")):
369
+ input_path = os.path.join(input_path, "text_encoder")
370
+ onnx_dir = build(input_path, args.output_dir, args.precision, parse_extra_options(args.extra_options))
371
+ print(f"\nSuccess: text_encoder exported to {onnx_dir}")
372
+
373
+
374
+ if __name__ == "__main__":
375
+ main()
model_exporter/build_transformer.py ADDED
@@ -0,0 +1,854 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ # Modifications Copyright (C) 2026 Intel Corporation. All rights reserved.
7
+ # --------------------------------------------------------------------------
8
+ """Standalone exporter for the Z-Image-Turbo transformer trunk (`ZImageTransformer2DModel`)."""
9
+
10
+ import argparse
11
+ import json
12
+ import math
13
+ import os
14
+ import types
15
+ from typing import Any
16
+
17
+ import onnx_ir as ir
18
+ import torch
19
+ from onnxruntime_genai.models.builders.base import Model
20
+
21
+ from external_data_utils import (
22
+ INLINE_SIZE_THRESHOLD_BYTES,
23
+ MAX_SHARD_SIZE_BYTES,
24
+ save_ir_model_sharded,
25
+ )
26
+
27
+ PRECISION_CONFIGS = {
28
+ "f16": {"builder_precision": "fp16", "int4_quant": False},
29
+ "f32": {"builder_precision": "fp32", "int4_quant": False},
30
+ "f16_int4_quant": {"builder_precision": "int4", "int4_quant": True},
31
+ "f32_int4_quant": {"builder_precision": "int4", "int4_quant": True},
32
+ }
33
+
34
+ FILENAME_SUFFIXES = {
35
+ "f16": "f16",
36
+ "f32": "f32",
37
+ "f16_int4_quant": "q4f16",
38
+ "f32_int4_quant": "q4f32",
39
+ }
40
+
41
+ DEFAULT_OUTPUT_DIR = "z-image-turbo-onnx"
42
+
43
+
44
+ # Vendored from onnxruntime_genai.models.builder.
45
+ def set_io_dtype(precision, execution_provider, extra_options) -> ir.DataType:
46
+ """Set the input/output precision of the ONNX model based on the provided precision and execution provider."""
47
+ cpu_quant = precision in {"int4", "int8"} and execution_provider == "cpu"
48
+ fp32_webgpu = execution_provider == "webgpu" and extra_options.get("use_webgpu_fp32", False)
49
+ bf16_cuda = precision == "int4" and execution_provider in {"cuda", "trt-rtx"} and extra_options.get("use_cuda_bf16", False)
50
+
51
+ if precision == "fp32" or cpu_quant or fp32_webgpu:
52
+ return ir.DataType.FLOAT
53
+ if precision == "bf16" or bf16_cuda:
54
+ return ir.DataType.BFLOAT16
55
+ return ir.DataType.FLOAT16
56
+
57
+
58
+ def set_onnx_dtype(precision: str, extra_options: dict[str, Any]) -> ir.DataType:
59
+ """Set the ONNX model's internal precision based on the provided precision and extra options."""
60
+ if precision == "int4":
61
+ return ir.DataType.INT4 if extra_options.get("is_symmetric", True) else ir.DataType.UINT4
62
+ if precision == "int8":
63
+ return ir.DataType.INT8 if extra_options.get("is_symmetric", True) else ir.DataType.UINT8
64
+ to_onnx_dtype = {
65
+ "fp32": ir.DataType.FLOAT,
66
+ "fp16": ir.DataType.FLOAT16,
67
+ "bf16": ir.DataType.BFLOAT16,
68
+ }
69
+ return to_onnx_dtype[precision]
70
+
71
+
72
+ def load_diffusers_config(input_path):
73
+ """Load a diffusers-style `config.json` (e.g. Z-Image-Turbo's `transformer/config.json`)."""
74
+ config_path = os.path.join(input_path, "config.json")
75
+ with open(config_path) as f:
76
+ raw_config = json.load(f)
77
+ raw_config.setdefault("_name_or_path", input_path)
78
+ return types.SimpleNamespace(**raw_config)
79
+
80
+
81
+ def parse_extra_options(pairs):
82
+ """Parse `key=value` strings (as passed via `--extra_options`) into a dict."""
83
+ extra_options = {}
84
+ for kv_str in pairs or []:
85
+ key, _, value = kv_str.partition("=")
86
+ extra_options[key.strip()] = value.strip()
87
+
88
+ if "op_types_to_quantize" in extra_options:
89
+ extra_options["op_types_to_quantize"] = tuple(extra_options["op_types_to_quantize"].split("/"))
90
+
91
+ for bool_key in ("hf_remote", "use_webgpu_fp32", "is_symmetric", "use_qdq"):
92
+ if bool_key in extra_options:
93
+ extra_options[bool_key] = extra_options[bool_key] not in ("false", "False", "0")
94
+
95
+ for int_key in ("block_size", "accuracy_level"):
96
+ if int_key in extra_options:
97
+ extra_options[int_key] = int(extra_options[int_key])
98
+
99
+ return extra_options
100
+
101
+
102
+ class ZImageTransformerModel(Model):
103
+ def __init__(self, config, io_dtype, onnx_dtype, ep, cache_dir, extra_options):
104
+ # Translates the diffusers config into the causal-LM-shaped namespace Model.__init__
105
+ # expects; everything LLM-specific it sets up is unused by this class.
106
+ fake_config = types.SimpleNamespace(
107
+ _name_or_path=getattr(config, "_name_or_path", "z-image-transformer"),
108
+ architectures=["ZImageTransformer2DModel"],
109
+ hidden_size=config.dim,
110
+ num_attention_heads=config.n_heads,
111
+ num_key_value_heads=config.n_kv_heads,
112
+ num_hidden_layers=config.n_layers,
113
+ intermediate_size=config.dim,
114
+ vocab_size=0,
115
+ hidden_act="silu",
116
+ max_position_embeddings=max(config.axes_lens),
117
+ rms_norm_eps=config.norm_eps,
118
+ )
119
+ super().__init__(fake_config, io_dtype, onnx_dtype, ep, cache_dir, extra_options)
120
+
121
+ self.model_type = "z-image-transformer"
122
+ # Bidirectional attention everywhere in this model (no causal mask, no KV cache).
123
+ self.attention_attrs["unidirectional"] = False
124
+
125
+ self.dim = config.dim
126
+ self.n_heads = config.n_heads
127
+ self.n_kv_heads = config.n_kv_heads
128
+ self.n_layers = config.n_layers
129
+ self.n_refiner_layers = config.n_refiner_layers
130
+ self.in_channels = config.in_channels
131
+ self.cap_feat_dim = config.cap_feat_dim
132
+ self.norm_eps = config.norm_eps
133
+ self.qk_norm = config.qk_norm
134
+ self.rope_theta = config.rope_theta
135
+ self.t_scale = config.t_scale
136
+ self.axes_dims = list(config.axes_dims)
137
+ self.axes_lens = list(config.axes_lens)
138
+ self.patch_size = config.all_patch_size[0]
139
+ self.f_patch_size = config.all_f_patch_size[0]
140
+ self.patch_key = f"{self.patch_size}-{self.f_patch_size}"
141
+
142
+ assert self.head_size == sum(self.axes_dims), (
143
+ f"head_size ({self.head_size}) must equal sum(axes_dims) ({sum(self.axes_dims)})"
144
+ )
145
+
146
+ # TimestepEmbedder / AdaLN embedding width (diffusers: `ADALN_EMBED_DIM = 256`).
147
+ self.adaln_embed_dim = min(self.dim, 256)
148
+ self.t_freq_dim = 256
149
+ self.t_mid_dim = 1024
150
+ self.patch_dim = self.f_patch_size * self.patch_size * self.patch_size * self.in_channels
151
+
152
+ # float16 overflow workaround, exact powers of two, RMSNorm-scale-invariant.
153
+ self.pre_out_proj_scale = 1.0 / 128.0
154
+ self.ff_gate_scale = 1.0 / 8.0
155
+ self.ff_up_scale = 1.0 / 16.0
156
+
157
+ # ------------------------------------------------------------------
158
+ # Weight loading
159
+ # ------------------------------------------------------------------
160
+ def load_weights(self, input_path):
161
+ from diffusers import ZImageTransformer2DModel
162
+
163
+ model = ZImageTransformer2DModel.from_pretrained(
164
+ self.model_name_or_path,
165
+ cache_dir=self.cache_dir,
166
+ token=self.hf_token,
167
+ trust_remote_code=self.hf_remote,
168
+ )
169
+ model.eval()
170
+ return model
171
+
172
+ # ------------------------------------------------------------------
173
+ # Saving
174
+ # ------------------------------------------------------------------
175
+ def save_model(self, out_dir):
176
+ """Save with small weights inline and sharded external data (overrides Model.save_model)."""
177
+ from tqdm import tqdm
178
+
179
+ print(f"Saving ONNX model in {out_dir}")
180
+ already_quantized_in_qdq_format = self.quant_type is not None and self.quant_attrs["use_qdq"]
181
+ if self.onnx_dtype in {ir.DataType.INT4, ir.DataType.UINT4, ir.DataType.INT8, ir.DataType.UINT8} and not already_quantized_in_qdq_format:
182
+ model = self.to_nbits()
183
+ else:
184
+ model = self.model
185
+ model.graph.sort()
186
+
187
+ with tqdm() as pbar:
188
+ total_set = False
189
+
190
+ def callback(tensor, metadata):
191
+ nonlocal total_set
192
+ if not total_set:
193
+ pbar.total = metadata.total
194
+ total_set = True
195
+ pbar.update()
196
+ pbar.set_description(f"Saving {tensor.name} ({tensor.dtype.short_name()}, {tensor.shape})")
197
+
198
+ save_ir_model_sharded(
199
+ model, out_dir, self.filename,
200
+ size_threshold_bytes=INLINE_SIZE_THRESHOLD_BYTES,
201
+ max_shard_size_bytes=MAX_SHARD_SIZE_BYTES,
202
+ callback=callback,
203
+ )
204
+
205
+ if not os.listdir(self.cache_dir):
206
+ os.rmdir(self.cache_dir)
207
+
208
+ # ------------------------------------------------------------------
209
+ # Inputs / outputs
210
+ # ------------------------------------------------------------------
211
+ def make_inputs_and_outputs(self):
212
+ self.input_names = {
213
+ "hidden_states": "hidden_states",
214
+ "encoder_hidden_states": "encoder_hidden_states",
215
+ "timestep": "timestep",
216
+ }
217
+ self.output_names = {"sample": "sample"}
218
+
219
+ hidden_states = self.make_value(
220
+ "hidden_states", self.io_dtype, shape=[1, self.in_channels, "height", "width"]
221
+ )
222
+ encoder_hidden_states = self.make_value(
223
+ "encoder_hidden_states", self.io_dtype, shape=[1, "cap_seq_len", self.cap_feat_dim]
224
+ )
225
+ timestep = self.make_value("timestep", self.io_dtype, shape=[1])
226
+ self.model.graph.inputs.extend([hidden_states, encoder_hidden_states, timestep])
227
+
228
+ sample = self.make_value("sample", self.io_dtype, shape=[1, self.in_channels, "height", "width"])
229
+ self.model.graph.outputs.append(sample)
230
+
231
+ # ------------------------------------------------------------------
232
+ # Small node-building helpers (thin, name-returning wrappers around the
233
+ # low-level builders inherited from `Model`)
234
+ # ------------------------------------------------------------------
235
+ def _const(self, dtype: ir.DataType, value) -> str:
236
+ """Return the name of an auto-created scalar/list constant (see `Model.make_constant`)."""
237
+ return f"/model/constants/{self.to_str_dtype(dtype)}/{value}"
238
+
239
+ def _linear(self, name, root_input, linear, shape, seq_dim=None, exclude_from_quant=False):
240
+ """Apply an `nn.Linear` (weight + optional bias) to `root_input`, returning the output name.
241
+
242
+ seq_dim must be unique per logically-distinct sequence, not the shared default.
243
+ """
244
+ if seq_dim is None:
245
+ seq_dim = shape[1] if len(shape) == 3 and isinstance(shape[1], str) else f"dim1_of_{name}"
246
+ if exclude_from_quant:
247
+ # Registers `name` so genai 0.15.2's deferred int4 quantization (to_nbits) skips this weight.
248
+ self.quant_attrs["nodes_to_exclude"].append(name)
249
+ self.make_matmul(linear, name, root_input, seq_dim=seq_dim)
250
+ output = f"{name}/output_0"
251
+ # Re-stamp: make_matmul assumes the generic 3D shape, which doesn't always match.
252
+ self.make_value(output, self.io_dtype, shape=shape)
253
+ if linear.bias is not None:
254
+ self.make_add_bias(linear.bias, f"{name}/Add", output, seq_dim=seq_dim)
255
+ output = f"{name}/Add/output_0"
256
+ self.make_value(output, self.io_dtype, shape=shape)
257
+ return output
258
+
259
+ def _rms_norm(self, name, root_input, weight, shape, eps=None):
260
+ weight_name = name[1:].replace("/", ".") + ".weight"
261
+ self.make_initializer(weight, weight_name, to=self.io_dtype)
262
+ output = f"{name}/output_0"
263
+ self.make_node(
264
+ "SimplifiedLayerNormalization",
265
+ inputs=[root_input, weight_name],
266
+ outputs=[output],
267
+ name=name,
268
+ axis=-1,
269
+ epsilon=eps if eps is not None else self.norm_eps,
270
+ stash_type=1,
271
+ )
272
+ self.make_value(output, self.io_dtype, shape=shape)
273
+ return output
274
+
275
+ def _silu(self, name, root_input, shape):
276
+ sigmoid_name = f"{name}/Sigmoid"
277
+ self.make_sigmoid(sigmoid_name, root_input, self.io_dtype, shape)
278
+ self.make_mul(name, [root_input, f"{sigmoid_name}/output_0"], self.io_dtype, shape)
279
+ return f"{name}/output_0"
280
+
281
+ def _mul(self, name, inputs, shape):
282
+ self.make_mul(name, inputs, self.io_dtype, shape)
283
+ return f"{name}/output_0"
284
+
285
+ def _add(self, name, inputs, shape):
286
+ self.make_add(name, inputs, self.io_dtype, shape)
287
+ return f"{name}/output_0"
288
+
289
+ def _add_scalar(self, name, root_input, value, shape):
290
+ self.make_add(name, [root_input, self._const(self.io_dtype, value)], self.io_dtype, shape)
291
+ return f"{name}/output_0"
292
+
293
+ def _unsqueeze(self, name, root_input, axes, shape, dtype=None):
294
+ axes_name = self._const(ir.DataType.INT64, list(axes))
295
+ self.make_unsqueeze(name, [root_input, axes_name], dtype or self.io_dtype, shape)
296
+ return f"{name}/output_0"
297
+
298
+ def _reshape(self, name, root_input, shape_parts, out_shape, dtype=None):
299
+ """Reshape `root_input`; each of `shape_parts` is a Python int or a 1D INT64 tensor name."""
300
+ dtype = dtype or self.io_dtype
301
+ parts = []
302
+ for part in shape_parts:
303
+ if isinstance(part, int):
304
+ parts.append(self._const(ir.DataType.INT64, [part]))
305
+ else:
306
+ parts.append(part)
307
+ if len(parts) == 1:
308
+ shape_tensor = parts[0]
309
+ else:
310
+ shape_concat_name = f"{name}/ShapeConcat"
311
+ self.make_concat(shape_concat_name, parts, ir.DataType.INT64, shape=[len(parts)], axis=0)
312
+ shape_tensor = f"{shape_concat_name}/output_0"
313
+ self.make_reshape(name, [root_input, shape_tensor], dtype, out_shape)
314
+ return f"{name}/output_0"
315
+
316
+ def _dim_of(self, name, root_input, axis, full_shape_len):
317
+ """Return the name of a 1D INT64 tensor of length 1 holding `root_input`'s size along `axis`."""
318
+ shape_name = f"{name}/Shape"
319
+ self.make_shape(shape_name, root_input, shape=[full_shape_len])
320
+ gather_name = f"{name}/Gather"
321
+ self.make_gather(
322
+ gather_name, [f"{shape_name}/output_0", self._const(ir.DataType.INT64, [axis])],
323
+ dtype=ir.DataType.INT64, shape=[1], axis=0,
324
+ )
325
+ return f"{gather_name}/output_0"
326
+
327
+ def _scalar(self, name, dim1_tensor):
328
+ """Squeeze a 1D length-1 INT64 tensor down to a 0-D scalar (needed by `Range`)."""
329
+ self.make_squeeze(name, [dim1_tensor, self._const(ir.DataType.INT64, [0])], ir.DataType.INT64, shape=[])
330
+ return f"{name}/output_0"
331
+
332
+ def _int_scalar_add(self, name, a, b):
333
+ """Add two 0-D INT64 scalars."""
334
+ self.make_add(name, [a, b], ir.DataType.INT64, shape=[])
335
+ return f"{name}/output_0"
336
+
337
+ def _int_div(self, name, dim1_tensor, divisor):
338
+ self.make_div(name, [dim1_tensor, self._const(ir.DataType.INT64, [divisor])], ir.DataType.INT64, shape=[1])
339
+ return f"{name}/output_0"
340
+
341
+ def _int_mul(self, name, a, b):
342
+ self.make_mul(name, [a, b], ir.DataType.INT64, shape=[1])
343
+ return f"{name}/output_0"
344
+
345
+ # ------------------------------------------------------------------
346
+ # RoPE: precomputed per-axis frequency tables + dynamic position ids
347
+ # ------------------------------------------------------------------
348
+ def _make_rope_tables(self):
349
+ """Precompute the 3 per-axis (cos, sin) frequency tables, [length, dim//2, 2]."""
350
+ self.rope_table_names = []
351
+ for i, (dim, length) in enumerate(zip(self.axes_dims, self.axes_lens)):
352
+ freqs = 1.0 / (self.rope_theta ** (torch.arange(0, dim, 2, dtype=torch.float64) / dim))
353
+ positions = torch.arange(length, dtype=torch.float64)
354
+ angles = torch.outer(positions, freqs).float() # [length, dim//2]
355
+ cos_vals = torch.cos(angles) # [length, dim//2]
356
+ sin_vals = torch.sin(angles) # [length, dim//2]
357
+ table = torch.stack([cos_vals, sin_vals], dim=-1) # [length, dim//2, 2]
358
+ name = f"model.rope.axis_{i}_freqs"
359
+ self.make_initializer(table, name, to=self.io_dtype)
360
+ self.rope_table_names.append(name)
361
+
362
+ def _gather_axis_freqs(self, name, axis_idx, position_ids, num_tokens_shape):
363
+ dim = self.axes_dims[axis_idx]
364
+ self.make_gather(
365
+ name, [self.rope_table_names[axis_idx], position_ids], dtype=self.io_dtype,
366
+ shape=[num_tokens_shape, dim // 2, 2], axis=0,
367
+ )
368
+ return f"{name}/output_0"
369
+
370
+ def _build_freqs_cis(self, name, axis0_ids, axis1_ids, axis2_ids, num_tokens_shape):
371
+ """Gather + concat the 3 axes into a per-token `[num_tokens, head_size//2, 2]` (cos, sin) tensor."""
372
+ parts = [
373
+ self._gather_axis_freqs(f"{name}/axis_{i}/Gather", i, ids, num_tokens_shape)
374
+ for i, ids in enumerate((axis0_ids, axis1_ids, axis2_ids))
375
+ ]
376
+ self.make_concat(name, parts, self.io_dtype, shape=[num_tokens_shape, self.head_size // 2, 2], axis=1)
377
+ return f"{name}/output_0"
378
+
379
+ def _cos_sin_caches_from_freqs_cis(self, name, freqs_cis, num_tokens_shape):
380
+ """Split `[tokens, head_size//2, 2]` into 2D cos/sin caches `[tokens, head_size//2]`."""
381
+ half = self.head_size // 2
382
+ cos_cache = f"{name}/Cos"
383
+ sin_cache = f"{name}/Sin"
384
+ self.make_gather(cos_cache, [freqs_cis, self._const(ir.DataType.INT64, 0)], dtype=self.io_dtype, shape=[num_tokens_shape, half], axis=2)
385
+ self.make_gather(sin_cache, [freqs_cis, self._const(ir.DataType.INT64, 1)], dtype=self.io_dtype, shape=[num_tokens_shape, half], axis=2)
386
+ return f"{cos_cache}/output_0", f"{sin_cache}/output_0"
387
+
388
+ def _identity_position_ids(self, name, seq_len_scalar, out_dim_name):
389
+ """Build identity `position_ids` `[1, seq] = [[0, 1, ..., seq-1]]` (int64)."""
390
+ self.make_range(
391
+ name, [self._const(ir.DataType.INT64, 0), seq_len_scalar, self._const(ir.DataType.INT64, 1)],
392
+ ir.DataType.INT64, shape=[out_dim_name],
393
+ )
394
+ return self._unsqueeze(f"{name}/Unsqueeze", f"{name}/output_0", [0], [1, out_dim_name], dtype=ir.DataType.INT64)
395
+
396
+ def _apply_rope(self, name, x, num_tokens_shape, num_heads, cos_cache, sin_cache, position_ids):
397
+ """Apply interleaved-pair RoPE via `com.microsoft.RotaryEmbedding`; x: [1,tokens,num_heads,head_size]."""
398
+ hidden = num_heads * self.head_size
399
+ shape3 = [1, num_tokens_shape, hidden]
400
+ x3d = self._reshape(f"{name}/Reshape3D", x, [1, -1, hidden], shape3)
401
+ output = f"{name}/output_0"
402
+ self.make_node(
403
+ "RotaryEmbedding",
404
+ inputs=[x3d, position_ids, cos_cache, sin_cache],
405
+ outputs=[output],
406
+ name=name,
407
+ domain="com.microsoft",
408
+ interleaved=1,
409
+ num_heads=num_heads,
410
+ )
411
+ self.make_value(output, self.io_dtype, shape=shape3)
412
+ return output
413
+
414
+ def _build_position_grids(self, height, width, cap_seq_len):
415
+ """Build dynamic position-id tensors for the image and caption token grids."""
416
+ h_tok = self._int_div("/model/z_image/h_tokens", height, self.patch_size)
417
+ w_tok = self._int_div("/model/z_image/w_tokens", width, self.patch_size)
418
+ num_img_tokens = self._int_mul("/model/z_image/num_img_tokens", h_tok, w_tok)
419
+
420
+ cap_len_scalar = self._scalar("/model/z_image/cap_len_scalar", cap_seq_len)
421
+ cap_len_plus1 = self._int_scalar_add(
422
+ "/model/z_image/cap_len_plus1", cap_len_scalar, self._const(ir.DataType.INT64, 1)
423
+ )
424
+
425
+ # --- caption position ids ---
426
+ self.make_range(
427
+ "/model/z_image/cap_axis0",
428
+ [self._const(ir.DataType.INT64, 1), cap_len_plus1, self._const(ir.DataType.INT64, 1)],
429
+ ir.DataType.INT64, shape=["cap_seq_len"],
430
+ )
431
+ cap_axis0 = "/model/z_image/cap_axis0/output_0"
432
+ cap_axis12 = self._zeros_like_1d("/model/z_image/cap_axis12", cap_seq_len, "cap_seq_len")
433
+
434
+ # --- image position ids ---
435
+ img_axis0 = self._expand_scalar("/model/z_image/img_axis0", cap_len_plus1, num_img_tokens, "img_seq_len")
436
+
437
+ h_tok_scalar = self._scalar("/model/z_image/h_tok_scalar", h_tok)
438
+ w_tok_scalar = self._scalar("/model/z_image/w_tok_scalar", w_tok)
439
+ self.make_range("/model/z_image/row_ids", [self._const(ir.DataType.INT64, 0), h_tok_scalar, self._const(ir.DataType.INT64, 1)], ir.DataType.INT64, shape=["h_tokens"])
440
+ self.make_range("/model/z_image/col_ids", [self._const(ir.DataType.INT64, 0), w_tok_scalar, self._const(ir.DataType.INT64, 1)], ir.DataType.INT64, shape=["w_tokens"])
441
+ row_ids = self._unsqueeze("/model/z_image/row_ids_u", "/model/z_image/row_ids/output_0", [1], ["h_tokens", 1], dtype=ir.DataType.INT64)
442
+ col_ids = self._unsqueeze("/model/z_image/col_ids_u", "/model/z_image/col_ids/output_0", [0], [1, "w_tokens"], dtype=ir.DataType.INT64)
443
+ grid_shape = self._concat_shape("/model/z_image/grid_shape", [h_tok, w_tok])
444
+ row_grid = self._expand("/model/z_image/row_grid", row_ids, grid_shape, ["h_tokens", "w_tokens"])
445
+ col_grid = self._expand("/model/z_image/col_grid", col_ids, grid_shape, ["h_tokens", "w_tokens"])
446
+
447
+ img_axis1 = self._reshape("/model/z_image/img_axis1", row_grid, [num_img_tokens], ["img_seq_len"], dtype=ir.DataType.INT64)
448
+ img_axis2 = self._reshape("/model/z_image/img_axis2", col_grid, [num_img_tokens], ["img_seq_len"], dtype=ir.DataType.INT64)
449
+
450
+ return {
451
+ "h_tok": h_tok,
452
+ "w_tok": w_tok,
453
+ "num_img_tokens": num_img_tokens,
454
+ "cap_axis": (cap_axis0, cap_axis12, cap_axis12),
455
+ "img_axis": (img_axis0, img_axis1, img_axis2),
456
+ }
457
+
458
+ def _zeros_like_1d(self, name, dim1_tensor, out_dim_name):
459
+ scalar = self._scalar(f"{name}/scalar", dim1_tensor)
460
+ shape_1d = self._unsqueeze(f"{name}/shape", scalar, [0], [1], dtype=ir.DataType.INT64)
461
+ self.make_constant_of_shape(name, shape_1d, ir.tensor([0], dtype=ir.DataType.INT64), ir.DataType.INT64, shape=[out_dim_name])
462
+ return f"{name}/output_0"
463
+
464
+ def _expand_scalar(self, name, scalar_value, count_dim1_tensor, out_dim_name):
465
+ """Broadcast a 0-D scalar to a 1D tensor whose length is given by `count_dim1_tensor`'s value."""
466
+ value_1d = self._unsqueeze(f"{name}/Value", scalar_value, [0], [1], dtype=ir.DataType.INT64)
467
+ self.make_expand(name, [value_1d, count_dim1_tensor], ir.DataType.INT64, shape=[out_dim_name])
468
+ return f"{name}/output_0"
469
+
470
+ def _concat_shape(self, name, dim1_tensors):
471
+ self.make_concat(name, list(dim1_tensors), ir.DataType.INT64, shape=[len(dim1_tensors)], axis=0)
472
+ return f"{name}/output_0"
473
+
474
+ def _expand(self, name, root_input, shape_tensor, out_shape):
475
+ self.make_expand(name, [root_input, shape_tensor], ir.DataType.INT64, shape=out_shape)
476
+ return f"{name}/output_0"
477
+
478
+ # ------------------------------------------------------------------
479
+ # Timestep embedding
480
+ # ------------------------------------------------------------------
481
+ def _make_timestep_freqs(self):
482
+ half = self.t_freq_dim // 2
483
+ freqs = torch.exp(-math.log(10000.0) * torch.arange(0, half, dtype=torch.float32) / half)
484
+ self.make_initializer(freqs, "model.t_embedder.freqs", to=self.io_dtype)
485
+
486
+ def _make_timestep_embedding(self, timestep, weights):
487
+ half = self.t_freq_dim // 2
488
+ t_scaled = self._mul("/model/t_embedder/Scale", [timestep, self._const(self.io_dtype, self.t_scale)], [1])
489
+ t_unsq = self._unsqueeze("/model/t_embedder/Unsqueeze", t_scaled, [1], [1, 1])
490
+ args = self._mul("/model/t_embedder/Args", [t_unsq, "model.t_embedder.freqs"], [1, half])
491
+ cos_name = "/model/t_embedder/Cos"
492
+ sin_name = "/model/t_embedder/Sin"
493
+ self.make_cos(cos_name, args, self.io_dtype, [1, half])
494
+ self.make_sin(sin_name, args, self.io_dtype, [1, half])
495
+ freq_embed_name = "/model/t_embedder/Concat"
496
+ self.make_concat(freq_embed_name, [f"{cos_name}/output_0", f"{sin_name}/output_0"], self.io_dtype, shape=[1, self.t_freq_dim], axis=-1)
497
+ freq_embed = f"{freq_embed_name}/output_0"
498
+
499
+ hidden = self._linear(
500
+ "/model/t_embedder/mlp.0", freq_embed, weights.mlp[0], [1, self.t_mid_dim], exclude_from_quant=True
501
+ )
502
+ hidden = self._silu("/model/t_embedder/mlp.0/Silu", hidden, [1, self.t_mid_dim])
503
+ adaln_input = self._linear(
504
+ "/model/t_embedder/mlp.2", hidden, weights.mlp[2], [1, self.adaln_embed_dim], exclude_from_quant=True
505
+ )
506
+ return adaln_input
507
+
508
+ # ------------------------------------------------------------------
509
+ # AdaLN modulation
510
+ # ------------------------------------------------------------------
511
+ def _make_adaln(self, name, adaln_input, linear, dim):
512
+ mod = self._linear(f"{name}/Linear", adaln_input, linear, [1, 4 * dim], exclude_from_quant=True)
513
+ split_sizes = self._const(ir.DataType.INT64, [dim, dim, dim, dim])
514
+ outs = [f"{name}/Split/output_{i}" for i in range(4)]
515
+ self.make_split(f"{name}/Split", [mod, split_sizes], outs, [self.io_dtype] * 4, [[1, dim]] * 4, axis=-1)
516
+ scale_msa_raw, gate_msa_raw, scale_mlp_raw, gate_mlp_raw = outs
517
+
518
+ scale_msa = self._add_scalar(f"{name}/ScaleMsaPlus1", scale_msa_raw, 1.0, [1, dim])
519
+ scale_mlp = self._add_scalar(f"{name}/ScaleMlpPlus1", scale_mlp_raw, 1.0, [1, dim])
520
+ self.make_tanh(f"{name}/GateMsaTanh", gate_msa_raw, self.io_dtype, [1, dim])
521
+ self.make_tanh(f"{name}/GateMlpTanh", gate_mlp_raw, self.io_dtype, [1, dim])
522
+ gate_msa = f"{name}/GateMsaTanh/output_0"
523
+ gate_mlp = f"{name}/GateMlpTanh/output_0"
524
+
525
+ scale_msa = self._unsqueeze(f"{name}/ScaleMsaU", scale_msa, [1], [1, 1, dim])
526
+ scale_mlp = self._unsqueeze(f"{name}/ScaleMlpU", scale_mlp, [1], [1, 1, dim])
527
+ gate_msa = self._unsqueeze(f"{name}/GateMsaU", gate_msa, [1], [1, 1, dim])
528
+ gate_mlp = self._unsqueeze(f"{name}/GateMlpU", gate_mlp, [1], [1, 1, dim])
529
+ return scale_msa, gate_msa, scale_mlp, gate_mlp
530
+
531
+ # ------------------------------------------------------------------
532
+ # Attention / FeedForward / transformer block
533
+ # ------------------------------------------------------------------
534
+ def _rescale_preout(self, name, root_input, shape, scale=None):
535
+ """Scale down an output-projection input by `scale` to avoid float16 overflow."""
536
+ if self.io_dtype != ir.DataType.FLOAT16:
537
+ return root_input
538
+ if scale is None:
539
+ scale = self.pre_out_proj_scale
540
+ return self._mul(name, [root_input, self._const(self.io_dtype, scale)], shape)
541
+
542
+ def _make_attention(self, name, x, num_tokens_shape, cos_cache, sin_cache, position_ids, attn):
543
+ shape3 = [1, num_tokens_shape, self.dim]
544
+ q = self._linear(f"{name}/to_q", x, attn.to_q, shape3)
545
+ k = self._linear(f"{name}/to_k", x, attn.to_k, shape3)
546
+ v = self._linear(f"{name}/to_v", x, attn.to_v, shape3)
547
+
548
+ heads_shape = [1, num_tokens_shape, self.n_heads, self.head_size]
549
+ q_heads = self._reshape(f"{name}/QHeads", q, [1, -1, self.n_heads, self.head_size], heads_shape)
550
+ k_heads = self._reshape(f"{name}/KHeads", k, [1, -1, self.n_heads, self.head_size], heads_shape)
551
+
552
+ if self.qk_norm:
553
+ q_heads = self._rms_norm(f"{name}/NormQ", q_heads, attn.norm_q.weight, heads_shape)
554
+ k_heads = self._rms_norm(f"{name}/NormK", k_heads, attn.norm_k.weight, heads_shape)
555
+
556
+ q_flat = self._apply_rope(f"{name}/RopeQ", q_heads, num_tokens_shape, self.n_heads, cos_cache, sin_cache, position_ids)
557
+ k_flat = self._apply_rope(f"{name}/RopeK", k_heads, num_tokens_shape, self.n_heads, cos_cache, sin_cache, position_ids)
558
+
559
+ self.make_multi_head_attention(f"{name}/MHA", q_path=q_flat, k_path=k_flat, v_path=v)
560
+ attn_out = f"{name}/MHA/output_0"
561
+ self.make_value(attn_out, self.io_dtype, shape=shape3) # re-stamp (see _linear's seq_dim note)
562
+
563
+ attn_out = self._rescale_preout(f"{name}/to_out/PreScale", attn_out, shape3)
564
+ return self._linear(f"{name}/to_out", attn_out, attn.to_out[0], shape3)
565
+
566
+ def _make_feed_forward(self, name, x, num_tokens_shape, ff):
567
+ shape3 = [1, num_tokens_shape, self.dim]
568
+ hidden_shape = [1, num_tokens_shape, ff.w1.out_features]
569
+ gate = self._linear(f"{name}/w1", x, ff.w1, hidden_shape)
570
+ gate = self._silu(f"{name}/w1/Silu", gate, hidden_shape)
571
+ up = self._linear(f"{name}/w3", x, ff.w3, hidden_shape)
572
+ gate = self._rescale_preout(f"{name}/w1/Silu/PreScale", gate, hidden_shape, self.ff_gate_scale)
573
+ up = self._rescale_preout(f"{name}/w3/PreScale", up, hidden_shape, self.ff_up_scale)
574
+ gated = self._mul(f"{name}/Gated", [gate, up], hidden_shape)
575
+ return self._linear(f"{name}/w2", gated, ff.w2, shape3)
576
+
577
+ def _make_block(self, name, x, num_tokens_shape, cos_cache, sin_cache, position_ids, block, modulation, adaln_input=None):
578
+ shape3 = [1, num_tokens_shape, self.dim]
579
+ if modulation:
580
+ scale_msa, gate_msa, scale_mlp, gate_mlp = self._make_adaln(
581
+ f"{name}/adaLN_modulation", adaln_input, block.adaLN_modulation[0], self.dim
582
+ )
583
+
584
+ normed1 = self._rms_norm(f"{name}/attention_norm1", x, block.attention_norm1.weight, shape3)
585
+ if modulation:
586
+ normed1 = self._mul(f"{name}/AttnScale", [normed1, scale_msa], shape3)
587
+ attn_out = self._make_attention(f"{name}/attention", normed1, num_tokens_shape, cos_cache, sin_cache, position_ids, block.attention)
588
+ attn_out = self._rms_norm(f"{name}/attention_norm2", attn_out, block.attention_norm2.weight, shape3)
589
+ if modulation:
590
+ attn_out = self._mul(f"{name}/GateMsaMul", [attn_out, gate_msa], shape3)
591
+ x = self._add(f"{name}/Residual1", [x, attn_out], shape3)
592
+
593
+ normed2 = self._rms_norm(f"{name}/ffn_norm1", x, block.ffn_norm1.weight, shape3)
594
+ if modulation:
595
+ normed2 = self._mul(f"{name}/FfnScale", [normed2, scale_mlp], shape3)
596
+ ffn_out = self._make_feed_forward(f"{name}/feed_forward", normed2, num_tokens_shape, block.feed_forward)
597
+ ffn_out = self._rms_norm(f"{name}/ffn_norm2", ffn_out, block.ffn_norm2.weight, shape3)
598
+ if modulation:
599
+ ffn_out = self._mul(f"{name}/GateMlpMul", [ffn_out, gate_mlp], shape3)
600
+ x = self._add(f"{name}/Residual2", [x, ffn_out], shape3)
601
+ return x
602
+
603
+ # ------------------------------------------------------------------
604
+ # LayerNorm without affine params (`FinalLayer.norm_final`)
605
+ # ------------------------------------------------------------------
606
+ def _layer_norm_no_affine(self, name, root_input, shape, eps=1e-6):
607
+ """`FinalLayer.norm_final` (no affine). Needs `stash_type=1` to avoid a WebGPU/WebNN
608
+ float16 overflow."""
609
+ dim = shape[-1]
610
+ base = name[1:].replace("/", ".")
611
+ scale_name, bias_name = f"{base}.scale_ones", f"{base}.bias_zeros"
612
+ self.make_initializer(torch.ones(dim), scale_name, to=self.io_dtype)
613
+ self.make_initializer(torch.zeros(dim), bias_name, to=self.io_dtype)
614
+ output = f"{name}/output_0"
615
+ self.make_node(
616
+ "LayerNormalization",
617
+ inputs=[root_input, scale_name, bias_name],
618
+ outputs=[output],
619
+ name=name,
620
+ axis=-1,
621
+ epsilon=eps,
622
+ stash_type=1,
623
+ )
624
+ self.make_value(output, self.io_dtype, shape=shape)
625
+ return output
626
+
627
+ # ------------------------------------------------------------------
628
+ # Sequence concatenation / slicing
629
+ # ------------------------------------------------------------------
630
+ def _concat_seq(self, name, parts, feat_dim, out_dim_name):
631
+ self.make_concat(name, parts, self.io_dtype, shape=[1, out_dim_name, feat_dim], axis=1)
632
+ return f"{name}/output_0"
633
+
634
+ def _slice_seq(self, name, root_input, count_dim1_tensor, feat_dim, out_dim_name):
635
+ starts = self._const(ir.DataType.INT64, [0])
636
+ axes = self._const(ir.DataType.INT64, [1])
637
+ self.make_slice(name, [root_input, starts, count_dim1_tensor, axes], self.io_dtype, shape=[1, out_dim_name, feat_dim])
638
+ return f"{name}/output_0"
639
+
640
+ # ------------------------------------------------------------------
641
+ # Top-level graph construction
642
+ # ------------------------------------------------------------------
643
+ def make_model(self, input_path):
644
+ self.make_inputs_and_outputs()
645
+ self.weights = self.load_weights(input_path)
646
+ self._make_rope_tables()
647
+ self._make_timestep_freqs()
648
+
649
+ hidden_states = self.input_names["hidden_states"]
650
+ encoder_hidden_states = self.input_names["encoder_hidden_states"]
651
+ timestep = self.input_names["timestep"]
652
+
653
+ # --- dynamic dims ---
654
+ height = self._dim_of("/model/z_image/height", hidden_states, 2, 4)
655
+ width = self._dim_of("/model/z_image/width", hidden_states, 3, 4)
656
+ cap_seq_len = self._dim_of("/model/z_image/cap_seq_len", encoder_hidden_states, 1, 3)
657
+
658
+ grids = self._build_position_grids(height, width, cap_seq_len)
659
+ h_tok, w_tok, num_img_tokens = grids["h_tok"], grids["w_tok"], grids["num_img_tokens"]
660
+
661
+ img_freqs = self._build_freqs_cis("/model/z_image/img_freqs", *grids["img_axis"], "img_seq_len")
662
+ cap_freqs = self._build_freqs_cis("/model/z_image/cap_freqs", *grids["cap_axis"], "cap_seq_len")
663
+ img_cos, img_sin = self._cos_sin_caches_from_freqs_cis("/model/z_image/img_cs", img_freqs, "img_seq_len")
664
+ cap_cos, cap_sin = self._cos_sin_caches_from_freqs_cis("/model/z_image/cap_cs", cap_freqs, "cap_seq_len")
665
+
666
+ img_len_scalar = self._scalar("/model/z_image/img_len_scalar", num_img_tokens)
667
+ cap_len_scalar = self._scalar("/model/z_image/cap_pos_len_scalar", cap_seq_len)
668
+ img_pos = self._identity_position_ids("/model/z_image/img_pos", img_len_scalar, "img_seq_len")
669
+ cap_pos = self._identity_position_ids("/model/z_image/cap_pos", cap_len_scalar, "cap_seq_len")
670
+
671
+ # --- patchify image: [1, C, H, W] -> [1, H_t*W_t, patch_dim] ---
672
+ img_squeezed = self._reshape(
673
+ "/model/z_image/patchify/Squeeze", hidden_states,
674
+ [self.in_channels, height, width], [self.in_channels, "height", "width"],
675
+ )
676
+ img_view = self._reshape(
677
+ "/model/z_image/patchify/View", img_squeezed,
678
+ [self.in_channels, h_tok, self.patch_size, w_tok, self.patch_size],
679
+ [self.in_channels, "h_tokens", self.patch_size, "w_tokens", self.patch_size],
680
+ )
681
+ img_perm = "/model/z_image/patchify/Transpose"
682
+ self.make_transpose(
683
+ img_perm, img_view, self.io_dtype,
684
+ ["h_tokens", "w_tokens", self.patch_size, self.patch_size, self.in_channels],
685
+ perm=[1, 3, 2, 4, 0],
686
+ )
687
+ img_patches = self._reshape(
688
+ "/model/z_image/patchify/Flatten", f"{img_perm}/output_0",
689
+ [num_img_tokens, self.patch_dim], ["img_seq_len", self.patch_dim],
690
+ )
691
+ img_patches_b = self._unsqueeze("/model/z_image/patchify/Batch", img_patches, [0], [1, "img_seq_len", self.patch_dim])
692
+
693
+ x_embedder = self.weights.all_x_embedder[self.patch_key]
694
+ img_tokens = self._linear(
695
+ "/model/x_embedder", img_patches_b, x_embedder, [1, "img_seq_len", self.dim],
696
+ exclude_from_quant=True,
697
+ )
698
+
699
+ # --- caption embed ---
700
+ cap_norm = self._rms_norm(
701
+ "/model/cap_embedder.0", encoder_hidden_states, self.weights.cap_embedder[0].weight,
702
+ [1, "cap_seq_len", self.cap_feat_dim],
703
+ )
704
+ cap_tokens = self._linear(
705
+ "/model/cap_embedder.1", cap_norm, self.weights.cap_embedder[1], [1, "cap_seq_len", self.dim],
706
+ exclude_from_quant=True,
707
+ )
708
+
709
+ # --- timestep / AdaLN input ---
710
+ adaln_input = self._make_timestep_embedding(timestep, self.weights.t_embedder)
711
+
712
+ # --- noise refiner (image tokens only) ---
713
+ x = img_tokens
714
+ for i in range(self.n_refiner_layers):
715
+ x = self._make_block(
716
+ f"/model/noise_refiner.{i}", x, "img_seq_len", img_cos, img_sin, img_pos,
717
+ self.weights.noise_refiner[i], modulation=True, adaln_input=adaln_input,
718
+ )
719
+ img_tokens = x
720
+
721
+ # --- context refiner (caption tokens only) ---
722
+ x = cap_tokens
723
+ for i in range(self.n_refiner_layers):
724
+ x = self._make_block(
725
+ f"/model/context_refiner.{i}", x, "cap_seq_len", cap_cos, cap_sin, cap_pos,
726
+ self.weights.context_refiner[i], modulation=False,
727
+ )
728
+ cap_tokens = x
729
+
730
+ # --- unify: image tokens first, caption tokens second ---
731
+ unified = self._concat_seq("/model/z_image/unify_tokens", [img_tokens, cap_tokens], self.dim, "unified_seq_len")
732
+ half = self.head_size // 2
733
+ self.make_concat("/model/z_image/unify_cos", [img_cos, cap_cos], self.io_dtype, shape=["unified_seq_len", half], axis=0)
734
+ self.make_concat("/model/z_image/unify_sin", [img_sin, cap_sin], self.io_dtype, shape=["unified_seq_len", half], axis=0)
735
+ unified_cos = "/model/z_image/unify_cos/output_0"
736
+ unified_sin = "/model/z_image/unify_sin/output_0"
737
+ unified_len_scalar = self._int_scalar_add("/model/z_image/unified_len_scalar", img_len_scalar, cap_len_scalar)
738
+ unified_pos = self._identity_position_ids("/model/z_image/unified_pos", unified_len_scalar, "unified_seq_len")
739
+
740
+ # --- main layers (unified sequence) ---
741
+ x = unified
742
+ for i in range(self.n_layers):
743
+ x = self._make_block(
744
+ f"/model/layers.{i}", x, "unified_seq_len", unified_cos, unified_sin, unified_pos,
745
+ self.weights.layers[i], modulation=True, adaln_input=adaln_input,
746
+ )
747
+
748
+ # --- final layer (AdaLN + LayerNorm(no affine) + Linear) ---
749
+ final_layer = self.weights.all_final_layer[self.patch_key]
750
+ final_silu = self._silu("/model/final_layer/adaLN_modulation/Silu", adaln_input, [1, self.adaln_embed_dim])
751
+ final_scale_raw = self._linear(
752
+ "/model/final_layer/adaLN_modulation.1", final_silu, final_layer.adaLN_modulation[1], [1, self.dim],
753
+ exclude_from_quant=True,
754
+ )
755
+ final_scale = self._add_scalar("/model/final_layer/adaLN_modulation.1/Plus1", final_scale_raw, 1.0, [1, self.dim])
756
+ final_scale = self._unsqueeze("/model/final_layer/adaLN_modulation.1/Unsqueeze", final_scale, [1], [1, 1, self.dim])
757
+
758
+ normed = self._layer_norm_no_affine("/model/final_layer/norm_final", x, [1, "unified_seq_len", self.dim])
759
+ scaled = self._mul("/model/final_layer/ScaleMul", [normed, final_scale], [1, "unified_seq_len", self.dim])
760
+ out_patches = self._linear(
761
+ "/model/final_layer/linear", scaled, final_layer.linear, [1, "unified_seq_len", self.patch_dim]
762
+ )
763
+
764
+ # --- unpatchify: image tokens are the first `num_img_tokens` rows ---
765
+ img_out = self._slice_seq("/model/z_image/unpatchify/Slice", out_patches, num_img_tokens, self.patch_dim, "img_seq_len")
766
+ img_out = self._reshape(
767
+ "/model/z_image/unpatchify/Squeeze", img_out, [num_img_tokens, self.patch_dim], ["img_seq_len", self.patch_dim]
768
+ )
769
+ img_view_out = self._reshape(
770
+ "/model/z_image/unpatchify/View", img_out,
771
+ [h_tok, w_tok, self.patch_size, self.patch_size, self.in_channels],
772
+ ["h_tokens", "w_tokens", self.patch_size, self.patch_size, self.in_channels],
773
+ )
774
+ img_perm_out = "/model/z_image/unpatchify/Transpose"
775
+ self.make_transpose(
776
+ img_perm_out, img_view_out, self.io_dtype,
777
+ [self.in_channels, "h_tokens", self.patch_size, "w_tokens", self.patch_size],
778
+ perm=[4, 0, 2, 1, 3],
779
+ )
780
+ img_merged = self._reshape(
781
+ "/model/z_image/unpatchify/Merge", f"{img_perm_out}/output_0",
782
+ [self.in_channels, height, width], [self.in_channels, "height", "width"],
783
+ )
784
+ sample = self._unsqueeze("/model/z_image/unpatchify/Batch", img_merged, [0], [1, self.in_channels, "height", "width"])
785
+
786
+ self.make_node("Identity", inputs=[sample], outputs=["sample"], name="/model/z_image/output_identity")
787
+
788
+ del self.weights
789
+
790
+
791
+ # Standalone build driver (replaces builder.py's create_model, scoped to this one architecture).
792
+ def build(input_path, output_dir, precision="f16_int4_quant", extra_options=None):
793
+ if precision not in PRECISION_CONFIGS:
794
+ raise ValueError(f"Unknown precision '{precision}'; choose from {sorted(PRECISION_CONFIGS)}")
795
+
796
+ precision_config = PRECISION_CONFIGS[precision]
797
+ extra_options = dict(extra_options or {})
798
+ extra_options.setdefault("hf_remote", False)
799
+ if precision_config["int4_quant"]:
800
+ extra_options.setdefault("block_size", 32)
801
+ extra_options.setdefault("accuracy_level", 4)
802
+ # MatMul only -- Gather would int4-quantize the RoPE frequency tables (corrupting them).
803
+ extra_options.setdefault("op_types_to_quantize", ("MatMul",))
804
+ if precision == "f32_int4_quant":
805
+ extra_options.setdefault("use_webgpu_fp32", True)
806
+
807
+ extra_options["filename"] = f"transformer_model_{FILENAME_SUFFIXES[precision]}.onnx"
808
+
809
+ builder_precision = precision_config["builder_precision"]
810
+ io_dtype = set_io_dtype(builder_precision, "webgpu", extra_options)
811
+ onnx_dtype = set_onnx_dtype(builder_precision, extra_options)
812
+
813
+ config = load_diffusers_config(input_path)
814
+
815
+ onnx_dir = os.path.join(output_dir, "onnx")
816
+ os.makedirs(onnx_dir, exist_ok=True)
817
+ cache_dir = os.path.join(output_dir, "cache")
818
+ os.makedirs(cache_dir, exist_ok=True)
819
+
820
+ model = ZImageTransformerModel(config, io_dtype, onnx_dtype, "webgpu", cache_dir, extra_options)
821
+ model.make_model(input_path)
822
+ model.save_model(onnx_dir)
823
+ return onnx_dir
824
+
825
+
826
+ def get_args():
827
+ parser = argparse.ArgumentParser(description="Export the Z-Image-Turbo transformer trunk to ONNX.")
828
+ parser.add_argument("input_path", help="Path to the Z-Image-Turbo `transformer/` folder (or its parent).")
829
+ parser.add_argument(
830
+ "-o", "--output_dir", default=DEFAULT_OUTPUT_DIR,
831
+ help=f"Directory to write the ONNX model to (under an `onnx/` subdir). Default: {DEFAULT_OUTPUT_DIR}",
832
+ )
833
+ parser.add_argument(
834
+ "-p", "--precision", default="f16_int4_quant", choices=sorted(PRECISION_CONFIGS),
835
+ help="Output precision/quantization. Default: f16_int4_quant.",
836
+ )
837
+ parser.add_argument(
838
+ "--extra_options", nargs="*", default=[],
839
+ help="Extra key=value options, e.g. block_size=32 accuracy_level=4.",
840
+ )
841
+ return parser.parse_args()
842
+
843
+
844
+ def main():
845
+ args = get_args()
846
+ input_path = args.input_path
847
+ if os.path.isdir(os.path.join(input_path, "transformer")):
848
+ input_path = os.path.join(input_path, "transformer")
849
+ onnx_dir = build(input_path, args.output_dir, args.precision, parse_extra_options(args.extra_options))
850
+ print(f"\nSuccess: transformer exported to {onnx_dir}")
851
+
852
+
853
+ if __name__ == "__main__":
854
+ main()
model_exporter/build_vae_decoder.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ # Modifications Copyright (C) 2026 Intel Corporation. All rights reserved.
7
+ # --------------------------------------------------------------------------
8
+ """Standalone exporter for the Z-Image-Turbo VAE decoder (`AutoencoderKL.decoder`)."""
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import types
14
+ from typing import Any
15
+
16
+ import onnx_ir as ir
17
+ import torch
18
+ from onnxruntime_genai.models.builders.base import Model
19
+
20
+ PRECISION_CONFIGS = {
21
+ "f16": {"builder_precision": "fp16"},
22
+ "f32": {"builder_precision": "fp32"},
23
+ }
24
+
25
+ DEFAULT_OUTPUT_DIR = "z-image-turbo-onnx"
26
+
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Vendored from onnxruntime_genai.models.builder.
30
+ # ---------------------------------------------------------------------------
31
+ def set_io_dtype(precision, execution_provider, extra_options) -> ir.DataType:
32
+ cpu_quant = precision in {"int4", "int8"} and execution_provider == "cpu"
33
+ fp32_webgpu = execution_provider == "webgpu" and extra_options.get("use_webgpu_fp32", False)
34
+ bf16_cuda = precision == "int4" and execution_provider in {"cuda", "trt-rtx"} and extra_options.get("use_cuda_bf16", False)
35
+
36
+ if precision == "fp32" or cpu_quant or fp32_webgpu:
37
+ return ir.DataType.FLOAT
38
+ if precision == "bf16" or bf16_cuda:
39
+ return ir.DataType.BFLOAT16
40
+ return ir.DataType.FLOAT16
41
+
42
+
43
+ def set_onnx_dtype(precision: str, extra_options: dict[str, Any]) -> ir.DataType:
44
+ if precision == "int4":
45
+ return ir.DataType.INT4 if extra_options.get("is_symmetric", True) else ir.DataType.UINT4
46
+ if precision == "int8":
47
+ return ir.DataType.INT8 if extra_options.get("is_symmetric", True) else ir.DataType.UINT8
48
+ to_onnx_dtype = {
49
+ "fp32": ir.DataType.FLOAT,
50
+ "fp16": ir.DataType.FLOAT16,
51
+ "bf16": ir.DataType.BFLOAT16,
52
+ }
53
+ return to_onnx_dtype[precision]
54
+
55
+
56
+ def load_diffusers_config(input_path):
57
+ config_path = os.path.join(input_path, "config.json")
58
+ with open(config_path) as f:
59
+ raw_config = json.load(f)
60
+ raw_config.setdefault("_name_or_path", input_path)
61
+ return types.SimpleNamespace(**raw_config)
62
+
63
+
64
+ def parse_extra_options(pairs):
65
+ extra_options = {}
66
+ for kv_str in pairs or []:
67
+ key, _, value = kv_str.partition("=")
68
+ extra_options[key.strip()] = value.strip()
69
+
70
+ for bool_key in ("hf_remote", "use_webgpu_fp32", "fuse_group_norm"):
71
+ if bool_key in extra_options:
72
+ extra_options[bool_key] = extra_options[bool_key] not in ("false", "False", "0")
73
+
74
+ return extra_options
75
+
76
+
77
+ class ZImageVAEDecoderModel(Model):
78
+ def __init__(self, config, io_dtype, onnx_dtype, ep, cache_dir, extra_options):
79
+ mid_channels = int(config.block_out_channels[-1])
80
+ fake_config = types.SimpleNamespace(
81
+ _name_or_path=getattr(config, "_name_or_path", "z-image-vae-decoder"),
82
+ architectures=["AutoencoderKL"],
83
+ hidden_size=mid_channels,
84
+ num_attention_heads=1,
85
+ num_key_value_heads=1,
86
+ num_hidden_layers=1,
87
+ intermediate_size=mid_channels,
88
+ vocab_size=0,
89
+ hidden_act="silu",
90
+ max_position_embeddings=1,
91
+ rms_norm_eps=1e-6,
92
+ )
93
+ super().__init__(fake_config, io_dtype, onnx_dtype, ep, cache_dir, extra_options)
94
+
95
+ self.model_type = "z-image-vae-decoder"
96
+ # Spatial self-attention: bidirectional, no KV cache.
97
+ self.attention_attrs["unidirectional"] = False
98
+
99
+ self.mid_channels = mid_channels
100
+ self.latent_channels = int(config.latent_channels)
101
+ self.out_channels = int(config.out_channels)
102
+ self.block_out_channels = [int(c) for c in config.block_out_channels]
103
+ self.norm_num_groups = int(config.norm_num_groups)
104
+ # False (default): decomposed standard-ONNX GroupNorm; True: com.microsoft GroupNorm/SkipGroupNorm.
105
+ self.fuse_group_norm = bool(extra_options.get("fuse_group_norm", False))
106
+ self._io_dtype = self.io_dtype
107
+
108
+ # ------------------------------------------------------------------
109
+ # Weight loading
110
+ # ------------------------------------------------------------------
111
+ def load_weights(self, input_path):
112
+ from diffusers import AutoencoderKL
113
+
114
+ # Load from `input_path` (the vae/ dir) rather than `self.model_name_or_path`.
115
+ model = AutoencoderKL.from_pretrained(
116
+ input_path,
117
+ cache_dir=self.cache_dir,
118
+ token=self.hf_token,
119
+ trust_remote_code=self.hf_remote,
120
+ )
121
+ model.eval()
122
+ return model.decoder
123
+
124
+ # ------------------------------------------------------------------
125
+ # Inputs / outputs
126
+ # ------------------------------------------------------------------
127
+ def make_inputs_and_outputs(self):
128
+ self.input_names = {"latent_sample": "latent_sample"}
129
+ self.output_names = {"sample": "sample"}
130
+
131
+ latent = self.make_value(
132
+ "latent_sample", self._io_dtype,
133
+ shape=[1, self.latent_channels, "latent_height", "latent_width"],
134
+ )
135
+ self.model.graph.inputs.extend([latent])
136
+
137
+ sample = self.make_value(
138
+ "sample", self._io_dtype, shape=[1, self.out_channels, "height", "width"]
139
+ )
140
+ self.model.graph.outputs.append(sample)
141
+
142
+ # ------------------------------------------------------------------
143
+ # Small node-building helpers
144
+ # ------------------------------------------------------------------
145
+ def _init_name(self, node_name, suffix):
146
+ return node_name[1:].replace("/", ".") + suffix
147
+
148
+ def _const(self, dtype, value):
149
+ return f"/model/constants/{self.to_str_dtype(dtype)}/{value}"
150
+
151
+ def _transpose(self, name, root_input, perm):
152
+ self.make_transpose(name, root_input, self._io_dtype, shape=None, perm=perm)
153
+ return f"{name}/output_0"
154
+
155
+ def _add(self, name, inputs):
156
+ self.make_add(name, inputs, self._io_dtype, shape=None)
157
+ return f"{name}/output_0"
158
+
159
+ def _mul(self, name, inputs):
160
+ self.make_mul(name, inputs, self._io_dtype, shape=None)
161
+ return f"{name}/output_0"
162
+
163
+ def _reshape(self, name, root_input, shape_tensor_name):
164
+ self.make_reshape(name, [root_input, shape_tensor_name], self._io_dtype, shape=None)
165
+ return f"{name}/output_0"
166
+
167
+ def _conv(self, name, root_input, conv):
168
+ weight = self._init_name(name, ".weight")
169
+ self.make_initializer(conv.weight, weight, to=self._io_dtype)
170
+ inputs = [root_input, weight]
171
+ if conv.bias is not None:
172
+ bias = self._init_name(name, ".bias")
173
+ self.make_initializer(conv.bias, bias, to=self._io_dtype)
174
+ inputs.append(bias)
175
+
176
+ kh, kw = conv.kernel_size
177
+ ph, pw = conv.padding
178
+ sh, sw = conv.stride
179
+ dh, dw = conv.dilation
180
+ self.make_conv(
181
+ name, inputs, self._io_dtype, shape=None,
182
+ strides=[sh, sw], pads=[ph, pw, ph, pw], dilations=[dh, dw],
183
+ group=conv.groups, kernel_shape=[kh, kw],
184
+ )
185
+ return f"{name}/output_0"
186
+
187
+ def _linear(self, name, root_input, linear):
188
+ """Attention Q/K/V/out projection. Goes through `make_matmul` so `-p int4/int8` applies."""
189
+ self.make_matmul(linear, name, root_input, seq_dim="attn_seq")
190
+ output = f"{name}/output_0"
191
+ if linear.bias is not None:
192
+ self.make_add_bias(linear.bias, f"{name}/Add", output, seq_dim="attn_seq")
193
+ output = f"{name}/Add/output_0"
194
+ return output
195
+
196
+ # ------------------------------------------------------------------
197
+ # GroupNorm (fused contrib op or decomposed standard ops)
198
+ # ------------------------------------------------------------------
199
+ def _group_norm(self, name, source, gnmod, swish, expose_skip=True):
200
+ if self.fuse_group_norm:
201
+ return self._group_norm_fused(name, source, gnmod, swish, expose_skip)
202
+
203
+ skip_sum = None
204
+ if isinstance(source, tuple):
205
+ conv_branch, skip_branch = source
206
+ skip_sum = self._add(f"{name}/skip_add", [conv_branch, skip_branch])
207
+ x = skip_sum
208
+ else:
209
+ x = source
210
+ normed = self._group_norm_decomposed(name, x, gnmod, swish)
211
+ return normed, (skip_sum if expose_skip else None)
212
+
213
+ def _group_norm_decomposed(self, name, x_nchw, gnmod, swish):
214
+ groups = int(gnmod.num_groups)
215
+ channels = int(gnmod.num_channels)
216
+ eps = float(gnmod.eps)
217
+
218
+ gamma = self._init_name(name, ".weight")
219
+ beta = self._init_name(name, ".bias")
220
+ self.make_initializer(gnmod.weight.detach().reshape(channels, 1, 1), gamma, to=self._io_dtype)
221
+ self.make_initializer(gnmod.bias.detach().reshape(channels, 1, 1), beta, to=self._io_dtype)
222
+ in_scale = f"{name}/instnorm_scale"
223
+ in_bias = f"{name}/instnorm_bias"
224
+ self.make_initializer(torch.ones(groups), in_scale, to=self._io_dtype)
225
+ self.make_initializer(torch.zeros(groups), in_bias, to=self._io_dtype)
226
+
227
+ self.make_shape(f"{name}/in_shape", x_nchw, shape=[4])
228
+ grouped = self._reshape(
229
+ f"{name}/to_groups", x_nchw, self._const(ir.DataType.INT64, [0, groups, -1])
230
+ )
231
+ in_normed = f"{name}/InstanceNormalization/output_0"
232
+ self.make_node(
233
+ "InstanceNormalization", inputs=[grouped, in_scale, in_bias], outputs=[in_normed],
234
+ name=f"{name}/InstanceNormalization", epsilon=eps,
235
+ )
236
+ self.make_value(in_normed, self._io_dtype)
237
+ normed = self._reshape(f"{name}/from_groups", in_normed, f"{name}/in_shape/output_0")
238
+ normed = self._mul(f"{name}/Mul", [normed, gamma])
239
+ normed = self._add(f"{name}/Add", [normed, beta])
240
+ if swish:
241
+ self.make_sigmoid(f"{name}/Sigmoid", normed, self._io_dtype, shape=None)
242
+ normed = self._mul(f"{name}/silu", [normed, f"{name}/Sigmoid/output_0"])
243
+ return normed
244
+
245
+ def _group_norm_fused(self, name, source, gnmod, swish, expose_skip):
246
+ gamma = self._init_name(name, ".weight")
247
+ beta = self._init_name(name, ".bias")
248
+ self.make_initializer(gnmod.weight, gamma, to=self._io_dtype)
249
+ self.make_initializer(gnmod.bias, beta, to=self._io_dtype)
250
+ groups = int(gnmod.num_groups)
251
+ eps = float(gnmod.eps)
252
+ activation = 1 if swish else 0
253
+
254
+ if isinstance(source, tuple):
255
+ conv_branch, skip_branch = source
256
+ x_nhwc = self._transpose(f"{name}/x_t", conv_branch, [0, 2, 3, 1])
257
+ skip_nhwc = self._transpose(f"{name}/skip_t", skip_branch, [0, 2, 3, 1])
258
+ normed_nhwc = f"{name}/output_0"
259
+ outputs = [normed_nhwc]
260
+ skip_sum_nhwc = None
261
+ if expose_skip:
262
+ skip_sum_nhwc = f"{name}/sum"
263
+ outputs.append(skip_sum_nhwc)
264
+ self.make_node(
265
+ "SkipGroupNorm", inputs=[x_nhwc, gamma, beta, skip_nhwc], outputs=outputs,
266
+ name=name, domain="com.microsoft",
267
+ activation=activation, channels_last=1, epsilon=eps, groups=groups,
268
+ )
269
+ for output in outputs:
270
+ self.make_value(output, self._io_dtype)
271
+ normed = self._transpose(f"{name}/post_t", normed_nhwc, [0, 3, 1, 2])
272
+ skip_sum = self._transpose(f"{name}/sum_post_t", skip_sum_nhwc, [0, 3, 1, 2]) if skip_sum_nhwc else None
273
+ return normed, skip_sum
274
+
275
+ x_nhwc = self._transpose(f"{name}/x_t", source, [0, 2, 3, 1])
276
+ normed_nhwc = f"{name}/output_0"
277
+ self.make_node(
278
+ "GroupNorm", inputs=[x_nhwc, gamma, beta], outputs=[normed_nhwc],
279
+ name=name, domain="com.microsoft",
280
+ activation=activation, channels_last=1, epsilon=eps, groups=groups,
281
+ )
282
+ self.make_value(normed_nhwc, self._io_dtype)
283
+ normed = self._transpose(f"{name}/post_t", normed_nhwc, [0, 3, 1, 2])
284
+ return normed, None
285
+
286
+ # ------------------------------------------------------------------
287
+ # ResNet block
288
+ # ------------------------------------------------------------------
289
+ def _resnet(self, name, source, resnet):
290
+ normed, skip_sum = self._group_norm(f"{name}/norm1", source, resnet.norm1, swish=True, expose_skip=True)
291
+ if skip_sum is not None:
292
+ # SkipGroupNorm case: identity shortcut, residual base is the fused skip sum.
293
+ residual_base = skip_sum
294
+ elif resnet.conv_shortcut is not None:
295
+ residual_base = self._conv(f"{name}/conv_shortcut", source, resnet.conv_shortcut)
296
+ else:
297
+ residual_base = source
298
+
299
+ hidden = self._conv(f"{name}/conv1", normed, resnet.conv1)
300
+ normed2, _ = self._group_norm(f"{name}/norm2", hidden, resnet.norm2, swish=True)
301
+ hidden = self._conv(f"{name}/conv2", normed2, resnet.conv2)
302
+ return (hidden, residual_base)
303
+
304
+ # ------------------------------------------------------------------
305
+ # Mid-block self-attention (unfused, single-head)
306
+ # ------------------------------------------------------------------
307
+ def _mid_attention(self, name, x_nchw, attn):
308
+ assert attn.heads == 1, f"expected single-head VAE attention, got heads={attn.heads}"
309
+ normed, _ = self._group_norm(f"{name}/group_norm", x_nchw, attn.group_norm, swish=False)
310
+
311
+ to_seq_shape = self._const(ir.DataType.INT64, [0, self.mid_channels, -1])
312
+ flat = self._reshape(f"{name}/flatten", normed, to_seq_shape)
313
+ seq = self._transpose(f"{name}/to_seq", flat, [0, 2, 1])
314
+
315
+ q = self._linear(f"{name}/to_q", seq, attn.to_q)
316
+ k = self._linear(f"{name}/to_k", seq, attn.to_k)
317
+ v = self._linear(f"{name}/to_v", seq, attn.to_v)
318
+
319
+ scale = self._const(self._io_dtype, self.mid_channels ** -0.25)
320
+ q = self._mul(f"{name}/q_scale", [q, scale])
321
+ k_t = self._transpose(f"{name}/kT", k, [0, 2, 1]) # [1, C, H*W]
322
+ k_t = self._mul(f"{name}/k_scale", [k_t, scale])
323
+ scores = f"{name}/scores/output_0"
324
+ self.make_node("MatMul", inputs=[q, k_t], outputs=[scores], name=f"{name}/scores")
325
+ self.make_value(scores, self._io_dtype)
326
+ probs = f"{name}/softmax/output_0"
327
+ self.make_node("Softmax", inputs=[scores], outputs=[probs], name=f"{name}/softmax", axis=-1)
328
+ self.make_value(probs, self._io_dtype)
329
+ ctx = f"{name}/context/output_0"
330
+ self.make_node("MatMul", inputs=[probs, v], outputs=[ctx], name=f"{name}/context")
331
+ self.make_value(ctx, self._io_dtype)
332
+ attn_out = self._linear(f"{name}/to_out.0", ctx, attn.to_out[0])
333
+
334
+ back_seq = self._transpose(f"{name}/from_seq", attn_out, [0, 2, 1])
335
+ self.make_shape(f"{name}/in_shape", x_nchw, shape=[4])
336
+ spatial = self._reshape(f"{name}/unflatten", back_seq, f"{name}/in_shape/output_0")
337
+
338
+ return self._add(f"{name}/Add", [spatial, x_nchw])
339
+
340
+ # ------------------------------------------------------------------
341
+ # Upsampler (nearest 2x, then conv)
342
+ # ------------------------------------------------------------------
343
+ def _upsample(self, name, x_nchw, conv):
344
+ if self.fuse_group_norm:
345
+ x = self._transpose(f"{name}/pre_t", x_nchw, [0, 2, 3, 1])
346
+ scales = self._const(ir.DataType.FLOAT, [1.0, 2.0, 2.0, 1.0])
347
+ else:
348
+ x = x_nchw
349
+ scales = self._const(ir.DataType.FLOAT, [1.0, 1.0, 2.0, 2.0])
350
+ resize_out = f"{name}/Resize/output_0"
351
+ self.make_node(
352
+ "Resize", inputs=[x, "", scales], outputs=[resize_out], name=f"{name}/Resize",
353
+ coordinate_transformation_mode="asymmetric", cubic_coeff_a=-0.75,
354
+ mode="nearest", nearest_mode="floor",
355
+ )
356
+ self.make_value(resize_out, self._io_dtype)
357
+ y_nchw = self._transpose(f"{name}/post_t", resize_out, [0, 3, 1, 2]) if self.fuse_group_norm else resize_out
358
+ return self._conv(f"{name}/conv", y_nchw, conv)
359
+
360
+ # ------------------------------------------------------------------
361
+ # Top-level graph construction
362
+ # ------------------------------------------------------------------
363
+ def make_model(self, input_path):
364
+ self.make_inputs_and_outputs()
365
+ self.weights = self.load_weights(input_path)
366
+ dec = self.weights
367
+
368
+ x = self.input_names["latent_sample"]
369
+
370
+ # --- conv_in ---
371
+ x = self._conv("/decoder/conv_in", x, dec.conv_in)
372
+
373
+ # --- mid block: resnet0 -> attention -> resnet1 ---
374
+ mid = dec.mid_block
375
+ r0 = self._resnet("/decoder/mid_block/resnets.0", x, mid.resnets[0])
376
+ x = self._add("/decoder/mid_block/resnets.0/Add", list(r0)) # feeds attention (non-norm)
377
+ x = self._mid_attention("/decoder/mid_block/attentions.0", x, mid.attentions[0])
378
+ source = self._resnet("/decoder/mid_block/resnets.1", x, mid.resnets[1])
379
+
380
+ # --- up blocks ---
381
+ for bi, up in enumerate(dec.up_blocks):
382
+ n_res = len(up.resnets)
383
+ for rj in range(n_res):
384
+ r = self._resnet(f"/decoder/up_blocks.{bi}/resnets.{rj}", source, up.resnets[rj])
385
+ if rj < n_res - 1:
386
+ source = r
387
+ elif getattr(up, "upsamplers", None):
388
+ x = self._add(f"/decoder/up_blocks.{bi}/resnets.{rj}/Add", list(r))
389
+ x = self._upsample(f"/decoder/up_blocks.{bi}/upsamplers.0", x, up.upsamplers[0].conv)
390
+ source = x
391
+ else:
392
+ source = r
393
+
394
+ # --- conv_norm_out (SkipGroupNorm, swish) -> conv_out ---
395
+ y, _ = self._group_norm(
396
+ "/decoder/conv_norm_out", source, dec.conv_norm_out, swish=True, expose_skip=False
397
+ )
398
+ out = self._conv("/decoder/conv_out", y, dec.conv_out)
399
+
400
+ self.make_node("Identity", inputs=[out], outputs=["sample"], name="/decoder/output_identity")
401
+
402
+ del self.weights
403
+
404
+ # ------------------------------------------------------------------
405
+ # Save (single self-contained .onnx file)
406
+ # ------------------------------------------------------------------
407
+ def save_model(self, out_dir):
408
+ print(f"Saving ONNX model in {out_dir}")
409
+ already_quantized_in_qdq_format = self.quant_type is not None and self.quant_attrs["use_qdq"]
410
+ if self.onnx_dtype in {ir.DataType.INT4, ir.DataType.UINT4, ir.DataType.INT8, ir.DataType.UINT8} and not already_quantized_in_qdq_format:
411
+ model = self.to_nbits()
412
+ else:
413
+ model = self.model
414
+
415
+ model.graph.sort()
416
+
417
+ out_path = os.path.join(out_dir, self.filename)
418
+ data_path = out_path + ".data"
419
+ for stale in (out_path, data_path):
420
+ if os.path.exists(stale):
421
+ print(f"Overwriting {stale}")
422
+ os.remove(stale)
423
+
424
+ ir.save(model, out_path)
425
+
426
+ if os.path.isdir(self.cache_dir) and not os.listdir(self.cache_dir):
427
+ os.rmdir(self.cache_dir)
428
+
429
+
430
+ # ---------------------------------------------------------------------------
431
+ # Standalone build driver (replaces builder.py's `create_model`, scoped to
432
+ # just this one architecture)
433
+ # ---------------------------------------------------------------------------
434
+ def build(input_path, output_dir, precision="f16", extra_options=None):
435
+ if precision not in PRECISION_CONFIGS:
436
+ raise ValueError(f"Unknown precision '{precision}'; choose from {sorted(PRECISION_CONFIGS)}")
437
+
438
+ precision_config = PRECISION_CONFIGS[precision]
439
+ extra_options = dict(extra_options or {})
440
+ extra_options.setdefault("hf_remote", False)
441
+ extra_options["filename"] = f"vae_decoder_model_{precision}.onnx"
442
+
443
+ builder_precision = precision_config["builder_precision"]
444
+ io_dtype = set_io_dtype(builder_precision, "webgpu", extra_options)
445
+ onnx_dtype = set_onnx_dtype(builder_precision, extra_options)
446
+
447
+ config = load_diffusers_config(input_path)
448
+
449
+ onnx_dir = os.path.join(output_dir, "onnx")
450
+ os.makedirs(onnx_dir, exist_ok=True)
451
+ cache_dir = os.path.join(output_dir, "cache")
452
+ os.makedirs(cache_dir, exist_ok=True)
453
+
454
+ model = ZImageVAEDecoderModel(config, io_dtype, onnx_dtype, "webgpu", cache_dir, extra_options)
455
+ model.make_model(input_path)
456
+ model.save_model(onnx_dir)
457
+ return onnx_dir
458
+
459
+
460
+ def get_args():
461
+ parser = argparse.ArgumentParser(description="Export the Z-Image-Turbo VAE decoder to ONNX.")
462
+ parser.add_argument("input_path", help="Path to the Z-Image-Turbo `vae/` folder (or its parent).")
463
+ parser.add_argument(
464
+ "-o", "--output_dir", default=DEFAULT_OUTPUT_DIR,
465
+ help=f"Directory to write the ONNX model to (under an `onnx/` subdir). Default: {DEFAULT_OUTPUT_DIR}",
466
+ )
467
+ parser.add_argument(
468
+ "-p", "--precision", default="f16", choices=sorted(PRECISION_CONFIGS),
469
+ help="Output precision. Default: f16.",
470
+ )
471
+ parser.add_argument(
472
+ "--extra_options", nargs="*", default=[],
473
+ help="Extra key=value options, e.g. fuse_group_norm=true.",
474
+ )
475
+ return parser.parse_args()
476
+
477
+
478
+ def main():
479
+ args = get_args()
480
+ input_path = args.input_path
481
+ if os.path.isdir(os.path.join(input_path, "vae")):
482
+ input_path = os.path.join(input_path, "vae")
483
+ onnx_dir = build(input_path, args.output_dir, args.precision, parse_extra_options(args.extra_options))
484
+ print(f"\nSuccess: vae_decoder exported to {onnx_dir}")
485
+
486
+
487
+ if __name__ == "__main__":
488
+ main()
model_exporter/export_models.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ # Modifications Copyright (C) 2026 Intel Corporation. All rights reserved.
7
+ # --------------------------------------------------------------------------
8
+ """Main entry point for exporting the Z-Image-Turbo pipeline to standalone ONNX models."""
9
+
10
+ import argparse
11
+ import os
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+
16
+ import build_helper_models
17
+ import build_safety_checker
18
+ import build_text_encoder
19
+ import build_transformer
20
+ import build_vae_decoder
21
+
22
+ ALL_COMPONENTS = ("transformer", "text_encoder", "vae_decoder", "helper_models", "safety_checker")
23
+
24
+ # Small tokenizer files that AutoTokenizer.from_pretrained needs; they live in the checkpoint's
25
+ # sibling `tokenizer/` folder, not `text_encoder/`.
26
+ TOKENIZER_FILES = ("merges.txt", "tokenizer.json", "tokenizer_config.json", "vocab.json")
27
+
28
+
29
+ def get_args():
30
+ parser = argparse.ArgumentParser(description="Export the Z-Image-Turbo pipeline to ONNX.")
31
+ parser.add_argument("input_path", help="Path to the Z-Image-Turbo checkpoint (repo root or component subfolder).")
32
+ parser.add_argument(
33
+ "-o", "--output_dir", default=build_transformer.DEFAULT_OUTPUT_DIR,
34
+ help=f"Directory to write the ONNX model(s) to (under an `onnx/` subdir). Default: {build_transformer.DEFAULT_OUTPUT_DIR}",
35
+ )
36
+ parser.add_argument(
37
+ "-m", "--model", default="all",
38
+ choices=["transformer", "vae_decoder", "helper_models", "text_encoder", "safety_checker", "all"],
39
+ help="Which component to build. Default: all.",
40
+ )
41
+ parser.add_argument(
42
+ "--extra_options", nargs="*", default=[],
43
+ help="Extra key=value options passed through to the component's builder.",
44
+ )
45
+ parser.add_argument(
46
+ "--safety_checker_checkpoint", default="",
47
+ help="Path to a local CompVis/stable-diffusion-safety-checker-compatible checkpoint "
48
+ "(e.g. via huggingface_hub.snapshot_download('CompVis/stable-diffusion-safety-checker', "
49
+ "local_dir=...)). This is a separate download from input_path. Required for "
50
+ "-m safety_checker; for -m all, safety_checker is skipped if this isn't given.",
51
+ )
52
+ return parser.parse_args()
53
+
54
+
55
+ def build_one(model, input_path, output_dir, extra_options, safety_checker_checkpoint=""):
56
+ if model == "transformer":
57
+ transformer_input = input_path
58
+ if os.path.isdir(os.path.join(input_path, "transformer")):
59
+ transformer_input = os.path.join(input_path, "transformer")
60
+ return build_transformer.build(
61
+ transformer_input, output_dir, extra_options=build_transformer.parse_extra_options(extra_options)
62
+ )
63
+ if model == "text_encoder":
64
+ text_encoder_input = input_path
65
+ if os.path.isdir(os.path.join(input_path, "text_encoder")):
66
+ text_encoder_input = os.path.join(input_path, "text_encoder")
67
+ return build_text_encoder.build(
68
+ text_encoder_input, output_dir, extra_options=build_text_encoder.parse_extra_options(extra_options)
69
+ )
70
+ if model == "vae_decoder":
71
+ vae_input = input_path
72
+ if os.path.isdir(os.path.join(input_path, "vae")):
73
+ vae_input = os.path.join(input_path, "vae")
74
+ return build_vae_decoder.build(
75
+ vae_input, output_dir, extra_options=build_vae_decoder.parse_extra_options(extra_options)
76
+ )
77
+ if model == "helper_models":
78
+ return build_helper_models.build(
79
+ input_path, output_dir, extra_options=build_helper_models.parse_extra_options(extra_options)
80
+ )
81
+ if model == "safety_checker":
82
+ if not safety_checker_checkpoint:
83
+ raise NotImplementedError(
84
+ "-m safety_checker requires --safety_checker_checkpoint (a separate local "
85
+ "CompVis/stable-diffusion-safety-checker-compatible checkpoint, not input_path)."
86
+ )
87
+ return build_safety_checker.build(
88
+ safety_checker_checkpoint, output_dir, extra_options=build_safety_checker.parse_extra_options(extra_options)
89
+ )
90
+ raise ValueError(f"Unknown -m/--model value: {model}")
91
+
92
+
93
+ def resolve_tokenizer_dir(input_path):
94
+ text_encoder_dir = input_path
95
+ if os.path.isdir(os.path.join(input_path, "text_encoder")):
96
+ text_encoder_dir = os.path.join(input_path, "text_encoder")
97
+ return os.path.join(os.path.dirname(os.path.normpath(text_encoder_dir)), "tokenizer")
98
+
99
+
100
+ def _link_or_copy(src, dst):
101
+ if os.path.exists(dst):
102
+ os.remove(dst)
103
+ try:
104
+ os.link(src, dst)
105
+ except OSError:
106
+ shutil.copy2(src, dst)
107
+
108
+
109
+ def copy_tokenizer(input_path, output_dir):
110
+ tokenizer_dir = resolve_tokenizer_dir(input_path)
111
+ if not os.path.isdir(tokenizer_dir):
112
+ print(f"Skipping tokenizer copy: {tokenizer_dir} not found", file=sys.stderr)
113
+ return
114
+
115
+ dest_dir = os.path.join(output_dir, "tokenizer")
116
+ os.makedirs(dest_dir, exist_ok=True)
117
+ missing = []
118
+ for fname in TOKENIZER_FILES:
119
+ src = os.path.join(tokenizer_dir, fname)
120
+ if os.path.isfile(src):
121
+ _link_or_copy(src, os.path.join(dest_dir, fname))
122
+ else:
123
+ missing.append(fname)
124
+
125
+ if missing:
126
+ print(f"Warning: tokenizer files not found in {tokenizer_dir}: {missing}", file=sys.stderr)
127
+ else:
128
+ print(f"Copied tokenizer to {dest_dir}")
129
+
130
+
131
+ def build_component_subprocess(model, args):
132
+ cmd = [sys.executable, os.path.abspath(__file__), args.input_path, "-m", model, "-o", args.output_dir]
133
+ if args.extra_options:
134
+ cmd += ["--extra_options", *args.extra_options]
135
+ if args.safety_checker_checkpoint:
136
+ cmd += ["--safety_checker_checkpoint", args.safety_checker_checkpoint]
137
+ return subprocess.run(cmd).returncode
138
+
139
+
140
+ def build_all(args):
141
+ results = {}
142
+ for model in ALL_COMPONENTS:
143
+ if model == "safety_checker" and not args.safety_checker_checkpoint:
144
+ print(f"\nSkipping {model}: no --safety_checker_checkpoint given")
145
+ results[model] = "skipped"
146
+ continue
147
+ print(f"\n=== Building {model} (isolated subprocess) ===")
148
+ returncode = build_component_subprocess(model, args)
149
+ results[model] = "ok" if returncode == 0 else f"FAILED (exit {returncode})"
150
+
151
+ print("\n=== Summary ===")
152
+ for model in ALL_COMPONENTS:
153
+ print(f" {model:<14} {results.get(model, 'skipped')}")
154
+
155
+ failed = [m for m, status in results.items() if status.startswith("FAILED")]
156
+ return results, failed
157
+
158
+
159
+ def main():
160
+ args = get_args()
161
+ if args.model == "all":
162
+ _results, failed = build_all(args)
163
+ copy_tokenizer(args.input_path, args.output_dir)
164
+ onnx_dir = os.path.join(args.output_dir, "onnx")
165
+ if failed:
166
+ print(f"\nFailure: {len(failed)} component(s) failed: {', '.join(failed)}", file=sys.stderr)
167
+ sys.exit(1)
168
+ print(f"\nSuccess: all exported to {onnx_dir}")
169
+ else:
170
+ onnx_dir = build_one(
171
+ args.model, args.input_path, args.output_dir, args.extra_options, args.safety_checker_checkpoint
172
+ )
173
+ copy_tokenizer(args.input_path, args.output_dir)
174
+ print(f"\nSuccess: {args.model} exported to {onnx_dir}")
175
+
176
+
177
+ if __name__ == "__main__":
178
+ main()
model_exporter/external_data_utils.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See License.txt in the project root for
4
+ # license information.
5
+ # --------------------------------------------------------------------------
6
+ # Modifications Copyright (C) 2026 Intel Corporation. All rights reserved.
7
+ # --------------------------------------------------------------------------
8
+ """Shared ONNX external-data save helper for the Z-Image-Turbo exporters."""
9
+
10
+ import glob
11
+ import os
12
+ import re
13
+
14
+ import onnx
15
+ import onnx_ir as ir
16
+
17
+ INLINE_SIZE_THRESHOLD_BYTES = 1 * 1024**2
18
+ MAX_SHARD_SIZE_BYTES = int(1.9 * 1024**3) # stays under the browser's 2 GiB ArrayBuffer ceiling
19
+
20
+ _SHARD_RE = re.compile(r"-(\d{5})-of-(\d{5})") # onnx_ir's "<stem>-000i-of-000N<ext>" naming
21
+
22
+
23
+ def save_ir_model_sharded(
24
+ model, out_dir, onnx_filename, *, size_threshold_bytes, max_shard_size_bytes, callback=None
25
+ ):
26
+ """Save with small weights inline and external data sharded; returns the `.onnx` path."""
27
+ out_path = os.path.join(out_dir, onnx_filename)
28
+ data_base = onnx_filename + "_data"
29
+ stem, ext = os.path.splitext(data_base)
30
+
31
+ # onnx_ir refuses to overwrite a pre-existing shard file, so clear stale outputs first.
32
+ stale = [out_path, *glob.glob(os.path.join(out_dir, data_base + "*")),
33
+ *glob.glob(os.path.join(out_dir, f"{stem}-*-of-*{ext}"))]
34
+ for path in stale:
35
+ if os.path.exists(path):
36
+ os.remove(path)
37
+
38
+ ir.save(
39
+ model, out_path, external_data=data_base,
40
+ size_threshold_bytes=size_threshold_bytes, max_shard_size_bytes=max_shard_size_bytes,
41
+ callback=callback,
42
+ )
43
+
44
+ temp_shards = sorted(glob.glob(os.path.join(out_dir, f"{stem}-*-of-*{ext}")))
45
+ if not temp_shards:
46
+ return out_path
47
+
48
+ remap = {}
49
+ for path in temp_shards:
50
+ base = os.path.basename(path)
51
+ idx = int(_SHARD_RE.search(base).group(1))
52
+ final = data_base if idx == 1 else f"{data_base}_{idx - 1}"
53
+ os.replace(path, os.path.join(out_dir, final))
54
+ remap[base] = final
55
+
56
+ proto = onnx.load(out_path, load_external_data=False)
57
+ for init in proto.graph.initializer:
58
+ for kv in init.external_data:
59
+ if kv.key == "location" and kv.value in remap:
60
+ kv.value = remap[kv.value]
61
+ onnx.save(proto, out_path)
62
+ return out_path
model_exporter/requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CPU-only build: avoids pulling in nvidia-*-cu12 CUDA packages.
2
+ --extra-index-url https://download.pytorch.org/whl/cpu
3
+ torch==2.14.0+cpu
4
+
5
+ onnxruntime-genai==0.15.2
6
+ onnxruntime==1.29.0
7
+ transformers==5.16.1
8
+ tqdm==4.70.0
9
+ accelerate==1.14.0
10
+ onnx==1.22.0
11
+ onnx-ir==1.0.0
12
+ diffusers==0.40.0
13
+ numpy==2.5.3
14
+ onnxconverter-common==1.16.0
onnx/safety_checker_model_f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82cf82437fecf1e91fa4f10fd7bc505ed5a489f434d2a2390d2b9ddd467cc09c
3
+ size 1604491
onnx/safety_checker_model_f16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a2494eff6418d97eb184770018767e2284934a4476c97d5d94b1c33345da3411
3
+ size 606797824
onnx/sc_prep_model_f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97bfaf6d8ec65ec220afd8035a93c5d3395d677a66f82aef6f4f118e06c6c6c4
3
+ size 1434
onnx/scheduler_step_model_f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3ddc54c5f2963c87d28b6e3956b7f2602a6f0ecc1b248653bd44f5d17f129cd
3
+ size 3902
onnx/text_encoder_model_q4f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97cb87b20147da5ba44c3666ec17b7d9a1c90cabbaee71649bcb1a374371fb66
3
+ size 57983622
onnx/text_encoder_model_q4f16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a23fd9188f4ac8eb5e0ae3cb9eae970005f869eac499c7048d951db30a04617
3
+ size 2036236288
onnx/text_encoder_model_q4f16.onnx_data_1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c10bbb8670f2605f3bbc11fd302b15c4fdf264a2ac132d4ebec17717196cf6e
3
+ size 124387328
onnx/transformer_model_q4f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a19a13c20e040041dd5298bc57e24158fd4bae6ef1127beb26947c23b42ec7ff
3
+ size 129947430
onnx/transformer_model_q4f16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19889aa5bce49b5b79b6c736d276797a6e826a7f3cb51f3e71b2d416cbbdebc7
3
+ size 2032271360
onnx/transformer_model_q4f16.onnx_data_1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:562bfd080c3ebbb5aaf176e47b24a71003403a4e0f9c5344ac85f8e687da1e47
3
+ size 1507590144
onnx/vae_decoder_model_f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b194f594d893ebcdd9afc6cf06944105fc58493870eb810ee7d4d5c333d8544
3
+ size 99209498
onnx/vae_pre_process_model_f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42d77874d1322d2a9849982f3c449273e91cfd66f5e8b0e42e9defa5dccaba1e
3
+ size 346
tokenizer/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
3
+ size 11422654
tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ }
213
+ },
214
+ "additional_special_tokens": [
215
+ "<|im_start|>",
216
+ "<|im_end|>",
217
+ "<|object_ref_start|>",
218
+ "<|object_ref_end|>",
219
+ "<|box_start|>",
220
+ "<|box_end|>",
221
+ "<|quad_start|>",
222
+ "<|quad_end|>",
223
+ "<|vision_start|>",
224
+ "<|vision_end|>",
225
+ "<|vision_pad|>",
226
+ "<|image_pad|>",
227
+ "<|video_pad|>"
228
+ ],
229
+ "bos_token": null,
230
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if message.content is string %}\n {%- set content = message.content %}\n {%- else %}\n {%- set content = '' %}\n {%- endif %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in content %}\n {%- set reasoning_content = content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- set content = content.split('</think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}",
231
+ "clean_up_tokenization_spaces": false,
232
+ "eos_token": "<|im_end|>",
233
+ "errors": "replace",
234
+ "model_max_length": 131072,
235
+ "pad_token": "<|endoftext|>",
236
+ "split_special_tokens": false,
237
+ "tokenizer_class": "Qwen2Tokenizer",
238
+ "unk_token": null
239
+ }
tokenizer/vocab.json ADDED
The diff for this file is too large to render. See raw diff