INC4AI commited on
Commit
e8a054d
·
verified ·
1 Parent(s): 7396d65

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +58 -0
  2. README.md +308 -0
  3. README_zh_CN.md +534 -0
  4. __init__.py +18 -0
  5. assets/WECHAT.md +6 -0
  6. assets/banner.png +3 -0
  7. assets/banner_all.jpg +3 -0
  8. assets/demo_instruct_imgs/input_0_0.png +3 -0
  9. assets/demo_instruct_imgs/input_1_0.png +0 -0
  10. assets/demo_instruct_imgs/input_1_1.png +3 -0
  11. assets/demo_instruct_imgs/input_2_0.png +3 -0
  12. assets/demo_instruct_imgs/input_2_1.png +3 -0
  13. assets/demo_instruct_imgs/input_2_2.png +3 -0
  14. assets/framework.png +3 -0
  15. assets/gsb.png +3 -0
  16. assets/gsb_instruct.png +0 -0
  17. assets/logo.png +0 -0
  18. assets/pg_imgs/image1.png +3 -0
  19. assets/pg_imgs/image2.png +3 -0
  20. assets/pg_imgs/image3.png +3 -0
  21. assets/pg_imgs/image4.png +3 -0
  22. assets/pg_imgs/image5.png +3 -0
  23. assets/pg_imgs/image6.png +3 -0
  24. assets/pg_imgs/image7.png +3 -0
  25. assets/pg_imgs/image8.png +3 -0
  26. assets/pg_instruct_imgs/cot_ti2i.gif +3 -0
  27. assets/pg_instruct_imgs/image0.png +3 -0
  28. assets/pg_instruct_imgs/image1.png +3 -0
  29. assets/pg_instruct_imgs/image2.png +3 -0
  30. assets/pg_instruct_imgs/image3.png +3 -0
  31. assets/pg_instruct_imgs/image4.png +3 -0
  32. assets/robot.png +0 -0
  33. assets/ssae_side_by_side_comparison.png +3 -0
  34. assets/ssae_side_by_side_heatmap.png +3 -0
  35. assets/user.png +0 -0
  36. assets/wechat.png +0 -0
  37. autoencoder_kl_3d.py +1081 -0
  38. cache_utils.py +226 -0
  39. config.json +1628 -0
  40. config.json.pristine +1628 -0
  41. configuration_hunyuan_image_3.py +310 -0
  42. generation_config.json +21 -0
  43. hunyuan_image_3_pipeline.py +913 -0
  44. image_processor.py +465 -0
  45. images/ar_dit_full_tp1x1.png +3 -0
  46. images/bf16_dit_only_reference.png +3 -0
  47. images/dit_only_tp2.png +3 -0
  48. images/sibling_llm_compressor_ar_dit.png +3 -0
  49. images/sibling_llm_compressor_dit_only.png +3 -0
  50. model-00001-of-00032.safetensors +3 -0
.gitattributes CHANGED
@@ -33,3 +33,61 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
+ utils/__pycache__/import_utils.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
38
+ utils/__pycache__/import_utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
39
+ banner.png filter=lfs diff=lfs merge=lfs -text
40
+ banner_all.jpg filter=lfs diff=lfs merge=lfs -text
41
+ demo_instruct_imgs/input_0_0.png filter=lfs diff=lfs merge=lfs -text
42
+ demo_instruct_imgs/input_1_1.png filter=lfs diff=lfs merge=lfs -text
43
+ demo_instruct_imgs/input_2_0.png filter=lfs diff=lfs merge=lfs -text
44
+ demo_instruct_imgs/input_2_1.png filter=lfs diff=lfs merge=lfs -text
45
+ demo_instruct_imgs/input_2_2.png filter=lfs diff=lfs merge=lfs -text
46
+ framework.png filter=lfs diff=lfs merge=lfs -text
47
+ gsb.png filter=lfs diff=lfs merge=lfs -text
48
+ pg_imgs/image1.png filter=lfs diff=lfs merge=lfs -text
49
+ pg_imgs/image2.png filter=lfs diff=lfs merge=lfs -text
50
+ pg_imgs/image3.png filter=lfs diff=lfs merge=lfs -text
51
+ pg_imgs/image4.png filter=lfs diff=lfs merge=lfs -text
52
+ pg_imgs/image5.png filter=lfs diff=lfs merge=lfs -text
53
+ pg_imgs/image6.png filter=lfs diff=lfs merge=lfs -text
54
+ pg_imgs/image7.png filter=lfs diff=lfs merge=lfs -text
55
+ pg_imgs/image8.png filter=lfs diff=lfs merge=lfs -text
56
+ pg_instruct_imgs/cot_ti2i.gif filter=lfs diff=lfs merge=lfs -text
57
+ pg_instruct_imgs/image0.png filter=lfs diff=lfs merge=lfs -text
58
+ pg_instruct_imgs/image1.png filter=lfs diff=lfs merge=lfs -text
59
+ pg_instruct_imgs/image2.png filter=lfs diff=lfs merge=lfs -text
60
+ pg_instruct_imgs/image3.png filter=lfs diff=lfs merge=lfs -text
61
+ pg_instruct_imgs/image4.png filter=lfs diff=lfs merge=lfs -text
62
+ ssae_side_by_side_comparison.png filter=lfs diff=lfs merge=lfs -text
63
+ ssae_side_by_side_heatmap.png filter=lfs diff=lfs merge=lfs -text
64
+ assets/banner.png filter=lfs diff=lfs merge=lfs -text
65
+ assets/banner_all.jpg filter=lfs diff=lfs merge=lfs -text
66
+ assets/demo_instruct_imgs/input_0_0.png filter=lfs diff=lfs merge=lfs -text
67
+ assets/demo_instruct_imgs/input_1_1.png filter=lfs diff=lfs merge=lfs -text
68
+ assets/demo_instruct_imgs/input_2_0.png filter=lfs diff=lfs merge=lfs -text
69
+ assets/demo_instruct_imgs/input_2_1.png filter=lfs diff=lfs merge=lfs -text
70
+ assets/demo_instruct_imgs/input_2_2.png filter=lfs diff=lfs merge=lfs -text
71
+ assets/framework.png filter=lfs diff=lfs merge=lfs -text
72
+ assets/gsb.png filter=lfs diff=lfs merge=lfs -text
73
+ assets/pg_imgs/image1.png filter=lfs diff=lfs merge=lfs -text
74
+ assets/pg_imgs/image2.png filter=lfs diff=lfs merge=lfs -text
75
+ assets/pg_imgs/image3.png filter=lfs diff=lfs merge=lfs -text
76
+ assets/pg_imgs/image4.png filter=lfs diff=lfs merge=lfs -text
77
+ assets/pg_imgs/image5.png filter=lfs diff=lfs merge=lfs -text
78
+ assets/pg_imgs/image6.png filter=lfs diff=lfs merge=lfs -text
79
+ assets/pg_imgs/image7.png filter=lfs diff=lfs merge=lfs -text
80
+ assets/pg_imgs/image8.png filter=lfs diff=lfs merge=lfs -text
81
+ assets/pg_instruct_imgs/cot_ti2i.gif filter=lfs diff=lfs merge=lfs -text
82
+ assets/pg_instruct_imgs/image0.png filter=lfs diff=lfs merge=lfs -text
83
+ assets/pg_instruct_imgs/image1.png filter=lfs diff=lfs merge=lfs -text
84
+ assets/pg_instruct_imgs/image2.png filter=lfs diff=lfs merge=lfs -text
85
+ assets/pg_instruct_imgs/image3.png filter=lfs diff=lfs merge=lfs -text
86
+ assets/pg_instruct_imgs/image4.png filter=lfs diff=lfs merge=lfs -text
87
+ assets/ssae_side_by_side_comparison.png filter=lfs diff=lfs merge=lfs -text
88
+ assets/ssae_side_by_side_heatmap.png filter=lfs diff=lfs merge=lfs -text
89
+ images/ar_dit_full_tp1x1.png filter=lfs diff=lfs merge=lfs -text
90
+ images/bf16_dit_only_reference.png filter=lfs diff=lfs merge=lfs -text
91
+ images/dit_only_tp2.png filter=lfs diff=lfs merge=lfs -text
92
+ images/sibling_llm_compressor_ar_dit.png filter=lfs diff=lfs merge=lfs -text
93
+ images/sibling_llm_compressor_dit_only.png filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HunyuanImage-3.0-Instruct-Distil · MXFP4 mixed-precision (`auto-round` / vLLM INC path)
2
+
3
+ This is the **`--format auto_round`** sibling of
4
+ [`HunyuanImage-3.0-Instruct-Distil-MXFP4-mixed`](../HunyuanImage-3.0-Instruct-Distil-MXFP4-mixed/README.md):
5
+ the same MXFP4-for-experts / MXFP8-for-everything-else recipe, but exporting
6
+ `quant_method = "auto-round"` so vLLM loads it through the **INC** dispatch instead of the
7
+ `compressed-tensors` one. AR-only, DiT-only and AR+DiT were all run successfully on
8
+ vLLM 0.29.0 + vLLM-Omni `main`.
9
+
10
+ ![AR+DiT full-pipeline output](images/ar_dit_full_tp1x1.png)
11
+
12
+ > Generated output, not a ground-truth reference: AR+DiT on **2 GPUs** (AR TP1 + DiT TP1),
13
+ > `seed=42`, 8 steps, prompt `A cute cat`.
14
+
15
+ ---
16
+
17
+ ## ⚠️ Read this first
18
+
19
+ 1. **A stock `--format auto_round` export of this recipe does NOT load.** It fails during weight
20
+ loading, in all three run modes, with
21
+
22
+ ```
23
+ KeyError: 'layers.0.mlp.experts.routed_experts.w2_weight_packed'
24
+ ```
25
+
26
+ because AutoRound writes the `--layer_config` pattern into `extra_config` **verbatim**
27
+ (key = `.mlp.experts.`), which vLLM's INC parser can never match ⇒ the 4-bit override is
28
+ *silently dropped* and the MoE is treated as 8-bit.
29
+ **Fix: run the one-file metadata normalizer shipped with this checkpoint** — see
30
+ [Required metadata fix](#required-metadata-fix-) (already applied here; the pristine export is kept
31
+ as `config.json.pristine`).
32
+
33
+ 2. **On Hopper (SM90: H100/H200) this is a memory saving, not a speed saving.** There are no FP4
34
+ tensor cores, so the experts run through Marlin as **weight-only FP4 (effectively W4A16)**:
35
+
36
+ ```
37
+ Using MarlinExperts (weight-only FP4) for AutoRound MXFP4 MoE
38
+ Using MarlinMxfp8LinearKernel for MXFP8 GEMM
39
+ ```
40
+
41
+ Blackwell (`b12x` / CUTLASS MXFP4) paths exist in vLLM but are **untested** for this build.
42
+
43
+ ---
44
+
45
+ ## Overview
46
+
47
+ | Field | Value |
48
+ |---|---|
49
+ | Base model | `tencent/HunyuanImage-3.0-Instruct-Distil` (`cfg_distilled=true`, `use_meanflow=true`) |
50
+ | MoE geometry | 32 layers × 64 routed experts, `moe_topk=8`, 1 shared expert/layer, hidden 4096, `moe_intermediate=3072` |
51
+ | Scheme | **Mixed**: routed experts → **MXFP4** (E2M1, group 32, E8M0); all other quantized `Linear` → **MXFP8** (E4M3, group 32, E8M0) |
52
+ | Export format | **`--format auto_round`** → `quant_method = "auto-round"`, `packing_format = "auto_round:llm_compressor"` |
53
+ | Loader path | vLLM **INC** (`INCConfig.override_quantization_method()` maps `"auto-round"` → `"inc"`) |
54
+ | Quantization tool | auto-round **0.15.0**, `--model_free` (no calibration data); wall time **707 s** on 1 GPU |
55
+ | Disk size | **52.59 GB** (48.98 GiB) — MXFP8-ct build 91.25 GB, BF16 base 158 GB ⇒ **0.33× BF16** |
56
+ | Parameters | total **83.04 B**: routed experts **77.31 B (93.1 %) @4-bit**, `self_attn` 1.49 B + `shared_mlp` 1.21 B @8-bit, **3.03 B BF16/FP32** |
57
+ | Expert tensor layout | `…experts.N.{gate_and_up_proj,down_proj}.weight_packed` = `uint8 [N, K/2]` (two E2M1 per byte, **low nibble = even column**) + `weight_scale` = `uint8 [N, K/32]` (E8M0: `value = 2^(byte−127)`) |
58
+ | Kept in BF16 / FP32 | ViT (`vision_model`, BF16), VAE (FP32, as in the base model), `wte`/`lm_head`, `guidance_emb`, `timestep_emb`, `timestep_r_emb`, `patch_embed`, `final_layer`, `time_embed*`, `vision_aligner`, and the **MoE router of all 32 blocks** (`…mlp.gate.wg`) |
59
+
60
+ `quantization_config` from `config.json` (verbatim, minus the long `extra_config`):
61
+
62
+ ```json
63
+ {
64
+ "quant_method": "auto-round",
65
+ "packing_format": "auto_round:llm_compressor",
66
+ "bits": 8, "group_size": 32, "sym": true, "data_type": "mx_fp",
67
+ "act_bits": 8, "act_data_type": "mx_fp", "act_dynamic": true, "act_group_size": 32, "act_sym": true,
68
+ "model_free": true, "iters": 0, "enable_quanted_input": false,
69
+ "autoround_version": "0.15.0",
70
+ "block_name_to_quantize": "model.layers",
71
+ "extra_config": {
72
+ ".*mlp\\.experts": { "bits": 4 }, // ← the fix; stock export has ".mlp.experts."
73
+ "final_layer.model.0.emb_layers.1": { "bits": 16, "data_type": "float", "act_bits": 16, "act_data_type": "float" },
74
+ "... 220 more entries, all bits:16 overrides ..."
75
+ }
76
+ }
77
+ ```
78
+
79
+ Note there is **no `ignore` list** in this format (unlike the `compressed-tensors` sibling): the
80
+ 16-bit exceptions are expressed as `extra_config` entries with `bits: 16`, and the non-Linear modules
81
+ that never quantize anyway (VAE convolutions, ViT patch/position embeddings) simply are not listed.
82
+
83
+ > `act_*` fields describe the *declared* scheme. What actually runs on SM90: dynamic MXFP8 activation
84
+ > quantization for dense `Linear`, but **no activation quantization for the experts** (Marlin W4A16).
85
+
86
+ ---
87
+
88
+ ## Relationship to the sibling `-MXFP4-mixed` build (measured)
89
+
90
+ The user-facing question: *is this also mixed, and are the same modules quantized?* — yes to both, and
91
+ this is verifiable, not asserted:
92
+
93
+ | Check | Result |
94
+ |---|---|
95
+ | Tensor name sets | **identical** (9393 = 9393, set equality) |
96
+ | Shard assignment per tensor | **identical** |
97
+ | **Shard bytes (md5 of 3 sampled shards)** | **identical** ⇒ weights are byte-for-byte the same tensors |
98
+ | Per-family dtype/byte account | **row-for-row identical**: routed_experts 77.31 B @MXFP4 (38.65 GB + 2.42 GB scales); `self_attn` 1.49 B + `shared_mlp` 1.21 B @MXFP8 (2.55 GB); ViT/embed BF16 3.84 GB; VAE FP32 5.04 GB; router 0.02 GB BF16 |
99
+ | Total | 52.59 GB, 83.04 B params, same 4096 `weight_packed` + 4224 `weight_scale` |
100
+ | Where they differ | **only the metadata carrier**: `config_groups[*].targets` (4096 literal names + patch) vs `extra_config` (1 pattern + 220 × `bits:16`); consequently the `ignore` list has 301 entries there and 0 here — the 81 extra ones are conv/embedding modules that are not Linear-quantization candidates |
101
+ | Consequence for outputs | same weights, different kernel entry points ⇒ images agree structurally but **not bit-exactly** (see *Fidelity*) |
102
+
103
+ Do **not** mix outputs of the two builds in one A/B comparison: switching loader changes the result
104
+ (33 dB, below the 41 dB same-build re-run floor).
105
+
106
+ ---
107
+
108
+ ## Required metadata fix ⚠️
109
+
110
+ **Why the stock key cannot match.** For `layer_name = "model.layers.0.mlp.experts"` and
111
+ `extra_config` key `".mlp.experts."`, every branch of
112
+ `vllm/model_executor/layers/quantization/inc/config_parser.py` misses (each verified by direct
113
+ invocation, not by reading):
114
+
115
+ | branch | predicate | result |
116
+ |---|---|---|
117
+ | exact | `layer_name in extra_config` | no |
118
+ | regex | tried only if the key contains one of ``*+?^$()[]{}\|\\`` — **a bare `.` does not qualify** | skipped |
119
+ | short-name suffix | `layer_name.endswith(".mlp.experts.")` | no (prefix has no trailing dot) |
120
+ | MoE-specific | `"fusedmoe" in layer.__class__.__name__.lower()` | **never true on vLLM ≥ 0.29**, where the module is `RoutedExperts` |
121
+ | → fallback | top-level `bits = 8` | **4-bit override lost** |
122
+
123
+ **Which spellings actually work** (`re.search(key, "model.layers.0.mlp.experts")`):
124
+
125
+ | candidate key | matches |
126
+ |---|---|
127
+ | `.mlp.experts.` (stock export) | ✗ |
128
+ | `.*\.mlp\.experts\.` | ✗ ← same trailing-dot trap as the compressed-tensors side |
129
+ | **`.*mlp\.experts`** | **✓ used here** |
130
+ | `\.mlp\.experts$` | ✓ |
131
+
132
+ **Apply it** (metadata only; backs up `config.json` as `config.json.pristine`):
133
+
134
+ ```bash
135
+ python tools/normalize_experts_extra_config_key.py . --check # report only
136
+ python tools/normalize_experts_extra_config_key.py . # apply to config.json + quantization_config.json
137
+ python tools/normalize_experts_extra_config_key.py . --revert # restore stock export
138
+ ```
139
+
140
+ After the fix, INC resolves exactly as intended:
141
+
142
+ ```
143
+ experts container bits=4 is_mxfp4=True → INCMxfp4Scheme → MarlinExperts (weight-only FP4)
144
+ shared_mlp / attn bits=8 is_mxfp8=True → INCMxfp8Scheme → MarlinMxfp8LinearKernel
145
+ mlp.gate.wg router bits=16 unquantized → Unquantized*
146
+ ```
147
+
148
+ vLLM reads `config.json`; `quantization_config.json` is a secondary discovery file — the tool
149
+ normalizes both so they cannot disagree.
150
+
151
+ ---
152
+
153
+ ## Quantization command
154
+
155
+ ```bash
156
+ auto-round \
157
+ --model_name tencent/HunyuanImage-3.0-Instruct-Distil \
158
+ --model_free \
159
+ --scheme MXFP8 \
160
+ --layer_config '{.mlp.experts.:{bits:4,data_type:mx_fp}}' \
161
+ --ignore_layers "vision,guidance_emb,timestep_emb,timestep_r_emb,final_layer,wte" \
162
+ --format auto_round \
163
+ --device cuda:0 \
164
+ --output_dir ./HunyuanImage-3.0-Instruct-Distil-MXFP4-ar
165
+
166
+ python tools/normalize_experts_extra_config_key.py ./HunyuanImage-3.0-Instruct-Distil-MXFP4-ar
167
+ ```
168
+
169
+ - Everything except `--format` is identical to the `-MXFP4-mixed` build.
170
+ - Do **not** add a bare `gate` to `--ignore_layers`: it expands to `.*gate.*` and silently swallows the
171
+ fused expert projections `gate_and_up_proj` (4096 tensors).
172
+ - The MoE router needs no entry: AutoRound hard-skips anything matching `.gate.`.
173
+ - `vision` must stay ignored: ViT `mlp.fc2` input dim 4304 is not divisible by the 32-element MX block.
174
+ - The run log echoes `Scheme: … bits=8` / `Packing format: mxfp8-quantized` — that is the **default**
175
+ scheme only, not evidence that `--layer_config` was ignored. Check the artifact instead
176
+ (`weight_packed` count must be 4096).
177
+
178
+ ---
179
+
180
+ ## Inference environment
181
+
182
+ | Component | Version |
183
+ |---|---|
184
+ | vLLM | **0.29.0** |
185
+ | vLLM-Omni | latest `main` (validated at `1c7476ec`, `0.29.0rc2.dev161+g1c7476ec1`, editable) |
186
+ | PyTorch | 2.13.0+cu132 |
187
+ | FlashInfer | 0.6.18 |
188
+ | GPU | NVIDIA H200 141 GB — AR-only 1×, DiT-only 2×, AR+DiT 2× |
189
+
190
+ ```bash
191
+ pip install vllm==0.29.0 && pip install -e /path/to/vllm-omni
192
+ python -c "import vllm, vllm_omni, os; print(vllm.__version__, os.path.dirname(vllm_omni.__file__))"
193
+
194
+ # host-specific, drop if unneeded here
195
+ export NCCL_NVLS_ENABLE=0
196
+ export VLLM_USE_FLASHINFER_SAMPLER=0
197
+ cd /tmp # cwd must be neutral: children re-import vllm_omni from cwd
198
+ ```
199
+
200
+ ---
201
+
202
+ ## Validated run modes (2 GPUs, cards 0 and 1)
203
+
204
+ | Mode | deploy YAML | Result | Evidence from logs |
205
+ |---|---|---|---|
206
+ | AR-only | `hunyuan_image3_ar_tp1.yaml` (TP1) | ✅ | `Model loading took 46.69 GiB`; MXFP4 MoE dispatch line above; text `It's a warm and healing style` (matches the `-mixed` and MXFP8 builds verbatim) |
207
+ | DiT-only | `hunyuan_image3_dit_tp2.yaml` (TP2) | ✅ image | `Model loading took 25.3899 GiB`/card; `Saved generated image …` (std 49.34) |
208
+ | AR+DiT | `hunyuan_image_3_moe_2gpu_tp1.yaml` (TP1+TP1) | ✅ image | both stages loaded (46.69 + 46.63 GiB); `Saved generated image …` (std 46.44) |
209
+
210
+ Before the metadata fix, **all three** failed with the `KeyError` quoted at the top.
211
+
212
+ ```bash
213
+ export CUDA_VISIBLE_DEVICES=0,1
214
+ cd /tmp
215
+ python /path/to/vllm-omni/examples/offline_inference/text_to_image/text_to_image.py \
216
+ --model /path/to/HunyuanImage-3.0-Instruct-Distil-MXFP4-ar \
217
+ --deploy-config ./hunyuan_image_3_moe_2gpu_tp1.yaml \
218
+ --prompt "A cute cat" \
219
+ --num-inference-steps 8 \
220
+ --guidance-scale 5.0 \
221
+ --seed 42 \
222
+ --output ./output.png
223
+ ```
224
+
225
+ The two-stage YAML (`stage 0` AR with `omni_kv_config.need_send_cache`, `stage 1` DiT with
226
+ `need_recv_cache`, joined by a `SharedMemoryConnector`) is reproduced in the sibling build's card;
227
+ `devices` are **local** indices, combine with `CUDA_VISIBLE_DEVICES`.
228
+
229
+ **Parameter notes** — `--num-inference-steps 8` (distilled: do not use 50); `--guidance-scale` is a real
230
+ input (`cfg_distilled=true`, vLLM-Omni feeds `1000 × guidance_scale` as the guidance embedding; the image
231
+ above used `5.0`, vLLM-Omni's Distil e2e reference uses `2.5`); `--prompt` reaches only the AR stage.
232
+
233
+ ---
234
+
235
+ ## Fidelity
236
+
237
+ ### Weight side — identical to the sibling build by construction
238
+
239
+ The tensors are byte-identical, so the dequantization error is the same:
240
+
241
+ | Module | scheme | rel. L2 vs BF16 | ≈ effective bits |
242
+ |---|---|---:|---:|
243
+ | routed experts `gate_and_up_proj` / `down_proj` | MXFP4 | **0.1120 – 0.1124** | 3.65 |
244
+ | `self_attn.*`, `shared_mlp.*` | MXFP8 | 0.0267 | 5.73 |
245
+ | router / ViT / VAE / embed (unquantized) | BF16/FP32 | 0.0000 | — |
246
+
247
+ MXFP4 experts carry **4.21×** the relative error of the MXFP8 group (**17.7×** in noise power) on
248
+ **93 %** of the parameters, and this equals the ideal per-group E8M0 search (optimized RTN) to four
249
+ decimals — i.e. it is the format's own floor, not a tuning miss.
250
+
251
+ ### Image side (DiT-only TP2 — topology matched, noise floor 41.4 dB)
252
+
253
+ | Candidate | vs BF16 PSNR | SSIM@1 | @1/2 | @1/4 | **@1/8** | std |
254
+ |---|---:|---:|---:|---:|---:|---:|
255
+ | MXFP8-ct (for reference) | 31.59 | 0.979 | 0.976 | 0.978 | 0.982 | 53.62 |
256
+ | **this build (INC path)** | **12.91** | **0.6698** | 0.5417 | 0.3910 | **0.2611** | 49.34 |
257
+ | sibling `-mixed` (CT path) | 12.99 | 0.6720 | 0.5449 | 0.3963 | 0.2707 | 48.86 |
258
+ | **this build vs `-mixed`** | **33.03** | 0.9799 | 0.9772 | 0.9758 | **0.9822 (flat)** | — |
259
+
260
+ | BF16 base (DiT TP2) | this build (DiT TP2) | sibling `-mixed` (DiT TP2) |
261
+ |---|---|---|
262
+ | ![bf16](images/bf16_dit_only_reference.png) | ![ar](images/dit_only_tp2.png) | ![mix](images/sibling_llm_compressor_dit_only.png) |
263
+
264
+ - SSIM **falls with coarser scale** vs BF16 ⇒ **composition-level divergence**, not a texture/style
265
+ shift. The image is a valid, un-degraded *different* picture of a cute cat.
266
+ - This build vs the sibling is **flat across scales** ⇒ same composition, small texture-level numeric
267
+ differences from the different kernel entry points.
268
+
269
+ ### Not measured
270
+
271
+ No task-level benchmark (GenEval / DPG-Bench / CVTG-2K / DrawBench) has been run for this build or for
272
+ the `-mixed` sibling. "Different composition" is measured; "worse quality" is not established.
273
+
274
+ ---
275
+
276
+ ## Known limitations
277
+
278
+ 1. **Requires the metadata fix** above; without it the checkpoint does not load at all (fails loudly,
279
+ which is preferable to loading silently with the wrong scheme).
280
+ 2. **Memory-only on Hopper** — experts run W4A16 through Marlin.
281
+ 3. **Composition diverges from BF16/MXFP8** (SSIM@1/8 ≈ 0.26); do not assume parity, and do not mix
282
+ outputs from this build with outputs from the `-mixed` build in one A/B comparison (33 dB apart).
283
+ 4. **The ViT stays BF16** (4304 % 32 ≠ 0) ⇒ not a whole-model MXFP4 build.
284
+ 5. The upstream INC matcher's MoE branch is keyed on a class name containing `fusedmoe`, which never
285
+ matches `RoutedExperts` on vLLM ≥ 0.29; this build works around the resulting brittleness by using an
286
+ explicit regex key. A cleaner fix belongs in AutoRound (emit a matchable key) or in the INC parser.
287
+ 6. `block_name_to_quantize = "model.layers"` scopes quantization to the 32 shared backbone layers; AR and
288
+ DiT load the same tensors through different stacks.
289
+ 7. `images/` holds verification snapshots only; it is not read when loading weights.
290
+
291
+ ## Contents
292
+
293
+ ```
294
+ config.json [FIXED] quant_method=auto-round + extra_config (221 entries)
295
+ config.json.pristine stock AutoRound export (key ".mlp.experts.") — fails to load
296
+ quantization_config.json [FIXED] flat secondary carrier, kept in sync
297
+ model-000NN-of-00032.safetensors 52.59 GB total
298
+ model.safetensors.index.json
299
+ tools/normalize_experts_extra_config_key.py apply / --check / --revert the fix
300
+ images/ verification snapshots
301
+ ar_dit_full_tp1x1.png AR+DiT, 2 GPUs
302
+ dit_only_tp2.png this build, DiT-only TP2
303
+ bf16_dit_only_reference.png BF16 base, DiT-only TP2
304
+ sibling_llm_compressor_dit_only.png -mixed build, DiT-only TP2
305
+ sibling_llm_compressor_ar_dit.png -mixed build, AR+DiT
306
+ *.py / tokenizer* / assets/ inherited from the base model
307
+ README_zh_CN.md upstream Chinese card (unchanged)
308
+ ```
README_zh_CN.md ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ pipeline_tag: image-to-image
4
+ ---
5
+
6
+
7
+ [English Documentation](./README.md)
8
+
9
+ <div align="center">
10
+
11
+ <img src="./assets/logo.png" alt="HunyuanImage-3.0 Logo" width="600">
12
+
13
+ # 🎨 HunyuanImage-3.0: 强大的原生多模态图像生成模型
14
+
15
+ </div>
16
+
17
+
18
+ <div align="center">
19
+ <img src="./assets/banner.png" alt="HunyuanImage-3.0 Banner" width="800">
20
+
21
+ </div>
22
+
23
+ <div align="center">
24
+ <a href=https://hunyuan.tencent.com/image target="_blank"><img src=https://img.shields.io/badge/Official%20Site-333399.svg?logo=homepage height=22px></a>
25
+ <a href=https://huggingface.co/tencent/HunyuanImage-3.0-Instruct-Distil target="_blank"><img src=https://img.shields.io/badge/%F0%9F%A4%97%20Models-d96902.svg height=22px></a>
26
+ <a href=https://github.com/Tencent-Hunyuan/HunyuanImage-3.0 target="_blank"><img src= https://img.shields.io/badge/Page-bb8a2e.svg?logo=github height=22px></a>
27
+ <a href=https://arxiv.org/pdf/2509.23951 target="_blank"><img src=https://img.shields.io/badge/Report-b5212f.svg?logo=arxiv height=22px></a>
28
+ <a href=https://x.com/TencentHunyuan target="_blank"><img src=https://img.shields.io/badge/Hunyuan-black.svg?logo=x height=22px></a>
29
+ <a href=https://docs.qq.com/doc/DUVVadmhCdG9qRXBU target="_blank"><img src=https://img.shields.io/badge/📚-提示词手册-blue.svg?logo=book height=22px></a>
30
+ </div>
31
+
32
+
33
+ <p align="center">
34
+ 👏 加入我们的 <a href="./assets/WECHAT.md" target="_blank">微信</a> 和 <a href="https://discord.gg/ehjWMqF5wY">Discord</a> |
35
+ 💻 <a href="https://hunyuan.tencent.com/chat/HunyuanDefault?from=modelSquare&modelId=Hunyuan-Image-3.0-Instruct">官网试用我们的模型!</a>&nbsp&nbsp
36
+ </p>
37
+
38
+ ## 🔥🔥🔥 最新消息
39
+
40
+ - **2026年1月26日**: 🚀 **[HunyuanImage-3.0-Instruct-Distil](https://huggingface.co/tencent/HunyuanImage-3.0-Instruct-Distil)** - 蒸馏版本用于高效部署(推荐8步采样)。
41
+ - **2026年1月26日**: 🎉 **[HunyuanImage-3.0-Instruct](https://huggingface.co/tencent/HunyuanImage-3.0-Instruct)** - 发布了 **Instruct(带推理能力)**版本,支持智能提示词增强和**图像到图像**生成用于创意编辑。
42
+ - **2025年10月30日**: 🚀 **[HunyuanImage-3.0 vLLM 加速](./vllm_infer/README.md)** - 通过 vLLM 支持实现显著更快的推理速度。
43
+ - **2025年09月28日**: 📖 **[HunyuanImage-3.0 技术报告](https://arxiv.org/pdf/2509.23951)** - 全面的技术文档现已发布。
44
+ - **2025年09月28日**: 🎉 **[HunyuanImage-3.0 开源](https://github.com/Tencent-Hunyuan/HunyuanImage-3.0)** - 推理代码和模型权重现已公开可用。
45
+
46
+
47
+ ## 🧩 社区贡献
48
+
49
+ 如果您在项目中使用或开发了 HunyuanImage-3.0,欢迎告知我们。
50
+
51
+ ## 📑 开源计划
52
+
53
+ - HunyuanImage-3.0 (图像生成模型)
54
+ - [x] 推理代码
55
+ - [x] HunyuanImage-3.0 模型权重
56
+ - [x] HunyuanImage-3.0-Instruct 模型权重(带推理能力)
57
+ - [x] vLLM 支持
58
+ - [x] 蒸馏版本权重
59
+ - [x] 图像到图像生成
60
+ - [ ] 多轮交互能力
61
+
62
+
63
+ ## 🗂️ 目录
64
+ - [🔥🔥🔥 最新消息](#-最新消息)
65
+ - [🧩 社区贡献](#-社区贡献)
66
+ - [📑 开源计划](#-开源计划)
67
+ - [📖 概览](#-概览)
68
+ - [✨ 模型亮点](#-模型亮点)
69
+ - [🚀 使用方法](#-使用方法)
70
+ - [📦 环境配置](#-环境配置)
71
+ - [📥 安装依赖](#-安装依赖)
72
+ - [HunyuanImage-3.0-Instruct](#hunyuanimage-30-instruct-指令推理和图像到图像生成包括编辑和多图像融合)
73
+ - [🔥 使用 Transformers 快速开始](#-使用-transformers-快速开始)
74
+ - [1️⃣ 下载模型权重](#1-下载模型权重)
75
+ - [2️⃣ 使用 Transformers 运行](#2-使用-transformers-运行)
76
+ - [🏠 本地安装和使用](#-本地安装和使用)
77
+ - [1️⃣ 克隆仓库](#1-克隆仓库)
78
+ - [2️⃣ 下载模型权重](#2-下载模型权重)
79
+ - [3️⃣ 运行演示](#3-运行演示)
80
+ - [4️⃣ 命令行参数](#4-命令行参数)
81
+ - [5️⃣ 更少的采样步数](#5-更少的采样步数)
82
+ - [HunyuanImage-3.0 (文本生成图像)](#hunyuanimage-30-文本生成图像)
83
+ - [📥 安装依赖](#-安装依赖-1)
84
+ - [🔥 使用 Transformers 快速开始](#-使用-transformers-快速开始-1)
85
+ - [1️⃣ 下载模型权重](#1-下载模型权重-1)
86
+ - [2️⃣ 使用 Transformers 运行](#2-使用-transformers-运行-1)
87
+ - [🏠 本地安装和使用](#-本地安装和使用-1)
88
+ - [1️⃣ 克隆仓库](#1-克隆仓库-1)
89
+ - [2️⃣ 下载模型权重](#2-下载模型权重-1)
90
+ - [3️⃣ 运行演示](#3-运行演示-1)
91
+ - [4️⃣ 命令行参数](#4-命令行参数-1)
92
+ - [🎨 交互式 Gradio 演示](#-交互式-gradio-演示)
93
+ - [1️⃣ 安装 Gradio](#1-安装-gradio)
94
+ - [2️⃣ 配置环境](#2-配置环境)
95
+ - [3️⃣ 启动 Web 界面](#3-启动-web-界面)
96
+ - [4️⃣ 访问界面](#4-访问界面)
97
+ - [🧱 模型卡片](#-模型卡片)
98
+ - [📊 评估结果](#-评估结果)
99
+ - [HunyuanImage-3.0-Instruct 评估](#hunyuanimage-30-instruct-评估)
100
+ - [HunyuanImage-3.0 评估](#hunyuanimage-30-评估)
101
+ - [🖼️ 展示](#-展示)
102
+ - [HunyuanImage-3.0-Instruct 展示](#hunyuanimage-30-instruct-展示)
103
+ - [📚 引用](#-引用)
104
+ - [🙏 致谢](#-致谢)
105
+ - [🌟🚀 GitHub Star 历史](#-github-star-历史)
106
+
107
+ ---
108
+
109
+ ## 📖 概览
110
+
111
+ **HunyuanImage-3.0** 是一个突破性的原生多模态模型,它在自回归框架内统一了多模态理解和生成任务。它的文生图和图生图能力实现了与领先的闭源模型**相当或更优**的性能。
112
+
113
+
114
+ <div align="center">
115
+ <img src="./assets/framework.png" alt="HunyuanImage-3.0 Framework" width="90%">
116
+ </div>
117
+
118
+ ## ✨ 模型亮点
119
+
120
+ * 🧠 **统一的多模态架构:** HunyuanImage-3.0 突破当前主流的 DiT 架构,采用统一的自回归框架。该设计能更直接、统一地对文本与图像模态进行建模,实现了语义理解与图像生成的高度融合,从而生成效果惊人、语境丰富的图像。
121
+
122
+ * 🏆 **最大规模图像生成MoE模型:** 作为当前开源社区参数规模最大的图像生成 MoE 模型,其拥有64个专家、总参数量达 800 亿,单 token 激活 130 亿参数,显著提升了模型容量与性能表现。
123
+
124
+ * 🎨 **卓越的图像生成质量:** 通过精细的数据集构建与强化学习后训练,我们在语义准确性与视觉表现力间取得最佳平衡。该模型不仅能精准遵循提示词要求,更可生成细节丰富、具有摄影级真实感与艺术美感的图像。
125
+
126
+ * 💭 **智能图像理解与世界知识推理:** 得益于统一的多模态架构,HunyuanImage-3.0 拥有强大的推理能力。它不仅能深度理解用户输入的图像,还能利用其海量的世界知识精准解读用户意图。针对简略的提示词(prompts),它能够自动补全符合语境的细节,从而生成更出色、更完整的视觉作品。
127
+
128
+
129
+ ## 🚀 使用方法
130
+
131
+ ### 📦 环境配置
132
+
133
+ * 🐍 **Python:** 3.12+ (推荐并已测试)
134
+ * ⚡ **CUDA:** 12.8
135
+
136
+ #### 📥 安装依赖
137
+
138
+ ```bash
139
+ # 1. 首先安装 PyTorch (CUDA 12.8 版本)
140
+ pip install torch==2.8.0 torchvision==0.23.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cu128
141
+
142
+ # 2. 安装 tencentcloud-sdk
143
+ pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python
144
+
145
+ # 3. 然后安装其他依赖
146
+ pip install -r requirements.txt
147
+ ```
148
+
149
+ 为了**获得多达3倍的推理加速**,请安装以下优化:
150
+
151
+ ```bash
152
+ # FlashInfer 用于优化的 moe 推理。v0.5.0 已测试。
153
+ pip install flashinfer-python==0.5.0
154
+ ```
155
+ > 💡**安装提示:** PyTorch 使用的 CUDA 版本必须与系统的 CUDA 版本匹配,这一点至关重要。
156
+ > FlashInfer 依赖此兼容性在运行时编译内核。
157
+ > 推荐使用 GCC 版本 >=9 来编译 FlashAttention 和 FlashInfer。
158
+
159
+ > ⚡ **性能提示:** 这些优化可以显著加快您的推理速度!
160
+
161
+ > 💡**注意:** 启用 FlashInfer 时,首次推理可能会较慢(约 10 分钟),因为需要编译内核。在同一台机器上的后续推理会快得多。
162
+
163
+ ### HunyuanImage-3.0-Instruct (指令推理和图像到图像生成,包括编辑和多图像融合)
164
+
165
+ #### 🔥 使用 Transformers 快速开始
166
+
167
+ ##### 1️⃣ 下载模型权重
168
+
169
+ ```bash
170
+ # 从 HuggingFace 下载并重命名目录。
171
+ # 注意目录名称不应包含点号,否则使用 Transformers 加载时可能出现问题。
172
+ hf download tencent/HunyuanImage-3.0-Instruct-Distil --local-dir ./HunyuanImage-3-Instruct-Distil
173
+ ```
174
+
175
+ ##### 2️⃣ 使用 Transformers 运行
176
+
177
+ ```python
178
+ from transformers import AutoModelForCausalLM
179
+
180
+ # 加载模型
181
+ model_id = "./HunyuanImage-3-Instruct-Distil"
182
+ # 目前我们无法使用 HF 模型 ID `tencent/HunyuanImage-3.0-Instruct-Distil` 直接加载模型
183
+ # 因为名称中包含点号。
184
+
185
+ kwargs = dict(
186
+ attn_implementation="sdpa",
187
+ trust_remote_code=True,
188
+ torch_dtype="auto",
189
+ device_map="auto",
190
+ moe_impl="eager", # 如果已安装 FlashInfer,可使用 "flashinfer"
191
+ moe_drop_tokens=True,
192
+ )
193
+
194
+ model = AutoModelForCausalLM.from_pretrained(model_id, **kwargs)
195
+ model.load_tokenizer(model_id)
196
+
197
+ # 图像到图像生成 (TI2I)
198
+ prompt = "基于图一的logo,参考图二中冰箱贴的材质,制作一个新的冰箱贴"
199
+
200
+ input_img1 = "./assets/demo_instruct_imgs/input_1_0.png"
201
+ input_img2 = "./assets/demo_instruct_imgs/input_1_1.png"
202
+ imgs_input = [input_img1, input_img2]
203
+
204
+ cot_text, samples = model.generate_image(
205
+ prompt=prompt,
206
+ image=imgs_input,
207
+ seed=42,
208
+ image_size="auto",
209
+ use_system_prompt="en_unified",
210
+ bot_task="think_recaption", # 使用 "think_recaption" 进行推理和增强
211
+ infer_align_image_size=True, # 将输出图像大小对齐到输入图像大小
212
+ diff_infer_steps=8,
213
+ verbose=2
214
+ )
215
+
216
+ # 保存生成的图像
217
+ samples[0].save("image_edit.png")
218
+ ```
219
+
220
+ ##### 4️⃣ 命令行参数
221
+
222
+ | 参数 | 说明 | 推荐值 |
223
+ |----------------------|------------------------------------------------|-------------|
224
+ | `--prompt` | 输入提示词 | (必填) |
225
+ | `--image` | 要处理的图像。多个图像使用逗号分隔的路径(例如 'img1.png,img2.png') | (必填) |
226
+ | `--model-id` | 模型路径 | (必填) |
227
+ | `--attn-impl` | Attention 实现方式。目前仅支持 'sdpa' | `sdpa` |
228
+ | `--moe-impl` | MoE 实现方式。可选 `eager` 或 `flashinfer` | `flashinfer` |
229
+ | `--seed` | 图像生成的随机种子。使用 None 表示随机种子 | `None` |
230
+ | `--diff-infer-steps` | 推理步数 | `50` |
231
+ | `--image-size` | 图像分辨率。可以是 `auto`、`1280x768` 或 `16:9` | `auto` |
232
+ | `--use-system-prompt` | 系统提示词类型。选项:`None`、`dynamic`、`en_vanilla`、`en_recaption`、`en_think_recaption`、`en_unified`、`custom` | `en_unified` |
233
+ | `--system-prompt` | 自定义系统提示词。当 `--use-system-prompt` 为 `custom` 时使用 | `None` |
234
+ | `--bot-task` | 任务类型。`image` 用于直接生成;`auto` 用于文本;`recaption` 用于重写->图像;`think_recaption` 用于思考->重写->图像 | `think_recaption` |
235
+ | `--save` | 图像保存路径 | `image.png` |
236
+ | `--verbose` | 详细程度 | `2` |
237
+ | `--reproduce` | 是否复现结果 | `True` |
238
+ | `--infer-align-image-size` | 是否将目标图像大小对齐到源图像大小 | `True` |
239
+ | `--max_new_tokens` | 生成的最大 token 数 | `2048` |
240
+ | `--use-taylor-cache` | 采样时使用 Taylor Cache | `False` |
241
+
242
+
243
+ <details>
244
+ <summary> 先前版本(纯文本生成图像) </summary>
245
+
246
+ ### HunyuanImage-3.0 (文本生成图像)
247
+
248
+ #### 📥 安装依赖
249
+
250
+ ```bash
251
+ # 1. 首先安装 PyTorch (CUDA 12.8 版本)
252
+ pip install torch==2.8.0 torchvision==0.23.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cu128
253
+
254
+ # 2. 安装 tencentcloud-sdk
255
+ pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python
256
+
257
+ # 3. 然后安装其他依赖
258
+ pip install -r requirements.txt
259
+ ```
260
+
261
+ 为了**获得多达3倍的推理加速**,请安装以下优化:
262
+
263
+ ```bash
264
+ # FlashInfer 用于优化的 moe 推理。v0.5.0 已测试。
265
+ pip install flashinfer-python==0.5.0
266
+ ```
267
+
268
+ #### 🔥 使用 Transformers 快速开始
269
+
270
+ ##### 1️⃣ 下载模型权重
271
+
272
+ ```bash
273
+ # 从 HuggingFace 下载并重命名目录。
274
+ # 注意目录名称不应包含点号,否则使用 Transformers 加载时可能出现问题。
275
+ hf download tencent/HunyuanImage-3.0 --local-dir ./HunyuanImage-3
276
+ ```
277
+
278
+ ##### 2️⃣ 使用 Transformers 运行
279
+
280
+ ```python
281
+ from transformers import AutoModelForCausalLM
282
+
283
+ # 加载模型
284
+ model_id = "./HunyuanImage-3"
285
+ # 目前我们无法使用 HF 模型 ID `tencent/HunyuanImage-3.0` 直接加载模型
286
+ # 因为名称中包含点号。
287
+
288
+ kwargs = dict(
289
+ attn_implementation="sdpa", # 如果已安装 FlashAttention,可使用 "flash_attention_2"
290
+ trust_remote_code=True,
291
+ torch_dtype="auto",
292
+ device_map="auto",
293
+ moe_impl="eager", # 如果已安装 FlashInfer,可使用 "flashinfer"
294
+ )
295
+
296
+ model = AutoModelForCausalLM.from_pretrained(model_id, **kwargs)
297
+ model.load_tokenizer(model_id)
298
+
299
+ # 生成图像
300
+ prompt = "一只棕色和白色相间的小狗奔跑在草地上"
301
+ image = model.generate_image(prompt=prompt, stream=True)
302
+ image.save("image.png")
303
+ ```
304
+
305
+ #### 🏠 本地安装和使用
306
+
307
+ ##### 1️⃣ 克隆仓库
308
+
309
+ ```bash
310
+ git clone https://github.com/Tencent-Hunyuan/HunyuanImage-3.0.git
311
+ cd HunyuanImage-3.0/
312
+ ```
313
+
314
+ ##### 2️⃣ 下载模型权重
315
+
316
+ ```bash
317
+ # 从 HuggingFace 下载
318
+ hf download tencent/HunyuanImage-3.0 --local-dir ./HunyuanImage-3
319
+ ```
320
+
321
+ ##### 3️⃣ 运行演示
322
+
323
+ 预训练检查点不会自动重写或增强输入提示词,为了获得最佳效果,我们目前建议社区伙伴使用 deepseek 来重写提示词。您可以前往[腾讯云](https://cloud.tencent.com/document/product/1772/115963#.E5.BF.AB.E9.80.9F.E6.8E.A5.E5.85.A5)申请 API Key。
324
+
325
+ ```bash
326
+ # 设置环境变量
327
+ export DEEPSEEK_KEY_ID="your_deepseek_key_id"
328
+ export DEEPSEEK_KEY_SECRET="your_deepseek_key_secret"
329
+
330
+ bash run_demo.sh
331
+ ```
332
+
333
+ ##### 4️⃣ 命令行参数
334
+
335
+ | 参数 | 说明 | 推荐值 |
336
+ |----------------------|------------------------------------------------|-------------|
337
+ | `--prompt` | 输入提示词 | (必填) |
338
+ | `--model-id` | 模型路径 | (必填) |
339
+ | `--attn-impl` | Attention 实现方式。可选 `sdpa` 或 `flash_attention_2` | `sdpa` |
340
+ | `--moe-impl` | MoE 实现方式。可选 `eager` 或 `flashinfer` | `flashinfer` |
341
+ | `--seed` | 图像生成的随机种子 | `None` |
342
+ | `--diff-infer-steps` | Diffusion 推理步数 | `50` |
343
+ | `--image-size` | 图像分辨率。可以是 `auto`、`1280x768` 或 `16:9` | `auto` |
344
+ | `--save` | 图像保存路径 | `image.png` |
345
+ | `--verbose` | 详细程度。0: 无日志;1: 记录推理信息。 | `0` |
346
+ | `--rewrite` | 是否启用重写 | `1` |
347
+ | `--sys-deepseek-prompt` | 从 `universal` 或 `text_rendering` 中选择系统提示词 | `universal` |
348
+
349
+ #### 🎨 交互式 Gradio 演示
350
+
351
+ 启动交互式 Web 界面,方便进行文本到图像生成。
352
+
353
+ ##### 1️⃣ 安装 Gradio
354
+
355
+ ```bash
356
+ pip install gradio>=4.21.0
357
+ ```
358
+
359
+ ##### 2️⃣ 配置环境
360
+
361
+ ```bash
362
+ # 设置您的模型路径
363
+ export MODEL_ID="path/to/your/model"
364
+
365
+ # 可选:配置 GPU 使用(默认:0,1,2,3)
366
+ export GPUS="0,1,2,3"
367
+
368
+ # 可选:配置主机和端口(默认:0.0.0.0:443)
369
+ export HOST="0.0.0.0"
370
+ export PORT="443"
371
+ ```
372
+
373
+ ##### 3️⃣ 启动 Web 界面
374
+
375
+ **基础启动:**
376
+ ```bash
377
+ sh run_app.sh
378
+ ```
379
+
380
+ **使用性能优化:**
381
+ ```bash
382
+ # 同时使用两种优化以获得最佳性能
383
+ sh run_app.sh --moe-impl flashinfer --attn-impl flash_attention_2
384
+ ```
385
+
386
+ ##### 4️⃣ 访问界面
387
+
388
+ > 🌐 **Web 界面:** 打开浏览器并访问 `http://localhost:443`(或您配置的端口)
389
+
390
+ </details>
391
+
392
+ ## 🧱 模型卡片
393
+
394
+ | 模型 | 参数量 | 下载地址 | 推荐显存 | 支持功能 |
395
+ |---------------------------| --- | --- | --- | --- |
396
+ | HunyuanImage-3.0 | 总计 80B (激活 13B) | [HuggingFace](https://huggingface.co/tencent/HunyuanImage-3.0) | ≥ 3 × 80 GB | ✅ 文本生成图像
397
+ | HunyuanImage-3.0-Instruct | 总计 80B (激活 13B) | [HuggingFace](https://huggingface.co/tencent/HunyuanImage-3.0-Instruct) | ≥ 8 × 80 GB | ✅ 文本生成图像<br>✅ 文本图像到图像<br>✅ 提示词自动重写 <br>✅ CoT 思考
398
+ | HunyuanImage-3.0-Instruct-Distil | 总计 80B (激活 13B) | [HuggingFace](https://huggingface.co/tencent/HunyuanImage-3.0-Instruct-Distil) | ≥ 8 × 80 GB |✅ 文本生成图像<br>✅ 文本图像到图像<br>✅ 提示词自动重写 <br>✅ CoT 思考 <br>✅ 更少的采样步数(推荐 8 步)
399
+
400
+ 注意事项:
401
+ - 安装性能优化工具(FlashAttention、FlashInfer)以获得更快的推理速度。
402
+ - 基础模型推荐使用多 GPU 推理。
403
+
404
+ ## 📊 评估结果
405
+
406
+ ### HunyuanImage-3.0-Instruct 评估
407
+ * 👥 **GSB (人工评估)**
408
+ 我们采用了 GSB(好/相同/差)评估方法,该方法通常用于从整体图像感知角度评估两个模型之间的相对性能。我们总共使用了 1000+ 个单图像和多图像编辑案例,在一次运行中为所有比较的模型生成相等数量的图像样本。为了公平比较,我们对每个提示词只进行一次推理,避免任何结果筛选。在与基线方法比较时,我们保持了所有选定模型的默认设置。评估由 100 多名专业评估员执行。
409
+
410
+ <p align="center">
411
+ <img src="./assets/gsb_instruct.png" width=60% alt="Human Evaluation with Other Models">
412
+ </p>
413
+
414
+
415
+ ### HunyuanImage-3.0 评估
416
+
417
+ * 🤖 **SSAE (机器评估)**
418
+ SSAE(结构化语义对齐评估)是一种基于先进多模态大语言模型(MLLMs)的图像-文本对齐智能评估指标。我们提取了 12 个类别的 3500 个关键点,然后使用多模态大语言模型通过将生成的图像与这些关键点进行比较,基于图像的视觉内容自动评估和打分。平均图像准确率表示所有关键点的图像级平均分数,而全局准确率直接计算所有关键点的平均分数。
419
+
420
+ <p align="center">
421
+ <img src="./assets/ssae_side_by_side_comparison.png" width=98% alt="Human Evaluation with Other Models">
422
+ </p>
423
+
424
+ <p align="center">
425
+ <img src="./assets/ssae_side_by_side_heatmap.png" width=98% alt="Human Evaluation with Other Models">
426
+ </p>
427
+
428
+
429
+ * 👥 **GSB (人工评估)**
430
+
431
+ 我们采用了 GSB(好/相同/差)评估方法,该方法通常用于从整体图像感知角度评估两个模型之间的相对性能。我们总共使用了 1000 个文本提示词,在一次运行中为所有比较的模型生成相等数量的图像样本。为了公平比较,我们对每个提示词只进行一次推理,避免任何结果筛选。在与基线方法比较时,我们保持了所有选定模型的默认设置。评估由 100 多名专业评估员执行。
432
+
433
+ <p align="center">
434
+ <img src="./assets/gsb.png" width=98% alt="Human Evaluation with Other Models">
435
+ </p>
436
+
437
+ ## 🖼️ 展示
438
+
439
+ 我们的模型可以遵循复杂��令生成高质量、富有创意的图像。
440
+
441
+ <div align="center">
442
+ <img src="./assets/banner_all.jpg" width=100% alt="HunyuanImage 3.0 Demo">
443
+ </div>
444
+
445
+ 文本生成图像的展示,请点击以下链接:
446
+
447
+ - [HunyuanImage-3.0](./Hunyuan-Image3.md)
448
+
449
+ ### HunyuanImage-3.0-Instruct 展示
450
+
451
+ HunyuanImage-3.0-Instruct 展示了在智能图像生成和编辑方面的强大能力。以下展示突出了其核心功能:
452
+
453
+ * 🧠 **智能视觉理解与推理(CoT Think)**: 模型执行结构化思考,分析用户输入的图像和提示词,将用户的意图和编辑任务扩展为结构化、全面的指令,从而带来更好的图像生成和编辑表现。
454
+
455
+ 将复杂的提示词和编辑任务分解为详细的视觉组件,包括主体、构图、光照、色彩搭配和风格。
456
+
457
+ * ✏️ **提示词自动重写**: 自动将稀疏或模糊的提示词增强为专业级、细节丰富的描述,更准确地捕捉用户意图。
458
+
459
+ * 🎨 **文本生成图像(T2I)**: 从文本提示词生成高质量图像,具有出色的提示词遵循度和照片级真实感。
460
+
461
+ * 🖼️ **图像到图像(TI2I)**: 支持创意图像编辑,包括添加元素、移除对象、修改风格和无缝背景替换,同时保留关键视觉元素。
462
+
463
+ * 🔀 **多图像融合**: 智能组合多个参考图像(最多3个参考图输入),创建融合来自不同来源的视觉元素的连贯合成图像。
464
+
465
+
466
+ **展示 1: 详细的思考和推理过程**
467
+
468
+ <div align="center">
469
+ <img src="./assets/pg_instruct_imgs/cot_ti2i.gif" alt="HunyuanImage-3.0-Instruct Showcase 1" width="90%">
470
+ </div>
471
+
472
+ **展示 2: 具有复杂场景理解的创意 T2I 生成**
473
+
474
+ > Prompt: 3D 毛绒质感拟人化马,暖棕浅棕肌理,穿藏蓝西装、白衬衫,戴深棕手套;疲惫带期待,坐于电脑前,旁置印 "HAPPY AGAIN" 的马克杯。橙红渐变背景,配超大号藏蓝粗体 "马上下班",叠加米黄 "Happy New Year" 并标 "(2026)"。橙红为主,藏蓝米黄撞色,毛绒温暖柔和。
475
+
476
+ <div align="center">
477
+ <img src="./assets/pg_instruct_imgs/image0.png" alt="HunyuanImage-3.0-Instruct Showcase 2" width="75%">
478
+ </div>
479
+
480
+ **展示 3: 精确图像编辑与元素保留**
481
+
482
+ <div align="center">
483
+ <img src="./assets/pg_instruct_imgs/image1.png" alt="HunyuanImage-3.0-Instruct Showcase 3" width="85%">
484
+ </div>
485
+
486
+ **展示 4: 风格转换与主题增强**
487
+
488
+ <div align="center">
489
+ <img src="./assets/pg_instruct_imgs/image2.png" alt="HunyuanImage-3.0-Instruct Showcase 4" width="85%">
490
+ </div>
491
+
492
+
493
+ **展示 5: 高级风格转换与产品效果图生成**
494
+
495
+ <div align="center">
496
+ <img src="./assets/pg_instruct_imgs/image3.png" alt="HunyuanImage-3.0-Instruct Showcase 5" width="85%">
497
+ </div>
498
+
499
+
500
+ **展示 6: 多图像融合与创意合成**
501
+
502
+ <div align="center">
503
+ <img src="./assets/pg_instruct_imgs/image4.png" alt="HunyuanImage-3.0-Instruct Showcase 6" width="85%">
504
+ </div>
505
+
506
+ ## 📚 引用
507
+
508
+ 如果您在研究中发现 HunyuanImage-3.0 有用,请引用我们的工作:
509
+
510
+ ```bibtex
511
+ @article{cao2025hunyuanimage,
512
+ title={HunyuanImage 3.0 Technical Report},
513
+ author={Cao, Siyu and Chen, Hangting and Chen, Peng and Cheng, Yiji and Cui, Yutao and Deng, Xinchi and Dong, Ying and Gong, Kipper and Gu, Tianpeng and Gu, Xiusen and others},
514
+ journal={arXiv preprint arXiv:2509.23951},
515
+ year={2025}
516
+ }
517
+ ```
518
+
519
+ ## 🙏 致谢
520
+
521
+ 我们衷心感谢以下开源项目和社区的宝贵贡献:
522
+
523
+ * 🤗 [Transformers](https://github.com/huggingface/transformers) - 最先进的 NLP 库
524
+ * 🎨 [Diffusers](https://github.com/huggingface/diffusers) - 扩散模型库
525
+ * 🌐 [HuggingFace](https://huggingface.co/) - AI 模型中心和社区
526
+ * ⚡ [FlashAttention](https://github.com/Dao-AILab/flash-attention) - 内存高效的注意力机制
527
+ * 🚀 [FlashInfer](https://github.com/flashinfer-ai/flashinfer) - 优化的推理引擎
528
+
529
+ ## 🌟🚀 GitHub Star 历史
530
+
531
+ [![GitHub stars](https://img.shields.io/github/stars/Tencent-Hunyuan/HunyuanImage-3.0?style=social)](https://github.com/Tencent-Hunyuan/HunyuanImage-3.0)
532
+ [![GitHub forks](https://img.shields.io/github/forks/Tencent-Hunyuan/HunyuanImage-3.0?style=social)](https://github.com/Tencent-Hunyuan/HunyuanImage-3.0)
533
+
534
+ [![Star History Chart](https://api.star-history.com/svg?repos=Tencent-Hunyuan/HunyuanImage-3.0&type=Date)](https://www.star-history.com/#Tencent-Hunyuan/HunyuanImage-3.0&Date)
__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING
2
+
3
+ from utils import _LazyModule
4
+ from utils.import_utils import define_import_structure
5
+
6
+
7
+ if TYPE_CHECKING:
8
+ from .configuration_hunyuan_image_3 import *
9
+ from .modeling_hunyuan_image_3 import *
10
+ from .autoencoder_kl_3d import *
11
+ from .image_processor import *
12
+ from .siglip2 import *
13
+ from .tokenization_hunyuan_image_3 import *
14
+ else:
15
+ import sys
16
+
17
+ _file = globals()["__file__"]
18
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
assets/WECHAT.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <img src=wechat.png width="60%"/>
3
+
4
+ <p> 扫码关注混元图像系列工作,加入「 腾讯混元生图交流群 」 </p>
5
+ <p> Scan the QR code to join the "Tencent Hunyuan Image Generation Discussion Group" </p>
6
+ </div>
assets/banner.png ADDED

Git LFS Details

  • SHA256: 53bef578e373fc53c8c16d26a1011f85ce8d4f46aeac1222be7263a09a3d8c7f
  • Pointer size: 132 Bytes
  • Size of remote file: 1.41 MB
assets/banner_all.jpg ADDED

Git LFS Details

  • SHA256: 667e956a3c27f6722eceacebe907b56b6669cc35b706a4957893b7ae88b7fbc0
  • Pointer size: 133 Bytes
  • Size of remote file: 15.3 MB
assets/demo_instruct_imgs/input_0_0.png ADDED

Git LFS Details

  • SHA256: 36d373a42642830e6cbe5f71b4da058bda52e074191342c94d00959103d9bdf7
  • Pointer size: 132 Bytes
  • Size of remote file: 1.05 MB
assets/demo_instruct_imgs/input_1_0.png ADDED
assets/demo_instruct_imgs/input_1_1.png ADDED

Git LFS Details

  • SHA256: fd1ba82af0f6374c52cfd412f142817a9b1516ab769d7b05eb6774201e8ff3d6
  • Pointer size: 132 Bytes
  • Size of remote file: 1.19 MB
assets/demo_instruct_imgs/input_2_0.png ADDED

Git LFS Details

  • SHA256: d95260cb9efed53907d9964b73c4335427bd981cf2cf04a19c250973597df86e
  • Pointer size: 131 Bytes
  • Size of remote file: 111 kB
assets/demo_instruct_imgs/input_2_1.png ADDED

Git LFS Details

  • SHA256: 7828363e20b7b0faa7fa19d2c58ce335c931125a668345726070e7943166a07f
  • Pointer size: 131 Bytes
  • Size of remote file: 955 kB
assets/demo_instruct_imgs/input_2_2.png ADDED

Git LFS Details

  • SHA256: b977d8ed0f9dc2f37378947e91d5af97c65a3240261f9758ab1db89be6a02516
  • Pointer size: 131 Bytes
  • Size of remote file: 191 kB
assets/framework.png ADDED

Git LFS Details

  • SHA256: f6c0e6751b4bf0f30daeb6a2b7cdb4dc3276bd61ea58294ba528fd807a17473f
  • Pointer size: 131 Bytes
  • Size of remote file: 248 kB
assets/gsb.png ADDED

Git LFS Details

  • SHA256: 8570c87bbb477e206f61d99c036a53d3671dc589829b335656931dcf01194536
  • Pointer size: 131 Bytes
  • Size of remote file: 191 kB
assets/gsb_instruct.png ADDED
assets/logo.png ADDED
assets/pg_imgs/image1.png ADDED

Git LFS Details

  • SHA256: a385db722efc89cff4d5e4afdb82c96156f223907d70f0d3c7eb8b3e59edbccb
  • Pointer size: 132 Bytes
  • Size of remote file: 1.64 MB
assets/pg_imgs/image2.png ADDED

Git LFS Details

  • SHA256: 84a7d37d3ff8452c32ecb79f98692ad38f8f190dc201922a924ae2fda4515e12
  • Pointer size: 132 Bytes
  • Size of remote file: 1.7 MB
assets/pg_imgs/image3.png ADDED

Git LFS Details

  • SHA256: 913376a1ad5d10bc1549f9f28fc25a0c9f94a119b99434618bacacc7429996fa
  • Pointer size: 132 Bytes
  • Size of remote file: 1.39 MB
assets/pg_imgs/image4.png ADDED

Git LFS Details

  • SHA256: 71dcfd968f4c76ccec2ccc1806e9ce97babed56c73441d744f7264433bf9339a
  • Pointer size: 132 Bytes
  • Size of remote file: 1.55 MB
assets/pg_imgs/image5.png ADDED

Git LFS Details

  • SHA256: b93338e2f81f9809f8a9f674e0fe3da7c03de4fc4d7aba1819acb878384abb3e
  • Pointer size: 132 Bytes
  • Size of remote file: 3.31 MB
assets/pg_imgs/image6.png ADDED

Git LFS Details

  • SHA256: 84e7c73dafea831bf1ceb8c3dd76c16238c9b4a31ac30e3f46c38d61005b5895
  • Pointer size: 132 Bytes
  • Size of remote file: 2.02 MB
assets/pg_imgs/image7.png ADDED

Git LFS Details

  • SHA256: 701f2449436f8d46f537100bdaa63569586e39448e30fffe2e5bc3e95e558daa
  • Pointer size: 132 Bytes
  • Size of remote file: 1.55 MB
assets/pg_imgs/image8.png ADDED

Git LFS Details

  • SHA256: b80b97174d4f98030eda02d5dbaac2e294d814f086d957d47957482eb7b70251
  • Pointer size: 132 Bytes
  • Size of remote file: 1.27 MB
assets/pg_instruct_imgs/cot_ti2i.gif ADDED

Git LFS Details

  • SHA256: ee9c34030c17aa2b56557ea2f6080d99db85627fbb1f314f437e8541560d6190
  • Pointer size: 133 Bytes
  • Size of remote file: 43.5 MB
assets/pg_instruct_imgs/image0.png ADDED

Git LFS Details

  • SHA256: 54de287f7fc6e982a358fac0b29ef901c31ed06baac39919d516c976f20a633f
  • Pointer size: 132 Bytes
  • Size of remote file: 1.44 MB
assets/pg_instruct_imgs/image1.png ADDED

Git LFS Details

  • SHA256: ed594219f6043c1ce01e4c5f659a376fad53f7df79cdc2a3bc6b7cd27aa2cea1
  • Pointer size: 132 Bytes
  • Size of remote file: 2.03 MB
assets/pg_instruct_imgs/image2.png ADDED

Git LFS Details

  • SHA256: 9cf7a4233e0acbb0cd2454646d4f5a72327196b8e5515ca7c3932238b7d71128
  • Pointer size: 132 Bytes
  • Size of remote file: 2.13 MB
assets/pg_instruct_imgs/image3.png ADDED

Git LFS Details

  • SHA256: 9ff765ee0821eec5abc6c6c4d07be27be8188e8c46df067b613e047319375aeb
  • Pointer size: 132 Bytes
  • Size of remote file: 2.1 MB
assets/pg_instruct_imgs/image4.png ADDED

Git LFS Details

  • SHA256: 484c711acfeb0fe34169d0dee4d6e2f47b56cd00d3301f2261b1325bcd226c28
  • Pointer size: 132 Bytes
  • Size of remote file: 2.54 MB
assets/robot.png ADDED
assets/ssae_side_by_side_comparison.png ADDED

Git LFS Details

  • SHA256: 665dce959769e799a14fa7d176d4a676feb33193c6575db21da97458732488fc
  • Pointer size: 132 Bytes
  • Size of remote file: 1.52 MB
assets/ssae_side_by_side_heatmap.png ADDED

Git LFS Details

  • SHA256: 00e2342afb5cabaf20b9b415587fb2986456f8c7c8cb96dd6ecc68455457045e
  • Pointer size: 131 Bytes
  • Size of remote file: 639 kB
assets/user.png ADDED
assets/wechat.png ADDED
autoencoder_kl_3d.py ADDED
@@ -0,0 +1,1081 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reference code
3
+ [FLUX] https://github.com/black-forest-labs/flux/blob/main/src/flux/modules/autoencoder.py
4
+ [DCAE] https://github.com/mit-han-lab/efficientvit/blob/master/efficientvit/models/efficientvit/dc_ae.py
5
+ """
6
+ import os
7
+ from dataclasses import dataclass
8
+ from typing import Tuple, Optional
9
+ import math
10
+ import random
11
+ import numpy as np
12
+ from einops import rearrange
13
+ import torch
14
+ from torch import Tensor, nn
15
+ import torch.nn.functional as F
16
+ import torch.distributed as dist
17
+ import torch.multiprocessing as mp
18
+
19
+ from safetensors import safe_open
20
+ import os
21
+ from collections import OrderedDict
22
+ from collections.abc import Iterable
23
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
24
+ from diffusers.models.modeling_outputs import AutoencoderKLOutput
25
+ from diffusers.models.modeling_utils import ModelMixin
26
+ from diffusers.utils.torch_utils import randn_tensor
27
+ from diffusers.utils import BaseOutput
28
+
29
+
30
+
31
+ class DiagonalGaussianDistribution(object):
32
+ def __init__(self, parameters: torch.Tensor, deterministic: bool = False):
33
+ if parameters.ndim == 3:
34
+ dim = 2 # (B, L, C)
35
+ elif parameters.ndim == 5 or parameters.ndim == 4:
36
+ dim = 1 # (B, C, T, H ,W) / (B, C, H, W)
37
+ else:
38
+ raise NotImplementedError
39
+ self.parameters = parameters
40
+ self.mean, self.logvar = torch.chunk(parameters, 2, dim=dim)
41
+ self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
42
+ self.deterministic = deterministic
43
+ self.std = torch.exp(0.5 * self.logvar)
44
+ self.var = torch.exp(self.logvar)
45
+ if self.deterministic:
46
+ self.var = self.std = torch.zeros_like(
47
+ self.mean, device=self.parameters.device, dtype=self.parameters.dtype
48
+ )
49
+
50
+ def sample(self, generator: Optional[torch.Generator] = None) -> torch.FloatTensor:
51
+ # make sure sample is on the same device as the parameters and has same dtype
52
+ sample = randn_tensor(
53
+ self.mean.shape,
54
+ generator=generator,
55
+ device=self.parameters.device,
56
+ dtype=self.parameters.dtype,
57
+ )
58
+ x = self.mean + self.std * sample
59
+ return x
60
+
61
+ def kl(self, other: "DiagonalGaussianDistribution" = None) -> torch.Tensor:
62
+ if self.deterministic:
63
+ return torch.Tensor([0.0])
64
+ else:
65
+ reduce_dim = list(range(1, self.mean.ndim))
66
+ if other is None:
67
+ return 0.5 * torch.sum(
68
+ torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar,
69
+ dim=reduce_dim,
70
+ )
71
+ else:
72
+ return 0.5 * torch.sum(
73
+ torch.pow(self.mean - other.mean, 2) / other.var +
74
+ self.var / other.var -
75
+ 1.0 -
76
+ self.logvar +
77
+ other.logvar,
78
+ dim=reduce_dim,
79
+ )
80
+
81
+ def nll(self, sample: torch.Tensor, dims: Tuple[int, ...] = [1, 2, 3]) -> torch.Tensor:
82
+ if self.deterministic:
83
+ return torch.Tensor([0.0])
84
+ logtwopi = np.log(2.0 * np.pi)
85
+ return 0.5 * torch.sum(
86
+ logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
87
+ dim=dims,
88
+ )
89
+
90
+ def mode(self) -> torch.Tensor:
91
+ return self.mean
92
+
93
+ @dataclass
94
+ class DecoderOutput(BaseOutput):
95
+ sample: torch.FloatTensor
96
+ posterior: Optional[DiagonalGaussianDistribution] = None
97
+
98
+ def swish(x: Tensor) -> Tensor:
99
+ return x * torch.sigmoid(x)
100
+
101
+ def forward_with_checkpointing(module, *inputs, use_checkpointing=False):
102
+ def create_custom_forward(module):
103
+ def custom_forward(*inputs):
104
+ return module(*inputs)
105
+ return custom_forward
106
+
107
+ if use_checkpointing:
108
+ return torch.utils.checkpoint.checkpoint(create_custom_forward(module), *inputs, use_reentrant=False)
109
+ else:
110
+ return module(*inputs)
111
+
112
+
113
+ class Conv3d(nn.Conv3d):
114
+ """Perform Conv3d on patches with numerical differences from nn.Conv3d within 1e-5. Only symmetric padding is supported."""
115
+
116
+ def forward(self, input):
117
+ B, C, T, H, W = input.shape
118
+ memory_count = (C * T * H * W) * 2 / 1024**3
119
+ if memory_count > 2:
120
+ n_split = math.ceil(memory_count / 2)
121
+ assert n_split >= 2
122
+ chunks = torch.chunk(input, chunks=n_split, dim=-3)
123
+ padded_chunks = []
124
+ for i in range(len(chunks)):
125
+ if self.padding[0] > 0:
126
+ padded_chunk = F.pad(
127
+ chunks[i],
128
+ (0, 0, 0, 0, self.padding[0], self.padding[0]),
129
+ mode="constant" if self.padding_mode == "zeros" else self.padding_mode,
130
+ value=0,
131
+ )
132
+ if i > 0:
133
+ padded_chunk[:, :, :self.padding[0]] = chunks[i - 1][:, :, -self.padding[0]:]
134
+ if i < len(chunks) - 1:
135
+ padded_chunk[:, :, -self.padding[0]:] = chunks[i + 1][:, :, :self.padding[0]]
136
+ else:
137
+ padded_chunk = chunks[i]
138
+ padded_chunks.append(padded_chunk)
139
+ padding_bak = self.padding
140
+ self.padding = (0, self.padding[1], self.padding[2])
141
+ outputs = []
142
+ for i in range(len(padded_chunks)):
143
+ outputs.append(super().forward(padded_chunks[i]))
144
+ self.padding = padding_bak
145
+ return torch.cat(outputs, dim=-3)
146
+ else:
147
+ return super().forward(input)
148
+
149
+
150
+ class AttnBlock(nn.Module):
151
+ def __init__(self, in_channels: int):
152
+ super().__init__()
153
+ self.in_channels = in_channels
154
+
155
+ self.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
156
+
157
+ self.q = Conv3d(in_channels, in_channels, kernel_size=1)
158
+ self.k = Conv3d(in_channels, in_channels, kernel_size=1)
159
+ self.v = Conv3d(in_channels, in_channels, kernel_size=1)
160
+ self.proj_out = Conv3d(in_channels, in_channels, kernel_size=1)
161
+
162
+ def attention(self, h_: Tensor) -> Tensor:
163
+ h_ = self.norm(h_)
164
+ q = self.q(h_)
165
+ k = self.k(h_)
166
+ v = self.v(h_)
167
+
168
+ b, c, f, h, w = q.shape
169
+ q = rearrange(q, "b c f h w -> b 1 (f h w) c").contiguous()
170
+ k = rearrange(k, "b c f h w -> b 1 (f h w) c").contiguous()
171
+ v = rearrange(v, "b c f h w -> b 1 (f h w) c").contiguous()
172
+ h_ = nn.functional.scaled_dot_product_attention(q, k, v)
173
+
174
+ return rearrange(h_, "b 1 (f h w) c -> b c f h w", f=f, h=h, w=w, c=c, b=b)
175
+
176
+ def forward(self, x: Tensor) -> Tensor:
177
+ return x + self.proj_out(self.attention(x))
178
+
179
+
180
+ class ResnetBlock(nn.Module):
181
+ def __init__(self, in_channels: int, out_channels: int):
182
+ super().__init__()
183
+ self.in_channels = in_channels
184
+ out_channels = in_channels if out_channels is None else out_channels
185
+ self.out_channels = out_channels
186
+
187
+ self.norm1 = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
188
+ self.conv1 = Conv3d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
189
+ self.norm2 = nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=1e-6, affine=True)
190
+ self.conv2 = Conv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
191
+ if self.in_channels != self.out_channels:
192
+ self.nin_shortcut = Conv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
193
+
194
+ def forward(self, x):
195
+ h = x
196
+ h = self.norm1(h)
197
+ h = swish(h)
198
+ h = self.conv1(h)
199
+
200
+ h = self.norm2(h)
201
+ h = swish(h)
202
+ h = self.conv2(h)
203
+
204
+ if self.in_channels != self.out_channels:
205
+ x = self.nin_shortcut(x)
206
+ return x + h
207
+
208
+
209
+ class Downsample(nn.Module):
210
+ def __init__(self, in_channels: int, add_temporal_downsample: bool = True):
211
+ super().__init__()
212
+ self.add_temporal_downsample = add_temporal_downsample
213
+ stride = (2, 2, 2) if add_temporal_downsample else (1, 2, 2) # THW
214
+ # no asymmetric padding in torch conv, must do it ourselves
215
+ self.conv = Conv3d(in_channels, in_channels, kernel_size=3, stride=stride, padding=0)
216
+
217
+ def forward(self, x: Tensor):
218
+ spatial_pad = (0, 1, 0, 1, 0, 0) # WHT
219
+ x = nn.functional.pad(x, spatial_pad, mode="constant", value=0)
220
+
221
+ temporal_pad = (0, 0, 0, 0, 0, 1) if self.add_temporal_downsample else (0, 0, 0, 0, 1, 1)
222
+ x = nn.functional.pad(x, temporal_pad, mode="replicate")
223
+
224
+ x = self.conv(x)
225
+ return x
226
+
227
+
228
+ class DownsampleDCAE(nn.Module):
229
+ def __init__(self, in_channels: int, out_channels: int, add_temporal_downsample: bool = True):
230
+ super().__init__()
231
+ factor = 2 * 2 * 2 if add_temporal_downsample else 1 * 2 * 2
232
+ assert out_channels % factor == 0
233
+ self.conv = Conv3d(in_channels, out_channels // factor, kernel_size=3, stride=1, padding=1)
234
+
235
+ self.add_temporal_downsample = add_temporal_downsample
236
+ self.group_size = factor * in_channels // out_channels
237
+
238
+ def forward(self, x: Tensor):
239
+ r1 = 2 if self.add_temporal_downsample else 1
240
+ h = self.conv(x)
241
+ h = rearrange(h, "b c (f r1) (h r2) (w r3) -> b (r1 r2 r3 c) f h w", r1=r1, r2=2, r3=2)
242
+ shortcut = rearrange(x, "b c (f r1) (h r2) (w r3) -> b (r1 r2 r3 c) f h w", r1=r1, r2=2, r3=2)
243
+
244
+ B, C, T, H, W = shortcut.shape
245
+ shortcut = shortcut.view(B, h.shape[1], self.group_size, T, H, W).mean(dim=2)
246
+ return h + shortcut
247
+
248
+
249
+ class Upsample(nn.Module):
250
+ def __init__(self, in_channels: int, add_temporal_upsample: bool = True):
251
+ super().__init__()
252
+ self.add_temporal_upsample = add_temporal_upsample
253
+ self.scale_factor = (2, 2, 2) if add_temporal_upsample else (1, 2, 2) # THW
254
+ self.conv = Conv3d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
255
+
256
+ def forward(self, x: Tensor):
257
+ x = nn.functional.interpolate(x, scale_factor=self.scale_factor, mode="nearest")
258
+ x = self.conv(x)
259
+ return x
260
+
261
+
262
+ class UpsampleDCAE(nn.Module):
263
+ def __init__(self, in_channels: int, out_channels: int, add_temporal_upsample: bool = True):
264
+ super().__init__()
265
+ factor = 2 * 2 * 2 if add_temporal_upsample else 1 * 2 * 2
266
+ self.conv = Conv3d(in_channels, out_channels * factor, kernel_size=3, stride=1, padding=1)
267
+
268
+ self.add_temporal_upsample = add_temporal_upsample
269
+ self.repeats = factor * out_channels // in_channels
270
+
271
+ def forward(self, x: Tensor):
272
+ r1 = 2 if self.add_temporal_upsample else 1
273
+ h = self.conv(x)
274
+ h = rearrange(h, "b (r1 r2 r3 c) f h w -> b c (f r1) (h r2) (w r3)", r1=r1, r2=2, r3=2)
275
+ shortcut = x.repeat_interleave(repeats=self.repeats, dim=1)
276
+ shortcut = rearrange(shortcut, "b (r1 r2 r3 c) f h w -> b c (f r1) (h r2) (w r3)", r1=r1, r2=2, r3=2)
277
+ return h + shortcut
278
+
279
+
280
+ class Encoder(nn.Module):
281
+ def __init__(
282
+ self,
283
+ in_channels: int,
284
+ z_channels: int,
285
+ block_out_channels: Tuple[int, ...],
286
+ num_res_blocks: int,
287
+ ffactor_spatial: int,
288
+ ffactor_temporal: int,
289
+ downsample_match_channel: bool = True,
290
+ ):
291
+ super().__init__()
292
+ assert block_out_channels[-1] % (2 * z_channels) == 0
293
+
294
+ self.z_channels = z_channels
295
+ self.block_out_channels = block_out_channels
296
+ self.num_res_blocks = num_res_blocks
297
+
298
+ # downsampling
299
+ self.conv_in = Conv3d(in_channels, block_out_channels[0], kernel_size=3, stride=1, padding=1)
300
+
301
+ self.down = nn.ModuleList()
302
+ block_in = block_out_channels[0]
303
+ for i_level, ch in enumerate(block_out_channels):
304
+ block = nn.ModuleList()
305
+ block_out = ch
306
+ for _ in range(self.num_res_blocks):
307
+ block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))
308
+ block_in = block_out
309
+ down = nn.Module()
310
+ down.block = block
311
+
312
+ add_spatial_downsample = bool(i_level < np.log2(ffactor_spatial))
313
+ add_temporal_downsample = add_spatial_downsample and bool(i_level >= np.log2(ffactor_spatial // ffactor_temporal))
314
+ if add_spatial_downsample or add_temporal_downsample:
315
+ assert i_level < len(block_out_channels) - 1
316
+ block_out = block_out_channels[i_level + 1] if downsample_match_channel else block_in
317
+ down.downsample = DownsampleDCAE(block_in, block_out, add_temporal_downsample)
318
+ block_in = block_out
319
+ self.down.append(down)
320
+
321
+ # middle
322
+ self.mid = nn.Module()
323
+ self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)
324
+ self.mid.attn_1 = AttnBlock(block_in)
325
+ self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)
326
+
327
+ # end
328
+ self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
329
+ self.conv_out = Conv3d(block_in, 2 * z_channels, kernel_size=3, stride=1, padding=1)
330
+
331
+ self.gradient_checkpointing = False
332
+
333
+ def forward(self, x: Tensor) -> Tensor:
334
+ with torch.no_grad():
335
+ use_checkpointing = bool(self.training and self.gradient_checkpointing)
336
+
337
+ # downsampling
338
+ h = self.conv_in(x)
339
+ for i_level in range(len(self.block_out_channels)):
340
+ for i_block in range(self.num_res_blocks):
341
+ h = forward_with_checkpointing(self.down[i_level].block[i_block], h, use_checkpointing=use_checkpointing)
342
+ if hasattr(self.down[i_level], "downsample"):
343
+ h = forward_with_checkpointing(self.down[i_level].downsample, h, use_checkpointing=use_checkpointing)
344
+
345
+ # middle
346
+ h = forward_with_checkpointing(self.mid.block_1, h, use_checkpointing=use_checkpointing)
347
+ h = forward_with_checkpointing(self.mid.attn_1, h, use_checkpointing=use_checkpointing)
348
+ h = forward_with_checkpointing(self.mid.block_2, h, use_checkpointing=use_checkpointing)
349
+
350
+ # end
351
+ group_size = self.block_out_channels[-1] // (2 * self.z_channels)
352
+ shortcut = rearrange(h, "b (c r) f h w -> b c r f h w", r=group_size).mean(dim=2)
353
+ h = self.norm_out(h)
354
+ h = swish(h)
355
+ h = self.conv_out(h)
356
+ h += shortcut
357
+ return h
358
+
359
+
360
+ class Decoder(nn.Module):
361
+ def __init__(
362
+ self,
363
+ z_channels: int,
364
+ out_channels: int,
365
+ block_out_channels: Tuple[int, ...],
366
+ num_res_blocks: int,
367
+ ffactor_spatial: int,
368
+ ffactor_temporal: int,
369
+ upsample_match_channel: bool = True,
370
+ ):
371
+ super().__init__()
372
+ assert block_out_channels[0] % z_channels == 0
373
+
374
+ self.z_channels = z_channels
375
+ self.block_out_channels = block_out_channels
376
+ self.num_res_blocks = num_res_blocks
377
+
378
+ # z to block_in
379
+ block_in = block_out_channels[0]
380
+ self.conv_in = Conv3d(z_channels, block_in, kernel_size=3, stride=1, padding=1)
381
+
382
+ # middle
383
+ self.mid = nn.Module()
384
+ self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)
385
+ self.mid.attn_1 = AttnBlock(block_in)
386
+ self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)
387
+
388
+ # upsampling
389
+ self.up = nn.ModuleList()
390
+ for i_level, ch in enumerate(block_out_channels):
391
+ block = nn.ModuleList()
392
+ block_out = ch
393
+ for _ in range(self.num_res_blocks + 1):
394
+ block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))
395
+ block_in = block_out
396
+ up = nn.Module()
397
+ up.block = block
398
+
399
+ add_spatial_upsample = bool(i_level < np.log2(ffactor_spatial))
400
+ add_temporal_upsample = bool(i_level < np.log2(ffactor_temporal))
401
+ if add_spatial_upsample or add_temporal_upsample:
402
+ assert i_level < len(block_out_channels) - 1
403
+ block_out = block_out_channels[i_level + 1] if upsample_match_channel else block_in
404
+ up.upsample = UpsampleDCAE(block_in, block_out, add_temporal_upsample)
405
+ block_in = block_out
406
+ self.up.append(up)
407
+
408
+ # end
409
+ self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
410
+ self.conv_out = Conv3d(block_in, out_channels, kernel_size=3, stride=1, padding=1)
411
+
412
+ self.gradient_checkpointing = False
413
+
414
+
415
+ def forward(self, z: Tensor) -> Tensor:
416
+ with torch.no_grad():
417
+ use_checkpointing = bool(self.training and self.gradient_checkpointing)
418
+ # z to block_in
419
+ repeats = self.block_out_channels[0] // (self.z_channels)
420
+ h = self.conv_in(z) + z.repeat_interleave(repeats=repeats, dim=1)
421
+ # middle
422
+ h = forward_with_checkpointing(self.mid.block_1, h, use_checkpointing=use_checkpointing)
423
+ h = forward_with_checkpointing(self.mid.attn_1, h, use_checkpointing=use_checkpointing)
424
+ h = forward_with_checkpointing(self.mid.block_2, h, use_checkpointing=use_checkpointing)
425
+ # upsampling
426
+ for i_level in range(len(self.block_out_channels)):
427
+ for i_block in range(self.num_res_blocks + 1):
428
+ h = forward_with_checkpointing(self.up[i_level].block[i_block], h, use_checkpointing=use_checkpointing)
429
+ if hasattr(self.up[i_level], "upsample"):
430
+ h = forward_with_checkpointing(self.up[i_level].upsample, h, use_checkpointing=use_checkpointing)
431
+ # end
432
+ h = self.norm_out(h)
433
+ h = swish(h)
434
+ h = self.conv_out(h)
435
+ return h
436
+
437
+
438
+ class AutoencoderKLConv3D(ModelMixin, ConfigMixin):
439
+ _supports_gradient_checkpointing = True
440
+
441
+ @register_to_config
442
+ def __init__(
443
+ self,
444
+ in_channels: int,
445
+ out_channels: int,
446
+ latent_channels: int,
447
+ block_out_channels: Tuple[int, ...],
448
+ layers_per_block: int,
449
+ ffactor_spatial: int,
450
+ ffactor_temporal: int,
451
+ sample_size: int,
452
+ sample_tsize: int,
453
+ scaling_factor: float = None,
454
+ shift_factor: Optional[float] = None,
455
+ downsample_match_channel: bool = True,
456
+ upsample_match_channel: bool = True,
457
+ only_encoder: bool = False,
458
+ only_decoder: bool = False,
459
+ ):
460
+ super().__init__()
461
+ self.ffactor_spatial = ffactor_spatial
462
+ self.ffactor_temporal = ffactor_temporal
463
+ self.scaling_factor = scaling_factor
464
+ self.shift_factor = shift_factor
465
+
466
+ if not only_decoder:
467
+ self.encoder = Encoder(
468
+ in_channels=in_channels,
469
+ z_channels=latent_channels,
470
+ block_out_channels=block_out_channels,
471
+ num_res_blocks=layers_per_block,
472
+ ffactor_spatial=ffactor_spatial,
473
+ ffactor_temporal=ffactor_temporal,
474
+ downsample_match_channel=downsample_match_channel,
475
+ )
476
+ if not only_encoder:
477
+ self.decoder = Decoder(
478
+ z_channels=latent_channels,
479
+ out_channels=out_channels,
480
+ block_out_channels=list(reversed(block_out_channels)),
481
+ num_res_blocks=layers_per_block,
482
+ ffactor_spatial=ffactor_spatial,
483
+ ffactor_temporal=ffactor_temporal,
484
+ upsample_match_channel=upsample_match_channel,
485
+ )
486
+
487
+ self.use_slicing = False
488
+ self.slicing_bsz = 1
489
+ self.use_spatial_tiling = False
490
+ self.use_temporal_tiling = False
491
+ self.use_tiling_during_training = False
492
+
493
+ # only relevant if vae tiling is enabled
494
+ self.tile_sample_min_size = sample_size
495
+ self.tile_latent_min_size = sample_size // ffactor_spatial
496
+ self.tile_sample_min_tsize = sample_tsize
497
+ self.tile_latent_min_tsize = sample_tsize // ffactor_temporal
498
+ self.tile_overlap_factor = 0.125
499
+
500
+ self.use_compile = False
501
+
502
+ self.empty_cache = torch.empty(0, device="cuda")
503
+
504
+ def _set_gradient_checkpointing(self, module, value=False):
505
+ if isinstance(module, (Encoder, Decoder)):
506
+ module.gradient_checkpointing = value
507
+
508
+ def enable_tiling_during_training(self, use_tiling: bool = True):
509
+ self.use_tiling_during_training = use_tiling
510
+
511
+ def disable_tiling_during_training(self):
512
+ self.enable_tiling_during_training(False)
513
+
514
+ def enable_temporal_tiling(self, use_tiling: bool = True):
515
+ self.use_temporal_tiling = use_tiling
516
+
517
+ def disable_temporal_tiling(self):
518
+ self.enable_temporal_tiling(False)
519
+
520
+ def enable_spatial_tiling(self, use_tiling: bool = True):
521
+ self.use_spatial_tiling = use_tiling
522
+
523
+ def disable_spatial_tiling(self):
524
+ self.enable_spatial_tiling(False)
525
+
526
+ def enable_tiling(self, use_tiling: bool = True):
527
+ self.enable_spatial_tiling(use_tiling)
528
+
529
+ def disable_tiling(self):
530
+ self.disable_spatial_tiling()
531
+
532
+ def enable_slicing(self):
533
+ self.use_slicing = True
534
+
535
+ def disable_slicing(self):
536
+ self.use_slicing = False
537
+
538
+ def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int):
539
+ blend_extent = min(a.shape[-1], b.shape[-1], blend_extent)
540
+ for x in range(blend_extent):
541
+ b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * (x / blend_extent)
542
+ return b
543
+
544
+ def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int):
545
+ blend_extent = min(a.shape[-2], b.shape[-2], blend_extent)
546
+ for y in range(blend_extent):
547
+ b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * (y / blend_extent)
548
+ return b
549
+
550
+ def blend_t(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int):
551
+ blend_extent = min(a.shape[-3], b.shape[-3], blend_extent)
552
+ for x in range(blend_extent):
553
+ b[:, :, x, :, :] = a[:, :, -blend_extent + x, :, :] * (1 - x / blend_extent) + b[:, :, x, :, :] * (x / blend_extent)
554
+ return b
555
+
556
+ def spatial_tiled_encode(self, x: torch.Tensor):
557
+ B, C, T, H, W = x.shape
558
+ overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor)) # 256 * (1 - 0.25) = 192
559
+ blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor) # 8 * 0.25 = 2
560
+ row_limit = self.tile_latent_min_size - blend_extent # 8 - 2 = 6
561
+
562
+ rows = []
563
+ for i in range(0, H, overlap_size):
564
+ row = []
565
+ for j in range(0, W, overlap_size):
566
+ tile = x[:, :, :, i: i + self.tile_sample_min_size, j: j + self.tile_sample_min_size]
567
+ tile = self.encoder(tile)
568
+ row.append(tile)
569
+ rows.append(row)
570
+ result_rows = []
571
+ for i, row in enumerate(rows):
572
+ result_row = []
573
+ for j, tile in enumerate(row):
574
+ if i > 0:
575
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
576
+ if j > 0:
577
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
578
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
579
+ result_rows.append(torch.cat(result_row, dim=-1))
580
+ moments = torch.cat(result_rows, dim=-2)
581
+ return moments
582
+
583
+ def temporal_tiled_encode(self, x: torch.Tensor):
584
+ B, C, T, H, W = x.shape
585
+ overlap_size = int(self.tile_sample_min_tsize * (1 - self.tile_overlap_factor)) # 64 * (1 - 0.25) = 48
586
+ blend_extent = int(self.tile_latent_min_tsize * self.tile_overlap_factor) # 8 * 0.25 = 2
587
+ t_limit = self.tile_latent_min_tsize - blend_extent # 8 - 2 = 6
588
+
589
+ row = []
590
+ for i in range(0, T, overlap_size):
591
+ tile = x[:, :, i: i + self.tile_sample_min_tsize, :, :]
592
+ if self.use_spatial_tiling and (tile.shape[-1] > self.tile_sample_min_size or tile.shape[-2] > self.tile_sample_min_size):
593
+ tile = self.spatial_tiled_encode(tile)
594
+ else:
595
+ tile = self.encoder(tile)
596
+ row.append(tile)
597
+ result_row = []
598
+ for i, tile in enumerate(row):
599
+ if i > 0:
600
+ tile = self.blend_t(row[i - 1], tile, blend_extent)
601
+ result_row.append(tile[:, :, :t_limit, :, :])
602
+ moments = torch.cat(result_row, dim=-3)
603
+ return moments
604
+
605
+ def spatial_tiled_decode(self, z: torch.Tensor):
606
+ B, C, T, H, W = z.shape
607
+ overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor)) # 24 * (1 - 0.125) = 21
608
+ blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor) # 384 * 0.125 = 48
609
+ row_limit = self.tile_sample_min_size - blend_extent # 384 - 48 = 336
610
+
611
+ # 分布式/多卡:输入不做 padding -> 每 rank 对解码输出做右/下 padding -> GPU all_gather -> rank0重组/融合/裁剪
612
+ if dist.is_available() and dist.is_initialized() and dist.get_world_size() > 1:
613
+ rank = dist.get_rank()
614
+ world_size = dist.get_world_size()
615
+
616
+ # 统计tile
617
+ num_rows = math.ceil(H / overlap_size)
618
+ num_cols = math.ceil(W / overlap_size)
619
+ total_tiles = num_rows * num_cols
620
+ tiles_per_rank = math.ceil(total_tiles / world_size)
621
+
622
+ print(f"==={torch.distributed.get_rank()}, {total_tiles=}, {tiles_per_rank=}, {world_size=}")
623
+
624
+ # 本 rank 的 tile 索引(循环分配):rank, rank+world_size,
625
+ my_linear_indices = list(range(rank, total_tiles, world_size))
626
+ if my_linear_indices == []:
627
+ my_linear_indices = [0]
628
+ print(f"==={torch.distributed.get_rank()}, {my_linear_indices=}")
629
+ decoded_tiles = [] # tiles
630
+ decoded_metas = [] # (ri, rj, pad_w, pad_h)
631
+ H_out_std = self.tile_sample_min_size
632
+ W_out_std = self.tile_sample_min_size
633
+ for lin_idx in my_linear_indices:
634
+ ri = lin_idx // num_cols
635
+ rj = lin_idx % num_cols
636
+ i = ri * overlap_size
637
+ j = rj * overlap_size
638
+ tile = z[
639
+ :,
640
+ :,
641
+ :,
642
+ i : i + self.tile_latent_min_size,
643
+ j : j + self.tile_latent_min_size,
644
+ ]
645
+ dec = self.decoder(tile)
646
+ # 对边界 tile 的输出做右/下方向 padding 到标准尺寸
647
+ pad_h = max(0, H_out_std - dec.shape[-2])
648
+ pad_w = max(0, W_out_std - dec.shape[-1])
649
+ if pad_h > 0 or pad_w > 0:
650
+ dec = F.pad(dec, (0, pad_w, 0, pad_h, 0, 0), "constant", 0)
651
+ decoded_tiles.append(dec)
652
+ decoded_metas.append(torch.tensor([ri, rj, pad_w, pad_h], device=z.device, dtype=torch.int64))
653
+
654
+ # 各rank数量不一定相同,进行padding到相同长度
655
+ T_out = decoded_tiles[0].shape[2] if len(decoded_tiles) > 0 else (T-1)*self.ffactor_temporal+1
656
+ while len(decoded_tiles) < tiles_per_rank:
657
+ decoded_tiles.append(torch.zeros([1, 3, T_out, self.tile_sample_min_size, self.tile_sample_min_size], device=z.device, dtype=dec.dtype))
658
+ decoded_metas.append(torch.tensor([-1, -1, self.tile_sample_min_size, self.tile_sample_min_size], device=z.device, dtype=torch.int64))
659
+
660
+ # 进行gpu的all_gather
661
+ decoded_tiles = torch.stack(decoded_tiles, dim=0)
662
+ decoded_metas = torch.stack(decoded_metas, dim=0)
663
+
664
+ tiles_gather_list = [torch.empty_like(decoded_tiles) for _ in range(world_size)]
665
+ metas_gather_list = [torch.empty_like(decoded_metas) for _ in range(world_size)]
666
+
667
+ dist.all_gather(tiles_gather_list, decoded_tiles)
668
+ dist.all_gather(metas_gather_list, decoded_metas)
669
+
670
+ if rank != 0:
671
+ # 非0号rank返回空占位,结果只在rank0上有效
672
+ return torch.empty(0, device=z.device)
673
+
674
+ # rank0:根据 (ri, rj) 元信息重建 tile 网格;跳过占位项 (ri, rj) == (-1, -1)
675
+ rows = [[None for _ in range(num_cols)] for _ in range(num_rows)]
676
+ for r in range(world_size):
677
+ gathered_tiles_r = tiles_gather_list[r] # [tiles_per_rank, B, C, T, H, W]
678
+ gathered_metas_r = metas_gather_list[r] # [tiles_per_rank, 4],元素: (ri, rj, pad_w, pad_h)
679
+ for k in range(gathered_tiles_r.shape[0]):
680
+ ri = int(gathered_metas_r[k][0])
681
+ rj = int(gathered_metas_r[k][1])
682
+ if ri < 0 or rj < 0:
683
+ continue
684
+ if ri < num_rows and rj < num_cols:
685
+ # 去除padding
686
+ pad_w = int(gathered_metas_r[k][2])
687
+ pad_h = int(gathered_metas_r[k][3])
688
+ h_end = None if pad_h == 0 else -pad_h
689
+ w_end = None if pad_w == 0 else -pad_w
690
+ rows[ri][rj] = gathered_tiles_r[k][:, :, :, :h_end, :w_end]
691
+
692
+ result_rows = []
693
+ for i, row in enumerate(rows):
694
+ result_row = []
695
+ for j, tile in enumerate(row):
696
+ if tile is None:
697
+ continue
698
+ if i > 0:
699
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
700
+ if j > 0:
701
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
702
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
703
+ result_rows.append(torch.cat(result_row, dim=-1))
704
+
705
+ dec = torch.cat(result_rows, dim=-2)
706
+ return dec
707
+
708
+ # 单卡:原有串行逻辑
709
+ rows = []
710
+ for i in range(0, H, overlap_size):
711
+ row = []
712
+ for j in range(0, W, overlap_size):
713
+ tile = z[
714
+ :,
715
+ :,
716
+ :,
717
+ i : i + self.tile_latent_min_size,
718
+ j : j + self.tile_latent_min_size,
719
+ ]
720
+ decoded = self.decoder(tile)
721
+ row.append(decoded)
722
+ rows.append(row)
723
+
724
+ result_rows = []
725
+ for i, row in enumerate(rows):
726
+ result_row = []
727
+ for j, tile in enumerate(row):
728
+ if i > 0:
729
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
730
+ if j > 0:
731
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
732
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
733
+ result_rows.append(torch.cat(result_row, dim=-1))
734
+ dec = torch.cat(result_rows, dim=-2)
735
+ return dec
736
+
737
+ def temporal_tiled_decode(self, z: torch.Tensor):
738
+ B, C, T, H, W = z.shape
739
+ overlap_size = int(self.tile_latent_min_tsize * (1 - self.tile_overlap_factor)) # 8 * (1 - 0.25) = 6
740
+ blend_extent = int(self.tile_sample_min_tsize * self.tile_overlap_factor) # 64 * 0.25 = 16
741
+ t_limit = self.tile_sample_min_tsize - blend_extent # 64 - 16 = 48
742
+ assert 0 < overlap_size < self.tile_latent_min_tsize
743
+
744
+ row = []
745
+ for i in range(0, T, overlap_size):
746
+ tile = z[:, :, i: i + self.tile_latent_min_tsize, :, :]
747
+ if self.use_spatial_tiling and (tile.shape[-1] > self.tile_latent_min_size or tile.shape[-2] > self.tile_latent_min_size):
748
+ decoded = self.spatial_tiled_decode(tile)
749
+ else:
750
+ decoded = self.decoder(tile)
751
+ row.append(decoded)
752
+
753
+ result_row = []
754
+ for i, tile in enumerate(row):
755
+ if i > 0:
756
+ tile = self.blend_t(row[i - 1], tile, blend_extent)
757
+ result_row.append(tile[:, :, :t_limit, :, :])
758
+ dec = torch.cat(result_row, dim=-3)
759
+ return dec
760
+
761
+ def encode(self, x: Tensor, return_dict: bool = True):
762
+
763
+ def _encode(x):
764
+ if self.use_temporal_tiling and x.shape[-3] > self.tile_sample_min_tsize:
765
+ return self.temporal_tiled_encode(x)
766
+ if self.use_spatial_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
767
+ return self.spatial_tiled_encode(x)
768
+
769
+ if self.use_compile:
770
+ @torch.compile
771
+ def encoder(x):
772
+ return self.encoder(x)
773
+ return encoder(x)
774
+ return self.encoder(x)
775
+
776
+ if len(x.shape) != 5: # (B, C, T, H, W)
777
+ x = x[:, :, None]
778
+ assert len(x.shape) == 5 # (B, C, T, H, W)
779
+ if x.shape[2] == 1:
780
+ x = x.expand(-1, -1, self.ffactor_temporal, -1, -1)
781
+ else:
782
+ assert x.shape[2] != self.ffactor_temporal and x.shape[2] % self.ffactor_temporal == 0
783
+
784
+ if self.use_slicing and x.shape[0] > 1:
785
+ if self.slicing_bsz == 1:
786
+ encoded_slices = [_encode(x_slice) for x_slice in x.split(1)]
787
+ else:
788
+ sections = [self.slicing_bsz] * (x.shape[0] // self.slicing_bsz)
789
+ if x.shape[0] % self.slicing_bsz != 0:
790
+ sections.append(x.shape[0] % self.slicing_bsz)
791
+ encoded_slices = [_encode(x_slice) for x_slice in x.split(sections)]
792
+ h = torch.cat(encoded_slices)
793
+ else:
794
+ h = _encode(x)
795
+ posterior = DiagonalGaussianDistribution(h)
796
+
797
+ if not return_dict:
798
+ return (posterior,)
799
+
800
+ return AutoencoderKLOutput(latent_dist=posterior)
801
+
802
+ def decode(self, z: Tensor, return_dict: bool = True, generator=None):
803
+
804
+ def _decode(z):
805
+ if self.use_temporal_tiling and z.shape[-3] > self.tile_latent_min_tsize:
806
+ return self.temporal_tiled_decode(z)
807
+ if self.use_spatial_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
808
+ return self.spatial_tiled_decode(z)
809
+ return self.decoder(z)
810
+
811
+ if self.use_slicing and z.shape[0] > 1:
812
+ decoded_slices = [_decode(z_slice) for z_slice in z.split(1)]
813
+ decoded = torch.cat(decoded_slices)
814
+ else:
815
+ decoded = _decode(z)
816
+ if torch.distributed.is_initialized():
817
+ if torch.distributed.get_rank() != 0:
818
+ return self.empty_cache
819
+
820
+ if z.shape[-3] == 1:
821
+ decoded = decoded[:, :, -1:]
822
+ if not return_dict:
823
+ return (decoded,)
824
+
825
+ return DecoderOutput(sample=decoded)
826
+
827
+ def decode_dist(self, z: Tensor, return_dict: bool = True, generator=None):
828
+ z = z.cuda()
829
+ self.use_spatial_tiling = True
830
+ decoded = self.decode(z)
831
+ self.use_spatial_tiling = False
832
+ return decoded
833
+
834
+ def forward(
835
+ self,
836
+ sample: torch.Tensor,
837
+ sample_posterior: bool = False,
838
+ return_posterior: bool = True,
839
+ return_dict: bool = True
840
+ ):
841
+ posterior = self.encode(sample).latent_dist
842
+ z = posterior.sample() if sample_posterior else posterior.mode()
843
+ dec = self.decode(z).sample
844
+ return DecoderOutput(sample=dec, posterior=posterior) if return_dict else (dec, posterior)
845
+
846
+ def random_reset_tiling(self, x: torch.Tensor):
847
+ if x.shape[-3] == 1:
848
+ self.disable_spatial_tiling()
849
+ self.disable_temporal_tiling()
850
+ return
851
+
852
+ # tiling在input_shape和sample_size上限制很多,任意的input_shape和sample_size很可能不满足条件,因此这里使用固定值
853
+ min_sample_size = int(1 / self.tile_overlap_factor) * self.ffactor_spatial
854
+ min_sample_tsize = int(1 / self.tile_overlap_factor) * self.ffactor_temporal
855
+ sample_size = random.choice([None, 1 * min_sample_size, 2 * min_sample_size, 3 * min_sample_size])
856
+ if sample_size is None:
857
+ self.disable_spatial_tiling()
858
+ else:
859
+ self.tile_sample_min_size = sample_size
860
+ self.tile_latent_min_size = sample_size // self.ffactor_spatial
861
+ self.enable_spatial_tiling()
862
+
863
+ sample_tsize = random.choice([None, 1 * min_sample_tsize, 2 * min_sample_tsize, 3 * min_sample_tsize])
864
+ if sample_tsize is None:
865
+ self.disable_temporal_tiling()
866
+ else:
867
+ self.tile_sample_min_tsize = sample_tsize
868
+ self.tile_latent_min_tsize = sample_tsize // self.ffactor_temporal
869
+ self.enable_temporal_tiling()
870
+
871
+ def load_sharded_safetensors(model_dir):
872
+ """
873
+ 手动加载分片的 safetensors 文件
874
+
875
+ Args:
876
+ model_dir: 包含分片文件的目录路径
877
+
878
+ Returns:
879
+ 合并后的完整权重字典
880
+ """
881
+ # 获取所有分片文件并按编号排序
882
+ shard_files = []
883
+ for file in os.listdir(model_dir):
884
+ if file.endswith(".safetensors"):
885
+ shard_files.append(file)
886
+
887
+ # 按分片编号排序
888
+ shard_files.sort(key=lambda x: int(x.split("-")[1]))
889
+
890
+ print(f"找到 {len(shard_files)} 个分片文件")
891
+
892
+ # 合并所有权重
893
+ merged_state_dict = dict()
894
+
895
+ for shard_file in shard_files:
896
+ shard_path = os.path.join(model_dir, shard_file)
897
+ print(f"加载分片: {shard_file}")
898
+
899
+ # 使用 safetensors 加载当前分片
900
+ with safe_open(shard_path, framework="pt", device="cpu") as f:
901
+ for key in f.keys():
902
+ tensor = f.get_tensor(key)
903
+ merged_state_dict[key] = tensor
904
+
905
+ print(f"合并完成,总键数量: {len(merged_state_dict)}")
906
+ return merged_state_dict
907
+
908
+ def load_weights(model, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
909
+ def update_state_dict(state_dict: dict[str, torch.Tensor], name, weight):
910
+ if name not in state_dict:
911
+ raise ValueError(f"Unexpected weight {name}")
912
+
913
+ model_tensor = state_dict[name]
914
+ if model_tensor.shape != weight.shape:
915
+ raise ValueError(
916
+ f"Shape mismatch for weight {name}: "
917
+ f"model tensor shape {model_tensor.shape} vs. "
918
+ f"loaded tensor shape {weight.shape}"
919
+ )
920
+ if isinstance(weight, torch.Tensor):
921
+ model_tensor.data.copy_(weight.data)
922
+ else:
923
+ raise ValueError(
924
+ f"Unsupported tensor type in load_weights "
925
+ f"for {name}: {type(weight)}"
926
+ )
927
+
928
+ loaded_params = set()
929
+ for name, load_tensor in weights.items():
930
+ updated = True
931
+ name = name.replace('vae.', '')
932
+ if name in model.state_dict():
933
+ update_state_dict(model.state_dict(), name, load_tensor)
934
+ else:
935
+ updated = False
936
+
937
+ if updated:
938
+ loaded_params.add(name)
939
+
940
+ return loaded_params
941
+
942
+ def _worker(path, config,
943
+ rank=None, world_size=None, port=None, req_queue=None, rsp_queue=None):
944
+ """
945
+ each rank's worker:
946
+ - idle: block on req_queue.get() (CPU blocking, no GPU)
947
+ - receive request: run runner.predict(), all ranks forward
948
+ - only rank0 put result to rsp_queue
949
+ """
950
+ # _tame_cpu_threads_and_comm()
951
+ # basic env
952
+ os.environ["MASTER_ADDR"] = "127.0.0.1"
953
+ os.environ["MASTER_PORT"] = str(port)
954
+ os.environ["WORLD_SIZE"] = str(world_size)
955
+ os.environ["RANK"] = str(rank)
956
+ os.environ["LOCAL_RANK"] = str(rank)
957
+
958
+ # device binding should be early than all CUDA operations
959
+ visible = torch.cuda.device_count()
960
+ assert visible >= world_size, f"可见卡数 {visible} < world_size {world_size}"
961
+ local_rank = int(os.environ["LOCAL_RANK"])
962
+
963
+ print(f"[worker {rank}] bind to cuda:{local_rank} (visible={visible})", flush=True)
964
+ if not torch.distributed.is_initialized():
965
+ dist.init_process_group("nccl")
966
+ torch.cuda.set_device(local_rank)
967
+ #from .. import load_vae
968
+
969
+ #vae = load_vae(vae_type, vae_precision, device, logger, args, weights_only, only_encoder, only_decoder, sample_size, skip_create_dist=True)
970
+ #vae = vae.cuda()
971
+ vae = AutoencoderKLConv3D.from_config(config)
972
+ merged_state_dict = load_sharded_safetensors(path)
973
+ loaded_params = load_weights(vae, merged_state_dict)
974
+ vae = vae.cuda()
975
+ vae.eval() # 关闭 Dropout、BatchNorm 训练行为
976
+ for param in vae.parameters():
977
+ param.requires_grad = False #
978
+
979
+ while True:
980
+ req = req_queue.get() # blocking
981
+ if req == "__STOP__":
982
+ break
983
+ out = vae.decode_dist(req, return_dict=False)
984
+ if rank == 0:
985
+ rsp_queue.put(out)
986
+
987
+ #try:
988
+ # while True:
989
+ # # blocking on CPU queue
990
+ # req = req_queue.get() # blocking
991
+ # if req == "__STOP__":
992
+ # break
993
+ # out = vae.decode_dist(req, return_dict=False)
994
+ # if rank == 0:
995
+ # rsp_queue.put(out)
996
+ #finally:
997
+ # # destroy process group before exit
998
+ # try:
999
+ # dist.destroy_process_group()
1000
+ # except Exception:
1001
+ # pass
1002
+
1003
+ #def _find_free_port():
1004
+ # import socket
1005
+ # with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
1006
+ # s.bind(("127.0.0.1", 0))
1007
+ # return s.getsockname()[1]
1008
+
1009
+ # 避免端口冲突的常见做法
1010
+ def _find_free_port(start_port=8100, max_attempts=900):
1011
+ import socket
1012
+ """获取一个可用的端口"""
1013
+ for port in range(start_port, start_port + max_attempts):
1014
+ try:
1015
+ with socket.socket() as s:
1016
+ s.bind(('localhost', port))
1017
+ return s.getsockname()[1] # 返回实际绑定的端口
1018
+ except OSError:
1019
+ continue
1020
+ raise RuntimeError("找不到可用端口")
1021
+
1022
+ class AutoencoderKLConv3D_Dist(AutoencoderKLConv3D):
1023
+ def __init__(
1024
+ self,
1025
+ in_channels: int,
1026
+ out_channels: int,
1027
+ latent_channels: int,
1028
+ block_out_channels: Tuple[int, ...],
1029
+ layers_per_block: int,
1030
+ ffactor_spatial: int,
1031
+ ffactor_temporal: int,
1032
+ sample_size: int,
1033
+ sample_tsize: int,
1034
+ scaling_factor: float = None,
1035
+ shift_factor: Optional[float] = None,
1036
+ downsample_match_channel: bool = True,
1037
+ upsample_match_channel: bool = True,
1038
+ only_encoder: bool = False,
1039
+ only_decoder: bool = False,
1040
+ ):
1041
+ super().__init__(in_channels, out_channels, latent_channels, block_out_channels, layers_per_block, ffactor_spatial, ffactor_temporal, sample_size, sample_tsize, scaling_factor, shift_factor, downsample_match_channel, upsample_match_channel, only_encoder, only_decoder)
1042
+
1043
+ def create_dist(self, path, config,
1044
+ ):
1045
+ self.world_size = 8
1046
+ self.port = _find_free_port()
1047
+ ctx = mp.get_context("spawn")
1048
+ # 每个 rank 一个请求队列(纯 CPU),再加一个公共响应队列
1049
+ self.req_queues = [ctx.Queue() for _ in range(self.world_size)]
1050
+ self.rsp_queue = ctx.Queue()
1051
+
1052
+ self.procs = []
1053
+ for rank in range(self.world_size):
1054
+ p = ctx.Process(
1055
+ target=_worker,
1056
+ args=(
1057
+ path, config,
1058
+ rank, self.world_size, self.port,
1059
+ self.req_queues[rank], self.rsp_queue,
1060
+ ),
1061
+ daemon=True,
1062
+ )
1063
+ p.start()
1064
+ self.procs.append(p)
1065
+
1066
+ def decode(self, z: Tensor, return_dict: bool = True, generator=None):
1067
+ """
1068
+ synchronous inference: put the same request to all ranks' queues.
1069
+ return rank0's result.
1070
+ """
1071
+ # check alive
1072
+ for p in self.procs:
1073
+ if not p.is_alive():
1074
+ raise RuntimeError("One of the processes is not alive")
1075
+
1076
+ # put to each rank's queue
1077
+ for q in self.req_queues:
1078
+ q.put(z)
1079
+
1080
+ # wait for rank0's result
1081
+ return self.rsp_queue.get(timeout=None)
cache_utils.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import math
4
+ from typing import Tuple
5
+
6
+ def cache_init(cache_interval, max_order, num_steps=None,
7
+ enable_first_enhance=False, first_enhance_steps=3,
8
+ enable_tailing_enhance=False, tailing_enhance_steps=1,
9
+ low_freqs_order=0, high_freqs_order=2):
10
+ cache_dic = {}
11
+ cache_dic['counter']= 0
12
+ cache_dic['current_step'] = 0
13
+ cache_dic['cache_interval']= cache_interval
14
+ cache_dic['max_order'] = max_order
15
+ cache_dic['num_steps'] = num_steps
16
+
17
+ # enhance related utils
18
+
19
+ # first enhance: fully compute first some steps, enhancing contour infos
20
+ cache_dic['enable_first_enhance'] = enable_first_enhance
21
+ cache_dic['first_enhance_steps'] = first_enhance_steps
22
+
23
+ # tailing enhance: fully compute the last 1 steps, enhancing details
24
+ cache_dic['enable_tailing_enhance'] = enable_tailing_enhance
25
+ cache_dic['tailing_enhance_steps'] = tailing_enhance_steps
26
+
27
+ # freqs related utils
28
+ cache_dic['low_freqs_order'] = low_freqs_order
29
+ cache_dic['high_freqs_order'] = high_freqs_order
30
+
31
+ # features for training-aware cache, here we don't use these
32
+ cache_dic['enable_force_control']= False
33
+ cache_dic['force_compute']=False
34
+ return cache_dic
35
+
36
+ class TaylorCacheContainer(nn.Module):
37
+ def __init__(self, max_order):
38
+ super().__init__()
39
+ self.max_order = max_order
40
+ # 逐个注册buffer
41
+ for i in range(max_order + 1):
42
+ self.register_buffer(f"derivative_{i}", None, persistent=False)
43
+ self.register_buffer(f"temp_derivative_{i}", None, persistent=False)
44
+
45
+ def get_derivative(self, order):
46
+ return getattr(self, f"derivative_{order}")
47
+
48
+ def set_derivative(self, order, tensor):
49
+ setattr(self, f"derivative_{order}", tensor)
50
+
51
+ def set_temp_derivative(self, order, tensor):
52
+ setattr(self, f"temp_derivative_{order}", tensor)
53
+
54
+ def get_temp_derivative(self, order):
55
+ return getattr(self, f"temp_derivative_{order}")
56
+
57
+ def clear_temp_derivative(self):
58
+ for i in range(self.max_order + 1):
59
+ setattr(self, f"temp_derivative_{i}", None)
60
+
61
+ def move_temp_to_derivative(self):
62
+ for i in range(self.max_order + 1):
63
+ if self.get_temp_derivative(i) is not None:
64
+ setattr(self, f"derivative_{i}", self.get_temp_derivative(i))
65
+ else:
66
+ break
67
+ self.clear_temp_derivative()
68
+
69
+ def get_all_derivatives(self):
70
+ return [getattr(self, f"derivative_{i}") for i in range(self.max_order + 1)]
71
+
72
+ def get_all_filled_derivatives(self):
73
+ return [self.get_derivative(i) for i in range(self.max_order + 1) if self.get_derivative(i) is not None]
74
+
75
+ def taylor_formula(self, distance):
76
+ output = 0
77
+ for i in range(len(self.get_all_filled_derivatives())):
78
+ output += (1 / math.factorial(i)) * self.get_derivative(i) * (distance ** i)
79
+ return output
80
+
81
+ def derivatives_computation(self, x, distance):
82
+ '''
83
+ x: tensor, the new x_0
84
+ distance: int, the distance between the current step and the last full computation step
85
+ '''
86
+ self.set_temp_derivative(0, x)
87
+ for i in range(self.max_order):
88
+ if self.get_derivative(i) is not None:
89
+ self.set_temp_derivative(i+1, (self.get_temp_derivative(i) - self.get_derivative(i)) / distance)
90
+ else:
91
+ break
92
+ self.move_temp_to_derivative()
93
+
94
+ def clear_derivatives(self):
95
+ for i in range(self.max_order + 1):
96
+ setattr(self, f"derivative_{i}", None)
97
+ setattr(self, f"temp_derivative_{i}", None)
98
+
99
+
100
+ @torch.compile
101
+ def decomposition_FFT(x: torch.Tensor, cutoff_ratio: float = 0.1) -> Tuple[torch.Tensor, torch.Tensor]:
102
+ """
103
+ Fast Fourier Transform frequency domain decomposition
104
+
105
+ Args:
106
+ x: Input tensor [B, H*W, D]
107
+ cutoff_ratio: Cutoff frequency ratio (0~0.5)
108
+
109
+ Returns:
110
+ Tuple of (low_freq, high_freq) tensors with same dtype as input
111
+ """
112
+ orig_dtype = x.dtype
113
+ device = x.device
114
+
115
+ x_fp32 = x.to(torch.float32) # Convert to fp32 for FFT compatibility
116
+
117
+ B, HW, D = x_fp32.shape
118
+ freq = torch.fft.fft(x_fp32, dim=1) # FFT on spatial dimension
119
+
120
+ freqs = torch.fft.fftfreq(HW, d=1.0, device=device)
121
+ cutoff = cutoff_ratio * freqs.abs().max()
122
+
123
+ # Create frequency masks
124
+ low_mask = freqs.abs() <= cutoff
125
+ high_mask = ~low_mask
126
+
127
+ low_mask = low_mask[None, :, None] # Broadcast to (B, HW, D)
128
+ high_mask = high_mask[None, :, None]
129
+
130
+ low_freq_complex = freq * low_mask
131
+ high_freq_complex = freq * high_mask
132
+
133
+ # IFFT and take real part
134
+ low_fp32 = torch.fft.ifft(low_freq_complex, dim=1).real
135
+ high_fp32 = torch.fft.ifft(high_freq_complex, dim=1).real
136
+
137
+ low = low_fp32.to(device=device, dtype=orig_dtype)
138
+ high = high_fp32.to(device=device, dtype=orig_dtype)
139
+
140
+ return low, high
141
+
142
+ @torch.compile
143
+ def reconstruction(low_freq: torch.Tensor, high_freq: torch.Tensor) -> torch.Tensor:
144
+ return low_freq + high_freq
145
+
146
+ class CacheWithFreqsContainer(nn.Module):
147
+ def __init__(self, max_order):
148
+ super().__init__()
149
+ self.max_order = max_order
150
+ # 逐个注册buffer
151
+ for i in range(max_order + 1):
152
+ self.register_buffer(f"derivative_{i}_low_freqs", None, persistent=False)
153
+ self.register_buffer(f"derivative_{i}_high_freqs", None, persistent=False)
154
+ self.register_buffer(f"temp_derivative_{i}_low_freqs", None, persistent=False)
155
+ self.register_buffer(f"temp_derivative_{i}_high_freqs", None, persistent=False)
156
+
157
+ def get_derivative(self, order, freqs):
158
+ return getattr(self, f"derivative_{order}_{freqs}")
159
+
160
+ def set_derivative(self, order, freqs, tensor):
161
+ setattr(self, f"derivative_{order}_{freqs}", tensor)
162
+
163
+ def set_temp_derivative(self, order, freqs, tensor):
164
+ setattr(self, f"temp_derivative_{order}_{freqs}", tensor)
165
+
166
+ def get_temp_derivative(self, order, freqs):
167
+ return getattr(self, f"temp_derivative_{order}_{freqs}")
168
+
169
+ def move_temp_to_derivative(self):
170
+ for i in range(self.max_order + 1):
171
+ if self.get_temp_derivative(i, "low_freqs") is not None:
172
+ setattr(self, f"derivative_{i}_low_freqs", self.get_temp_derivative(i, "low_freqs"))
173
+ if self.get_temp_derivative(i, "high_freqs") is not None:
174
+ setattr(self, f"derivative_{i}_high_freqs", self.get_temp_derivative(i, "high_freqs"))
175
+ else:
176
+ break
177
+ self.clear_temp_derivative()
178
+
179
+ def get_all_filled_derivatives(self, freqs):
180
+ return [self.get_derivative(i, freqs) for i in range(self.max_order + 1) if self.get_derivative(i, freqs) is not None]
181
+
182
+ def taylor_formula(self, distance):
183
+ low_freqs_output = 0
184
+ high_freqs_output = 0
185
+ for i in range(len(self.get_all_filled_derivatives("low_freqs"))):
186
+ low_freqs_output += (1 / math.factorial(i)) * self.get_derivative(i, "low_freqs") * (distance ** i)
187
+ for i in range(len(self.get_all_filled_derivatives("high_freqs"))):
188
+ high_freqs_output += (1 / math.factorial(i)) * self.get_derivative(i, "high_freqs") * (distance ** i)
189
+ return reconstruction(low_freqs_output, high_freqs_output)
190
+
191
+ def hermite_formula(self, distance):
192
+ low_freqs_output = 0
193
+ high_freqs_output = 0
194
+ for i in range(len(self.get_all_filled_derivatives("low_freqs"))):
195
+ low_freqs_output += (1 / math.factorial(i)) * self.get_derivative(i, "low_freqs") * (distance ** i)
196
+ for i in range(len(self.get_all_filled_derivatives("high_freqs"))):
197
+ high_freqs_output += (1 / math.factorial(i)) * self.get_derivative(i, "high_freqs") * (distance ** i)
198
+ return reconstruction(low_freqs_output, high_freqs_output)
199
+
200
+ def derivatives_computation(self, x, distance, low_freqs_order, high_freqs_order):
201
+ '''
202
+ x: tensor, the new x_0
203
+ distance: int, the distance between the current step and the last full computation step
204
+ '''
205
+ x_low, x_high = decomposition_FFT(x, cutoff_ratio=0.1)
206
+ self.set_temp_derivative(0, "low_freqs", x_low)
207
+ self.set_temp_derivative(0, "high_freqs", x_high)
208
+ for i in range(low_freqs_order):
209
+ if self.get_derivative(i, "low_freqs") is not None:
210
+ self.set_temp_derivative(i+1, "low_freqs", (self.get_temp_derivative(i, "low_freqs") - self.get_derivative(i, "low_freqs")) / distance)
211
+ for i in range(high_freqs_order):
212
+ if self.get_derivative(i, "high_freqs") is not None:
213
+ self.set_temp_derivative(i+1, "high_freqs", (self.get_temp_derivative(i, "high_freqs") - self.get_derivative(i, "high_freqs")) / distance)
214
+ self.move_temp_to_derivative()
215
+
216
+ def clear_temp_derivative(self):
217
+ for i in range(self.max_order + 1):
218
+ setattr(self, f"temp_derivative_{i}_low_freqs", None)
219
+ setattr(self, f"temp_derivative_{i}_high_freqs", None)
220
+
221
+ def clear_derivatives(self):
222
+ for i in range(self.max_order + 1):
223
+ setattr(self, f"derivative_{i}_low_freqs", None)
224
+ setattr(self, f"derivative_{i}_high_freqs", None)
225
+ setattr(self, f"temp_derivative_{i}_low_freqs", None)
226
+ setattr(self, f"temp_derivative_{i}_high_freqs", None)
config.json ADDED
@@ -0,0 +1,1628 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cfg_distilled": true,
3
+ "use_meanflow": true,
4
+ "add_classification_head": false,
5
+ "anyres_pooling_size": 2,
6
+ "anyres_vit_max_image_size": null,
7
+ "anyres_vit_two_views": false,
8
+ "architectures": [
9
+ "HunyuanImage3ForCausalMM"
10
+ ],
11
+ "auto_map": {
12
+ "AutoConfig": "configuration_hunyuan_image_3.HunyuanImage3Config",
13
+ "AutoModel": "modeling_hunyuan_image_3.HunyuanImage3Model",
14
+ "AutoModelForCausalLM": "modeling_hunyuan_image_3.HunyuanImage3ForCausalMM"
15
+ },
16
+ "attention_bias": false,
17
+ "attention_dropout": 0.0,
18
+ "attention_head_dim": 128,
19
+ "bos_token_id": 127958,
20
+ "cla_share_factor": 2,
21
+ "class_num": 0,
22
+ "dense_list": [
23
+ 4096,
24
+ 0
25
+ ],
26
+ "eod_token_id": 3,
27
+ "eos_token_id": 127957,
28
+ "group_limited_greedy": false,
29
+ "hidden_act": "silu",
30
+ "hidden_size": 4096,
31
+ "im_end_id": 128001,
32
+ "im_newline_id": 11,
33
+ "im_start_id": 128000,
34
+ "image_token_id": 128006,
35
+ "initializer_range": 0.02,
36
+ "intermediate_size": 3072,
37
+ "kv_lora_rank": null,
38
+ "mask_init_id": 12,
39
+ "max_position_embeddings": 22800,
40
+ "mlp_bias": false,
41
+ "model_type": "hunyuan_image_3_moe",
42
+ "moe_drop_tokens": false,
43
+ "moe_intermediate_size": [
44
+ 3072,
45
+ 3072,
46
+ 3072,
47
+ 3072,
48
+ 3072,
49
+ 3072,
50
+ 3072,
51
+ 3072,
52
+ 3072,
53
+ 3072,
54
+ 3072,
55
+ 3072,
56
+ 3072,
57
+ 3072,
58
+ 3072,
59
+ 3072,
60
+ 3072,
61
+ 3072,
62
+ 3072,
63
+ 3072,
64
+ 3072,
65
+ 3072,
66
+ 3072,
67
+ 3072,
68
+ 3072,
69
+ 3072,
70
+ 3072,
71
+ 3072,
72
+ 3072,
73
+ 3072,
74
+ 3072,
75
+ 3072
76
+ ],
77
+ "moe_layer_num_skipped": 0,
78
+ "moe_random_routing_dropped_token": false,
79
+ "moe_topk": [
80
+ 8,
81
+ 8,
82
+ 8,
83
+ 8,
84
+ 8,
85
+ 8,
86
+ 8,
87
+ 8,
88
+ 8,
89
+ 8,
90
+ 8,
91
+ 8,
92
+ 8,
93
+ 8,
94
+ 8,
95
+ 8,
96
+ 8,
97
+ 8,
98
+ 8,
99
+ 8,
100
+ 8,
101
+ 8,
102
+ 8,
103
+ 8,
104
+ 8,
105
+ 8,
106
+ 8,
107
+ 8,
108
+ 8,
109
+ 8,
110
+ 8,
111
+ 8
112
+ ],
113
+ "n_group": false,
114
+ "norm_topk_prob": true,
115
+ "norm_type": "rms",
116
+ "num_attention_heads": 32,
117
+ "num_experts": 64,
118
+ "num_hidden_layers": 32,
119
+ "num_key_value_heads": 8,
120
+ "num_media_embeds": 257,
121
+ "num_shared_expert": [
122
+ 1,
123
+ 1,
124
+ 1,
125
+ 1,
126
+ 1,
127
+ 1,
128
+ 1,
129
+ 1,
130
+ 1,
131
+ 1,
132
+ 1,
133
+ 1,
134
+ 1,
135
+ 1,
136
+ 1,
137
+ 1,
138
+ 1,
139
+ 1,
140
+ 1,
141
+ 1,
142
+ 1,
143
+ 1,
144
+ 1,
145
+ 1,
146
+ 1,
147
+ 1,
148
+ 1,
149
+ 1,
150
+ 1,
151
+ 1,
152
+ 1,
153
+ 1
154
+ ],
155
+ "pad_id": 128009,
156
+ "pad_token_id": 128009,
157
+ "pool_type": "last",
158
+ "position_embedding_xdrope": false,
159
+ "pretraining_tp": 1,
160
+ "q_lora_rank": null,
161
+ "qk_nope_head_dim": null,
162
+ "qk_rope_head_dim": null,
163
+ "rms_norm_eps": 1e-05,
164
+ "rope_scaling": {
165
+ "alpha": 1.0,
166
+ "beta_fast": 32,
167
+ "beta_slow": 1,
168
+ "factor": 1.0,
169
+ "mscale": 1.0,
170
+ "mscale_all_dim": 1.0,
171
+ "type": "custom"
172
+ },
173
+ "rope_theta": 10000.0,
174
+ "routed_scaling_factor": false,
175
+ "skip_cls_token": false,
176
+ "text_end_id": 7,
177
+ "text_start_id": 6,
178
+ "tie_word_embeddings": false,
179
+ "topk_group": false,
180
+ "torch_dtype": "bfloat16",
181
+ "transformers_version": "4.50.0",
182
+ "use_cache": true,
183
+ "use_cla": false,
184
+ "use_mixed_mlp_moe": true,
185
+ "use_mla": false,
186
+ "use_qk_norm": true,
187
+ "use_rotary_pos_emb": true,
188
+ "v_head_dim": null,
189
+ "video_end_id": 10,
190
+ "video_start_id": 9,
191
+ "vit_add_patchemb_bias": false,
192
+ "vit_input_resolution": 224,
193
+ "vit_mapping_type": "resampler",
194
+ "vit_norm_type": "fused",
195
+ "vit_patch": 1,
196
+ "vit_path": null,
197
+ "vit_remove_prenorm": false,
198
+ "vit_token": 64,
199
+ "vit_type": "siglip2-so400m-patch16-naflex",
200
+ "vit_used_rms_norm": false,
201
+ "vocab_size": 133120,
202
+ "xdrope_section": null,
203
+ "head_dim": 128,
204
+ "rope_type": "2d",
205
+ "vae_downsample_factor": [
206
+ 16,
207
+ 16
208
+ ],
209
+ "vit_downsample_factor": [
210
+ 16,
211
+ 16
212
+ ],
213
+ "cond_token_attn_type": "joint_full",
214
+ "cond_image_type": "vae_vit",
215
+ "vae_type": "hunyuan-image-vae-v1",
216
+ "vae_dtype": "float32",
217
+ "vae_autocast_dtype": "float16",
218
+ "vae": {
219
+ "_class_name": "AutoencoderKLConv3D",
220
+ "block_out_channels": [
221
+ 128,
222
+ 256,
223
+ 512,
224
+ 1024,
225
+ 1024
226
+ ],
227
+ "in_channels": 3,
228
+ "out_channels": 3,
229
+ "latent_channels": 32,
230
+ "layers_per_block": 2,
231
+ "ffactor_spatial": 16,
232
+ "ffactor_temporal": 4,
233
+ "sample_size": 384,
234
+ "sample_tsize": 96,
235
+ "downsample_match_channel": true,
236
+ "upsample_match_channel": true,
237
+ "scaling_factor": 0.562679178327931
238
+ },
239
+ "vit": {
240
+ "_attn_implementation": "sdpa",
241
+ "attention_dropout": 0.0,
242
+ "hidden_act": "gelu_pytorch_tanh",
243
+ "hidden_size": 1152,
244
+ "intermediate_size": 4304,
245
+ "layer_norm_eps": 1e-06,
246
+ "num_attention_heads": 16,
247
+ "num_channels": 3,
248
+ "num_hidden_layers": 27,
249
+ "num_patches": 256,
250
+ "patch_size": 16,
251
+ "torch_dtype": "float32",
252
+ "output_attentions": false,
253
+ "output_hidden_states": false,
254
+ "use_return_dict": true
255
+ },
256
+ "vit_processor": {
257
+ "do_convert_rgb": null,
258
+ "do_normalize": true,
259
+ "do_rescale": true,
260
+ "do_resize": true,
261
+ "image_mean": [
262
+ 0.5,
263
+ 0.5,
264
+ 0.5
265
+ ],
266
+ "image_processor_type": "Siglip2ImageProcessorFast",
267
+ "image_std": [
268
+ 0.5,
269
+ 0.5,
270
+ 0.5
271
+ ],
272
+ "max_num_patches": 1024,
273
+ "patch_size": 16,
274
+ "processor_class": "Siglip2Processor",
275
+ "resample": 2,
276
+ "rescale_factor": 0.00392156862745098
277
+ },
278
+ "vit_aligner": {
279
+ "projector_type": "mlp_gelu",
280
+ "input_dim": 1152,
281
+ "n_embed": 4096,
282
+ "depth": 2,
283
+ "torch_dtype": "float32"
284
+ },
285
+ "quantization_config": {
286
+ "quant_method": "auto-round",
287
+ "packing_format": "auto_round:llm_compressor",
288
+ "bits": 8,
289
+ "group_size": 32,
290
+ "sym": true,
291
+ "data_type": "mx_fp",
292
+ "iters": 0,
293
+ "model_free": true,
294
+ "autoround_version": "0.15.0",
295
+ "enable_quanted_input": false,
296
+ "block_name_to_quantize": "model.layers",
297
+ "act_bits": 8,
298
+ "act_data_type": "mx_fp",
299
+ "act_dynamic": true,
300
+ "act_group_size": 32,
301
+ "act_sym": true,
302
+ "extra_config": {
303
+ "final_layer.model.0.emb_layers.1": {
304
+ "bits": 16,
305
+ "data_type": "float",
306
+ "act_bits": 16,
307
+ "act_data_type": "float"
308
+ },
309
+ "final_layer.model.0.in_layers.2": {
310
+ "bits": 16,
311
+ "data_type": "float",
312
+ "act_bits": 16,
313
+ "act_data_type": "float"
314
+ },
315
+ "final_layer.model.0.out_layers.3": {
316
+ "bits": 16,
317
+ "data_type": "float",
318
+ "act_bits": 16,
319
+ "act_data_type": "float"
320
+ },
321
+ "final_layer.model.0.skip_connection": {
322
+ "bits": 16,
323
+ "data_type": "float",
324
+ "act_bits": 16,
325
+ "act_data_type": "float"
326
+ },
327
+ "final_layer.model.1.2": {
328
+ "bits": 16,
329
+ "data_type": "float",
330
+ "act_bits": 16,
331
+ "act_data_type": "float"
332
+ },
333
+ "guidance_emb.mlp.0": {
334
+ "bits": 16,
335
+ "data_type": "float",
336
+ "act_bits": 16,
337
+ "act_data_type": "float"
338
+ },
339
+ "guidance_emb.mlp.2": {
340
+ "bits": 16,
341
+ "data_type": "float",
342
+ "act_bits": 16,
343
+ "act_data_type": "float"
344
+ },
345
+ "lm_head": {
346
+ "bits": 16,
347
+ "data_type": "float",
348
+ "act_bits": 16,
349
+ "act_data_type": "float"
350
+ },
351
+ "model.layers.0.mlp.gate.wg": {
352
+ "bits": 16,
353
+ "data_type": "float",
354
+ "act_bits": 16,
355
+ "act_data_type": "float"
356
+ },
357
+ "model.layers.1.mlp.gate.wg": {
358
+ "bits": 16,
359
+ "data_type": "float",
360
+ "act_bits": 16,
361
+ "act_data_type": "float"
362
+ },
363
+ "model.layers.2.mlp.gate.wg": {
364
+ "bits": 16,
365
+ "data_type": "float",
366
+ "act_bits": 16,
367
+ "act_data_type": "float"
368
+ },
369
+ "model.layers.3.mlp.gate.wg": {
370
+ "bits": 16,
371
+ "data_type": "float",
372
+ "act_bits": 16,
373
+ "act_data_type": "float"
374
+ },
375
+ "model.layers.4.mlp.gate.wg": {
376
+ "bits": 16,
377
+ "data_type": "float",
378
+ "act_bits": 16,
379
+ "act_data_type": "float"
380
+ },
381
+ "model.layers.5.mlp.gate.wg": {
382
+ "bits": 16,
383
+ "data_type": "float",
384
+ "act_bits": 16,
385
+ "act_data_type": "float"
386
+ },
387
+ "model.layers.6.mlp.gate.wg": {
388
+ "bits": 16,
389
+ "data_type": "float",
390
+ "act_bits": 16,
391
+ "act_data_type": "float"
392
+ },
393
+ "model.layers.7.mlp.gate.wg": {
394
+ "bits": 16,
395
+ "data_type": "float",
396
+ "act_bits": 16,
397
+ "act_data_type": "float"
398
+ },
399
+ "model.layers.8.mlp.gate.wg": {
400
+ "bits": 16,
401
+ "data_type": "float",
402
+ "act_bits": 16,
403
+ "act_data_type": "float"
404
+ },
405
+ "model.layers.9.mlp.gate.wg": {
406
+ "bits": 16,
407
+ "data_type": "float",
408
+ "act_bits": 16,
409
+ "act_data_type": "float"
410
+ },
411
+ "model.layers.10.mlp.gate.wg": {
412
+ "bits": 16,
413
+ "data_type": "float",
414
+ "act_bits": 16,
415
+ "act_data_type": "float"
416
+ },
417
+ "model.layers.11.mlp.gate.wg": {
418
+ "bits": 16,
419
+ "data_type": "float",
420
+ "act_bits": 16,
421
+ "act_data_type": "float"
422
+ },
423
+ "model.layers.12.mlp.gate.wg": {
424
+ "bits": 16,
425
+ "data_type": "float",
426
+ "act_bits": 16,
427
+ "act_data_type": "float"
428
+ },
429
+ "model.layers.13.mlp.gate.wg": {
430
+ "bits": 16,
431
+ "data_type": "float",
432
+ "act_bits": 16,
433
+ "act_data_type": "float"
434
+ },
435
+ "model.layers.14.mlp.gate.wg": {
436
+ "bits": 16,
437
+ "data_type": "float",
438
+ "act_bits": 16,
439
+ "act_data_type": "float"
440
+ },
441
+ "model.layers.15.mlp.gate.wg": {
442
+ "bits": 16,
443
+ "data_type": "float",
444
+ "act_bits": 16,
445
+ "act_data_type": "float"
446
+ },
447
+ "model.layers.16.mlp.gate.wg": {
448
+ "bits": 16,
449
+ "data_type": "float",
450
+ "act_bits": 16,
451
+ "act_data_type": "float"
452
+ },
453
+ "model.layers.17.mlp.gate.wg": {
454
+ "bits": 16,
455
+ "data_type": "float",
456
+ "act_bits": 16,
457
+ "act_data_type": "float"
458
+ },
459
+ "model.layers.18.mlp.gate.wg": {
460
+ "bits": 16,
461
+ "data_type": "float",
462
+ "act_bits": 16,
463
+ "act_data_type": "float"
464
+ },
465
+ "model.layers.19.mlp.gate.wg": {
466
+ "bits": 16,
467
+ "data_type": "float",
468
+ "act_bits": 16,
469
+ "act_data_type": "float"
470
+ },
471
+ "model.layers.20.mlp.gate.wg": {
472
+ "bits": 16,
473
+ "data_type": "float",
474
+ "act_bits": 16,
475
+ "act_data_type": "float"
476
+ },
477
+ "model.layers.21.mlp.gate.wg": {
478
+ "bits": 16,
479
+ "data_type": "float",
480
+ "act_bits": 16,
481
+ "act_data_type": "float"
482
+ },
483
+ "model.layers.22.mlp.gate.wg": {
484
+ "bits": 16,
485
+ "data_type": "float",
486
+ "act_bits": 16,
487
+ "act_data_type": "float"
488
+ },
489
+ "model.layers.23.mlp.gate.wg": {
490
+ "bits": 16,
491
+ "data_type": "float",
492
+ "act_bits": 16,
493
+ "act_data_type": "float"
494
+ },
495
+ "model.layers.24.mlp.gate.wg": {
496
+ "bits": 16,
497
+ "data_type": "float",
498
+ "act_bits": 16,
499
+ "act_data_type": "float"
500
+ },
501
+ "model.layers.25.mlp.gate.wg": {
502
+ "bits": 16,
503
+ "data_type": "float",
504
+ "act_bits": 16,
505
+ "act_data_type": "float"
506
+ },
507
+ "model.layers.26.mlp.gate.wg": {
508
+ "bits": 16,
509
+ "data_type": "float",
510
+ "act_bits": 16,
511
+ "act_data_type": "float"
512
+ },
513
+ "model.layers.27.mlp.gate.wg": {
514
+ "bits": 16,
515
+ "data_type": "float",
516
+ "act_bits": 16,
517
+ "act_data_type": "float"
518
+ },
519
+ "model.layers.28.mlp.gate.wg": {
520
+ "bits": 16,
521
+ "data_type": "float",
522
+ "act_bits": 16,
523
+ "act_data_type": "float"
524
+ },
525
+ "model.layers.29.mlp.gate.wg": {
526
+ "bits": 16,
527
+ "data_type": "float",
528
+ "act_bits": 16,
529
+ "act_data_type": "float"
530
+ },
531
+ "model.layers.30.mlp.gate.wg": {
532
+ "bits": 16,
533
+ "data_type": "float",
534
+ "act_bits": 16,
535
+ "act_data_type": "float"
536
+ },
537
+ "model.layers.31.mlp.gate.wg": {
538
+ "bits": 16,
539
+ "data_type": "float",
540
+ "act_bits": 16,
541
+ "act_data_type": "float"
542
+ },
543
+ "model.wte": {
544
+ "bits": 16,
545
+ "data_type": "float",
546
+ "act_bits": 16,
547
+ "act_data_type": "float"
548
+ },
549
+ "timestep_emb.mlp.0": {
550
+ "bits": 16,
551
+ "data_type": "float",
552
+ "act_bits": 16,
553
+ "act_data_type": "float"
554
+ },
555
+ "timestep_emb.mlp.2": {
556
+ "bits": 16,
557
+ "data_type": "float",
558
+ "act_bits": 16,
559
+ "act_data_type": "float"
560
+ },
561
+ "timestep_r_emb.mlp.0": {
562
+ "bits": 16,
563
+ "data_type": "float",
564
+ "act_bits": 16,
565
+ "act_data_type": "float"
566
+ },
567
+ "timestep_r_emb.mlp.2": {
568
+ "bits": 16,
569
+ "data_type": "float",
570
+ "act_bits": 16,
571
+ "act_data_type": "float"
572
+ },
573
+ "vae.decoder.mid.attn_1.k": {
574
+ "bits": 16,
575
+ "data_type": "float",
576
+ "act_bits": 16,
577
+ "act_data_type": "float"
578
+ },
579
+ "vae.decoder.mid.attn_1.proj_out": {
580
+ "bits": 16,
581
+ "data_type": "float",
582
+ "act_bits": 16,
583
+ "act_data_type": "float"
584
+ },
585
+ "vae.decoder.mid.attn_1.q": {
586
+ "bits": 16,
587
+ "data_type": "float",
588
+ "act_bits": 16,
589
+ "act_data_type": "float"
590
+ },
591
+ "vae.decoder.mid.attn_1.v": {
592
+ "bits": 16,
593
+ "data_type": "float",
594
+ "act_bits": 16,
595
+ "act_data_type": "float"
596
+ },
597
+ "vae.encoder.mid.attn_1.k": {
598
+ "bits": 16,
599
+ "data_type": "float",
600
+ "act_bits": 16,
601
+ "act_data_type": "float"
602
+ },
603
+ "vae.encoder.mid.attn_1.proj_out": {
604
+ "bits": 16,
605
+ "data_type": "float",
606
+ "act_bits": 16,
607
+ "act_data_type": "float"
608
+ },
609
+ "vae.encoder.mid.attn_1.q": {
610
+ "bits": 16,
611
+ "data_type": "float",
612
+ "act_bits": 16,
613
+ "act_data_type": "float"
614
+ },
615
+ "vae.encoder.mid.attn_1.v": {
616
+ "bits": 16,
617
+ "data_type": "float",
618
+ "act_bits": 16,
619
+ "act_data_type": "float"
620
+ },
621
+ "vision_aligner.layers.0": {
622
+ "bits": 16,
623
+ "data_type": "float",
624
+ "act_bits": 16,
625
+ "act_data_type": "float"
626
+ },
627
+ "vision_aligner.layers.2": {
628
+ "bits": 16,
629
+ "data_type": "float",
630
+ "act_bits": 16,
631
+ "act_data_type": "float"
632
+ },
633
+ "vision_model.encoder.layers.0.mlp.fc1": {
634
+ "bits": 16,
635
+ "data_type": "float",
636
+ "act_bits": 16,
637
+ "act_data_type": "float"
638
+ },
639
+ "vision_model.encoder.layers.0.mlp.fc2": {
640
+ "bits": 16,
641
+ "data_type": "float",
642
+ "act_bits": 16,
643
+ "act_data_type": "float"
644
+ },
645
+ "vision_model.encoder.layers.0.self_attn.k_proj": {
646
+ "bits": 16,
647
+ "data_type": "float",
648
+ "act_bits": 16,
649
+ "act_data_type": "float"
650
+ },
651
+ "vision_model.encoder.layers.0.self_attn.out_proj": {
652
+ "bits": 16,
653
+ "data_type": "float",
654
+ "act_bits": 16,
655
+ "act_data_type": "float"
656
+ },
657
+ "vision_model.encoder.layers.0.self_attn.q_proj": {
658
+ "bits": 16,
659
+ "data_type": "float",
660
+ "act_bits": 16,
661
+ "act_data_type": "float"
662
+ },
663
+ "vision_model.encoder.layers.0.self_attn.v_proj": {
664
+ "bits": 16,
665
+ "data_type": "float",
666
+ "act_bits": 16,
667
+ "act_data_type": "float"
668
+ },
669
+ "vision_model.encoder.layers.1.mlp.fc1": {
670
+ "bits": 16,
671
+ "data_type": "float",
672
+ "act_bits": 16,
673
+ "act_data_type": "float"
674
+ },
675
+ "vision_model.encoder.layers.1.mlp.fc2": {
676
+ "bits": 16,
677
+ "data_type": "float",
678
+ "act_bits": 16,
679
+ "act_data_type": "float"
680
+ },
681
+ "vision_model.encoder.layers.1.self_attn.k_proj": {
682
+ "bits": 16,
683
+ "data_type": "float",
684
+ "act_bits": 16,
685
+ "act_data_type": "float"
686
+ },
687
+ "vision_model.encoder.layers.1.self_attn.out_proj": {
688
+ "bits": 16,
689
+ "data_type": "float",
690
+ "act_bits": 16,
691
+ "act_data_type": "float"
692
+ },
693
+ "vision_model.encoder.layers.1.self_attn.q_proj": {
694
+ "bits": 16,
695
+ "data_type": "float",
696
+ "act_bits": 16,
697
+ "act_data_type": "float"
698
+ },
699
+ "vision_model.encoder.layers.1.self_attn.v_proj": {
700
+ "bits": 16,
701
+ "data_type": "float",
702
+ "act_bits": 16,
703
+ "act_data_type": "float"
704
+ },
705
+ "vision_model.encoder.layers.10.mlp.fc1": {
706
+ "bits": 16,
707
+ "data_type": "float",
708
+ "act_bits": 16,
709
+ "act_data_type": "float"
710
+ },
711
+ "vision_model.encoder.layers.10.mlp.fc2": {
712
+ "bits": 16,
713
+ "data_type": "float",
714
+ "act_bits": 16,
715
+ "act_data_type": "float"
716
+ },
717
+ "vision_model.encoder.layers.10.self_attn.k_proj": {
718
+ "bits": 16,
719
+ "data_type": "float",
720
+ "act_bits": 16,
721
+ "act_data_type": "float"
722
+ },
723
+ "vision_model.encoder.layers.10.self_attn.out_proj": {
724
+ "bits": 16,
725
+ "data_type": "float",
726
+ "act_bits": 16,
727
+ "act_data_type": "float"
728
+ },
729
+ "vision_model.encoder.layers.10.self_attn.q_proj": {
730
+ "bits": 16,
731
+ "data_type": "float",
732
+ "act_bits": 16,
733
+ "act_data_type": "float"
734
+ },
735
+ "vision_model.encoder.layers.10.self_attn.v_proj": {
736
+ "bits": 16,
737
+ "data_type": "float",
738
+ "act_bits": 16,
739
+ "act_data_type": "float"
740
+ },
741
+ "vision_model.encoder.layers.11.mlp.fc1": {
742
+ "bits": 16,
743
+ "data_type": "float",
744
+ "act_bits": 16,
745
+ "act_data_type": "float"
746
+ },
747
+ "vision_model.encoder.layers.11.mlp.fc2": {
748
+ "bits": 16,
749
+ "data_type": "float",
750
+ "act_bits": 16,
751
+ "act_data_type": "float"
752
+ },
753
+ "vision_model.encoder.layers.11.self_attn.k_proj": {
754
+ "bits": 16,
755
+ "data_type": "float",
756
+ "act_bits": 16,
757
+ "act_data_type": "float"
758
+ },
759
+ "vision_model.encoder.layers.11.self_attn.out_proj": {
760
+ "bits": 16,
761
+ "data_type": "float",
762
+ "act_bits": 16,
763
+ "act_data_type": "float"
764
+ },
765
+ "vision_model.encoder.layers.11.self_attn.q_proj": {
766
+ "bits": 16,
767
+ "data_type": "float",
768
+ "act_bits": 16,
769
+ "act_data_type": "float"
770
+ },
771
+ "vision_model.encoder.layers.11.self_attn.v_proj": {
772
+ "bits": 16,
773
+ "data_type": "float",
774
+ "act_bits": 16,
775
+ "act_data_type": "float"
776
+ },
777
+ "vision_model.encoder.layers.12.mlp.fc1": {
778
+ "bits": 16,
779
+ "data_type": "float",
780
+ "act_bits": 16,
781
+ "act_data_type": "float"
782
+ },
783
+ "vision_model.encoder.layers.12.mlp.fc2": {
784
+ "bits": 16,
785
+ "data_type": "float",
786
+ "act_bits": 16,
787
+ "act_data_type": "float"
788
+ },
789
+ "vision_model.encoder.layers.12.self_attn.k_proj": {
790
+ "bits": 16,
791
+ "data_type": "float",
792
+ "act_bits": 16,
793
+ "act_data_type": "float"
794
+ },
795
+ "vision_model.encoder.layers.12.self_attn.out_proj": {
796
+ "bits": 16,
797
+ "data_type": "float",
798
+ "act_bits": 16,
799
+ "act_data_type": "float"
800
+ },
801
+ "vision_model.encoder.layers.12.self_attn.q_proj": {
802
+ "bits": 16,
803
+ "data_type": "float",
804
+ "act_bits": 16,
805
+ "act_data_type": "float"
806
+ },
807
+ "vision_model.encoder.layers.12.self_attn.v_proj": {
808
+ "bits": 16,
809
+ "data_type": "float",
810
+ "act_bits": 16,
811
+ "act_data_type": "float"
812
+ },
813
+ "vision_model.encoder.layers.13.mlp.fc1": {
814
+ "bits": 16,
815
+ "data_type": "float",
816
+ "act_bits": 16,
817
+ "act_data_type": "float"
818
+ },
819
+ "vision_model.encoder.layers.13.mlp.fc2": {
820
+ "bits": 16,
821
+ "data_type": "float",
822
+ "act_bits": 16,
823
+ "act_data_type": "float"
824
+ },
825
+ "vision_model.encoder.layers.13.self_attn.k_proj": {
826
+ "bits": 16,
827
+ "data_type": "float",
828
+ "act_bits": 16,
829
+ "act_data_type": "float"
830
+ },
831
+ "vision_model.encoder.layers.13.self_attn.out_proj": {
832
+ "bits": 16,
833
+ "data_type": "float",
834
+ "act_bits": 16,
835
+ "act_data_type": "float"
836
+ },
837
+ "vision_model.encoder.layers.13.self_attn.q_proj": {
838
+ "bits": 16,
839
+ "data_type": "float",
840
+ "act_bits": 16,
841
+ "act_data_type": "float"
842
+ },
843
+ "vision_model.encoder.layers.13.self_attn.v_proj": {
844
+ "bits": 16,
845
+ "data_type": "float",
846
+ "act_bits": 16,
847
+ "act_data_type": "float"
848
+ },
849
+ "vision_model.encoder.layers.14.mlp.fc1": {
850
+ "bits": 16,
851
+ "data_type": "float",
852
+ "act_bits": 16,
853
+ "act_data_type": "float"
854
+ },
855
+ "vision_model.encoder.layers.14.mlp.fc2": {
856
+ "bits": 16,
857
+ "data_type": "float",
858
+ "act_bits": 16,
859
+ "act_data_type": "float"
860
+ },
861
+ "vision_model.encoder.layers.14.self_attn.k_proj": {
862
+ "bits": 16,
863
+ "data_type": "float",
864
+ "act_bits": 16,
865
+ "act_data_type": "float"
866
+ },
867
+ "vision_model.encoder.layers.14.self_attn.out_proj": {
868
+ "bits": 16,
869
+ "data_type": "float",
870
+ "act_bits": 16,
871
+ "act_data_type": "float"
872
+ },
873
+ "vision_model.encoder.layers.14.self_attn.q_proj": {
874
+ "bits": 16,
875
+ "data_type": "float",
876
+ "act_bits": 16,
877
+ "act_data_type": "float"
878
+ },
879
+ "vision_model.encoder.layers.14.self_attn.v_proj": {
880
+ "bits": 16,
881
+ "data_type": "float",
882
+ "act_bits": 16,
883
+ "act_data_type": "float"
884
+ },
885
+ "vision_model.encoder.layers.15.mlp.fc1": {
886
+ "bits": 16,
887
+ "data_type": "float",
888
+ "act_bits": 16,
889
+ "act_data_type": "float"
890
+ },
891
+ "vision_model.encoder.layers.15.mlp.fc2": {
892
+ "bits": 16,
893
+ "data_type": "float",
894
+ "act_bits": 16,
895
+ "act_data_type": "float"
896
+ },
897
+ "vision_model.encoder.layers.15.self_attn.k_proj": {
898
+ "bits": 16,
899
+ "data_type": "float",
900
+ "act_bits": 16,
901
+ "act_data_type": "float"
902
+ },
903
+ "vision_model.encoder.layers.15.self_attn.out_proj": {
904
+ "bits": 16,
905
+ "data_type": "float",
906
+ "act_bits": 16,
907
+ "act_data_type": "float"
908
+ },
909
+ "vision_model.encoder.layers.15.self_attn.q_proj": {
910
+ "bits": 16,
911
+ "data_type": "float",
912
+ "act_bits": 16,
913
+ "act_data_type": "float"
914
+ },
915
+ "vision_model.encoder.layers.15.self_attn.v_proj": {
916
+ "bits": 16,
917
+ "data_type": "float",
918
+ "act_bits": 16,
919
+ "act_data_type": "float"
920
+ },
921
+ "vision_model.encoder.layers.16.mlp.fc1": {
922
+ "bits": 16,
923
+ "data_type": "float",
924
+ "act_bits": 16,
925
+ "act_data_type": "float"
926
+ },
927
+ "vision_model.encoder.layers.16.mlp.fc2": {
928
+ "bits": 16,
929
+ "data_type": "float",
930
+ "act_bits": 16,
931
+ "act_data_type": "float"
932
+ },
933
+ "vision_model.encoder.layers.16.self_attn.k_proj": {
934
+ "bits": 16,
935
+ "data_type": "float",
936
+ "act_bits": 16,
937
+ "act_data_type": "float"
938
+ },
939
+ "vision_model.encoder.layers.16.self_attn.out_proj": {
940
+ "bits": 16,
941
+ "data_type": "float",
942
+ "act_bits": 16,
943
+ "act_data_type": "float"
944
+ },
945
+ "vision_model.encoder.layers.16.self_attn.q_proj": {
946
+ "bits": 16,
947
+ "data_type": "float",
948
+ "act_bits": 16,
949
+ "act_data_type": "float"
950
+ },
951
+ "vision_model.encoder.layers.16.self_attn.v_proj": {
952
+ "bits": 16,
953
+ "data_type": "float",
954
+ "act_bits": 16,
955
+ "act_data_type": "float"
956
+ },
957
+ "vision_model.encoder.layers.17.mlp.fc1": {
958
+ "bits": 16,
959
+ "data_type": "float",
960
+ "act_bits": 16,
961
+ "act_data_type": "float"
962
+ },
963
+ "vision_model.encoder.layers.17.mlp.fc2": {
964
+ "bits": 16,
965
+ "data_type": "float",
966
+ "act_bits": 16,
967
+ "act_data_type": "float"
968
+ },
969
+ "vision_model.encoder.layers.17.self_attn.k_proj": {
970
+ "bits": 16,
971
+ "data_type": "float",
972
+ "act_bits": 16,
973
+ "act_data_type": "float"
974
+ },
975
+ "vision_model.encoder.layers.17.self_attn.out_proj": {
976
+ "bits": 16,
977
+ "data_type": "float",
978
+ "act_bits": 16,
979
+ "act_data_type": "float"
980
+ },
981
+ "vision_model.encoder.layers.17.self_attn.q_proj": {
982
+ "bits": 16,
983
+ "data_type": "float",
984
+ "act_bits": 16,
985
+ "act_data_type": "float"
986
+ },
987
+ "vision_model.encoder.layers.17.self_attn.v_proj": {
988
+ "bits": 16,
989
+ "data_type": "float",
990
+ "act_bits": 16,
991
+ "act_data_type": "float"
992
+ },
993
+ "vision_model.encoder.layers.18.mlp.fc1": {
994
+ "bits": 16,
995
+ "data_type": "float",
996
+ "act_bits": 16,
997
+ "act_data_type": "float"
998
+ },
999
+ "vision_model.encoder.layers.18.mlp.fc2": {
1000
+ "bits": 16,
1001
+ "data_type": "float",
1002
+ "act_bits": 16,
1003
+ "act_data_type": "float"
1004
+ },
1005
+ "vision_model.encoder.layers.18.self_attn.k_proj": {
1006
+ "bits": 16,
1007
+ "data_type": "float",
1008
+ "act_bits": 16,
1009
+ "act_data_type": "float"
1010
+ },
1011
+ "vision_model.encoder.layers.18.self_attn.out_proj": {
1012
+ "bits": 16,
1013
+ "data_type": "float",
1014
+ "act_bits": 16,
1015
+ "act_data_type": "float"
1016
+ },
1017
+ "vision_model.encoder.layers.18.self_attn.q_proj": {
1018
+ "bits": 16,
1019
+ "data_type": "float",
1020
+ "act_bits": 16,
1021
+ "act_data_type": "float"
1022
+ },
1023
+ "vision_model.encoder.layers.18.self_attn.v_proj": {
1024
+ "bits": 16,
1025
+ "data_type": "float",
1026
+ "act_bits": 16,
1027
+ "act_data_type": "float"
1028
+ },
1029
+ "vision_model.encoder.layers.19.mlp.fc1": {
1030
+ "bits": 16,
1031
+ "data_type": "float",
1032
+ "act_bits": 16,
1033
+ "act_data_type": "float"
1034
+ },
1035
+ "vision_model.encoder.layers.19.mlp.fc2": {
1036
+ "bits": 16,
1037
+ "data_type": "float",
1038
+ "act_bits": 16,
1039
+ "act_data_type": "float"
1040
+ },
1041
+ "vision_model.encoder.layers.19.self_attn.k_proj": {
1042
+ "bits": 16,
1043
+ "data_type": "float",
1044
+ "act_bits": 16,
1045
+ "act_data_type": "float"
1046
+ },
1047
+ "vision_model.encoder.layers.19.self_attn.out_proj": {
1048
+ "bits": 16,
1049
+ "data_type": "float",
1050
+ "act_bits": 16,
1051
+ "act_data_type": "float"
1052
+ },
1053
+ "vision_model.encoder.layers.19.self_attn.q_proj": {
1054
+ "bits": 16,
1055
+ "data_type": "float",
1056
+ "act_bits": 16,
1057
+ "act_data_type": "float"
1058
+ },
1059
+ "vision_model.encoder.layers.19.self_attn.v_proj": {
1060
+ "bits": 16,
1061
+ "data_type": "float",
1062
+ "act_bits": 16,
1063
+ "act_data_type": "float"
1064
+ },
1065
+ "vision_model.encoder.layers.2.mlp.fc1": {
1066
+ "bits": 16,
1067
+ "data_type": "float",
1068
+ "act_bits": 16,
1069
+ "act_data_type": "float"
1070
+ },
1071
+ "vision_model.encoder.layers.2.mlp.fc2": {
1072
+ "bits": 16,
1073
+ "data_type": "float",
1074
+ "act_bits": 16,
1075
+ "act_data_type": "float"
1076
+ },
1077
+ "vision_model.encoder.layers.2.self_attn.k_proj": {
1078
+ "bits": 16,
1079
+ "data_type": "float",
1080
+ "act_bits": 16,
1081
+ "act_data_type": "float"
1082
+ },
1083
+ "vision_model.encoder.layers.2.self_attn.out_proj": {
1084
+ "bits": 16,
1085
+ "data_type": "float",
1086
+ "act_bits": 16,
1087
+ "act_data_type": "float"
1088
+ },
1089
+ "vision_model.encoder.layers.2.self_attn.q_proj": {
1090
+ "bits": 16,
1091
+ "data_type": "float",
1092
+ "act_bits": 16,
1093
+ "act_data_type": "float"
1094
+ },
1095
+ "vision_model.encoder.layers.2.self_attn.v_proj": {
1096
+ "bits": 16,
1097
+ "data_type": "float",
1098
+ "act_bits": 16,
1099
+ "act_data_type": "float"
1100
+ },
1101
+ "vision_model.encoder.layers.20.mlp.fc1": {
1102
+ "bits": 16,
1103
+ "data_type": "float",
1104
+ "act_bits": 16,
1105
+ "act_data_type": "float"
1106
+ },
1107
+ "vision_model.encoder.layers.20.mlp.fc2": {
1108
+ "bits": 16,
1109
+ "data_type": "float",
1110
+ "act_bits": 16,
1111
+ "act_data_type": "float"
1112
+ },
1113
+ "vision_model.encoder.layers.20.self_attn.k_proj": {
1114
+ "bits": 16,
1115
+ "data_type": "float",
1116
+ "act_bits": 16,
1117
+ "act_data_type": "float"
1118
+ },
1119
+ "vision_model.encoder.layers.20.self_attn.out_proj": {
1120
+ "bits": 16,
1121
+ "data_type": "float",
1122
+ "act_bits": 16,
1123
+ "act_data_type": "float"
1124
+ },
1125
+ "vision_model.encoder.layers.20.self_attn.q_proj": {
1126
+ "bits": 16,
1127
+ "data_type": "float",
1128
+ "act_bits": 16,
1129
+ "act_data_type": "float"
1130
+ },
1131
+ "vision_model.encoder.layers.20.self_attn.v_proj": {
1132
+ "bits": 16,
1133
+ "data_type": "float",
1134
+ "act_bits": 16,
1135
+ "act_data_type": "float"
1136
+ },
1137
+ "vision_model.encoder.layers.21.mlp.fc1": {
1138
+ "bits": 16,
1139
+ "data_type": "float",
1140
+ "act_bits": 16,
1141
+ "act_data_type": "float"
1142
+ },
1143
+ "vision_model.encoder.layers.21.mlp.fc2": {
1144
+ "bits": 16,
1145
+ "data_type": "float",
1146
+ "act_bits": 16,
1147
+ "act_data_type": "float"
1148
+ },
1149
+ "vision_model.encoder.layers.21.self_attn.k_proj": {
1150
+ "bits": 16,
1151
+ "data_type": "float",
1152
+ "act_bits": 16,
1153
+ "act_data_type": "float"
1154
+ },
1155
+ "vision_model.encoder.layers.21.self_attn.out_proj": {
1156
+ "bits": 16,
1157
+ "data_type": "float",
1158
+ "act_bits": 16,
1159
+ "act_data_type": "float"
1160
+ },
1161
+ "vision_model.encoder.layers.21.self_attn.q_proj": {
1162
+ "bits": 16,
1163
+ "data_type": "float",
1164
+ "act_bits": 16,
1165
+ "act_data_type": "float"
1166
+ },
1167
+ "vision_model.encoder.layers.21.self_attn.v_proj": {
1168
+ "bits": 16,
1169
+ "data_type": "float",
1170
+ "act_bits": 16,
1171
+ "act_data_type": "float"
1172
+ },
1173
+ "vision_model.encoder.layers.22.mlp.fc1": {
1174
+ "bits": 16,
1175
+ "data_type": "float",
1176
+ "act_bits": 16,
1177
+ "act_data_type": "float"
1178
+ },
1179
+ "vision_model.encoder.layers.22.mlp.fc2": {
1180
+ "bits": 16,
1181
+ "data_type": "float",
1182
+ "act_bits": 16,
1183
+ "act_data_type": "float"
1184
+ },
1185
+ "vision_model.encoder.layers.22.self_attn.k_proj": {
1186
+ "bits": 16,
1187
+ "data_type": "float",
1188
+ "act_bits": 16,
1189
+ "act_data_type": "float"
1190
+ },
1191
+ "vision_model.encoder.layers.22.self_attn.out_proj": {
1192
+ "bits": 16,
1193
+ "data_type": "float",
1194
+ "act_bits": 16,
1195
+ "act_data_type": "float"
1196
+ },
1197
+ "vision_model.encoder.layers.22.self_attn.q_proj": {
1198
+ "bits": 16,
1199
+ "data_type": "float",
1200
+ "act_bits": 16,
1201
+ "act_data_type": "float"
1202
+ },
1203
+ "vision_model.encoder.layers.22.self_attn.v_proj": {
1204
+ "bits": 16,
1205
+ "data_type": "float",
1206
+ "act_bits": 16,
1207
+ "act_data_type": "float"
1208
+ },
1209
+ "vision_model.encoder.layers.23.mlp.fc1": {
1210
+ "bits": 16,
1211
+ "data_type": "float",
1212
+ "act_bits": 16,
1213
+ "act_data_type": "float"
1214
+ },
1215
+ "vision_model.encoder.layers.23.mlp.fc2": {
1216
+ "bits": 16,
1217
+ "data_type": "float",
1218
+ "act_bits": 16,
1219
+ "act_data_type": "float"
1220
+ },
1221
+ "vision_model.encoder.layers.23.self_attn.k_proj": {
1222
+ "bits": 16,
1223
+ "data_type": "float",
1224
+ "act_bits": 16,
1225
+ "act_data_type": "float"
1226
+ },
1227
+ "vision_model.encoder.layers.23.self_attn.out_proj": {
1228
+ "bits": 16,
1229
+ "data_type": "float",
1230
+ "act_bits": 16,
1231
+ "act_data_type": "float"
1232
+ },
1233
+ "vision_model.encoder.layers.23.self_attn.q_proj": {
1234
+ "bits": 16,
1235
+ "data_type": "float",
1236
+ "act_bits": 16,
1237
+ "act_data_type": "float"
1238
+ },
1239
+ "vision_model.encoder.layers.23.self_attn.v_proj": {
1240
+ "bits": 16,
1241
+ "data_type": "float",
1242
+ "act_bits": 16,
1243
+ "act_data_type": "float"
1244
+ },
1245
+ "vision_model.encoder.layers.24.mlp.fc1": {
1246
+ "bits": 16,
1247
+ "data_type": "float",
1248
+ "act_bits": 16,
1249
+ "act_data_type": "float"
1250
+ },
1251
+ "vision_model.encoder.layers.24.mlp.fc2": {
1252
+ "bits": 16,
1253
+ "data_type": "float",
1254
+ "act_bits": 16,
1255
+ "act_data_type": "float"
1256
+ },
1257
+ "vision_model.encoder.layers.24.self_attn.k_proj": {
1258
+ "bits": 16,
1259
+ "data_type": "float",
1260
+ "act_bits": 16,
1261
+ "act_data_type": "float"
1262
+ },
1263
+ "vision_model.encoder.layers.24.self_attn.out_proj": {
1264
+ "bits": 16,
1265
+ "data_type": "float",
1266
+ "act_bits": 16,
1267
+ "act_data_type": "float"
1268
+ },
1269
+ "vision_model.encoder.layers.24.self_attn.q_proj": {
1270
+ "bits": 16,
1271
+ "data_type": "float",
1272
+ "act_bits": 16,
1273
+ "act_data_type": "float"
1274
+ },
1275
+ "vision_model.encoder.layers.24.self_attn.v_proj": {
1276
+ "bits": 16,
1277
+ "data_type": "float",
1278
+ "act_bits": 16,
1279
+ "act_data_type": "float"
1280
+ },
1281
+ "vision_model.encoder.layers.25.mlp.fc1": {
1282
+ "bits": 16,
1283
+ "data_type": "float",
1284
+ "act_bits": 16,
1285
+ "act_data_type": "float"
1286
+ },
1287
+ "vision_model.encoder.layers.25.mlp.fc2": {
1288
+ "bits": 16,
1289
+ "data_type": "float",
1290
+ "act_bits": 16,
1291
+ "act_data_type": "float"
1292
+ },
1293
+ "vision_model.encoder.layers.25.self_attn.k_proj": {
1294
+ "bits": 16,
1295
+ "data_type": "float",
1296
+ "act_bits": 16,
1297
+ "act_data_type": "float"
1298
+ },
1299
+ "vision_model.encoder.layers.25.self_attn.out_proj": {
1300
+ "bits": 16,
1301
+ "data_type": "float",
1302
+ "act_bits": 16,
1303
+ "act_data_type": "float"
1304
+ },
1305
+ "vision_model.encoder.layers.25.self_attn.q_proj": {
1306
+ "bits": 16,
1307
+ "data_type": "float",
1308
+ "act_bits": 16,
1309
+ "act_data_type": "float"
1310
+ },
1311
+ "vision_model.encoder.layers.25.self_attn.v_proj": {
1312
+ "bits": 16,
1313
+ "data_type": "float",
1314
+ "act_bits": 16,
1315
+ "act_data_type": "float"
1316
+ },
1317
+ "vision_model.encoder.layers.26.mlp.fc1": {
1318
+ "bits": 16,
1319
+ "data_type": "float",
1320
+ "act_bits": 16,
1321
+ "act_data_type": "float"
1322
+ },
1323
+ "vision_model.encoder.layers.26.mlp.fc2": {
1324
+ "bits": 16,
1325
+ "data_type": "float",
1326
+ "act_bits": 16,
1327
+ "act_data_type": "float"
1328
+ },
1329
+ "vision_model.encoder.layers.26.self_attn.k_proj": {
1330
+ "bits": 16,
1331
+ "data_type": "float",
1332
+ "act_bits": 16,
1333
+ "act_data_type": "float"
1334
+ },
1335
+ "vision_model.encoder.layers.26.self_attn.out_proj": {
1336
+ "bits": 16,
1337
+ "data_type": "float",
1338
+ "act_bits": 16,
1339
+ "act_data_type": "float"
1340
+ },
1341
+ "vision_model.encoder.layers.26.self_attn.q_proj": {
1342
+ "bits": 16,
1343
+ "data_type": "float",
1344
+ "act_bits": 16,
1345
+ "act_data_type": "float"
1346
+ },
1347
+ "vision_model.encoder.layers.26.self_attn.v_proj": {
1348
+ "bits": 16,
1349
+ "data_type": "float",
1350
+ "act_bits": 16,
1351
+ "act_data_type": "float"
1352
+ },
1353
+ "vision_model.encoder.layers.3.mlp.fc1": {
1354
+ "bits": 16,
1355
+ "data_type": "float",
1356
+ "act_bits": 16,
1357
+ "act_data_type": "float"
1358
+ },
1359
+ "vision_model.encoder.layers.3.mlp.fc2": {
1360
+ "bits": 16,
1361
+ "data_type": "float",
1362
+ "act_bits": 16,
1363
+ "act_data_type": "float"
1364
+ },
1365
+ "vision_model.encoder.layers.3.self_attn.k_proj": {
1366
+ "bits": 16,
1367
+ "data_type": "float",
1368
+ "act_bits": 16,
1369
+ "act_data_type": "float"
1370
+ },
1371
+ "vision_model.encoder.layers.3.self_attn.out_proj": {
1372
+ "bits": 16,
1373
+ "data_type": "float",
1374
+ "act_bits": 16,
1375
+ "act_data_type": "float"
1376
+ },
1377
+ "vision_model.encoder.layers.3.self_attn.q_proj": {
1378
+ "bits": 16,
1379
+ "data_type": "float",
1380
+ "act_bits": 16,
1381
+ "act_data_type": "float"
1382
+ },
1383
+ "vision_model.encoder.layers.3.self_attn.v_proj": {
1384
+ "bits": 16,
1385
+ "data_type": "float",
1386
+ "act_bits": 16,
1387
+ "act_data_type": "float"
1388
+ },
1389
+ "vision_model.encoder.layers.4.mlp.fc1": {
1390
+ "bits": 16,
1391
+ "data_type": "float",
1392
+ "act_bits": 16,
1393
+ "act_data_type": "float"
1394
+ },
1395
+ "vision_model.encoder.layers.4.mlp.fc2": {
1396
+ "bits": 16,
1397
+ "data_type": "float",
1398
+ "act_bits": 16,
1399
+ "act_data_type": "float"
1400
+ },
1401
+ "vision_model.encoder.layers.4.self_attn.k_proj": {
1402
+ "bits": 16,
1403
+ "data_type": "float",
1404
+ "act_bits": 16,
1405
+ "act_data_type": "float"
1406
+ },
1407
+ "vision_model.encoder.layers.4.self_attn.out_proj": {
1408
+ "bits": 16,
1409
+ "data_type": "float",
1410
+ "act_bits": 16,
1411
+ "act_data_type": "float"
1412
+ },
1413
+ "vision_model.encoder.layers.4.self_attn.q_proj": {
1414
+ "bits": 16,
1415
+ "data_type": "float",
1416
+ "act_bits": 16,
1417
+ "act_data_type": "float"
1418
+ },
1419
+ "vision_model.encoder.layers.4.self_attn.v_proj": {
1420
+ "bits": 16,
1421
+ "data_type": "float",
1422
+ "act_bits": 16,
1423
+ "act_data_type": "float"
1424
+ },
1425
+ "vision_model.encoder.layers.5.mlp.fc1": {
1426
+ "bits": 16,
1427
+ "data_type": "float",
1428
+ "act_bits": 16,
1429
+ "act_data_type": "float"
1430
+ },
1431
+ "vision_model.encoder.layers.5.mlp.fc2": {
1432
+ "bits": 16,
1433
+ "data_type": "float",
1434
+ "act_bits": 16,
1435
+ "act_data_type": "float"
1436
+ },
1437
+ "vision_model.encoder.layers.5.self_attn.k_proj": {
1438
+ "bits": 16,
1439
+ "data_type": "float",
1440
+ "act_bits": 16,
1441
+ "act_data_type": "float"
1442
+ },
1443
+ "vision_model.encoder.layers.5.self_attn.out_proj": {
1444
+ "bits": 16,
1445
+ "data_type": "float",
1446
+ "act_bits": 16,
1447
+ "act_data_type": "float"
1448
+ },
1449
+ "vision_model.encoder.layers.5.self_attn.q_proj": {
1450
+ "bits": 16,
1451
+ "data_type": "float",
1452
+ "act_bits": 16,
1453
+ "act_data_type": "float"
1454
+ },
1455
+ "vision_model.encoder.layers.5.self_attn.v_proj": {
1456
+ "bits": 16,
1457
+ "data_type": "float",
1458
+ "act_bits": 16,
1459
+ "act_data_type": "float"
1460
+ },
1461
+ "vision_model.encoder.layers.6.mlp.fc1": {
1462
+ "bits": 16,
1463
+ "data_type": "float",
1464
+ "act_bits": 16,
1465
+ "act_data_type": "float"
1466
+ },
1467
+ "vision_model.encoder.layers.6.mlp.fc2": {
1468
+ "bits": 16,
1469
+ "data_type": "float",
1470
+ "act_bits": 16,
1471
+ "act_data_type": "float"
1472
+ },
1473
+ "vision_model.encoder.layers.6.self_attn.k_proj": {
1474
+ "bits": 16,
1475
+ "data_type": "float",
1476
+ "act_bits": 16,
1477
+ "act_data_type": "float"
1478
+ },
1479
+ "vision_model.encoder.layers.6.self_attn.out_proj": {
1480
+ "bits": 16,
1481
+ "data_type": "float",
1482
+ "act_bits": 16,
1483
+ "act_data_type": "float"
1484
+ },
1485
+ "vision_model.encoder.layers.6.self_attn.q_proj": {
1486
+ "bits": 16,
1487
+ "data_type": "float",
1488
+ "act_bits": 16,
1489
+ "act_data_type": "float"
1490
+ },
1491
+ "vision_model.encoder.layers.6.self_attn.v_proj": {
1492
+ "bits": 16,
1493
+ "data_type": "float",
1494
+ "act_bits": 16,
1495
+ "act_data_type": "float"
1496
+ },
1497
+ "vision_model.encoder.layers.7.mlp.fc1": {
1498
+ "bits": 16,
1499
+ "data_type": "float",
1500
+ "act_bits": 16,
1501
+ "act_data_type": "float"
1502
+ },
1503
+ "vision_model.encoder.layers.7.mlp.fc2": {
1504
+ "bits": 16,
1505
+ "data_type": "float",
1506
+ "act_bits": 16,
1507
+ "act_data_type": "float"
1508
+ },
1509
+ "vision_model.encoder.layers.7.self_attn.k_proj": {
1510
+ "bits": 16,
1511
+ "data_type": "float",
1512
+ "act_bits": 16,
1513
+ "act_data_type": "float"
1514
+ },
1515
+ "vision_model.encoder.layers.7.self_attn.out_proj": {
1516
+ "bits": 16,
1517
+ "data_type": "float",
1518
+ "act_bits": 16,
1519
+ "act_data_type": "float"
1520
+ },
1521
+ "vision_model.encoder.layers.7.self_attn.q_proj": {
1522
+ "bits": 16,
1523
+ "data_type": "float",
1524
+ "act_bits": 16,
1525
+ "act_data_type": "float"
1526
+ },
1527
+ "vision_model.encoder.layers.7.self_attn.v_proj": {
1528
+ "bits": 16,
1529
+ "data_type": "float",
1530
+ "act_bits": 16,
1531
+ "act_data_type": "float"
1532
+ },
1533
+ "vision_model.encoder.layers.8.mlp.fc1": {
1534
+ "bits": 16,
1535
+ "data_type": "float",
1536
+ "act_bits": 16,
1537
+ "act_data_type": "float"
1538
+ },
1539
+ "vision_model.encoder.layers.8.mlp.fc2": {
1540
+ "bits": 16,
1541
+ "data_type": "float",
1542
+ "act_bits": 16,
1543
+ "act_data_type": "float"
1544
+ },
1545
+ "vision_model.encoder.layers.8.self_attn.k_proj": {
1546
+ "bits": 16,
1547
+ "data_type": "float",
1548
+ "act_bits": 16,
1549
+ "act_data_type": "float"
1550
+ },
1551
+ "vision_model.encoder.layers.8.self_attn.out_proj": {
1552
+ "bits": 16,
1553
+ "data_type": "float",
1554
+ "act_bits": 16,
1555
+ "act_data_type": "float"
1556
+ },
1557
+ "vision_model.encoder.layers.8.self_attn.q_proj": {
1558
+ "bits": 16,
1559
+ "data_type": "float",
1560
+ "act_bits": 16,
1561
+ "act_data_type": "float"
1562
+ },
1563
+ "vision_model.encoder.layers.8.self_attn.v_proj": {
1564
+ "bits": 16,
1565
+ "data_type": "float",
1566
+ "act_bits": 16,
1567
+ "act_data_type": "float"
1568
+ },
1569
+ "vision_model.encoder.layers.9.mlp.fc1": {
1570
+ "bits": 16,
1571
+ "data_type": "float",
1572
+ "act_bits": 16,
1573
+ "act_data_type": "float"
1574
+ },
1575
+ "vision_model.encoder.layers.9.mlp.fc2": {
1576
+ "bits": 16,
1577
+ "data_type": "float",
1578
+ "act_bits": 16,
1579
+ "act_data_type": "float"
1580
+ },
1581
+ "vision_model.encoder.layers.9.self_attn.k_proj": {
1582
+ "bits": 16,
1583
+ "data_type": "float",
1584
+ "act_bits": 16,
1585
+ "act_data_type": "float"
1586
+ },
1587
+ "vision_model.encoder.layers.9.self_attn.out_proj": {
1588
+ "bits": 16,
1589
+ "data_type": "float",
1590
+ "act_bits": 16,
1591
+ "act_data_type": "float"
1592
+ },
1593
+ "vision_model.encoder.layers.9.self_attn.q_proj": {
1594
+ "bits": 16,
1595
+ "data_type": "float",
1596
+ "act_bits": 16,
1597
+ "act_data_type": "float"
1598
+ },
1599
+ "vision_model.encoder.layers.9.self_attn.v_proj": {
1600
+ "bits": 16,
1601
+ "data_type": "float",
1602
+ "act_bits": 16,
1603
+ "act_data_type": "float"
1604
+ },
1605
+ "vision_model.head.attention.out_proj": {
1606
+ "bits": 16,
1607
+ "data_type": "float",
1608
+ "act_bits": 16,
1609
+ "act_data_type": "float"
1610
+ },
1611
+ "vision_model.head.mlp.fc1": {
1612
+ "bits": 16,
1613
+ "data_type": "float",
1614
+ "act_bits": 16,
1615
+ "act_data_type": "float"
1616
+ },
1617
+ "vision_model.head.mlp.fc2": {
1618
+ "bits": 16,
1619
+ "data_type": "float",
1620
+ "act_bits": 16,
1621
+ "act_data_type": "float"
1622
+ },
1623
+ ".*mlp\\.experts": {
1624
+ "bits": 4
1625
+ }
1626
+ }
1627
+ }
1628
+ }
config.json.pristine ADDED
@@ -0,0 +1,1628 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cfg_distilled": true,
3
+ "use_meanflow": true,
4
+ "add_classification_head": false,
5
+ "anyres_pooling_size": 2,
6
+ "anyres_vit_max_image_size": null,
7
+ "anyres_vit_two_views": false,
8
+ "architectures": [
9
+ "HunyuanImage3ForCausalMM"
10
+ ],
11
+ "auto_map": {
12
+ "AutoConfig": "configuration_hunyuan_image_3.HunyuanImage3Config",
13
+ "AutoModel": "modeling_hunyuan_image_3.HunyuanImage3Model",
14
+ "AutoModelForCausalLM": "modeling_hunyuan_image_3.HunyuanImage3ForCausalMM"
15
+ },
16
+ "attention_bias": false,
17
+ "attention_dropout": 0.0,
18
+ "attention_head_dim": 128,
19
+ "bos_token_id": 127958,
20
+ "cla_share_factor": 2,
21
+ "class_num": 0,
22
+ "dense_list": [
23
+ 4096,
24
+ 0
25
+ ],
26
+ "eod_token_id": 3,
27
+ "eos_token_id": 127957,
28
+ "group_limited_greedy": false,
29
+ "hidden_act": "silu",
30
+ "hidden_size": 4096,
31
+ "im_end_id": 128001,
32
+ "im_newline_id": 11,
33
+ "im_start_id": 128000,
34
+ "image_token_id": 128006,
35
+ "initializer_range": 0.02,
36
+ "intermediate_size": 3072,
37
+ "kv_lora_rank": null,
38
+ "mask_init_id": 12,
39
+ "max_position_embeddings": 22800,
40
+ "mlp_bias": false,
41
+ "model_type": "hunyuan_image_3_moe",
42
+ "moe_drop_tokens": false,
43
+ "moe_intermediate_size": [
44
+ 3072,
45
+ 3072,
46
+ 3072,
47
+ 3072,
48
+ 3072,
49
+ 3072,
50
+ 3072,
51
+ 3072,
52
+ 3072,
53
+ 3072,
54
+ 3072,
55
+ 3072,
56
+ 3072,
57
+ 3072,
58
+ 3072,
59
+ 3072,
60
+ 3072,
61
+ 3072,
62
+ 3072,
63
+ 3072,
64
+ 3072,
65
+ 3072,
66
+ 3072,
67
+ 3072,
68
+ 3072,
69
+ 3072,
70
+ 3072,
71
+ 3072,
72
+ 3072,
73
+ 3072,
74
+ 3072,
75
+ 3072
76
+ ],
77
+ "moe_layer_num_skipped": 0,
78
+ "moe_random_routing_dropped_token": false,
79
+ "moe_topk": [
80
+ 8,
81
+ 8,
82
+ 8,
83
+ 8,
84
+ 8,
85
+ 8,
86
+ 8,
87
+ 8,
88
+ 8,
89
+ 8,
90
+ 8,
91
+ 8,
92
+ 8,
93
+ 8,
94
+ 8,
95
+ 8,
96
+ 8,
97
+ 8,
98
+ 8,
99
+ 8,
100
+ 8,
101
+ 8,
102
+ 8,
103
+ 8,
104
+ 8,
105
+ 8,
106
+ 8,
107
+ 8,
108
+ 8,
109
+ 8,
110
+ 8,
111
+ 8
112
+ ],
113
+ "n_group": false,
114
+ "norm_topk_prob": true,
115
+ "norm_type": "rms",
116
+ "num_attention_heads": 32,
117
+ "num_experts": 64,
118
+ "num_hidden_layers": 32,
119
+ "num_key_value_heads": 8,
120
+ "num_media_embeds": 257,
121
+ "num_shared_expert": [
122
+ 1,
123
+ 1,
124
+ 1,
125
+ 1,
126
+ 1,
127
+ 1,
128
+ 1,
129
+ 1,
130
+ 1,
131
+ 1,
132
+ 1,
133
+ 1,
134
+ 1,
135
+ 1,
136
+ 1,
137
+ 1,
138
+ 1,
139
+ 1,
140
+ 1,
141
+ 1,
142
+ 1,
143
+ 1,
144
+ 1,
145
+ 1,
146
+ 1,
147
+ 1,
148
+ 1,
149
+ 1,
150
+ 1,
151
+ 1,
152
+ 1,
153
+ 1
154
+ ],
155
+ "pad_id": 128009,
156
+ "pad_token_id": 128009,
157
+ "pool_type": "last",
158
+ "position_embedding_xdrope": false,
159
+ "pretraining_tp": 1,
160
+ "q_lora_rank": null,
161
+ "qk_nope_head_dim": null,
162
+ "qk_rope_head_dim": null,
163
+ "rms_norm_eps": 1e-05,
164
+ "rope_scaling": {
165
+ "alpha": 1.0,
166
+ "beta_fast": 32,
167
+ "beta_slow": 1,
168
+ "factor": 1.0,
169
+ "mscale": 1.0,
170
+ "mscale_all_dim": 1.0,
171
+ "type": "custom"
172
+ },
173
+ "rope_theta": 10000.0,
174
+ "routed_scaling_factor": false,
175
+ "skip_cls_token": false,
176
+ "text_end_id": 7,
177
+ "text_start_id": 6,
178
+ "tie_word_embeddings": false,
179
+ "topk_group": false,
180
+ "torch_dtype": "bfloat16",
181
+ "transformers_version": "4.50.0",
182
+ "use_cache": true,
183
+ "use_cla": false,
184
+ "use_mixed_mlp_moe": true,
185
+ "use_mla": false,
186
+ "use_qk_norm": true,
187
+ "use_rotary_pos_emb": true,
188
+ "v_head_dim": null,
189
+ "video_end_id": 10,
190
+ "video_start_id": 9,
191
+ "vit_add_patchemb_bias": false,
192
+ "vit_input_resolution": 224,
193
+ "vit_mapping_type": "resampler",
194
+ "vit_norm_type": "fused",
195
+ "vit_patch": 1,
196
+ "vit_path": null,
197
+ "vit_remove_prenorm": false,
198
+ "vit_token": 64,
199
+ "vit_type": "siglip2-so400m-patch16-naflex",
200
+ "vit_used_rms_norm": false,
201
+ "vocab_size": 133120,
202
+ "xdrope_section": null,
203
+ "head_dim": 128,
204
+ "rope_type": "2d",
205
+ "vae_downsample_factor": [
206
+ 16,
207
+ 16
208
+ ],
209
+ "vit_downsample_factor": [
210
+ 16,
211
+ 16
212
+ ],
213
+ "cond_token_attn_type": "joint_full",
214
+ "cond_image_type": "vae_vit",
215
+ "vae_type": "hunyuan-image-vae-v1",
216
+ "vae_dtype": "float32",
217
+ "vae_autocast_dtype": "float16",
218
+ "vae": {
219
+ "_class_name": "AutoencoderKLConv3D",
220
+ "block_out_channels": [
221
+ 128,
222
+ 256,
223
+ 512,
224
+ 1024,
225
+ 1024
226
+ ],
227
+ "in_channels": 3,
228
+ "out_channels": 3,
229
+ "latent_channels": 32,
230
+ "layers_per_block": 2,
231
+ "ffactor_spatial": 16,
232
+ "ffactor_temporal": 4,
233
+ "sample_size": 384,
234
+ "sample_tsize": 96,
235
+ "downsample_match_channel": true,
236
+ "upsample_match_channel": true,
237
+ "scaling_factor": 0.562679178327931
238
+ },
239
+ "vit": {
240
+ "_attn_implementation": "sdpa",
241
+ "attention_dropout": 0.0,
242
+ "hidden_act": "gelu_pytorch_tanh",
243
+ "hidden_size": 1152,
244
+ "intermediate_size": 4304,
245
+ "layer_norm_eps": 1e-06,
246
+ "num_attention_heads": 16,
247
+ "num_channels": 3,
248
+ "num_hidden_layers": 27,
249
+ "num_patches": 256,
250
+ "patch_size": 16,
251
+ "torch_dtype": "float32",
252
+ "output_attentions": false,
253
+ "output_hidden_states": false,
254
+ "use_return_dict": true
255
+ },
256
+ "vit_processor": {
257
+ "do_convert_rgb": null,
258
+ "do_normalize": true,
259
+ "do_rescale": true,
260
+ "do_resize": true,
261
+ "image_mean": [
262
+ 0.5,
263
+ 0.5,
264
+ 0.5
265
+ ],
266
+ "image_processor_type": "Siglip2ImageProcessorFast",
267
+ "image_std": [
268
+ 0.5,
269
+ 0.5,
270
+ 0.5
271
+ ],
272
+ "max_num_patches": 1024,
273
+ "patch_size": 16,
274
+ "processor_class": "Siglip2Processor",
275
+ "resample": 2,
276
+ "rescale_factor": 0.00392156862745098
277
+ },
278
+ "vit_aligner": {
279
+ "projector_type": "mlp_gelu",
280
+ "input_dim": 1152,
281
+ "n_embed": 4096,
282
+ "depth": 2,
283
+ "torch_dtype": "float32"
284
+ },
285
+ "quantization_config": {
286
+ "quant_method": "auto-round",
287
+ "packing_format": "auto_round:llm_compressor",
288
+ "bits": 8,
289
+ "group_size": 32,
290
+ "sym": true,
291
+ "data_type": "mx_fp",
292
+ "iters": 0,
293
+ "model_free": true,
294
+ "autoround_version": "0.15.0",
295
+ "enable_quanted_input": false,
296
+ "block_name_to_quantize": "model.layers",
297
+ "act_bits": 8,
298
+ "act_data_type": "mx_fp",
299
+ "act_dynamic": true,
300
+ "act_group_size": 32,
301
+ "act_sym": true,
302
+ "extra_config": {
303
+ ".mlp.experts.": {
304
+ "bits": 4
305
+ },
306
+ "final_layer.model.0.emb_layers.1": {
307
+ "bits": 16,
308
+ "data_type": "float",
309
+ "act_bits": 16,
310
+ "act_data_type": "float"
311
+ },
312
+ "final_layer.model.0.in_layers.2": {
313
+ "bits": 16,
314
+ "data_type": "float",
315
+ "act_bits": 16,
316
+ "act_data_type": "float"
317
+ },
318
+ "final_layer.model.0.out_layers.3": {
319
+ "bits": 16,
320
+ "data_type": "float",
321
+ "act_bits": 16,
322
+ "act_data_type": "float"
323
+ },
324
+ "final_layer.model.0.skip_connection": {
325
+ "bits": 16,
326
+ "data_type": "float",
327
+ "act_bits": 16,
328
+ "act_data_type": "float"
329
+ },
330
+ "final_layer.model.1.2": {
331
+ "bits": 16,
332
+ "data_type": "float",
333
+ "act_bits": 16,
334
+ "act_data_type": "float"
335
+ },
336
+ "guidance_emb.mlp.0": {
337
+ "bits": 16,
338
+ "data_type": "float",
339
+ "act_bits": 16,
340
+ "act_data_type": "float"
341
+ },
342
+ "guidance_emb.mlp.2": {
343
+ "bits": 16,
344
+ "data_type": "float",
345
+ "act_bits": 16,
346
+ "act_data_type": "float"
347
+ },
348
+ "lm_head": {
349
+ "bits": 16,
350
+ "data_type": "float",
351
+ "act_bits": 16,
352
+ "act_data_type": "float"
353
+ },
354
+ "model.layers.0.mlp.gate.wg": {
355
+ "bits": 16,
356
+ "data_type": "float",
357
+ "act_bits": 16,
358
+ "act_data_type": "float"
359
+ },
360
+ "model.layers.1.mlp.gate.wg": {
361
+ "bits": 16,
362
+ "data_type": "float",
363
+ "act_bits": 16,
364
+ "act_data_type": "float"
365
+ },
366
+ "model.layers.2.mlp.gate.wg": {
367
+ "bits": 16,
368
+ "data_type": "float",
369
+ "act_bits": 16,
370
+ "act_data_type": "float"
371
+ },
372
+ "model.layers.3.mlp.gate.wg": {
373
+ "bits": 16,
374
+ "data_type": "float",
375
+ "act_bits": 16,
376
+ "act_data_type": "float"
377
+ },
378
+ "model.layers.4.mlp.gate.wg": {
379
+ "bits": 16,
380
+ "data_type": "float",
381
+ "act_bits": 16,
382
+ "act_data_type": "float"
383
+ },
384
+ "model.layers.5.mlp.gate.wg": {
385
+ "bits": 16,
386
+ "data_type": "float",
387
+ "act_bits": 16,
388
+ "act_data_type": "float"
389
+ },
390
+ "model.layers.6.mlp.gate.wg": {
391
+ "bits": 16,
392
+ "data_type": "float",
393
+ "act_bits": 16,
394
+ "act_data_type": "float"
395
+ },
396
+ "model.layers.7.mlp.gate.wg": {
397
+ "bits": 16,
398
+ "data_type": "float",
399
+ "act_bits": 16,
400
+ "act_data_type": "float"
401
+ },
402
+ "model.layers.8.mlp.gate.wg": {
403
+ "bits": 16,
404
+ "data_type": "float",
405
+ "act_bits": 16,
406
+ "act_data_type": "float"
407
+ },
408
+ "model.layers.9.mlp.gate.wg": {
409
+ "bits": 16,
410
+ "data_type": "float",
411
+ "act_bits": 16,
412
+ "act_data_type": "float"
413
+ },
414
+ "model.layers.10.mlp.gate.wg": {
415
+ "bits": 16,
416
+ "data_type": "float",
417
+ "act_bits": 16,
418
+ "act_data_type": "float"
419
+ },
420
+ "model.layers.11.mlp.gate.wg": {
421
+ "bits": 16,
422
+ "data_type": "float",
423
+ "act_bits": 16,
424
+ "act_data_type": "float"
425
+ },
426
+ "model.layers.12.mlp.gate.wg": {
427
+ "bits": 16,
428
+ "data_type": "float",
429
+ "act_bits": 16,
430
+ "act_data_type": "float"
431
+ },
432
+ "model.layers.13.mlp.gate.wg": {
433
+ "bits": 16,
434
+ "data_type": "float",
435
+ "act_bits": 16,
436
+ "act_data_type": "float"
437
+ },
438
+ "model.layers.14.mlp.gate.wg": {
439
+ "bits": 16,
440
+ "data_type": "float",
441
+ "act_bits": 16,
442
+ "act_data_type": "float"
443
+ },
444
+ "model.layers.15.mlp.gate.wg": {
445
+ "bits": 16,
446
+ "data_type": "float",
447
+ "act_bits": 16,
448
+ "act_data_type": "float"
449
+ },
450
+ "model.layers.16.mlp.gate.wg": {
451
+ "bits": 16,
452
+ "data_type": "float",
453
+ "act_bits": 16,
454
+ "act_data_type": "float"
455
+ },
456
+ "model.layers.17.mlp.gate.wg": {
457
+ "bits": 16,
458
+ "data_type": "float",
459
+ "act_bits": 16,
460
+ "act_data_type": "float"
461
+ },
462
+ "model.layers.18.mlp.gate.wg": {
463
+ "bits": 16,
464
+ "data_type": "float",
465
+ "act_bits": 16,
466
+ "act_data_type": "float"
467
+ },
468
+ "model.layers.19.mlp.gate.wg": {
469
+ "bits": 16,
470
+ "data_type": "float",
471
+ "act_bits": 16,
472
+ "act_data_type": "float"
473
+ },
474
+ "model.layers.20.mlp.gate.wg": {
475
+ "bits": 16,
476
+ "data_type": "float",
477
+ "act_bits": 16,
478
+ "act_data_type": "float"
479
+ },
480
+ "model.layers.21.mlp.gate.wg": {
481
+ "bits": 16,
482
+ "data_type": "float",
483
+ "act_bits": 16,
484
+ "act_data_type": "float"
485
+ },
486
+ "model.layers.22.mlp.gate.wg": {
487
+ "bits": 16,
488
+ "data_type": "float",
489
+ "act_bits": 16,
490
+ "act_data_type": "float"
491
+ },
492
+ "model.layers.23.mlp.gate.wg": {
493
+ "bits": 16,
494
+ "data_type": "float",
495
+ "act_bits": 16,
496
+ "act_data_type": "float"
497
+ },
498
+ "model.layers.24.mlp.gate.wg": {
499
+ "bits": 16,
500
+ "data_type": "float",
501
+ "act_bits": 16,
502
+ "act_data_type": "float"
503
+ },
504
+ "model.layers.25.mlp.gate.wg": {
505
+ "bits": 16,
506
+ "data_type": "float",
507
+ "act_bits": 16,
508
+ "act_data_type": "float"
509
+ },
510
+ "model.layers.26.mlp.gate.wg": {
511
+ "bits": 16,
512
+ "data_type": "float",
513
+ "act_bits": 16,
514
+ "act_data_type": "float"
515
+ },
516
+ "model.layers.27.mlp.gate.wg": {
517
+ "bits": 16,
518
+ "data_type": "float",
519
+ "act_bits": 16,
520
+ "act_data_type": "float"
521
+ },
522
+ "model.layers.28.mlp.gate.wg": {
523
+ "bits": 16,
524
+ "data_type": "float",
525
+ "act_bits": 16,
526
+ "act_data_type": "float"
527
+ },
528
+ "model.layers.29.mlp.gate.wg": {
529
+ "bits": 16,
530
+ "data_type": "float",
531
+ "act_bits": 16,
532
+ "act_data_type": "float"
533
+ },
534
+ "model.layers.30.mlp.gate.wg": {
535
+ "bits": 16,
536
+ "data_type": "float",
537
+ "act_bits": 16,
538
+ "act_data_type": "float"
539
+ },
540
+ "model.layers.31.mlp.gate.wg": {
541
+ "bits": 16,
542
+ "data_type": "float",
543
+ "act_bits": 16,
544
+ "act_data_type": "float"
545
+ },
546
+ "model.wte": {
547
+ "bits": 16,
548
+ "data_type": "float",
549
+ "act_bits": 16,
550
+ "act_data_type": "float"
551
+ },
552
+ "timestep_emb.mlp.0": {
553
+ "bits": 16,
554
+ "data_type": "float",
555
+ "act_bits": 16,
556
+ "act_data_type": "float"
557
+ },
558
+ "timestep_emb.mlp.2": {
559
+ "bits": 16,
560
+ "data_type": "float",
561
+ "act_bits": 16,
562
+ "act_data_type": "float"
563
+ },
564
+ "timestep_r_emb.mlp.0": {
565
+ "bits": 16,
566
+ "data_type": "float",
567
+ "act_bits": 16,
568
+ "act_data_type": "float"
569
+ },
570
+ "timestep_r_emb.mlp.2": {
571
+ "bits": 16,
572
+ "data_type": "float",
573
+ "act_bits": 16,
574
+ "act_data_type": "float"
575
+ },
576
+ "vae.decoder.mid.attn_1.k": {
577
+ "bits": 16,
578
+ "data_type": "float",
579
+ "act_bits": 16,
580
+ "act_data_type": "float"
581
+ },
582
+ "vae.decoder.mid.attn_1.proj_out": {
583
+ "bits": 16,
584
+ "data_type": "float",
585
+ "act_bits": 16,
586
+ "act_data_type": "float"
587
+ },
588
+ "vae.decoder.mid.attn_1.q": {
589
+ "bits": 16,
590
+ "data_type": "float",
591
+ "act_bits": 16,
592
+ "act_data_type": "float"
593
+ },
594
+ "vae.decoder.mid.attn_1.v": {
595
+ "bits": 16,
596
+ "data_type": "float",
597
+ "act_bits": 16,
598
+ "act_data_type": "float"
599
+ },
600
+ "vae.encoder.mid.attn_1.k": {
601
+ "bits": 16,
602
+ "data_type": "float",
603
+ "act_bits": 16,
604
+ "act_data_type": "float"
605
+ },
606
+ "vae.encoder.mid.attn_1.proj_out": {
607
+ "bits": 16,
608
+ "data_type": "float",
609
+ "act_bits": 16,
610
+ "act_data_type": "float"
611
+ },
612
+ "vae.encoder.mid.attn_1.q": {
613
+ "bits": 16,
614
+ "data_type": "float",
615
+ "act_bits": 16,
616
+ "act_data_type": "float"
617
+ },
618
+ "vae.encoder.mid.attn_1.v": {
619
+ "bits": 16,
620
+ "data_type": "float",
621
+ "act_bits": 16,
622
+ "act_data_type": "float"
623
+ },
624
+ "vision_aligner.layers.0": {
625
+ "bits": 16,
626
+ "data_type": "float",
627
+ "act_bits": 16,
628
+ "act_data_type": "float"
629
+ },
630
+ "vision_aligner.layers.2": {
631
+ "bits": 16,
632
+ "data_type": "float",
633
+ "act_bits": 16,
634
+ "act_data_type": "float"
635
+ },
636
+ "vision_model.encoder.layers.0.mlp.fc1": {
637
+ "bits": 16,
638
+ "data_type": "float",
639
+ "act_bits": 16,
640
+ "act_data_type": "float"
641
+ },
642
+ "vision_model.encoder.layers.0.mlp.fc2": {
643
+ "bits": 16,
644
+ "data_type": "float",
645
+ "act_bits": 16,
646
+ "act_data_type": "float"
647
+ },
648
+ "vision_model.encoder.layers.0.self_attn.k_proj": {
649
+ "bits": 16,
650
+ "data_type": "float",
651
+ "act_bits": 16,
652
+ "act_data_type": "float"
653
+ },
654
+ "vision_model.encoder.layers.0.self_attn.out_proj": {
655
+ "bits": 16,
656
+ "data_type": "float",
657
+ "act_bits": 16,
658
+ "act_data_type": "float"
659
+ },
660
+ "vision_model.encoder.layers.0.self_attn.q_proj": {
661
+ "bits": 16,
662
+ "data_type": "float",
663
+ "act_bits": 16,
664
+ "act_data_type": "float"
665
+ },
666
+ "vision_model.encoder.layers.0.self_attn.v_proj": {
667
+ "bits": 16,
668
+ "data_type": "float",
669
+ "act_bits": 16,
670
+ "act_data_type": "float"
671
+ },
672
+ "vision_model.encoder.layers.1.mlp.fc1": {
673
+ "bits": 16,
674
+ "data_type": "float",
675
+ "act_bits": 16,
676
+ "act_data_type": "float"
677
+ },
678
+ "vision_model.encoder.layers.1.mlp.fc2": {
679
+ "bits": 16,
680
+ "data_type": "float",
681
+ "act_bits": 16,
682
+ "act_data_type": "float"
683
+ },
684
+ "vision_model.encoder.layers.1.self_attn.k_proj": {
685
+ "bits": 16,
686
+ "data_type": "float",
687
+ "act_bits": 16,
688
+ "act_data_type": "float"
689
+ },
690
+ "vision_model.encoder.layers.1.self_attn.out_proj": {
691
+ "bits": 16,
692
+ "data_type": "float",
693
+ "act_bits": 16,
694
+ "act_data_type": "float"
695
+ },
696
+ "vision_model.encoder.layers.1.self_attn.q_proj": {
697
+ "bits": 16,
698
+ "data_type": "float",
699
+ "act_bits": 16,
700
+ "act_data_type": "float"
701
+ },
702
+ "vision_model.encoder.layers.1.self_attn.v_proj": {
703
+ "bits": 16,
704
+ "data_type": "float",
705
+ "act_bits": 16,
706
+ "act_data_type": "float"
707
+ },
708
+ "vision_model.encoder.layers.10.mlp.fc1": {
709
+ "bits": 16,
710
+ "data_type": "float",
711
+ "act_bits": 16,
712
+ "act_data_type": "float"
713
+ },
714
+ "vision_model.encoder.layers.10.mlp.fc2": {
715
+ "bits": 16,
716
+ "data_type": "float",
717
+ "act_bits": 16,
718
+ "act_data_type": "float"
719
+ },
720
+ "vision_model.encoder.layers.10.self_attn.k_proj": {
721
+ "bits": 16,
722
+ "data_type": "float",
723
+ "act_bits": 16,
724
+ "act_data_type": "float"
725
+ },
726
+ "vision_model.encoder.layers.10.self_attn.out_proj": {
727
+ "bits": 16,
728
+ "data_type": "float",
729
+ "act_bits": 16,
730
+ "act_data_type": "float"
731
+ },
732
+ "vision_model.encoder.layers.10.self_attn.q_proj": {
733
+ "bits": 16,
734
+ "data_type": "float",
735
+ "act_bits": 16,
736
+ "act_data_type": "float"
737
+ },
738
+ "vision_model.encoder.layers.10.self_attn.v_proj": {
739
+ "bits": 16,
740
+ "data_type": "float",
741
+ "act_bits": 16,
742
+ "act_data_type": "float"
743
+ },
744
+ "vision_model.encoder.layers.11.mlp.fc1": {
745
+ "bits": 16,
746
+ "data_type": "float",
747
+ "act_bits": 16,
748
+ "act_data_type": "float"
749
+ },
750
+ "vision_model.encoder.layers.11.mlp.fc2": {
751
+ "bits": 16,
752
+ "data_type": "float",
753
+ "act_bits": 16,
754
+ "act_data_type": "float"
755
+ },
756
+ "vision_model.encoder.layers.11.self_attn.k_proj": {
757
+ "bits": 16,
758
+ "data_type": "float",
759
+ "act_bits": 16,
760
+ "act_data_type": "float"
761
+ },
762
+ "vision_model.encoder.layers.11.self_attn.out_proj": {
763
+ "bits": 16,
764
+ "data_type": "float",
765
+ "act_bits": 16,
766
+ "act_data_type": "float"
767
+ },
768
+ "vision_model.encoder.layers.11.self_attn.q_proj": {
769
+ "bits": 16,
770
+ "data_type": "float",
771
+ "act_bits": 16,
772
+ "act_data_type": "float"
773
+ },
774
+ "vision_model.encoder.layers.11.self_attn.v_proj": {
775
+ "bits": 16,
776
+ "data_type": "float",
777
+ "act_bits": 16,
778
+ "act_data_type": "float"
779
+ },
780
+ "vision_model.encoder.layers.12.mlp.fc1": {
781
+ "bits": 16,
782
+ "data_type": "float",
783
+ "act_bits": 16,
784
+ "act_data_type": "float"
785
+ },
786
+ "vision_model.encoder.layers.12.mlp.fc2": {
787
+ "bits": 16,
788
+ "data_type": "float",
789
+ "act_bits": 16,
790
+ "act_data_type": "float"
791
+ },
792
+ "vision_model.encoder.layers.12.self_attn.k_proj": {
793
+ "bits": 16,
794
+ "data_type": "float",
795
+ "act_bits": 16,
796
+ "act_data_type": "float"
797
+ },
798
+ "vision_model.encoder.layers.12.self_attn.out_proj": {
799
+ "bits": 16,
800
+ "data_type": "float",
801
+ "act_bits": 16,
802
+ "act_data_type": "float"
803
+ },
804
+ "vision_model.encoder.layers.12.self_attn.q_proj": {
805
+ "bits": 16,
806
+ "data_type": "float",
807
+ "act_bits": 16,
808
+ "act_data_type": "float"
809
+ },
810
+ "vision_model.encoder.layers.12.self_attn.v_proj": {
811
+ "bits": 16,
812
+ "data_type": "float",
813
+ "act_bits": 16,
814
+ "act_data_type": "float"
815
+ },
816
+ "vision_model.encoder.layers.13.mlp.fc1": {
817
+ "bits": 16,
818
+ "data_type": "float",
819
+ "act_bits": 16,
820
+ "act_data_type": "float"
821
+ },
822
+ "vision_model.encoder.layers.13.mlp.fc2": {
823
+ "bits": 16,
824
+ "data_type": "float",
825
+ "act_bits": 16,
826
+ "act_data_type": "float"
827
+ },
828
+ "vision_model.encoder.layers.13.self_attn.k_proj": {
829
+ "bits": 16,
830
+ "data_type": "float",
831
+ "act_bits": 16,
832
+ "act_data_type": "float"
833
+ },
834
+ "vision_model.encoder.layers.13.self_attn.out_proj": {
835
+ "bits": 16,
836
+ "data_type": "float",
837
+ "act_bits": 16,
838
+ "act_data_type": "float"
839
+ },
840
+ "vision_model.encoder.layers.13.self_attn.q_proj": {
841
+ "bits": 16,
842
+ "data_type": "float",
843
+ "act_bits": 16,
844
+ "act_data_type": "float"
845
+ },
846
+ "vision_model.encoder.layers.13.self_attn.v_proj": {
847
+ "bits": 16,
848
+ "data_type": "float",
849
+ "act_bits": 16,
850
+ "act_data_type": "float"
851
+ },
852
+ "vision_model.encoder.layers.14.mlp.fc1": {
853
+ "bits": 16,
854
+ "data_type": "float",
855
+ "act_bits": 16,
856
+ "act_data_type": "float"
857
+ },
858
+ "vision_model.encoder.layers.14.mlp.fc2": {
859
+ "bits": 16,
860
+ "data_type": "float",
861
+ "act_bits": 16,
862
+ "act_data_type": "float"
863
+ },
864
+ "vision_model.encoder.layers.14.self_attn.k_proj": {
865
+ "bits": 16,
866
+ "data_type": "float",
867
+ "act_bits": 16,
868
+ "act_data_type": "float"
869
+ },
870
+ "vision_model.encoder.layers.14.self_attn.out_proj": {
871
+ "bits": 16,
872
+ "data_type": "float",
873
+ "act_bits": 16,
874
+ "act_data_type": "float"
875
+ },
876
+ "vision_model.encoder.layers.14.self_attn.q_proj": {
877
+ "bits": 16,
878
+ "data_type": "float",
879
+ "act_bits": 16,
880
+ "act_data_type": "float"
881
+ },
882
+ "vision_model.encoder.layers.14.self_attn.v_proj": {
883
+ "bits": 16,
884
+ "data_type": "float",
885
+ "act_bits": 16,
886
+ "act_data_type": "float"
887
+ },
888
+ "vision_model.encoder.layers.15.mlp.fc1": {
889
+ "bits": 16,
890
+ "data_type": "float",
891
+ "act_bits": 16,
892
+ "act_data_type": "float"
893
+ },
894
+ "vision_model.encoder.layers.15.mlp.fc2": {
895
+ "bits": 16,
896
+ "data_type": "float",
897
+ "act_bits": 16,
898
+ "act_data_type": "float"
899
+ },
900
+ "vision_model.encoder.layers.15.self_attn.k_proj": {
901
+ "bits": 16,
902
+ "data_type": "float",
903
+ "act_bits": 16,
904
+ "act_data_type": "float"
905
+ },
906
+ "vision_model.encoder.layers.15.self_attn.out_proj": {
907
+ "bits": 16,
908
+ "data_type": "float",
909
+ "act_bits": 16,
910
+ "act_data_type": "float"
911
+ },
912
+ "vision_model.encoder.layers.15.self_attn.q_proj": {
913
+ "bits": 16,
914
+ "data_type": "float",
915
+ "act_bits": 16,
916
+ "act_data_type": "float"
917
+ },
918
+ "vision_model.encoder.layers.15.self_attn.v_proj": {
919
+ "bits": 16,
920
+ "data_type": "float",
921
+ "act_bits": 16,
922
+ "act_data_type": "float"
923
+ },
924
+ "vision_model.encoder.layers.16.mlp.fc1": {
925
+ "bits": 16,
926
+ "data_type": "float",
927
+ "act_bits": 16,
928
+ "act_data_type": "float"
929
+ },
930
+ "vision_model.encoder.layers.16.mlp.fc2": {
931
+ "bits": 16,
932
+ "data_type": "float",
933
+ "act_bits": 16,
934
+ "act_data_type": "float"
935
+ },
936
+ "vision_model.encoder.layers.16.self_attn.k_proj": {
937
+ "bits": 16,
938
+ "data_type": "float",
939
+ "act_bits": 16,
940
+ "act_data_type": "float"
941
+ },
942
+ "vision_model.encoder.layers.16.self_attn.out_proj": {
943
+ "bits": 16,
944
+ "data_type": "float",
945
+ "act_bits": 16,
946
+ "act_data_type": "float"
947
+ },
948
+ "vision_model.encoder.layers.16.self_attn.q_proj": {
949
+ "bits": 16,
950
+ "data_type": "float",
951
+ "act_bits": 16,
952
+ "act_data_type": "float"
953
+ },
954
+ "vision_model.encoder.layers.16.self_attn.v_proj": {
955
+ "bits": 16,
956
+ "data_type": "float",
957
+ "act_bits": 16,
958
+ "act_data_type": "float"
959
+ },
960
+ "vision_model.encoder.layers.17.mlp.fc1": {
961
+ "bits": 16,
962
+ "data_type": "float",
963
+ "act_bits": 16,
964
+ "act_data_type": "float"
965
+ },
966
+ "vision_model.encoder.layers.17.mlp.fc2": {
967
+ "bits": 16,
968
+ "data_type": "float",
969
+ "act_bits": 16,
970
+ "act_data_type": "float"
971
+ },
972
+ "vision_model.encoder.layers.17.self_attn.k_proj": {
973
+ "bits": 16,
974
+ "data_type": "float",
975
+ "act_bits": 16,
976
+ "act_data_type": "float"
977
+ },
978
+ "vision_model.encoder.layers.17.self_attn.out_proj": {
979
+ "bits": 16,
980
+ "data_type": "float",
981
+ "act_bits": 16,
982
+ "act_data_type": "float"
983
+ },
984
+ "vision_model.encoder.layers.17.self_attn.q_proj": {
985
+ "bits": 16,
986
+ "data_type": "float",
987
+ "act_bits": 16,
988
+ "act_data_type": "float"
989
+ },
990
+ "vision_model.encoder.layers.17.self_attn.v_proj": {
991
+ "bits": 16,
992
+ "data_type": "float",
993
+ "act_bits": 16,
994
+ "act_data_type": "float"
995
+ },
996
+ "vision_model.encoder.layers.18.mlp.fc1": {
997
+ "bits": 16,
998
+ "data_type": "float",
999
+ "act_bits": 16,
1000
+ "act_data_type": "float"
1001
+ },
1002
+ "vision_model.encoder.layers.18.mlp.fc2": {
1003
+ "bits": 16,
1004
+ "data_type": "float",
1005
+ "act_bits": 16,
1006
+ "act_data_type": "float"
1007
+ },
1008
+ "vision_model.encoder.layers.18.self_attn.k_proj": {
1009
+ "bits": 16,
1010
+ "data_type": "float",
1011
+ "act_bits": 16,
1012
+ "act_data_type": "float"
1013
+ },
1014
+ "vision_model.encoder.layers.18.self_attn.out_proj": {
1015
+ "bits": 16,
1016
+ "data_type": "float",
1017
+ "act_bits": 16,
1018
+ "act_data_type": "float"
1019
+ },
1020
+ "vision_model.encoder.layers.18.self_attn.q_proj": {
1021
+ "bits": 16,
1022
+ "data_type": "float",
1023
+ "act_bits": 16,
1024
+ "act_data_type": "float"
1025
+ },
1026
+ "vision_model.encoder.layers.18.self_attn.v_proj": {
1027
+ "bits": 16,
1028
+ "data_type": "float",
1029
+ "act_bits": 16,
1030
+ "act_data_type": "float"
1031
+ },
1032
+ "vision_model.encoder.layers.19.mlp.fc1": {
1033
+ "bits": 16,
1034
+ "data_type": "float",
1035
+ "act_bits": 16,
1036
+ "act_data_type": "float"
1037
+ },
1038
+ "vision_model.encoder.layers.19.mlp.fc2": {
1039
+ "bits": 16,
1040
+ "data_type": "float",
1041
+ "act_bits": 16,
1042
+ "act_data_type": "float"
1043
+ },
1044
+ "vision_model.encoder.layers.19.self_attn.k_proj": {
1045
+ "bits": 16,
1046
+ "data_type": "float",
1047
+ "act_bits": 16,
1048
+ "act_data_type": "float"
1049
+ },
1050
+ "vision_model.encoder.layers.19.self_attn.out_proj": {
1051
+ "bits": 16,
1052
+ "data_type": "float",
1053
+ "act_bits": 16,
1054
+ "act_data_type": "float"
1055
+ },
1056
+ "vision_model.encoder.layers.19.self_attn.q_proj": {
1057
+ "bits": 16,
1058
+ "data_type": "float",
1059
+ "act_bits": 16,
1060
+ "act_data_type": "float"
1061
+ },
1062
+ "vision_model.encoder.layers.19.self_attn.v_proj": {
1063
+ "bits": 16,
1064
+ "data_type": "float",
1065
+ "act_bits": 16,
1066
+ "act_data_type": "float"
1067
+ },
1068
+ "vision_model.encoder.layers.2.mlp.fc1": {
1069
+ "bits": 16,
1070
+ "data_type": "float",
1071
+ "act_bits": 16,
1072
+ "act_data_type": "float"
1073
+ },
1074
+ "vision_model.encoder.layers.2.mlp.fc2": {
1075
+ "bits": 16,
1076
+ "data_type": "float",
1077
+ "act_bits": 16,
1078
+ "act_data_type": "float"
1079
+ },
1080
+ "vision_model.encoder.layers.2.self_attn.k_proj": {
1081
+ "bits": 16,
1082
+ "data_type": "float",
1083
+ "act_bits": 16,
1084
+ "act_data_type": "float"
1085
+ },
1086
+ "vision_model.encoder.layers.2.self_attn.out_proj": {
1087
+ "bits": 16,
1088
+ "data_type": "float",
1089
+ "act_bits": 16,
1090
+ "act_data_type": "float"
1091
+ },
1092
+ "vision_model.encoder.layers.2.self_attn.q_proj": {
1093
+ "bits": 16,
1094
+ "data_type": "float",
1095
+ "act_bits": 16,
1096
+ "act_data_type": "float"
1097
+ },
1098
+ "vision_model.encoder.layers.2.self_attn.v_proj": {
1099
+ "bits": 16,
1100
+ "data_type": "float",
1101
+ "act_bits": 16,
1102
+ "act_data_type": "float"
1103
+ },
1104
+ "vision_model.encoder.layers.20.mlp.fc1": {
1105
+ "bits": 16,
1106
+ "data_type": "float",
1107
+ "act_bits": 16,
1108
+ "act_data_type": "float"
1109
+ },
1110
+ "vision_model.encoder.layers.20.mlp.fc2": {
1111
+ "bits": 16,
1112
+ "data_type": "float",
1113
+ "act_bits": 16,
1114
+ "act_data_type": "float"
1115
+ },
1116
+ "vision_model.encoder.layers.20.self_attn.k_proj": {
1117
+ "bits": 16,
1118
+ "data_type": "float",
1119
+ "act_bits": 16,
1120
+ "act_data_type": "float"
1121
+ },
1122
+ "vision_model.encoder.layers.20.self_attn.out_proj": {
1123
+ "bits": 16,
1124
+ "data_type": "float",
1125
+ "act_bits": 16,
1126
+ "act_data_type": "float"
1127
+ },
1128
+ "vision_model.encoder.layers.20.self_attn.q_proj": {
1129
+ "bits": 16,
1130
+ "data_type": "float",
1131
+ "act_bits": 16,
1132
+ "act_data_type": "float"
1133
+ },
1134
+ "vision_model.encoder.layers.20.self_attn.v_proj": {
1135
+ "bits": 16,
1136
+ "data_type": "float",
1137
+ "act_bits": 16,
1138
+ "act_data_type": "float"
1139
+ },
1140
+ "vision_model.encoder.layers.21.mlp.fc1": {
1141
+ "bits": 16,
1142
+ "data_type": "float",
1143
+ "act_bits": 16,
1144
+ "act_data_type": "float"
1145
+ },
1146
+ "vision_model.encoder.layers.21.mlp.fc2": {
1147
+ "bits": 16,
1148
+ "data_type": "float",
1149
+ "act_bits": 16,
1150
+ "act_data_type": "float"
1151
+ },
1152
+ "vision_model.encoder.layers.21.self_attn.k_proj": {
1153
+ "bits": 16,
1154
+ "data_type": "float",
1155
+ "act_bits": 16,
1156
+ "act_data_type": "float"
1157
+ },
1158
+ "vision_model.encoder.layers.21.self_attn.out_proj": {
1159
+ "bits": 16,
1160
+ "data_type": "float",
1161
+ "act_bits": 16,
1162
+ "act_data_type": "float"
1163
+ },
1164
+ "vision_model.encoder.layers.21.self_attn.q_proj": {
1165
+ "bits": 16,
1166
+ "data_type": "float",
1167
+ "act_bits": 16,
1168
+ "act_data_type": "float"
1169
+ },
1170
+ "vision_model.encoder.layers.21.self_attn.v_proj": {
1171
+ "bits": 16,
1172
+ "data_type": "float",
1173
+ "act_bits": 16,
1174
+ "act_data_type": "float"
1175
+ },
1176
+ "vision_model.encoder.layers.22.mlp.fc1": {
1177
+ "bits": 16,
1178
+ "data_type": "float",
1179
+ "act_bits": 16,
1180
+ "act_data_type": "float"
1181
+ },
1182
+ "vision_model.encoder.layers.22.mlp.fc2": {
1183
+ "bits": 16,
1184
+ "data_type": "float",
1185
+ "act_bits": 16,
1186
+ "act_data_type": "float"
1187
+ },
1188
+ "vision_model.encoder.layers.22.self_attn.k_proj": {
1189
+ "bits": 16,
1190
+ "data_type": "float",
1191
+ "act_bits": 16,
1192
+ "act_data_type": "float"
1193
+ },
1194
+ "vision_model.encoder.layers.22.self_attn.out_proj": {
1195
+ "bits": 16,
1196
+ "data_type": "float",
1197
+ "act_bits": 16,
1198
+ "act_data_type": "float"
1199
+ },
1200
+ "vision_model.encoder.layers.22.self_attn.q_proj": {
1201
+ "bits": 16,
1202
+ "data_type": "float",
1203
+ "act_bits": 16,
1204
+ "act_data_type": "float"
1205
+ },
1206
+ "vision_model.encoder.layers.22.self_attn.v_proj": {
1207
+ "bits": 16,
1208
+ "data_type": "float",
1209
+ "act_bits": 16,
1210
+ "act_data_type": "float"
1211
+ },
1212
+ "vision_model.encoder.layers.23.mlp.fc1": {
1213
+ "bits": 16,
1214
+ "data_type": "float",
1215
+ "act_bits": 16,
1216
+ "act_data_type": "float"
1217
+ },
1218
+ "vision_model.encoder.layers.23.mlp.fc2": {
1219
+ "bits": 16,
1220
+ "data_type": "float",
1221
+ "act_bits": 16,
1222
+ "act_data_type": "float"
1223
+ },
1224
+ "vision_model.encoder.layers.23.self_attn.k_proj": {
1225
+ "bits": 16,
1226
+ "data_type": "float",
1227
+ "act_bits": 16,
1228
+ "act_data_type": "float"
1229
+ },
1230
+ "vision_model.encoder.layers.23.self_attn.out_proj": {
1231
+ "bits": 16,
1232
+ "data_type": "float",
1233
+ "act_bits": 16,
1234
+ "act_data_type": "float"
1235
+ },
1236
+ "vision_model.encoder.layers.23.self_attn.q_proj": {
1237
+ "bits": 16,
1238
+ "data_type": "float",
1239
+ "act_bits": 16,
1240
+ "act_data_type": "float"
1241
+ },
1242
+ "vision_model.encoder.layers.23.self_attn.v_proj": {
1243
+ "bits": 16,
1244
+ "data_type": "float",
1245
+ "act_bits": 16,
1246
+ "act_data_type": "float"
1247
+ },
1248
+ "vision_model.encoder.layers.24.mlp.fc1": {
1249
+ "bits": 16,
1250
+ "data_type": "float",
1251
+ "act_bits": 16,
1252
+ "act_data_type": "float"
1253
+ },
1254
+ "vision_model.encoder.layers.24.mlp.fc2": {
1255
+ "bits": 16,
1256
+ "data_type": "float",
1257
+ "act_bits": 16,
1258
+ "act_data_type": "float"
1259
+ },
1260
+ "vision_model.encoder.layers.24.self_attn.k_proj": {
1261
+ "bits": 16,
1262
+ "data_type": "float",
1263
+ "act_bits": 16,
1264
+ "act_data_type": "float"
1265
+ },
1266
+ "vision_model.encoder.layers.24.self_attn.out_proj": {
1267
+ "bits": 16,
1268
+ "data_type": "float",
1269
+ "act_bits": 16,
1270
+ "act_data_type": "float"
1271
+ },
1272
+ "vision_model.encoder.layers.24.self_attn.q_proj": {
1273
+ "bits": 16,
1274
+ "data_type": "float",
1275
+ "act_bits": 16,
1276
+ "act_data_type": "float"
1277
+ },
1278
+ "vision_model.encoder.layers.24.self_attn.v_proj": {
1279
+ "bits": 16,
1280
+ "data_type": "float",
1281
+ "act_bits": 16,
1282
+ "act_data_type": "float"
1283
+ },
1284
+ "vision_model.encoder.layers.25.mlp.fc1": {
1285
+ "bits": 16,
1286
+ "data_type": "float",
1287
+ "act_bits": 16,
1288
+ "act_data_type": "float"
1289
+ },
1290
+ "vision_model.encoder.layers.25.mlp.fc2": {
1291
+ "bits": 16,
1292
+ "data_type": "float",
1293
+ "act_bits": 16,
1294
+ "act_data_type": "float"
1295
+ },
1296
+ "vision_model.encoder.layers.25.self_attn.k_proj": {
1297
+ "bits": 16,
1298
+ "data_type": "float",
1299
+ "act_bits": 16,
1300
+ "act_data_type": "float"
1301
+ },
1302
+ "vision_model.encoder.layers.25.self_attn.out_proj": {
1303
+ "bits": 16,
1304
+ "data_type": "float",
1305
+ "act_bits": 16,
1306
+ "act_data_type": "float"
1307
+ },
1308
+ "vision_model.encoder.layers.25.self_attn.q_proj": {
1309
+ "bits": 16,
1310
+ "data_type": "float",
1311
+ "act_bits": 16,
1312
+ "act_data_type": "float"
1313
+ },
1314
+ "vision_model.encoder.layers.25.self_attn.v_proj": {
1315
+ "bits": 16,
1316
+ "data_type": "float",
1317
+ "act_bits": 16,
1318
+ "act_data_type": "float"
1319
+ },
1320
+ "vision_model.encoder.layers.26.mlp.fc1": {
1321
+ "bits": 16,
1322
+ "data_type": "float",
1323
+ "act_bits": 16,
1324
+ "act_data_type": "float"
1325
+ },
1326
+ "vision_model.encoder.layers.26.mlp.fc2": {
1327
+ "bits": 16,
1328
+ "data_type": "float",
1329
+ "act_bits": 16,
1330
+ "act_data_type": "float"
1331
+ },
1332
+ "vision_model.encoder.layers.26.self_attn.k_proj": {
1333
+ "bits": 16,
1334
+ "data_type": "float",
1335
+ "act_bits": 16,
1336
+ "act_data_type": "float"
1337
+ },
1338
+ "vision_model.encoder.layers.26.self_attn.out_proj": {
1339
+ "bits": 16,
1340
+ "data_type": "float",
1341
+ "act_bits": 16,
1342
+ "act_data_type": "float"
1343
+ },
1344
+ "vision_model.encoder.layers.26.self_attn.q_proj": {
1345
+ "bits": 16,
1346
+ "data_type": "float",
1347
+ "act_bits": 16,
1348
+ "act_data_type": "float"
1349
+ },
1350
+ "vision_model.encoder.layers.26.self_attn.v_proj": {
1351
+ "bits": 16,
1352
+ "data_type": "float",
1353
+ "act_bits": 16,
1354
+ "act_data_type": "float"
1355
+ },
1356
+ "vision_model.encoder.layers.3.mlp.fc1": {
1357
+ "bits": 16,
1358
+ "data_type": "float",
1359
+ "act_bits": 16,
1360
+ "act_data_type": "float"
1361
+ },
1362
+ "vision_model.encoder.layers.3.mlp.fc2": {
1363
+ "bits": 16,
1364
+ "data_type": "float",
1365
+ "act_bits": 16,
1366
+ "act_data_type": "float"
1367
+ },
1368
+ "vision_model.encoder.layers.3.self_attn.k_proj": {
1369
+ "bits": 16,
1370
+ "data_type": "float",
1371
+ "act_bits": 16,
1372
+ "act_data_type": "float"
1373
+ },
1374
+ "vision_model.encoder.layers.3.self_attn.out_proj": {
1375
+ "bits": 16,
1376
+ "data_type": "float",
1377
+ "act_bits": 16,
1378
+ "act_data_type": "float"
1379
+ },
1380
+ "vision_model.encoder.layers.3.self_attn.q_proj": {
1381
+ "bits": 16,
1382
+ "data_type": "float",
1383
+ "act_bits": 16,
1384
+ "act_data_type": "float"
1385
+ },
1386
+ "vision_model.encoder.layers.3.self_attn.v_proj": {
1387
+ "bits": 16,
1388
+ "data_type": "float",
1389
+ "act_bits": 16,
1390
+ "act_data_type": "float"
1391
+ },
1392
+ "vision_model.encoder.layers.4.mlp.fc1": {
1393
+ "bits": 16,
1394
+ "data_type": "float",
1395
+ "act_bits": 16,
1396
+ "act_data_type": "float"
1397
+ },
1398
+ "vision_model.encoder.layers.4.mlp.fc2": {
1399
+ "bits": 16,
1400
+ "data_type": "float",
1401
+ "act_bits": 16,
1402
+ "act_data_type": "float"
1403
+ },
1404
+ "vision_model.encoder.layers.4.self_attn.k_proj": {
1405
+ "bits": 16,
1406
+ "data_type": "float",
1407
+ "act_bits": 16,
1408
+ "act_data_type": "float"
1409
+ },
1410
+ "vision_model.encoder.layers.4.self_attn.out_proj": {
1411
+ "bits": 16,
1412
+ "data_type": "float",
1413
+ "act_bits": 16,
1414
+ "act_data_type": "float"
1415
+ },
1416
+ "vision_model.encoder.layers.4.self_attn.q_proj": {
1417
+ "bits": 16,
1418
+ "data_type": "float",
1419
+ "act_bits": 16,
1420
+ "act_data_type": "float"
1421
+ },
1422
+ "vision_model.encoder.layers.4.self_attn.v_proj": {
1423
+ "bits": 16,
1424
+ "data_type": "float",
1425
+ "act_bits": 16,
1426
+ "act_data_type": "float"
1427
+ },
1428
+ "vision_model.encoder.layers.5.mlp.fc1": {
1429
+ "bits": 16,
1430
+ "data_type": "float",
1431
+ "act_bits": 16,
1432
+ "act_data_type": "float"
1433
+ },
1434
+ "vision_model.encoder.layers.5.mlp.fc2": {
1435
+ "bits": 16,
1436
+ "data_type": "float",
1437
+ "act_bits": 16,
1438
+ "act_data_type": "float"
1439
+ },
1440
+ "vision_model.encoder.layers.5.self_attn.k_proj": {
1441
+ "bits": 16,
1442
+ "data_type": "float",
1443
+ "act_bits": 16,
1444
+ "act_data_type": "float"
1445
+ },
1446
+ "vision_model.encoder.layers.5.self_attn.out_proj": {
1447
+ "bits": 16,
1448
+ "data_type": "float",
1449
+ "act_bits": 16,
1450
+ "act_data_type": "float"
1451
+ },
1452
+ "vision_model.encoder.layers.5.self_attn.q_proj": {
1453
+ "bits": 16,
1454
+ "data_type": "float",
1455
+ "act_bits": 16,
1456
+ "act_data_type": "float"
1457
+ },
1458
+ "vision_model.encoder.layers.5.self_attn.v_proj": {
1459
+ "bits": 16,
1460
+ "data_type": "float",
1461
+ "act_bits": 16,
1462
+ "act_data_type": "float"
1463
+ },
1464
+ "vision_model.encoder.layers.6.mlp.fc1": {
1465
+ "bits": 16,
1466
+ "data_type": "float",
1467
+ "act_bits": 16,
1468
+ "act_data_type": "float"
1469
+ },
1470
+ "vision_model.encoder.layers.6.mlp.fc2": {
1471
+ "bits": 16,
1472
+ "data_type": "float",
1473
+ "act_bits": 16,
1474
+ "act_data_type": "float"
1475
+ },
1476
+ "vision_model.encoder.layers.6.self_attn.k_proj": {
1477
+ "bits": 16,
1478
+ "data_type": "float",
1479
+ "act_bits": 16,
1480
+ "act_data_type": "float"
1481
+ },
1482
+ "vision_model.encoder.layers.6.self_attn.out_proj": {
1483
+ "bits": 16,
1484
+ "data_type": "float",
1485
+ "act_bits": 16,
1486
+ "act_data_type": "float"
1487
+ },
1488
+ "vision_model.encoder.layers.6.self_attn.q_proj": {
1489
+ "bits": 16,
1490
+ "data_type": "float",
1491
+ "act_bits": 16,
1492
+ "act_data_type": "float"
1493
+ },
1494
+ "vision_model.encoder.layers.6.self_attn.v_proj": {
1495
+ "bits": 16,
1496
+ "data_type": "float",
1497
+ "act_bits": 16,
1498
+ "act_data_type": "float"
1499
+ },
1500
+ "vision_model.encoder.layers.7.mlp.fc1": {
1501
+ "bits": 16,
1502
+ "data_type": "float",
1503
+ "act_bits": 16,
1504
+ "act_data_type": "float"
1505
+ },
1506
+ "vision_model.encoder.layers.7.mlp.fc2": {
1507
+ "bits": 16,
1508
+ "data_type": "float",
1509
+ "act_bits": 16,
1510
+ "act_data_type": "float"
1511
+ },
1512
+ "vision_model.encoder.layers.7.self_attn.k_proj": {
1513
+ "bits": 16,
1514
+ "data_type": "float",
1515
+ "act_bits": 16,
1516
+ "act_data_type": "float"
1517
+ },
1518
+ "vision_model.encoder.layers.7.self_attn.out_proj": {
1519
+ "bits": 16,
1520
+ "data_type": "float",
1521
+ "act_bits": 16,
1522
+ "act_data_type": "float"
1523
+ },
1524
+ "vision_model.encoder.layers.7.self_attn.q_proj": {
1525
+ "bits": 16,
1526
+ "data_type": "float",
1527
+ "act_bits": 16,
1528
+ "act_data_type": "float"
1529
+ },
1530
+ "vision_model.encoder.layers.7.self_attn.v_proj": {
1531
+ "bits": 16,
1532
+ "data_type": "float",
1533
+ "act_bits": 16,
1534
+ "act_data_type": "float"
1535
+ },
1536
+ "vision_model.encoder.layers.8.mlp.fc1": {
1537
+ "bits": 16,
1538
+ "data_type": "float",
1539
+ "act_bits": 16,
1540
+ "act_data_type": "float"
1541
+ },
1542
+ "vision_model.encoder.layers.8.mlp.fc2": {
1543
+ "bits": 16,
1544
+ "data_type": "float",
1545
+ "act_bits": 16,
1546
+ "act_data_type": "float"
1547
+ },
1548
+ "vision_model.encoder.layers.8.self_attn.k_proj": {
1549
+ "bits": 16,
1550
+ "data_type": "float",
1551
+ "act_bits": 16,
1552
+ "act_data_type": "float"
1553
+ },
1554
+ "vision_model.encoder.layers.8.self_attn.out_proj": {
1555
+ "bits": 16,
1556
+ "data_type": "float",
1557
+ "act_bits": 16,
1558
+ "act_data_type": "float"
1559
+ },
1560
+ "vision_model.encoder.layers.8.self_attn.q_proj": {
1561
+ "bits": 16,
1562
+ "data_type": "float",
1563
+ "act_bits": 16,
1564
+ "act_data_type": "float"
1565
+ },
1566
+ "vision_model.encoder.layers.8.self_attn.v_proj": {
1567
+ "bits": 16,
1568
+ "data_type": "float",
1569
+ "act_bits": 16,
1570
+ "act_data_type": "float"
1571
+ },
1572
+ "vision_model.encoder.layers.9.mlp.fc1": {
1573
+ "bits": 16,
1574
+ "data_type": "float",
1575
+ "act_bits": 16,
1576
+ "act_data_type": "float"
1577
+ },
1578
+ "vision_model.encoder.layers.9.mlp.fc2": {
1579
+ "bits": 16,
1580
+ "data_type": "float",
1581
+ "act_bits": 16,
1582
+ "act_data_type": "float"
1583
+ },
1584
+ "vision_model.encoder.layers.9.self_attn.k_proj": {
1585
+ "bits": 16,
1586
+ "data_type": "float",
1587
+ "act_bits": 16,
1588
+ "act_data_type": "float"
1589
+ },
1590
+ "vision_model.encoder.layers.9.self_attn.out_proj": {
1591
+ "bits": 16,
1592
+ "data_type": "float",
1593
+ "act_bits": 16,
1594
+ "act_data_type": "float"
1595
+ },
1596
+ "vision_model.encoder.layers.9.self_attn.q_proj": {
1597
+ "bits": 16,
1598
+ "data_type": "float",
1599
+ "act_bits": 16,
1600
+ "act_data_type": "float"
1601
+ },
1602
+ "vision_model.encoder.layers.9.self_attn.v_proj": {
1603
+ "bits": 16,
1604
+ "data_type": "float",
1605
+ "act_bits": 16,
1606
+ "act_data_type": "float"
1607
+ },
1608
+ "vision_model.head.attention.out_proj": {
1609
+ "bits": 16,
1610
+ "data_type": "float",
1611
+ "act_bits": 16,
1612
+ "act_data_type": "float"
1613
+ },
1614
+ "vision_model.head.mlp.fc1": {
1615
+ "bits": 16,
1616
+ "data_type": "float",
1617
+ "act_bits": 16,
1618
+ "act_data_type": "float"
1619
+ },
1620
+ "vision_model.head.mlp.fc2": {
1621
+ "bits": 16,
1622
+ "data_type": "float",
1623
+ "act_bits": 16,
1624
+ "act_data_type": "float"
1625
+ }
1626
+ }
1627
+ }
1628
+ }
configuration_hunyuan_image_3.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # https://github.com/Tencent-Hunyuan/HunyuanImage-3.0/blob/main/LICENSE
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+ # ==============================================================================
13
+
14
+ from transformers.configuration_utils import PretrainedConfig
15
+ from transformers.utils import logging
16
+ from typing import List, Union, Optional
17
+
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+
22
+ class HunyuanImage3Config(PretrainedConfig):
23
+ r"""
24
+ This is the configuration class to store the configuration of a [`HunyuanImage3Model`]. It is used to instantiate
25
+ an Hunyuan model according to the specified arguments, defining the model architecture. Instantiating a
26
+ configuration with the defaults will yield a similar configuration to that of the Hunyuan-7B.
27
+
28
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
29
+ documentation from [`PretrainedConfig`] for more information.
30
+
31
+
32
+ Args:
33
+ vocab_size (`int`, *optional*, defaults to 32000):
34
+ Vocabulary size of the Hunyuan Image 3 model. Defines the number of different tokens that can be
35
+ represented by the `inputs_ids` passed when calling [`HunyuanImage3Model`]
36
+ hidden_size (`int`, *optional*, defaults to 4096):
37
+ Dimension of the hidden representations.
38
+ intermediate_size (`int`, *optional*, defaults to 11008):
39
+ Dimension of the MLP representations or shared MLP representations.
40
+ moe_intermediate_size (`int` or `List`, *optional*, defaults to 11008):
41
+ Dimension of the MLP representations in MoE. Use a list if you want a different size per layer.
42
+ num_hidden_layers (`int`, *optional*, defaults to 32):
43
+ Number of hidden layers in the Transformer decoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 32):
45
+ Number of attention heads for each attention layer in the Transformer decoder.
46
+ num_key_value_heads (`int`, *optional*):
47
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
48
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
49
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
50
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
51
+ by meanpooling all the original heads within that group. For more details checkout [this
52
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
53
+ `num_attention_heads`.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
57
+ The maximum sequence length that this model might ever be used with.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ pad_token_id (`int`, *optional*):
66
+ Padding token id.
67
+ bos_token_id (`int`, *optional*, defaults to 1):
68
+ Beginning of stream token id.
69
+ eos_token_id (`int`, *optional*, defaults to 2):
70
+ End of stream token id.
71
+ pretraining_tp (`int`, *optional*, defaults to 1):
72
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
73
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
74
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
75
+ issue](https://github.com/pytorch/pytorch/issues/76232).
76
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
77
+ Whether to tie weight embeddings
78
+ rope_theta (`float`, *optional*, defaults to 10000.0):
79
+ The base period of the RoPE embeddings.
80
+ rope_scaling (`Dict`, *optional*):
81
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
82
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
83
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
84
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
85
+ these scaling strategies behave:
86
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
87
+ experimental feature, subject to breaking API changes in future versions.
88
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
89
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
90
+ attention_dropout (`float`, *optional*, defaults to 0.0):
91
+ The dropout ratio for the attention probabilities.
92
+ use_qk_norm (`bool`, *optional*, defaults to `False`):
93
+ Whether query and key in attention use norm
94
+ use_cla (`bool`, *optional*, defaults to `False`):
95
+ Whether to use CLA in attention
96
+ cla_share_factor (`int`, *optional*, defaults to 1):
97
+ The share factor of CLA
98
+ num_experts (`int` or `List`, *optional*, defaults to 1):
99
+ The number of experts for moe. If it is a list, it will be used as the number of experts for each layer.
100
+ num_shared_expert (`int` or `List`, *optional*, defaults to 1):
101
+ The number of shared experts for moe. If it is a list, it will be used as the number of shared experts
102
+ for each layer.
103
+ moe_topk (`int` or `List`, *optional*, defaults to 1):
104
+ The topk value for moe. If it is a list, it will be used as the topk value for each layer.
105
+ capacity_factor (Not used) (`float` or `List`, *optional*, defaults to 1.0):
106
+ The capacity factor for moe. If it is a list, it will be used as the capacity factor for each layer.
107
+ moe_layer_num_skipped (`int`, *optional*, defaults to 0):
108
+ First moe_layer_num_skipped layers do not use MoE.
109
+ """
110
+
111
+ model_type = "Hunyuan"
112
+ keys_to_ignore_at_inference = ["past_key_values"]
113
+
114
+ def __init__(
115
+ self,
116
+ vocab_size: int = 290943,
117
+ hidden_size: int = 4096,
118
+ intermediate_size: int = 11008,
119
+ moe_intermediate_size: Union[int, List] = None,
120
+ num_hidden_layers: int = 32,
121
+ num_attention_heads: int = 32,
122
+ num_key_value_heads: Optional[int] = None,
123
+ attention_head_dim: Optional[int] = None,
124
+ hidden_act="silu",
125
+ max_position_embeddings=2048,
126
+ initializer_range=0.02,
127
+ rms_norm_eps=1e-5,
128
+ use_cache=True,
129
+ pad_token_id=0,
130
+ bos_token_id=1,
131
+ eos_token_id=2,
132
+ eod_token_id=3,
133
+ im_start_id=4,
134
+ im_end_id=5,
135
+ text_start_id=6,
136
+ text_end_id=7,
137
+ image_token_id=8,
138
+ video_start_id=9,
139
+ video_end_id=10,
140
+ im_newline_id=11,
141
+ mask_init_id=12,
142
+ pretraining_tp=1,
143
+ tie_word_embeddings=False,
144
+ rope_theta=10000.0,
145
+ rope_scaling=None,
146
+ attention_bias=False,
147
+ mlp_bias=False,
148
+ attention_dropout=0.0,
149
+ use_qk_norm=False,
150
+ use_rotary_pos_emb=True,
151
+ use_cla=False,
152
+ cla_share_factor=1,
153
+ norm_type="hf_rms",
154
+ num_experts: Union[int, List] = 1,
155
+ use_mixed_mlp_moe=False,
156
+ num_shared_expert: Union[int, List] = 1,
157
+ moe_topk: Union[int, List] = 1,
158
+ capacity_factor: int = 1.0,
159
+ moe_drop_tokens=False,
160
+ moe_random_routing_dropped_token=False,
161
+ use_mla=False,
162
+ kv_lora_rank=512,
163
+ q_lora_rank=1536,
164
+ qk_rope_head_dim=64,
165
+ v_head_dim=128,
166
+ qk_nope_head_dim=128,
167
+ moe_layer_num_skipped=0,
168
+ norm_topk_prob=True,
169
+ routed_scaling_factor=1.0,
170
+ group_limited_greedy=False,
171
+ n_group=None,
172
+ topk_group=None,
173
+ add_classification_head=False,
174
+ class_num=0,
175
+ pool_type="last",
176
+ pad_id=-1,
177
+ # Added
178
+ moe_impl="eager",
179
+ vae_downsample_factor=(16, 16), # (h, w)
180
+ img_proj_type="unet",
181
+ patch_size=1,
182
+ patch_embed_hidden_dim=1024,
183
+ image_base_size=1024,
184
+ rope_type="2d",
185
+ cond_token_attn_type="full",
186
+ cond_image_type="vae_vit",
187
+ vae_type=None,
188
+ vae_dtype="float32",
189
+ vae_autocast_dtype="float16",
190
+ vae=None,
191
+ vit_type=None,
192
+ vit=None,
193
+ vit_processor=None,
194
+ vit_aligner=None,
195
+ cfg_distilled=False,
196
+ use_meanflow=False,
197
+ **kwargs,
198
+ ):
199
+ self.vocab_size = vocab_size
200
+ self.max_position_embeddings = max_position_embeddings
201
+ self.hidden_size = hidden_size
202
+ self.intermediate_size = intermediate_size
203
+ self.moe_intermediate_size = moe_intermediate_size
204
+ self.num_hidden_layers = num_hidden_layers
205
+ self.num_attention_heads = num_attention_heads
206
+ self.moe_impl = moe_impl
207
+ self.num_experts = num_experts
208
+ self.use_mixed_mlp_moe = use_mixed_mlp_moe
209
+ self.num_shared_expert = num_shared_expert
210
+ self.moe_topk = moe_topk
211
+ self.capacity_factor = capacity_factor
212
+ self.moe_drop_tokens = moe_drop_tokens
213
+ self.moe_random_routing_dropped_token = moe_random_routing_dropped_token
214
+
215
+ if attention_head_dim is not None:
216
+ self.attention_head_dim = attention_head_dim
217
+ else:
218
+ self.attention_head_dim = self.hidden_size // num_attention_heads
219
+
220
+ # for backward compatibility
221
+ if num_key_value_heads is None:
222
+ num_key_value_heads = num_attention_heads
223
+
224
+ self.num_key_value_heads = num_key_value_heads
225
+ self.hidden_act = hidden_act
226
+ self.initializer_range = initializer_range
227
+ self.rms_norm_eps = rms_norm_eps
228
+ self.pretraining_tp = pretraining_tp
229
+ self.use_cache = use_cache
230
+ self.rope_theta = rope_theta
231
+ self.rope_scaling = rope_scaling
232
+ self.attention_bias = attention_bias
233
+ self.mlp_bias = mlp_bias
234
+ self.attention_dropout = attention_dropout
235
+ self.use_qk_norm = use_qk_norm
236
+ self.use_rotary_pos_emb = use_rotary_pos_emb
237
+ self.use_cla = use_cla
238
+ self.cla_share_factor = cla_share_factor
239
+ self.norm_type = norm_type
240
+ # MLA args
241
+ self.use_mla = use_mla
242
+ self.kv_lora_rank = kv_lora_rank
243
+ self.q_lora_rank = q_lora_rank
244
+ self.qk_rope_head_dim = qk_rope_head_dim
245
+ self.qk_nope_head_dim = qk_nope_head_dim
246
+ self.v_head_dim = v_head_dim
247
+
248
+ # DeepSeek related args
249
+ self.moe_layer_num_skipped = moe_layer_num_skipped
250
+ self.norm_topk_prob = norm_topk_prob
251
+ self.routed_scaling_factor = routed_scaling_factor
252
+ self.group_limited_greedy = group_limited_greedy
253
+ self.n_group = n_group
254
+ self.topk_group = topk_group
255
+ self.add_classification_head = add_classification_head
256
+ self.class_num = class_num
257
+ self.pool_type = pool_type
258
+ self.pad_id = pad_id
259
+
260
+ if self.class_num is not None:
261
+ self.dense_list = [self.hidden_size, self.class_num]
262
+
263
+ # Conditioning image configs
264
+ self.cond_token_attn_type = cond_token_attn_type
265
+ self.cond_image_type = cond_image_type
266
+
267
+ # ViT args
268
+ self.vit_type = vit_type
269
+ self.vit = vit
270
+ self.vit_processor = vit_processor
271
+ self.vit_aligner = vit_aligner
272
+
273
+ # Image Gen args
274
+ self.vae_type = vae_type
275
+ self.vae_dtype = vae_dtype
276
+ self.vae_autocast_dtype = vae_autocast_dtype
277
+ self.vae = vae
278
+ self.vae_downsample_factor = vae_downsample_factor
279
+ self.img_proj_type = img_proj_type
280
+ self.patch_size = patch_size
281
+ self.patch_embed_hidden_dim = patch_embed_hidden_dim
282
+ self.image_base_size = image_base_size
283
+ self.rope_type = rope_type
284
+
285
+ # token id
286
+ self.eod_token_id = eod_token_id
287
+ self.im_start_id = im_start_id
288
+ self.im_end_id = im_end_id
289
+ self.text_start_id = text_start_id
290
+ self.text_end_id = text_end_id
291
+ self.image_token_id = image_token_id
292
+ self.video_start_id = video_start_id
293
+ self.video_end_id = video_end_id
294
+ self.im_newline_id = im_newline_id
295
+ self.mask_init_id = mask_init_id
296
+
297
+ # flag of cfg distilled model
298
+ self.cfg_distilled = cfg_distilled
299
+ # flag of meanflow distilled model
300
+ self.use_meanflow = use_meanflow
301
+ super().__init__(
302
+ pad_token_id=pad_token_id,
303
+ bos_token_id=bos_token_id,
304
+ eos_token_id=eos_token_id,
305
+ tie_word_embeddings=tie_word_embeddings,
306
+ **kwargs,
307
+ )
308
+
309
+
310
+ __all__ = ["HunyuanImage3Config"]
generation_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "disable_compile": true,
3
+ "eos_token_id": [
4
+ 127957
5
+ ],
6
+ "pad_token_id": 128009,
7
+ "do_sample": true,
8
+ "top_k": 1024,
9
+ "top_p": 0.95,
10
+ "temperature": 0.6,
11
+ "max_length": 22800,
12
+ "sequence_template": "instruct",
13
+ "diff_infer_steps": 8,
14
+ "diff_guidance_scale": 2.5,
15
+ "flow_shift": 3.0,
16
+ "use_system_prompt": "en_unified",
17
+ "drop_think": false,
18
+ "bot_task": "think_recaption",
19
+ "max_new_tokens": 2048,
20
+ "transformers_version": "4.50.0"
21
+ }
hunyuan_image_3_pipeline.py ADDED
@@ -0,0 +1,913 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # https://github.com/Tencent-Hunyuan/HunyuanImage-3.0/blob/main/LICENSE
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+ # ==============================================================================
13
+ #
14
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
15
+ #
16
+ # Licensed under the Apache License, Version 2.0 (the "License");
17
+ # you may not use this file except in compliance with the License.
18
+ # You may obtain a copy of the License at
19
+ #
20
+ # http://www.apache.org/licenses/LICENSE-2.0
21
+ #
22
+ # Unless required by applicable law or agreed to in writing, software
23
+ # distributed under the License is distributed on an "AS IS" BASIS,
24
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25
+ # See the License for the specific language governing permissions and
26
+ # limitations under the License.
27
+ # ==============================================================================================
28
+
29
+ import inspect
30
+ import math
31
+ from dataclasses import dataclass
32
+ from typing import Any, Callable, Dict, List
33
+ from typing import Optional, Tuple, Union
34
+
35
+ import numpy as np
36
+ import torch
37
+ from PIL import Image
38
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
39
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
40
+ from diffusers.image_processor import VaeImageProcessor
41
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
42
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
43
+ from diffusers.utils import BaseOutput, logging
44
+ from diffusers.utils.torch_utils import randn_tensor
45
+ from .cache_utils import cache_init
46
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
47
+
48
+
49
+ def retrieve_timesteps(
50
+ scheduler,
51
+ num_inference_steps: Optional[int] = None,
52
+ device: Optional[Union[str, torch.device]] = None,
53
+ timesteps: Optional[List[int]] = None,
54
+ sigmas: Optional[List[float]] = None,
55
+ **kwargs,
56
+ ):
57
+ """
58
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
59
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
60
+
61
+ Args:
62
+ scheduler (`SchedulerMixin`):
63
+ The scheduler to get timesteps from.
64
+ num_inference_steps (`int`):
65
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
66
+ must be `None`.
67
+ device (`str` or `torch.device`, *optional*):
68
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
69
+ timesteps (`List[int]`, *optional*):
70
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
71
+ `num_inference_steps` and `sigmas` must be `None`.
72
+ sigmas (`List[float]`, *optional*):
73
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
74
+ `num_inference_steps` and `timesteps` must be `None`.
75
+
76
+ Returns:
77
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
78
+ second element is the number of inference steps.
79
+ """
80
+ if timesteps is not None and sigmas is not None:
81
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
82
+ if timesteps is not None:
83
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
84
+ if not accepts_timesteps:
85
+ raise ValueError(
86
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
87
+ f" timestep schedules. Please check whether you are using the correct scheduler."
88
+ )
89
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
90
+ timesteps = scheduler.timesteps
91
+ num_inference_steps = len(timesteps)
92
+ elif sigmas is not None:
93
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
94
+ if not accept_sigmas:
95
+ raise ValueError(
96
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
97
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
98
+ )
99
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
100
+ timesteps = scheduler.timesteps
101
+ num_inference_steps = len(timesteps)
102
+ else:
103
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
104
+ timesteps = scheduler.timesteps
105
+ return timesteps, num_inference_steps
106
+
107
+
108
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
109
+ r"""
110
+ Rescales `noise_cfg` tensor based on `guidance_rescale` to improve image quality and fix overexposure. Based on
111
+ Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
112
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf).
113
+
114
+ Args:
115
+ noise_cfg (`torch.Tensor`):
116
+ The predicted noise tensor for the guided diffusion process.
117
+ noise_pred_text (`torch.Tensor`):
118
+ The predicted noise tensor for the text-guided diffusion process.
119
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
120
+ A rescale factor applied to the noise predictions.
121
+ Returns:
122
+ noise_cfg (`torch.Tensor`): The rescaled noise prediction tensor.
123
+ """
124
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
125
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
126
+ # rescale the results from guidance (fixes overexposure)
127
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
128
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
129
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
130
+ return noise_cfg
131
+
132
+
133
+ @dataclass
134
+ class HunyuanImage3Text2ImagePipelineOutput(BaseOutput):
135
+ samples: Union[List[Any], np.ndarray]
136
+
137
+
138
+ @dataclass
139
+ class FlowMatchDiscreteSchedulerOutput(BaseOutput):
140
+ """
141
+ Output class for the scheduler's `step` function output.
142
+
143
+ Args:
144
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
145
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
146
+ denoising loop.
147
+ """
148
+
149
+ prev_sample: torch.FloatTensor
150
+
151
+
152
+ class FlowMatchDiscreteScheduler(SchedulerMixin, ConfigMixin):
153
+ """
154
+ Euler scheduler.
155
+
156
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
157
+ methods the library implements for all schedulers such as loading and saving.
158
+
159
+ Args:
160
+ num_train_timesteps (`int`, defaults to 1000):
161
+ The number of diffusion steps to train the model.
162
+ timestep_spacing (`str`, defaults to `"linspace"`):
163
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
164
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
165
+ shift (`float`, defaults to 1.0):
166
+ The shift value for the timestep schedule.
167
+ reverse (`bool`, defaults to `True`):
168
+ Whether to reverse the timestep schedule.
169
+ """
170
+
171
+ _compatibles = []
172
+ order = 1
173
+
174
+ @register_to_config
175
+ def __init__(
176
+ self,
177
+ num_train_timesteps: int = 1000,
178
+ shift: float = 1.0,
179
+ reverse: bool = True,
180
+ solver: str = "euler",
181
+ use_flux_shift: bool = False,
182
+ flux_base_shift: float = 0.5,
183
+ flux_max_shift: float = 1.15,
184
+ n_tokens: Optional[int] = None,
185
+ ):
186
+ sigmas = torch.linspace(1, 0, num_train_timesteps + 1)
187
+
188
+ if not reverse:
189
+ sigmas = sigmas.flip(0)
190
+
191
+ self.sigmas = sigmas
192
+ # the value fed to model
193
+ self.timesteps = (sigmas[:-1] * num_train_timesteps).to(dtype=torch.float32)
194
+ self.timesteps_full = (sigmas * num_train_timesteps).to(dtype=torch.float32)
195
+
196
+ self._step_index = None
197
+ self._begin_index = None
198
+
199
+ self.supported_solver = [
200
+ "euler",
201
+ "heun-2", "midpoint-2",
202
+ "kutta-4",
203
+ ]
204
+ if solver not in self.supported_solver:
205
+ raise ValueError(f"Solver {solver} not supported. Supported solvers: {self.supported_solver}")
206
+
207
+ # empty dt and derivative (for heun)
208
+ self.derivative_1 = None
209
+ self.derivative_2 = None
210
+ self.derivative_3 = None
211
+ self.dt = None
212
+
213
+ @property
214
+ def step_index(self):
215
+ """
216
+ The index counter for current timestep. It will increase 1 after each scheduler step.
217
+ """
218
+ return self._step_index
219
+
220
+ @property
221
+ def begin_index(self):
222
+ """
223
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
224
+ """
225
+ return self._begin_index
226
+
227
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
228
+ def set_begin_index(self, begin_index: int = 0):
229
+ """
230
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
231
+
232
+ Args:
233
+ begin_index (`int`):
234
+ The begin index for the scheduler.
235
+ """
236
+ self._begin_index = begin_index
237
+
238
+ def _sigma_to_t(self, sigma):
239
+ return sigma * self.config.num_train_timesteps
240
+
241
+ @property
242
+ def state_in_first_order(self):
243
+ return self.derivative_1 is None
244
+
245
+ @property
246
+ def state_in_second_order(self):
247
+ return self.derivative_2 is None
248
+
249
+ @property
250
+ def state_in_third_order(self):
251
+ return self.derivative_3 is None
252
+
253
+ def get_timestep_r(self, timestep: Union[float, torch.FloatTensor]):
254
+ if self.step_index is None:
255
+ self._init_step_index(timestep)
256
+ return self.timesteps_full[self.step_index + 1]
257
+
258
+ def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None,
259
+ n_tokens: int = None):
260
+ """
261
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
262
+
263
+ Args:
264
+ num_inference_steps (`int`):
265
+ The number of diffusion steps used when generating samples with a pre-trained model.
266
+ device (`str` or `torch.device`, *optional*):
267
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
268
+ n_tokens (`int`, *optional*):
269
+ Number of tokens in the input sequence.
270
+ """
271
+ self.num_inference_steps = num_inference_steps
272
+
273
+ sigmas = torch.linspace(1, 0, num_inference_steps + 1)
274
+
275
+ # Apply timestep shift
276
+ if self.config.use_flux_shift:
277
+ assert isinstance(n_tokens, int), "n_tokens should be provided for flux shift"
278
+ mu = self.get_lin_function(y1=self.config.flux_base_shift, y2=self.config.flux_max_shift)(n_tokens)
279
+ sigmas = self.flux_time_shift(mu, 1.0, sigmas)
280
+ elif self.config.shift != 1.:
281
+ sigmas = self.sd3_time_shift(sigmas)
282
+
283
+ if not self.config.reverse:
284
+ sigmas = 1 - sigmas
285
+
286
+ self.sigmas = sigmas
287
+ self.timesteps = (sigmas[:-1] * self.config.num_train_timesteps).to(dtype=torch.float32, device=device)
288
+ self.timesteps_full = (sigmas * self.config.num_train_timesteps).to(dtype=torch.float32, device=device)
289
+
290
+ # empty dt and derivative (for kutta)
291
+ self.derivative_1 = None
292
+ self.derivative_2 = None
293
+ self.derivative_3 = None
294
+ self.dt = None
295
+
296
+ # Reset step index
297
+ self._step_index = None
298
+
299
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
300
+ if schedule_timesteps is None:
301
+ schedule_timesteps = self.timesteps
302
+
303
+ indices = (schedule_timesteps == timestep).nonzero()
304
+
305
+ # The sigma index that is taken for the **very** first `step`
306
+ # is always the second index (or the last index if there is only 1)
307
+ # This way we can ensure we don't accidentally skip a sigma in
308
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
309
+ pos = 1 if len(indices) > 1 else 0
310
+
311
+ return indices[pos].item()
312
+
313
+ def _init_step_index(self, timestep):
314
+ if self.begin_index is None:
315
+ if isinstance(timestep, torch.Tensor):
316
+ timestep = timestep.to(self.timesteps.device)
317
+ self._step_index = self.index_for_timestep(timestep)
318
+ else:
319
+ self._step_index = self._begin_index
320
+
321
+ def scale_model_input(self, sample: torch.Tensor, timestep: Optional[int] = None) -> torch.Tensor:
322
+ return sample
323
+
324
+ @staticmethod
325
+ def get_lin_function(x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15):
326
+ m = (y2 - y1) / (x2 - x1)
327
+ b = y1 - m * x1
328
+ return lambda x: m * x + b
329
+
330
+ @staticmethod
331
+ def flux_time_shift(mu: float, sigma: float, t: torch.Tensor):
332
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
333
+
334
+ def sd3_time_shift(self, t: torch.Tensor):
335
+ return (self.config.shift * t) / (1 + (self.config.shift - 1) * t)
336
+
337
+ def step(
338
+ self,
339
+ model_output: torch.FloatTensor,
340
+ timestep: Union[float, torch.FloatTensor],
341
+ sample: torch.FloatTensor,
342
+ pred_uncond: torch.FloatTensor = None,
343
+ generator: Optional[torch.Generator] = None,
344
+ n_tokens: Optional[int] = None,
345
+ return_dict: bool = True,
346
+ ) -> Union[FlowMatchDiscreteSchedulerOutput, Tuple]:
347
+ """
348
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
349
+ process from the learned model outputs (most often the predicted noise).
350
+
351
+ Args:
352
+ model_output (`torch.FloatTensor`):
353
+ The direct output from learned diffusion model.
354
+ timestep (`float`):
355
+ The current discrete timestep in the diffusion chain.
356
+ sample (`torch.FloatTensor`):
357
+ A current instance of a sample created by the diffusion process.
358
+ generator (`torch.Generator`, *optional*):
359
+ A random number generator.
360
+ n_tokens (`int`, *optional*):
361
+ Number of tokens in the input sequence.
362
+ return_dict (`bool`):
363
+ Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or
364
+ tuple.
365
+
366
+ Returns:
367
+ [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`:
368
+ If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is
369
+ returned, otherwise a tuple is returned where the first element is the sample tensor.
370
+ """
371
+
372
+ if (
373
+ isinstance(timestep, int)
374
+ or isinstance(timestep, torch.IntTensor)
375
+ or isinstance(timestep, torch.LongTensor)
376
+ ):
377
+ raise ValueError(
378
+ (
379
+ "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
380
+ " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
381
+ " one of the `scheduler.timesteps` as a timestep."
382
+ ),
383
+ )
384
+
385
+ if self.step_index is None:
386
+ self._init_step_index(timestep)
387
+
388
+ # Upcast to avoid precision issues when computing prev_sample
389
+ sample = sample.to(torch.float32)
390
+ model_output = model_output.to(torch.float32)
391
+ pred_uncond = pred_uncond.to(torch.float32) if pred_uncond is not None else None
392
+
393
+ # dt = self.sigmas[self.step_index + 1] - self.sigmas[self.step_index]
394
+ sigma = self.sigmas[self.step_index]
395
+ sigma_next = self.sigmas[self.step_index + 1]
396
+
397
+ last_inner_step = True
398
+ if self.config.solver == "euler":
399
+ derivative, dt, sample, last_inner_step = self.first_order_method(model_output, sigma, sigma_next, sample)
400
+ elif self.config.solver in ["heun-2", "midpoint-2"]:
401
+ derivative, dt, sample, last_inner_step = self.second_order_method(model_output, sigma, sigma_next, sample)
402
+ elif self.config.solver == "kutta-4":
403
+ derivative, dt, sample, last_inner_step = self.fourth_order_method(model_output, sigma, sigma_next, sample)
404
+ else:
405
+ raise ValueError(f"Solver {self.config.solver} not supported. Supported solvers: {self.supported_solver}")
406
+
407
+ prev_sample = sample + derivative * dt
408
+
409
+ # Cast sample back to model compatible dtype
410
+ # prev_sample = prev_sample.to(model_output.dtype)
411
+
412
+ # upon completion increase step index by one
413
+ if last_inner_step:
414
+ self._step_index += 1
415
+
416
+ if not return_dict:
417
+ return (prev_sample,)
418
+
419
+ return FlowMatchDiscreteSchedulerOutput(prev_sample=prev_sample)
420
+
421
+ def first_order_method(self, model_output, sigma, sigma_next, sample):
422
+ derivative = model_output
423
+ dt = sigma_next - sigma
424
+ return derivative, dt, sample, True
425
+
426
+ def second_order_method(self, model_output, sigma, sigma_next, sample):
427
+ if self.state_in_first_order:
428
+ # store for 2nd order step
429
+ self.derivative_1 = model_output
430
+ self.dt = sigma_next - sigma
431
+ self.sample = sample
432
+
433
+ derivative = model_output
434
+ if self.config.solver == 'heun-2':
435
+ dt = self.dt
436
+ elif self.config.solver == 'midpoint-2':
437
+ dt = self.dt / 2
438
+ else:
439
+ raise NotImplementedError(f"Solver {self.config.solver} not supported.")
440
+ last_inner_step = False
441
+
442
+ else:
443
+ if self.config.solver == 'heun-2':
444
+ derivative = 0.5 * (self.derivative_1 + model_output)
445
+ elif self.config.solver == 'midpoint-2':
446
+ derivative = model_output
447
+ else:
448
+ raise NotImplementedError(f"Solver {self.config.solver} not supported.")
449
+
450
+ # 3. take prev timestep & sample
451
+ dt = self.dt
452
+ sample = self.sample
453
+ last_inner_step = True
454
+
455
+ # free dt and derivative
456
+ # Note, this puts the scheduler in "first order mode"
457
+ self.derivative_1 = None
458
+ self.dt = None
459
+ self.sample = None
460
+
461
+ return derivative, dt, sample, last_inner_step
462
+
463
+ def fourth_order_method(self, model_output, sigma, sigma_next, sample):
464
+ if self.state_in_first_order:
465
+ self.derivative_1 = model_output
466
+ self.dt = sigma_next - sigma
467
+ self.sample = sample
468
+ derivative = model_output
469
+ dt = self.dt / 2
470
+ last_inner_step = False
471
+
472
+ elif self.state_in_second_order:
473
+ self.derivative_2 = model_output
474
+ derivative = model_output
475
+ dt = self.dt / 2
476
+ last_inner_step = False
477
+
478
+ elif self.state_in_third_order:
479
+ self.derivative_3 = model_output
480
+ derivative = model_output
481
+ dt = self.dt
482
+ last_inner_step = False
483
+
484
+ else:
485
+ derivative = (1/6 * self.derivative_1 + 1/3 * self.derivative_2 + 1/3 * self.derivative_3 +
486
+ 1/6 * model_output)
487
+
488
+ # 3. take prev timestep & sample
489
+ dt = self.dt
490
+ sample = self.sample
491
+ last_inner_step = True
492
+
493
+ # free dt and derivative
494
+ # Note, this puts the scheduler in "first order mode"
495
+ self.derivative_1 = None
496
+ self.derivative_2 = None
497
+ self.derivative_3 = None
498
+ self.dt = None
499
+ self.sample = None
500
+
501
+ return derivative, dt, sample, last_inner_step
502
+
503
+ def __len__(self):
504
+ return self.config.num_train_timesteps
505
+
506
+
507
+ class ClassifierFreeGuidance:
508
+ def __init__(
509
+ self,
510
+ use_original_formulation: bool = False,
511
+ start: float = 0.0,
512
+ stop: float = 1.0,
513
+ ):
514
+ super().__init__()
515
+ self.use_original_formulation = use_original_formulation
516
+
517
+ def __call__(
518
+ self,
519
+ pred_cond: torch.Tensor,
520
+ pred_uncond: Optional[torch.Tensor],
521
+ guidance_scale: float,
522
+ step: int,
523
+ ) -> torch.Tensor:
524
+
525
+ shift = pred_cond - pred_uncond
526
+ pred = pred_cond if self.use_original_formulation else pred_uncond
527
+ pred = pred + guidance_scale * shift
528
+
529
+ return pred
530
+
531
+
532
+ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
533
+ r"""
534
+ Pipeline for condition-to-sample generation using Stable Diffusion.
535
+
536
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
537
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
538
+
539
+ Args:
540
+ model ([`ModelMixin`]):
541
+ A model to denoise the diffused latents.
542
+ scheduler ([`SchedulerMixin`]):
543
+ A scheduler to be used in combination with `diffusion_model` to denoise the diffused latents. Can be one of
544
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
545
+ """
546
+
547
+ model_cpu_offload_seq = ""
548
+ _optional_components = []
549
+ _exclude_from_cpu_offload = []
550
+ _callback_tensor_inputs = ["latents"]
551
+
552
+ def __init__(
553
+ self,
554
+ model,
555
+ scheduler: SchedulerMixin,
556
+ vae,
557
+ progress_bar_config: Dict[str, Any] = None,
558
+ ):
559
+ super().__init__()
560
+
561
+ # ==========================================================================================
562
+ if progress_bar_config is None:
563
+ progress_bar_config = {}
564
+ if not hasattr(self, '_progress_bar_config'):
565
+ self._progress_bar_config = {}
566
+ self._progress_bar_config.update(progress_bar_config)
567
+ # ==========================================================================================
568
+
569
+ self.register_modules(
570
+ model=model,
571
+ scheduler=scheduler,
572
+ vae=vae,
573
+ )
574
+
575
+ # should be a tuple or a list corresponding to the size of latents (batch_size, channel, *size)
576
+ # if None, will be treated as a tuple of 1
577
+ self.latent_scale_factor = self.model.config.vae_downsample_factor
578
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.latent_scale_factor)
579
+
580
+ # Must start with APG_mode_
581
+ self.cfg_operator = ClassifierFreeGuidance()
582
+
583
+ @staticmethod
584
+ def denormalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
585
+ """
586
+ Denormalize an image array to [0,1].
587
+ """
588
+ return (images / 2 + 0.5).clamp(0, 1)
589
+
590
+ @staticmethod
591
+ def pt_to_numpy(images: torch.Tensor) -> np.ndarray:
592
+ """
593
+ Convert a PyTorch tensor to a NumPy image.
594
+ """
595
+ images = images.cpu().permute(0, 2, 3, 1).float().numpy()
596
+ return images
597
+
598
+ @staticmethod
599
+ def numpy_to_pil(images: np.ndarray):
600
+ """
601
+ Convert a numpy image or a batch of images to a PIL image.
602
+ """
603
+ if images.ndim == 3:
604
+ images = images[None, ...]
605
+ images = (images * 255).round().astype("uint8")
606
+ if images.shape[-1] == 1:
607
+ # special case for grayscale (single channel) images
608
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
609
+ else:
610
+ pil_images = [Image.fromarray(image) for image in images]
611
+
612
+ return pil_images
613
+
614
+ def prepare_extra_func_kwargs(self, func, kwargs):
615
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
616
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
617
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
618
+ # and should be between [0, 1]
619
+ extra_kwargs = {}
620
+
621
+ for k, v in kwargs.items():
622
+ accepts = k in set(inspect.signature(func).parameters.keys())
623
+ if accepts:
624
+ extra_kwargs[k] = v
625
+ return extra_kwargs
626
+
627
+ def prepare_latents(self, batch_size, latent_channel, image_size, dtype, device, generator, latents=None):
628
+ if self.latent_scale_factor is None:
629
+ latent_scale_factor = (1,) * len(image_size)
630
+ elif isinstance(self.latent_scale_factor, int):
631
+ latent_scale_factor = (self.latent_scale_factor,) * len(image_size)
632
+ elif isinstance(self.latent_scale_factor, tuple) or isinstance(self.latent_scale_factor, list):
633
+ assert len(self.latent_scale_factor) == len(image_size), \
634
+ "len(latent_scale_factor) shoudl be the same as len(image_size)"
635
+ latent_scale_factor = self.latent_scale_factor
636
+ else:
637
+ raise ValueError(
638
+ f"latent_scale_factor should be either None, int, tuple of int, or list of int, "
639
+ f"but got {self.latent_scale_factor}"
640
+ )
641
+
642
+ latents_shape = (
643
+ batch_size,
644
+ latent_channel,
645
+ *[int(s) // f for s, f in zip(image_size, latent_scale_factor)],
646
+ )
647
+ if isinstance(generator, list) and len(generator) != batch_size:
648
+ raise ValueError(
649
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
650
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
651
+ )
652
+
653
+ if latents is None:
654
+ latents = randn_tensor(latents_shape, generator=generator, device=device, dtype=dtype)
655
+ else:
656
+ latents = latents.to(device)
657
+
658
+ # Check existence to make it compatible with FlowMatchEulerDiscreteScheduler
659
+ if hasattr(self.scheduler, "init_noise_sigma"):
660
+ # scale the initial noise by the standard deviation required by the scheduler
661
+ latents = latents * self.scheduler.init_noise_sigma
662
+
663
+ return latents
664
+
665
+ @property
666
+ def guidance_scale(self):
667
+ return self._guidance_scale
668
+
669
+ @property
670
+ def guidance_rescale(self):
671
+ return self._guidance_rescale
672
+
673
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
674
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
675
+ # corresponds to doing no classifier free guidance.
676
+ @property
677
+ def do_classifier_free_guidance(self):
678
+ return self._guidance_scale > 1.0
679
+
680
+ @property
681
+ def num_timesteps(self):
682
+ return self._num_timesteps
683
+
684
+ def set_scheduler(self, new_scheduler):
685
+ self.register_modules(scheduler=new_scheduler)
686
+
687
+ @torch.no_grad()
688
+ def __call__(
689
+ self,
690
+ batch_size: int,
691
+ image_size: List[int],
692
+ num_inference_steps: int = 50,
693
+ timesteps: List[int] = None,
694
+ sigmas: List[float] = None,
695
+ guidance_scale: float = 7.5,
696
+ meanflow: bool = False,
697
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
698
+ latents: Optional[torch.Tensor] = None,
699
+ output_type: Optional[str] = "pil",
700
+ return_dict: bool = True,
701
+ guidance_rescale: float = 0.0,
702
+ callback_on_step_end: Optional[
703
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
704
+ ] = None,
705
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
706
+ model_kwargs: Dict[str, Any] = None,
707
+ **kwargs,
708
+ ):
709
+ r"""
710
+ The call function to the pipeline for generation.
711
+
712
+ Args:
713
+ prompt (`str` or `List[str]`):
714
+ The text to guide image generation.
715
+ image_size (`Tuple[int]` or `List[int]`):
716
+ The size (height, width) of the generated image.
717
+ num_inference_steps (`int`, *optional*, defaults to 50):
718
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
719
+ expense of slower inference.
720
+ timesteps (`List[int]`, *optional*):
721
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
722
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
723
+ passed will be used. Must be in descending order.
724
+ sigmas (`List[float]`, *optional*):
725
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
726
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
727
+ will be used.
728
+ guidance_scale (`float`, *optional*, defaults to 7.5):
729
+ A higher guidance scale value encourages the model to generate samples closely linked to the
730
+ `condition` at the expense of lower sample quality. Guidance scale is enabled when `guidance_scale > 1`.
731
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
732
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
733
+ generation deterministic.
734
+ latents (`torch.Tensor`, *optional*):
735
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for sample
736
+ generation. Can be used to tweak the same generation with different conditions. If not provided,
737
+ a latents tensor is generated by sampling using the supplied random `generator`.
738
+ output_type (`str`, *optional*, defaults to `"pil"`):
739
+ The output format of the generated sample.
740
+ return_dict (`bool`, *optional*, defaults to `True`):
741
+ Whether or not to return a [`~DiffusionPipelineOutput`] instead of a
742
+ plain tuple.
743
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
744
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
745
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
746
+ using zero terminal SNR.
747
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
748
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
749
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
750
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
751
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
752
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
753
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
754
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
755
+ `._callback_tensor_inputs` attribute of your pipeline class.
756
+
757
+ Examples:
758
+
759
+ Returns:
760
+ [`~DiffusionPipelineOutput`] or `tuple`:
761
+ If `return_dict` is `True`, [`~DiffusionPipelineOutput`] is returned,
762
+ otherwise a `tuple` is returned where the first element is a list with the generated samples.
763
+ """
764
+
765
+ callback_steps = kwargs.pop("callback_steps", None)
766
+ pbar_steps = kwargs.pop("pbar_steps", None)
767
+
768
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
769
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
770
+
771
+ self._guidance_scale = guidance_scale
772
+ self._guidance_rescale = guidance_rescale
773
+
774
+
775
+ if not kwargs.get('cfg_distilled', False):
776
+ cfg_factor = 1 + self.do_classifier_free_guidance
777
+ else:
778
+ cfg_factor = 1
779
+ # Define call parameters
780
+ device = self._execution_device
781
+
782
+ # Prepare timesteps
783
+ timesteps, num_inference_steps = retrieve_timesteps(
784
+ self.scheduler, num_inference_steps, device, timesteps, sigmas,
785
+ )
786
+
787
+ # Prepare latent variables
788
+ latents = self.prepare_latents(
789
+ batch_size=batch_size,
790
+ latent_channel=self.model.config.vae["latent_channels"],
791
+ image_size=image_size,
792
+ dtype=torch.bfloat16,
793
+ device=device,
794
+ generator=generator,
795
+ latents=latents,
796
+ )
797
+
798
+ # Prepare extra step kwargs.
799
+ _scheduler_step_extra_kwargs = self.prepare_extra_func_kwargs(
800
+ self.scheduler.step, {"generator": generator}
801
+ )
802
+
803
+ # Prepare model kwargs
804
+ input_ids = model_kwargs.pop("input_ids")
805
+ attention_mask = self.model._prepare_attention_mask_for_generation( # noqa
806
+ input_ids, self.model.generation_config, model_kwargs=model_kwargs,
807
+ )
808
+ model_kwargs["attention_mask"] = attention_mask.to(latents.device)
809
+
810
+ # Sampling loop
811
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
812
+ self._num_timesteps = len(timesteps)
813
+
814
+ # Taylor cache
815
+ cache_dic = None
816
+ if self.model.use_taylor_cache:
817
+ cache_dic = cache_init(cache_interval=self.model.taylor_cache_interval, max_order=self.model.taylor_cache_order, num_steps=len(timesteps),
818
+ enable_first_enhance=self.model.taylor_cache_enable_first_enhance, first_enhance_steps=self.model.taylor_cache_first_enhance_steps,
819
+ enable_tailing_enhance=self.model.taylor_cache_enable_tailing_enhance,
820
+ tailing_enhance_steps=self.model.taylor_cache_tailing_enhance_steps,
821
+ low_freqs_order=self.model.taylor_cache_low_freqs_order,
822
+ high_freqs_order=self.model.taylor_cache_high_freqs_order)
823
+ print(f"***use_taylor_cache: {self.model.use_taylor_cache}, cache_dic: {cache_dic}")
824
+
825
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
826
+ for i, t in enumerate(timesteps):
827
+ # expand the latents if we are doing classifier free guidance
828
+ latent_model_input = torch.cat([latents] * cfg_factor)
829
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
830
+
831
+ if meanflow:
832
+ r = self.scheduler.get_timestep_r(t)
833
+ r_expand = r.repeat(latent_model_input.shape[0])
834
+ else:
835
+ r_expand = None
836
+ model_kwargs["timesteps_r"] = r_expand
837
+
838
+ t_expand = t.repeat(latent_model_input.shape[0])
839
+
840
+ if self.model.use_taylor_cache:
841
+ cache_dic['current_step'] = i
842
+ model_kwargs['cache_dic'] = cache_dic
843
+ if kwargs.get('cfg_distilled', False):
844
+ model_kwargs["guidance"] = torch.tensor(
845
+ [1000.0*self._guidance_scale], device=self.device, dtype=torch.bfloat16
846
+ )
847
+ model_inputs = self.model.prepare_inputs_for_generation(
848
+ input_ids,
849
+ images=latent_model_input,
850
+ timesteps=t_expand,
851
+ **model_kwargs,
852
+ )
853
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True):
854
+ model_output = self.model(**model_inputs, first_step=(i == 0))
855
+ pred = model_output["diffusion_prediction"]
856
+ pred = pred.to(dtype=torch.float32)
857
+ # perform guidance
858
+ if self.do_classifier_free_guidance:
859
+ if not kwargs.get('cfg_distilled', False):
860
+ pred_cond, pred_uncond = pred.chunk(2)
861
+ pred = self.cfg_operator(pred_cond, pred_uncond, self.guidance_scale, step=i)
862
+
863
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
864
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
865
+ pred = rescale_noise_cfg(pred, pred_cond, guidance_rescale=self.guidance_rescale)
866
+
867
+ # compute the previous noisy sample x_t -> x_t-1
868
+ latents = self.scheduler.step(pred, t, latents, **_scheduler_step_extra_kwargs, return_dict=False)[0]
869
+
870
+ if i != len(timesteps) - 1:
871
+ model_kwargs = self.model._update_model_kwargs_for_generation( # noqa
872
+ model_output,
873
+ model_kwargs,
874
+ )
875
+ input_ids = None
876
+ # if input_ids.shape[1] != model_kwargs["position_ids"].shape[1]:
877
+ # input_ids = torch.gather(input_ids, 1, index=model_kwargs["position_ids"])
878
+
879
+ if callback_on_step_end is not None:
880
+ callback_kwargs = {}
881
+ for k in callback_on_step_end_tensor_inputs:
882
+ callback_kwargs[k] = locals()[k]
883
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
884
+
885
+ latents = callback_outputs.pop("latents", latents)
886
+
887
+ # call the callback, if provided
888
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
889
+ progress_bar.update()
890
+
891
+ if hasattr(self.vae.config, 'scaling_factor') and self.vae.config.scaling_factor:
892
+ latents = latents / self.vae.config.scaling_factor
893
+ if hasattr(self.vae.config, 'shift_factor') and self.vae.config.shift_factor:
894
+ latents = latents + self.vae.config.shift_factor
895
+
896
+ if hasattr(self.vae, "ffactor_temporal"):
897
+ latents = latents.unsqueeze(2)
898
+
899
+ with torch.autocast(device_type="cuda", dtype=torch.float16, enabled=True):
900
+ image = self.vae.decode(latents, return_dict=False, generator=generator)[0]
901
+
902
+ # b c t h w
903
+ if hasattr(self.vae, "ffactor_temporal"):
904
+ assert image.shape[2] == 1, "image should have shape [B, C, T, H, W] and T should be 1"
905
+ image = image.squeeze(2)
906
+
907
+ do_denormalize = [True] * image.shape[0]
908
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
909
+
910
+ if not return_dict:
911
+ return (image,)
912
+
913
+ return HunyuanImage3Text2ImagePipelineOutput(samples=image)
image_processor.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # https://github.com/Tencent-Hunyuan/HunyuanImage-3.0/blob/main/LICENSE
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+ # ==============================================================================
13
+
14
+ from dataclasses import dataclass, field, asdict
15
+ from typing import Tuple, Optional, Callable, Union, Any
16
+ import random
17
+ import math
18
+
19
+ import torch
20
+ from PIL import Image
21
+ from torchvision import transforms
22
+ from transformers.image_processing_utils import BaseImageProcessor
23
+ from transformers.image_utils import load_image
24
+ from transformers.models.siglip2.image_processing_siglip2_fast import Siglip2ImageProcessorFast
25
+ from transformers.generation.logits_process import LogitsProcessor, LogitsProcessorList
26
+
27
+ from .tokenization_hunyuan_image_3 import ImageInfo, ImageTensor, CondImage, Resolution, ResolutionGroup
28
+
29
+ InputImage = Union[Image.Image, str]
30
+
31
+
32
+ class SliceVocabLogitsProcessor(LogitsProcessor):
33
+ """
34
+ [`LogitsProcessor`] that performs vocab slicing, i.e. restricting probabilities with in some range. This processor
35
+ is often used in multimodal discrete LLMs, which ensure that we only sample within one modality
36
+
37
+ Args:
38
+ vocab_start (`int`): start of slice, default None meaning from 0
39
+ vocab_end (`int`): end of slice, default None meaning to the end of list
40
+ when start and end are all None, this processor does noting
41
+
42
+ """
43
+
44
+ def __init__(self, vocab_start: int = None, vocab_end: int = None, **kwargs):
45
+ if vocab_start is not None and vocab_end is not None:
46
+ assert vocab_start < vocab_end, f"Ensure vocab_start {vocab_start} < vocab_end {vocab_end}"
47
+ self.vocab_start = vocab_start
48
+ self.vocab_end = vocab_end
49
+ self.other_slices = kwargs.get("other_slices", [])
50
+
51
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
52
+ scores_processed = scores[:, self.vocab_start: self.vocab_end]
53
+ for other_slice in self.other_slices:
54
+ scores_processed = torch.cat([scores_processed, scores[:, other_slice[0]: other_slice[1]]], dim=-1)
55
+ return scores_processed
56
+
57
+ def __repr__(self):
58
+ return f"SliceVocabLogitsWarper(vocab_start={self.vocab_start}, vocab_end={self.vocab_end}, other_slices={self.other_slices})"
59
+
60
+
61
+ def resize_and_crop(image: Image.Image, target_size: Tuple[int, int], resample=Image.Resampling.LANCZOS, crop_type='center', crop_coords=None) -> Image.Image:
62
+ tw, th = target_size
63
+ w, h = image.size
64
+
65
+ tr = th / tw
66
+ r = h / w
67
+
68
+ if crop_type == "resize":
69
+ resize_width = tw
70
+ resize_height = th
71
+ crop_top = 0
72
+ crop_left = 0
73
+ image = image.resize((resize_width, resize_height), resample=resample)
74
+ else:
75
+ # maintain the aspect ratio
76
+ if r < tr:
77
+ resize_height = th
78
+ resize_width = int(round(th / h * w))
79
+ else:
80
+ resize_width = tw
81
+ resize_height = int(round(tw / w * h))
82
+
83
+ if crop_type == 'center':
84
+ crop_top = int(round((resize_height - th) / 2.0))
85
+ crop_left = int(round((resize_width - tw) / 2.0))
86
+ elif crop_type == 'random':
87
+ crop_top = random.randint(0, resize_height - th)
88
+ crop_left = random.randint(0, resize_width - tw)
89
+ elif crop_type == 'fixed':
90
+ assert crop_coords is not None, 'crop_coords should be provided when crop_type is fixed.'
91
+ crop_left, crop_top = crop_coords
92
+ else:
93
+ raise ValueError(f'crop_type must be center, random or fixed, but got {crop_type}')
94
+
95
+ image = image.resize((resize_width, resize_height), resample=resample)
96
+ image = image.crop((crop_left, crop_top, crop_left + tw, crop_top + th))
97
+
98
+ return image
99
+
100
+
101
+ @dataclass
102
+ class ResolutionGroupConfig:
103
+ base_size: int = None
104
+ step: Optional[int] = None
105
+ align: int = 16
106
+
107
+ def to_dict(self):
108
+ return asdict(self)
109
+
110
+
111
+ @dataclass
112
+ class VAEInfo:
113
+ encoder_type: str
114
+ down_h_factor: int = -1
115
+ down_w_factor: int = -1
116
+ patch_size: int = 1
117
+ h_factor: int = -1
118
+ w_factor: int = -1
119
+ image_type: str = None
120
+
121
+ def __post_init__(self):
122
+ self.h_factor = self.down_h_factor * self.patch_size
123
+ self.w_factor = self.down_w_factor * self.patch_size
124
+ if self.image_type is None:
125
+ self.image_type = "vae"
126
+
127
+
128
+ @dataclass
129
+ class ViTInfo:
130
+ encoder_type: str
131
+ h_factor: int = -1
132
+ w_factor: int = -1
133
+ max_token_length: int = 0 # pad to max_token_length
134
+ processor: Callable = field(default_factory=BaseImageProcessor)
135
+ image_type: str = None
136
+
137
+ def __post_init__(self):
138
+ if self.image_type is None:
139
+ self.image_type = self.encoder_type.split("-")[0]
140
+
141
+
142
+ class HunyuanImage3ImageProcessor(object):
143
+ def __init__(self, config):
144
+ self.config = config
145
+
146
+ self.reso_group_config = ResolutionGroupConfig(base_size=config.image_base_size)
147
+ self.vae_reso_group = ResolutionGroup(
148
+ **self.reso_group_config.to_dict(),
149
+ extra_resolutions=[
150
+ Resolution("1024x768"),
151
+ Resolution("1280x720"),
152
+ Resolution("768x1024"),
153
+ Resolution("720x1280"),
154
+ ]
155
+ )
156
+ self.img_ratio_slice_logits_processor = None
157
+ self.pil_image_to_tensor = transforms.Compose([
158
+ transforms.ToTensor(),
159
+ transforms.Normalize([0.5], [0.5]), # transform to [-1, 1]
160
+ ])
161
+ self.vae_info = VAEInfo(
162
+ encoder_type=config.vae_type,
163
+ down_h_factor=config.vae_downsample_factor[0], down_w_factor=config.vae_downsample_factor[0],
164
+ patch_size=config.patch_size,
165
+ )
166
+
167
+ if config.vit_type == "siglip2-so400m-patch16-naflex":
168
+ self.vit_processor = Siglip2ImageProcessorFast.from_dict(config.vit_processor)
169
+ else:
170
+ raise ValueError(f"Unsupported vit_type: {config.vit_type}")
171
+ self.vit_info = ViTInfo(
172
+ encoder_type=config.vit_type,
173
+ h_factor=self.vit_processor.patch_size,
174
+ w_factor=self.vit_processor.patch_size,
175
+ max_token_length=self.vit_processor.max_num_patches,
176
+ processor=self.vit_processor,
177
+ )
178
+ self.cond_token_attn_type = config.cond_token_attn_type
179
+ self.cond_image_type = config.cond_image_type
180
+
181
+ def build_gen_image_info(self, image_size, add_guidance_token=False, add_timestep_r_token=False) -> ImageInfo:
182
+ # parse image size (HxW, H:W, or <img_ratio_i>)
183
+ if isinstance(image_size, str):
184
+ if image_size.startswith("<img_ratio_"):
185
+ ratio_index = int(image_size.split("_")[-1].rstrip(">"))
186
+ reso = self.vae_reso_group[ratio_index]
187
+ image_size = reso.height, reso.width
188
+ elif 'x' in image_size:
189
+ image_size = [int(s) for s in image_size.split('x')]
190
+ elif ':' in image_size:
191
+ image_size = [int(s) for s in image_size.split(':')]
192
+ assert len(image_size) == 2, f"`image_size` should be in the format of 'W:H', got {image_size}."
193
+ # Note that ratio is width:height
194
+ image_size = [image_size[1], image_size[0]]
195
+ else:
196
+ raise ValueError(
197
+ f"`image_size` should be in the format of 'HxW', 'W:H' or <img_ratio_i>, got {image_size}.")
198
+ assert len(image_size) == 2, f"`image_size` should be in the format of 'HxW', got {image_size}."
199
+ elif isinstance(image_size, (list, tuple)):
200
+ assert len(image_size) == 2 and all(isinstance(s, int) for s in image_size), \
201
+ f"`image_size` should be a tuple of two integers or a string in the format of 'HxW', got {image_size}."
202
+ else:
203
+ raise ValueError(f"`image_size` should be a tuple of two integers or a string in the format of 'WxH', "
204
+ f"got {image_size}.")
205
+ image_width, image_height = self.vae_reso_group.get_target_size(image_size[1], image_size[0])
206
+ token_height = image_height // self.vae_info.h_factor
207
+ token_width = image_width // self.vae_info.w_factor
208
+ base_size, ratio_idx = self.vae_reso_group.get_base_size_and_ratio_index(image_size[1], image_size[0])
209
+ image_info = ImageInfo(
210
+ image_type="gen_image", image_width=image_width, image_height=image_height,
211
+ token_width=token_width, token_height=token_height, base_size=base_size, ratio_index=ratio_idx,
212
+ add_guidance_token=add_guidance_token, add_timestep_r_token=add_timestep_r_token,
213
+ )
214
+ return image_info
215
+
216
+ def as_image_tensor(self, image, image_type, **kwargs) -> ImageTensor:
217
+ if isinstance(image, Image.Image):
218
+ tensor = self.pil_image_to_tensor(image)
219
+ else:
220
+ tensor = image
221
+
222
+ origin_size = kwargs["origin_size"]
223
+ ori_image_width = origin_size[0]
224
+ ori_image_height = origin_size[1]
225
+
226
+ if image_type == "vae":
227
+ assert tensor.ndim == 3 or tensor.ndim == 4
228
+ h, w = tensor.shape[-2], tensor.shape[-1]
229
+ assert (h % self.vae_info.h_factor == 0 and w % self.vae_info.w_factor == 0), \
230
+ (f"Image size should be divisible by ({self.vae_info.h_factor}, {self.vae_info.w_factor}), "
231
+ f"but got ({h} x {w}).")
232
+ tk_height = h // self.vae_info.h_factor
233
+ tk_width = w // self.vae_info.w_factor
234
+ base_size, ratio_idx = self.vae_reso_group.get_base_size_and_ratio_index(w, h)
235
+ tensor.i = ImageInfo(
236
+ image_type=image_type,
237
+ image_width=w, image_height=h, token_width=tk_width, token_height=tk_height,
238
+ base_size=base_size, ratio_index=ratio_idx,
239
+ ori_image_width=ori_image_width,
240
+ ori_image_height=ori_image_height,
241
+ )
242
+ tensor.section_type = "cond_vae_image"
243
+ elif image_type == "siglip2":
244
+ spatial_shapes = kwargs["spatial_shapes"] # 2 (h, w)
245
+ pixel_attention_mask = kwargs["pixel_attention_mask"] # seq_len
246
+ tensor.i = ImageInfo(
247
+ image_type=image_type,
248
+ image_width=spatial_shapes[1].item() * self.vit_info.w_factor,
249
+ image_height=spatial_shapes[0].item() * self.vit_info.h_factor,
250
+ token_width=spatial_shapes[1].item(),
251
+ token_height=spatial_shapes[0].item(),
252
+ image_token_length=self.vit_info.max_token_length,
253
+ ori_image_width=ori_image_width,
254
+ ori_image_height=ori_image_height,
255
+ )
256
+ tensor.section_type = "cond_vit_image"
257
+ tensor.vision_encoder_kwargs = {
258
+ "spatial_shapes": spatial_shapes,
259
+ "pixel_attention_mask": pixel_attention_mask,
260
+ }
261
+ elif image_type == "anyres":
262
+ token_width = kwargs["resized_image_width"] // self.vit_info.w_factor
263
+ token_height = kwargs["resized_image_height"] // self.vit_info.h_factor
264
+ tensor.i = ImageInfo(
265
+ image_type=image_type,
266
+ image_width=kwargs["resized_image_width"],
267
+ image_height=kwargs["resized_image_height"],
268
+ token_width=token_width,
269
+ token_height=token_height,
270
+ image_token_length=token_height * (token_width + 1) + 2,
271
+ )
272
+ tensor.section_type = "cond_vit_image"
273
+ else:
274
+ raise ValueError(f"Unknown image type: {image_type}")
275
+ return tensor
276
+
277
+ def vae_process_image(self, image, target_size, random_crop: bool | str = False) -> ImageTensor:
278
+ origin_size = image.size
279
+ crop_type = random_crop if isinstance(random_crop, str) else ("random" if random_crop else "center")
280
+ resized_image = resize_and_crop(image, target_size, crop_type=crop_type)
281
+ return self.as_image_tensor(resized_image, image_type=self.vae_info.image_type, origin_size=origin_size)
282
+
283
+ def vit_process_image(self, image) -> ImageTensor:
284
+ origin_size = image.size
285
+ inputs = self.vit_info.processor(image)
286
+ image = inputs["pixel_values"].squeeze(0) # (seq_len, dim)
287
+
288
+ remain_keys = set(inputs.keys()) - {"pixel_values"}
289
+ remain_kwargs = {}
290
+ for key in remain_keys:
291
+ if isinstance(inputs[key], torch.Tensor):
292
+ remain_kwargs[key] = inputs[key].squeeze(0)
293
+ else:
294
+ remain_kwargs[key] = inputs[key]
295
+
296
+ return self.as_image_tensor(image, image_type=self.vit_info.image_type, origin_size=origin_size, **remain_kwargs)
297
+
298
+ def get_image_with_size(
299
+ self,
300
+ src: InputImage,
301
+ random_crop: bool | str = False,
302
+ return_type: str = "vae",
303
+ ) -> tuple[ImageTensor | CondImage, bool]:
304
+ """ For various image generation tasks, dynamic image sizes """
305
+ image = load_image(src)
306
+ image_flag = "normal"
307
+ img_success = image_flag != "gray"
308
+ origin_size = image.size # (w_ori, h_ori)
309
+
310
+ if "vae" in return_type:
311
+ target_size = self.vae_reso_group.get_target_size(*origin_size)
312
+ vae_image_tensor = self.vae_process_image(image, target_size, random_crop=random_crop)
313
+ else:
314
+ vae_image_tensor = None
315
+
316
+ if "vit" in return_type:
317
+ vit_image_tensor = self.vit_process_image(image)
318
+ else:
319
+ vit_image_tensor = None
320
+
321
+ if return_type == "vae":
322
+ image_tensor = vae_image_tensor
323
+ elif return_type == "vit":
324
+ image_tensor = vit_image_tensor
325
+ elif return_type == "vae_vit":
326
+ image_tensor = CondImage(image_type=return_type, vae_image=vae_image_tensor, vit_image=vit_image_tensor)
327
+ else:
328
+ raise ValueError(f"Unknown return_type: {return_type}")
329
+
330
+ return image_tensor, img_success
331
+
332
+ def build_cond_images(
333
+ self,
334
+ image_list: Optional[list[InputImage]] = None,
335
+ message_list: Optional[list[dict[str, Any]]] = None,
336
+ infer_align_image_size: bool = False,
337
+ ) -> Optional[list[CondImage]]:
338
+ if image_list is not None and message_list is not None:
339
+ raise ValueError("`image_list` and `message_list` cannot be provided at the same time.")
340
+ if message_list is not None:
341
+ image_list = []
342
+ for message in message_list:
343
+ visuals = [
344
+ content
345
+ for content in message["content"]
346
+ if isinstance(content, dict) and content["type"] in ["image"]
347
+ ]
348
+ image_list.extend([
349
+ vision_info[key]
350
+ for vision_info in visuals
351
+ for key in ["image", "url", "path", "base64"]
352
+ if key in vision_info and vision_info["type"] == "image"
353
+ ])
354
+
355
+ if infer_align_image_size:
356
+ random_crop = "resize"
357
+ else:
358
+ random_crop = "center"
359
+
360
+ return [
361
+ self.get_image_with_size(src, return_type=self.cond_image_type, random_crop=random_crop)[0]
362
+ for src in image_list
363
+ ]
364
+
365
+ def prepare_full_attn_slices(self, output, batch_idx=None, with_gen=True):
366
+ """ Determine full attention image slices according to strategies. """
367
+ if self.cond_image_type == "vae":
368
+ cond_choices = dict(
369
+ causal=[],
370
+ full=output.vae_image_slices[batch_idx] if batch_idx is not None else output.vae_image_slices
371
+ )
372
+
373
+ elif self.cond_image_type == "vit":
374
+ cond_choices = dict(
375
+ causal=[],
376
+ full=output.vit_image_slices[batch_idx] if batch_idx is not None else output.vit_image_slices
377
+ )
378
+
379
+ elif self.cond_image_type == "vae_vit":
380
+ cond_choices = {
381
+ "causal": [],
382
+ "full": (
383
+ output.vae_image_slices[batch_idx] + output.vit_image_slices[batch_idx]
384
+ if batch_idx is not None
385
+ else output.vae_image_slices + output.vit_image_slices
386
+ ),
387
+ "joint_full": (
388
+ output.joint_image_slices[batch_idx]
389
+ if batch_idx is not None
390
+ else output.joint_image_slices
391
+ ),
392
+ "full_causal": (
393
+ output.vae_image_slices[batch_idx]
394
+ if batch_idx is not None
395
+ else output.vae_image_slices
396
+ ),
397
+ }
398
+
399
+ else:
400
+ raise ValueError(f"Unknown cond_image_type: {self.cond_image_type}")
401
+ slices = cond_choices[self.cond_token_attn_type]
402
+
403
+ if with_gen:
404
+ gen_image_slices = (
405
+ output.gen_image_slices[batch_idx]
406
+ if batch_idx is not None
407
+ else output.gen_image_slices
408
+ )
409
+ slices = slices + gen_image_slices
410
+ return slices
411
+
412
+ def build_img_ratio_slice_logits_processor(self, tokenizer):
413
+ if self.img_ratio_slice_logits_processor is None:
414
+ self.img_ratio_slice_logits_processor = LogitsProcessorList()
415
+ self.img_ratio_slice_logits_processor.append(
416
+ SliceVocabLogitsProcessor(
417
+ vocab_start=tokenizer.start_ratio_token_id,
418
+ vocab_end=tokenizer.end_ratio_token_id + 1,
419
+ other_slices=getattr(tokenizer, "ratio_token_other_slices", []),
420
+ )
421
+ )
422
+
423
+ def postprocess_outputs(self, outputs: list[Image.Image], batch_cond_images, infer_align_image_size: bool = False):
424
+ if infer_align_image_size:
425
+ target_area = self.vae_reso_group.base_size ** 2
426
+
427
+ for batch_index, (output_image, cond_images) in enumerate(zip(outputs, batch_cond_images)):
428
+ output_image_ratio_index = self.vae_reso_group.get_base_size_and_ratio_index(width=output_image.width, height=output_image.height)[1]
429
+ cond_images_ratio_index_list = []
430
+ cond_images_ori_width_list = []
431
+ cond_images_ori_height_list = []
432
+ for cond_image in cond_images:
433
+ if isinstance(cond_image, ImageTensor):
434
+ cond_images_ratio_index_list.append(cond_image.i.ratio_index)
435
+ cond_images_ori_width_list.append(cond_image.i.ori_image_width)
436
+ cond_images_ori_height_list.append(cond_image.i.ori_image_height)
437
+ else: # CondImage
438
+ cond_images_ratio_index_list.append(cond_image.vae_image.i.ratio_index)
439
+ cond_images_ori_width_list.append(cond_image.vae_image.i.ori_image_width)
440
+ cond_images_ori_height_list.append(cond_image.vae_image.i.ori_image_height)
441
+
442
+ if len(cond_images) == 0:
443
+ continue
444
+ elif len(cond_images) == 1:
445
+ if output_image_ratio_index == cond_images_ratio_index_list[0]:
446
+ if abs(cond_images_ori_height_list[0] / cond_images_ori_width_list[0] - self.vae_reso_group[output_image_ratio_index].ratio) >= 0.01:
447
+ scale = math.sqrt(target_area / (cond_images_ori_width_list[0] * cond_images_ori_height_list[0]))
448
+ new_w = round(cond_images_ori_width_list[0] * scale)
449
+ new_h = round(cond_images_ori_height_list[0] * scale)
450
+ outputs[batch_index] = output_image.resize((new_w, new_h), resample=Image.Resampling.LANCZOS)
451
+ else:
452
+ for cond_image_ratio_index, cond_image_ori_width, cond_image_ori_height in zip(cond_images_ratio_index_list, cond_images_ori_width_list, cond_images_ori_height_list):
453
+ if output_image_ratio_index == cond_image_ratio_index:
454
+ if abs(cond_image_ori_height / cond_image_ori_width - self.vae_reso_group[output_image_ratio_index].ratio) >= 0.01:
455
+ scale = math.sqrt(target_area / (cond_image_ori_width * cond_image_ori_height))
456
+ new_w = round(cond_image_ori_width * scale)
457
+ new_h = round(cond_image_ori_height * scale)
458
+ outputs[batch_index] = output_image.resize((new_w, new_h), resample=Image.Resampling.LANCZOS)
459
+ break
460
+
461
+ return outputs
462
+
463
+ __all__ = [
464
+ "HunyuanImage3ImageProcessor"
465
+ ]
images/ar_dit_full_tp1x1.png ADDED

Git LFS Details

  • SHA256: b9fa2b0b197b6fb44b7409b527fa7b1b28633d250427bc25fa6c216c77c4d8cc
  • Pointer size: 132 Bytes
  • Size of remote file: 1.02 MB
images/bf16_dit_only_reference.png ADDED

Git LFS Details

  • SHA256: bbcaf91b66bca4ac19b074d19100eb9cb96cd3a8ee4d59ba42355f947313f448
  • Pointer size: 132 Bytes
  • Size of remote file: 1.08 MB
images/dit_only_tp2.png ADDED

Git LFS Details

  • SHA256: 60ad9a86890e3751b1f087ea88823bcd9fb19d18d876841e47d3fce95dba9ec3
  • Pointer size: 132 Bytes
  • Size of remote file: 1.16 MB
images/sibling_llm_compressor_ar_dit.png ADDED

Git LFS Details

  • SHA256: 53831594f324f530b65b5303513f981e0709da53169d1e4c5324488aa1b78032
  • Pointer size: 132 Bytes
  • Size of remote file: 1.09 MB
images/sibling_llm_compressor_dit_only.png ADDED

Git LFS Details

  • SHA256: 5186a824e8a64a5645a6429320dd84155e415fb3079fefb469b36bf7e8e7cd5f
  • Pointer size: 132 Bytes
  • Size of remote file: 1.15 MB
model-00001-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:91dff91f97cb53f95a8ab15cece0a568bd88a703ac64bb1c36b4aba8e1acad2b
3
+ size 2335990216