Image-to-Image
PEFT
Safetensors
CiaraRowles commited on
Commit
43bff6c
·
verified ·
1 Parent(s): 77b694d

Upload 4 files

Browse files
README.md CHANGED
@@ -1,5 +1,111 @@
 
 
 
 
 
1
  ---
2
- license: other
3
- license_name: stability-ai-community-license
4
- license_link: LICENSE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Layer Decomposition — Inference
2
+
3
+ Decomposes an image into ordered layers (background + separated objects) using
4
+ **Qwen-Image-Layered** with a GRPO-trained LoRA.
5
+
6
  ---
7
+
8
+ ## ⚠️ Recommended inference settings — USE THESE
9
+
10
+ > ### **Heun sampler · 50 steps · CFG 1.0 · 640 px · 4 layers**
11
+
12
+ These are the settings every published result was produced with, and they are
13
+ the **defaults** in `decompose.py`. If you override them the script prints a
14
+ warning — lowering the step count or raising CFG visibly degrades the
15
+ decomposition (blurrier background inpainting, mushier layer boundaries).
16
+
17
+ | Setting | Value | Flag |
18
+ |---|---|---|
19
+ | **Sampler** | **Heun (2nd order)** | always used — not configurable |
20
+ | **Steps** | **50** | `--steps 50` |
21
+ | **CFG / guidance** | **1.0 (off)** | `--guidance-scale 1.0` |
22
+ | Resolution | 640 px (max dim) | `--size 640` |
23
+ | Layers | 4 | `--num-layers 4` |
24
+
25
+ **Note:** 50 Heun steps ≈ **100 model evaluations** — Heun is second order, so
26
+ each step runs two forward passes. That is by design; don't "optimise" it by
27
+ halving the steps.
28
+
29
  ---
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ pip install torch diffusers transformers peft pillow numpy
35
+ ```
36
+
37
+ Tested with `torch 2.11`, `diffusers 0.37`, `transformers 5.5`, `peft 0.18`.
38
+ Requires **one GPU** — the base model is ~40 GB in bf16, so an 80 GB-class card
39
+ (A100-80 / H100 / H200) is comfortable.
40
+
41
+ ---
42
+
43
+ ## Weights
44
+
45
+ The base model is pulled from HuggingFace automatically
46
+ (`Qwen/Qwen-Image-Layered`). You supply the LoRA adapter:
47
+
48
+ ```
49
+ checkpoint-600/
50
+ adapter_config.json
51
+ adapter_model.safetensors # ~316 MB
52
+ ```
53
+
54
+ By default `decompose.py` looks for `checkpoint-600/` next to the script; point
55
+ elsewhere with `--lora /path/to/adapter`.
56
+
57
+ > **The LoRA is ~316 MB, which exceeds GitHub's 100 MB per-file limit.** Don't
58
+ > commit it directly — use Git LFS, or host it (e.g. on the HuggingFace Hub) and
59
+ > download it alongside this script.
60
+
61
+ ---
62
+
63
+ ## Usage
64
+
65
+ ```bash
66
+ # single image
67
+ python decompose.py --input photo.png --output results/
68
+
69
+ # a directory of images
70
+ python decompose.py --input images/ --output results/
71
+
72
+ # RGBA layers with real alpha (for compositing / editors)
73
+ python decompose.py --input images/ --output results/ --transparent
74
+
75
+ # explicit LoRA location
76
+ python decompose.py --input photo.png --output results/ --lora ./checkpoint-600
77
+ ```
78
+
79
+ ---
80
+
81
+ ## Output
82
+
83
+ ```
84
+ results/<image_name>/
85
+ source.png # input, resized
86
+ composite.png # layers recomposited — compare against source as a sanity check
87
+ layer_0.png # background (inpainted behind the removed objects)
88
+ layer_1.png # object layers, back-to-front
89
+ layer_2.png
90
+ layer_3.png
91
+ ```
92
+
93
+ Layers are ordered back-to-front: `layer_0` is the background, higher indices sit
94
+ on top. Not every image needs all 4 — unused layers come out blank, which is
95
+ normal.
96
+
97
+ By default layers are composited onto **white** (easy to eyeball). Pass
98
+ `--transparent` to get **RGBA with real alpha**, which is what you want when
99
+ importing into an editor or compositing them yourself.
100
+
101
+ ---
102
+
103
+ ## Notes
104
+
105
+ - **Reproducible:** noise is seeded per image as `seed + image_index`
106
+ (`--seed 42` by default), so the same inputs give the same outputs.
107
+ - **Prompt:** decomposition is driven by the source image; the text prompt only
108
+ nudges guidance. The default (`"a clean, well composed image"`) is fine —
109
+ override with `--prompt` if you want.
110
+ - **Aspect ratio** is preserved; the longest side is scaled to `--size` and both
111
+ dimensions are rounded to multiples of 16.
decompose.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Layer decomposition inference — Qwen-Image-Layered + GRPO LoRA.
4
+
5
+ Decomposes a source image into ordered RGBA layers (background + objects).
6
+
7
+ ============================================================================
8
+ RECOMMENDED INFERENCE SETTINGS *** USE THESE ***
9
+ ============================================================================
10
+ Sampler : Heun (2nd order) <- the only sampler here; always used
11
+ Steps : 50 <- --steps 50 (default)
12
+ CFG : 1.0 (disabled) <- --guidance-scale 1.0 (default)
13
+ Size : 640 px <- --size 640 (default)
14
+ Layers : 4 <- --num-layers 4 (default)
15
+
16
+ All published results were produced with exactly these settings, and they are
17
+ the defaults below. Lowering the step count or raising CFG noticeably degrades
18
+ the decomposition. Note 50 Heun steps == ~100 model evaluations (Heun is
19
+ 2nd order: two forward passes per step) — that is expected, not a bug.
20
+ ============================================================================
21
+
22
+ Usage:
23
+ python decompose.py --input photo.png --output out/
24
+ python decompose.py --input images/ --output out/ --transparent
25
+
26
+ Output per image:
27
+ out/<name>/source.png resized input
28
+ out/<name>/composite.png layers recomposited (sanity check vs source)
29
+ out/<name>/layer_0.png background (inpainted behind the objects)
30
+ out/<name>/layer_1..N.png object layers, back-to-front
31
+ """
32
+
33
+ import argparse
34
+ import os
35
+ from pathlib import Path
36
+
37
+ import numpy as np
38
+ import torch
39
+ from PIL import Image
40
+
41
+ IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tiff"}
42
+
43
+ # Qwen-Image prompt template (must match training/inference used for the LoRA)
44
+ PROMPT_TEMPLATE = (
45
+ "<|im_start|>system\nDescribe the image by detailing the color, shape, size, "
46
+ "texture, quantity, text, spatial relationships of the objects and background:"
47
+ "<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n"
48
+ )
49
+ PROMPT_TEMPLATE_DROP_IDX = 34
50
+ DEFAULT_PROMPT = "a clean, well composed image"
51
+ VAE_SCALE_FACTOR = 8
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # Latent helpers
56
+ # ---------------------------------------------------------------------------
57
+
58
+ def rgb_to_rgba(image):
59
+ b, _, h, w = image.shape
60
+ alpha = torch.ones(b, 1, h, w, device=image.device, dtype=image.dtype)
61
+ return torch.cat([image, alpha], dim=1)
62
+
63
+
64
+ def normalize_latents(latents, vae):
65
+ mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
66
+ std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
67
+ return (latents - mean) / std
68
+
69
+
70
+ def denormalize_latents(latents, vae):
71
+ mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
72
+ inv_std = (1.0 / torch.tensor(vae.config.latents_std)).view(1, -1, 1, 1, 1).to(latents.device, latents.dtype)
73
+ return latents / inv_std + mean
74
+
75
+
76
+ def pack_latents(latents, batch_size, num_channels, height, width, num_frames):
77
+ latents = latents.view(batch_size, num_frames, num_channels, height // 2, 2, width // 2, 2)
78
+ latents = latents.permute(0, 1, 3, 5, 2, 4, 6)
79
+ return latents.reshape(batch_size, num_frames * (height // 2) * (width // 2), num_channels * 4)
80
+
81
+
82
+ def unpack_latents(latents, height, width, num_layers, vae_scale_factor=VAE_SCALE_FACTOR):
83
+ batch_size, _, channels = latents.shape
84
+ frames = num_layers + 1
85
+ h = 2 * (int(height) // (vae_scale_factor * 2))
86
+ w = 2 * (int(width) // (vae_scale_factor * 2))
87
+ latents = latents.view(batch_size, frames, h // 2, w // 2, channels // 4, 2, 2)
88
+ latents = latents.permute(0, 1, 4, 2, 5, 3, 6)
89
+ latents = latents.reshape(batch_size, frames, channels // 4, h, w)
90
+ return latents.permute(0, 2, 1, 3, 4)
91
+
92
+
93
+ @torch.no_grad()
94
+ def encode_condition_image(vae, image):
95
+ """RGB image tensor in [-1,1], (B,3,H,W) -> packed condition latents."""
96
+ b = image.shape[0]
97
+ vae_input_ch = getattr(vae.config, "input_channels", 3)
98
+ if vae_input_ch == 4 and image.shape[1] == 3:
99
+ image = rgb_to_rgba(image)
100
+ elif vae_input_ch == 3 and image.shape[1] == 4:
101
+ image = image[:, :3]
102
+
103
+ image_5d = image.unsqueeze(2).to(dtype=vae.dtype)
104
+ dist = vae.encode(image_5d)
105
+ if hasattr(dist, "latent_dist"):
106
+ latents = dist.latent_dist.mode()
107
+ elif hasattr(dist, "mode"):
108
+ latents = dist.mode()
109
+ else:
110
+ latents = dist
111
+
112
+ latents = normalize_latents(latents, vae)
113
+ z_dim, lh, lw = latents.shape[1], latents.shape[3], latents.shape[4]
114
+ latents = latents.permute(0, 2, 1, 3, 4)
115
+ return pack_latents(latents, b, z_dim, lh, lw, 1).to(dtype=torch.bfloat16)
116
+
117
+
118
+ @torch.no_grad()
119
+ def decode_layers(vae, latents, height, width, num_layers):
120
+ b = latents.shape[0]
121
+ unpacked = unpack_latents(latents, height, width, num_layers)
122
+ unpacked = denormalize_latents(unpacked, vae)
123
+ layer_latents = unpacked[:, :, 1:].permute(0, 2, 1, 3, 4) # drop base frame
124
+ _, _, c, h, w = layer_latents.shape
125
+ decoded = vae.decode(layer_latents.reshape(b * num_layers, c, 1, h, w).to(dtype=vae.dtype),
126
+ return_dict=False)[0]
127
+ decoded = decoded.squeeze(2).float().clamp(-1.0, 1.0)
128
+ _, c_out, h_out, w_out = decoded.shape
129
+ return decoded.reshape(b, num_layers, c_out, h_out, w_out)
130
+
131
+
132
+ def composite_layers(layers):
133
+ """Porter-Duff 'over', back-to-front."""
134
+ if layers.shape[2] == 3:
135
+ return layers.mean(dim=1)
136
+ result = torch.zeros_like(layers[:, 0, :3])
137
+ for i in range(layers.shape[1]):
138
+ rgb = layers[:, i, :3]
139
+ alpha = (layers[:, i, 3:4] + 1.0) / 2.0
140
+ result = rgb * alpha + result * (1.0 - alpha)
141
+ return result
142
+
143
+
144
+ def tensor_to_pil(t, mode="RGB"):
145
+ arr = ((t.clamp(-1, 1) + 1) / 2 * 255).byte().permute(1, 2, 0).cpu().numpy()
146
+ return Image.fromarray(arr, mode=mode)
147
+
148
+
149
+ def layer_to_pil_white_bg(layer):
150
+ if layer.shape[0] == 4:
151
+ rgb, alpha = layer[:3], (layer[3:4] + 1.0) / 2.0
152
+ return tensor_to_pil(rgb * alpha + torch.ones_like(rgb) * (1.0 - alpha))
153
+ return tensor_to_pil(layer)
154
+
155
+
156
+ def layer_to_pil_rgba(layer):
157
+ layer = layer.clamp(-1, 1).float()
158
+ rgba = torch.cat([(layer[:3] + 1) / 2, (layer[3:4] + 1) / 2], dim=0)
159
+ arr = (rgba * 255).byte().permute(1, 2, 0).cpu().numpy()
160
+ return Image.fromarray(arr, mode="RGBA")
161
+
162
+
163
+ # ---------------------------------------------------------------------------
164
+ # Denoising — Heun (2nd order)
165
+ # ---------------------------------------------------------------------------
166
+
167
+ def transformer_forward(transformer, hidden_states, timestep, encoder_hidden_states,
168
+ img_shapes, encoder_hidden_states_mask=None, additional_t_cond=None):
169
+ return transformer(
170
+ hidden_states=hidden_states,
171
+ timestep=timestep / 1000,
172
+ encoder_hidden_states=encoder_hidden_states,
173
+ encoder_hidden_states_mask=encoder_hidden_states_mask,
174
+ img_shapes=img_shapes,
175
+ guidance=None,
176
+ additional_t_cond=additional_t_cond,
177
+ return_dict=False,
178
+ )[0]
179
+
180
+
181
+ def build_img_shapes(num_layers, packed_h, packed_w):
182
+ # (num_layers + 1) generated frames + 1 condition-image entry
183
+ return [[*[(1, packed_h, packed_w) for _ in range(num_layers + 1)], (1, packed_h, packed_w)]]
184
+
185
+
186
+ @torch.no_grad()
187
+ def denoise(transformer, scheduler, latents, timesteps, prompt_embeds, prompt_mask,
188
+ img_shapes, condition_latents, guidance_scale,
189
+ neg_embeds=None, neg_mask=None, additional_t_cond=None):
190
+ """Heun's method (2nd order) over the scheduler's sigmas."""
191
+ gen_seq_len = latents.shape[1]
192
+ do_cfg = guidance_scale > 1.0 and neg_embeds is not None
193
+
194
+ def velocity(lat, t_val):
195
+ ts = t_val.expand(1).to(lat.dtype)
196
+ model_input = lat if condition_latents is None else torch.cat([lat, condition_latents], dim=1)
197
+ v = transformer_forward(transformer, model_input, ts, prompt_embeds,
198
+ img_shapes, prompt_mask, additional_t_cond)[:, :gen_seq_len]
199
+ if do_cfg:
200
+ v_neg = transformer_forward(transformer, model_input, ts, neg_embeds,
201
+ img_shapes, neg_mask, additional_t_cond)[:, :gen_seq_len]
202
+ v = v_neg + guidance_scale * (v - v_neg)
203
+ return v
204
+
205
+ sigmas = scheduler.sigmas
206
+ for i, t in enumerate(timesteps):
207
+ sigma = sigmas[i]
208
+ sigma_next = sigmas[i + 1] if i + 1 < len(sigmas) else torch.tensor(0.0, device=t.device)
209
+ dt = sigma_next - sigma
210
+
211
+ v1 = velocity(latents, t)
212
+ latents_mid = latents + dt * v1
213
+ if sigma_next > 0: # Heun corrector
214
+ v2 = velocity(latents_mid, sigma_next * 1000)
215
+ latents = latents + dt * 0.5 * (v1 + v2)
216
+ else:
217
+ latents = latents_mid
218
+ return latents
219
+
220
+
221
+ # ---------------------------------------------------------------------------
222
+ # Pipeline
223
+ # ---------------------------------------------------------------------------
224
+
225
+ def compute_aspect_resize(orig_w, orig_h, max_size):
226
+ """Keep aspect ratio, max dim = max_size, both dims divisible by 16."""
227
+ scale = max_size / max(orig_w, orig_h)
228
+ return (max(int(round(orig_w * scale / 16)) * 16, 16),
229
+ max(int(round(orig_h * scale / 16)) * 16, 16))
230
+
231
+
232
+ def collect_images(input_path):
233
+ p = Path(input_path)
234
+ if p.is_file():
235
+ return [p]
236
+ if p.is_dir():
237
+ return sorted(f for f in p.iterdir() if f.suffix.lower() in IMAGE_EXTS)
238
+ raise FileNotFoundError(f"input not found: {input_path}")
239
+
240
+
241
+ def main():
242
+ ap = argparse.ArgumentParser(
243
+ description="Layer decomposition (Heun / 50 steps / cfg 1.0 recommended).",
244
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
245
+ )
246
+ ap.add_argument("--input", required=True, help="image file or directory of images")
247
+ ap.add_argument("--output", required=True, help="output directory")
248
+ ap.add_argument("--lora", default=str(Path(__file__).parent / "checkpoint-600"),
249
+ help="path to the LoRA adapter directory")
250
+ ap.add_argument("--base-model", default="Qwen/Qwen-Image-Layered",
251
+ help="base model (HuggingFace id or local path)")
252
+ # --- recommended settings (defaults) ---
253
+ ap.add_argument("--steps", type=int, default=50, help="Heun steps (RECOMMENDED: 50)")
254
+ ap.add_argument("--guidance-scale", type=float, default=1.0, help="CFG (RECOMMENDED: 1.0 = off)")
255
+ ap.add_argument("--num-layers", type=int, default=4)
256
+ ap.add_argument("--size", type=int, default=640, help="max image dimension")
257
+ # --- misc ---
258
+ ap.add_argument("--prompt", default=DEFAULT_PROMPT)
259
+ ap.add_argument("--seed", type=int, default=42)
260
+ ap.add_argument("--transparent", action="store_true",
261
+ help="save layers as RGBA with real alpha (for compositing) "
262
+ "instead of composited onto white")
263
+ ap.add_argument("--device", default="cuda")
264
+ ap.add_argument("--cache-dir", default=None, help="HuggingFace cache directory")
265
+ args = ap.parse_args()
266
+
267
+ if args.steps != 50 or args.guidance_scale != 1.0:
268
+ print(f"WARNING: using steps={args.steps}, cfg={args.guidance_scale}. "
269
+ f"Recommended is steps=50, cfg=1.0 — results may be worse.\n")
270
+
271
+ device = torch.device(args.device)
272
+ images = collect_images(args.input)
273
+ if not images:
274
+ raise SystemExit(f"no images found in {args.input}")
275
+ os.makedirs(args.output, exist_ok=True)
276
+ print(f"{len(images)} image(s) | Heun, {args.steps} steps, cfg {args.guidance_scale}, "
277
+ f"{args.size}px, {args.num_layers} layers")
278
+
279
+ # --- load base model -----------------------------------------------
280
+ print(f"Loading base model: {args.base_model}")
281
+ from diffusers import DiffusionPipeline
282
+
283
+ pipe = DiffusionPipeline.from_pretrained(
284
+ args.base_model, torch_dtype=torch.bfloat16,
285
+ trust_remote_code=True, cache_dir=args.cache_dir,
286
+ )
287
+ transformer = pipe.transformer.to(device).eval()
288
+ vae = pipe.vae.to(device).eval()
289
+ scheduler = pipe.scheduler
290
+ tokenizer = getattr(pipe, "tokenizer", None)
291
+ text_encoder = getattr(pipe, "text_encoder", None)
292
+ del pipe
293
+ transformer.requires_grad_(False)
294
+ vae.requires_grad_(False)
295
+
296
+ # --- apply LoRA ------------------------------------------------------
297
+ print(f"Loading LoRA: {args.lora}")
298
+ from peft import PeftModel
299
+ transformer = PeftModel.from_pretrained(transformer, args.lora)
300
+ transformer.eval()
301
+
302
+ in_channels = getattr(transformer.config, "in_channels", 64)
303
+ additional_t_cond = torch.zeros(1, dtype=torch.long, device=device)
304
+
305
+ # --- prompt encoding -------------------------------------------------
306
+ if text_encoder is None or tokenizer is None:
307
+ raise SystemExit("base model has no text encoder/tokenizer")
308
+ text_encoder = text_encoder.to(device).eval()
309
+ text_encoder.requires_grad_(False)
310
+
311
+ @torch.no_grad()
312
+ def encode_prompt(text):
313
+ tokens = tokenizer([PROMPT_TEMPLATE.format(text)], padding=True,
314
+ return_tensors="pt").to(text_encoder.device)
315
+ out = text_encoder(input_ids=tokens.input_ids,
316
+ attention_mask=tokens.attention_mask,
317
+ output_hidden_states=True)
318
+ hidden = out.hidden_states[-1]
319
+ mask_bool = tokens.attention_mask.bool()
320
+ lengths = mask_bool.sum(dim=1)
321
+ chunks = torch.split(hidden[mask_bool], lengths.tolist(), dim=0)
322
+ chunks = [c[PROMPT_TEMPLATE_DROP_IDX:] for c in chunks] # drop system prefix
323
+ max_len = max(c.size(0) for c in chunks)
324
+ embeds = torch.stack([torch.cat([c, c.new_zeros(max_len - c.size(0), c.size(1))]) for c in chunks])
325
+ mask = torch.stack([
326
+ torch.cat([torch.ones(c.size(0), dtype=torch.long, device=c.device),
327
+ torch.zeros(max_len - c.size(0), dtype=torch.long, device=c.device)])
328
+ for c in chunks
329
+ ])
330
+ return embeds.to(dtype=torch.bfloat16, device=device), mask.to(device)
331
+
332
+ prompt_embeds, prompt_mask = encode_prompt(args.prompt)
333
+ neg_embeds, neg_mask = encode_prompt("")
334
+
335
+ # scheduler may or may not accept sigmas/mu
336
+ import inspect
337
+ supports_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters)
338
+
339
+ # --- per-image loop --------------------------------------------------
340
+ for idx, img_path in enumerate(images):
341
+ name = img_path.stem
342
+ out_dir = Path(args.output) / name
343
+ out_dir.mkdir(parents=True, exist_ok=True)
344
+ print(f"[{idx + 1}/{len(images)}] {img_path.name}", flush=True)
345
+
346
+ image = Image.open(img_path).convert("RGB")
347
+ tw, th = compute_aspect_resize(*image.size, args.size)
348
+ source = image.resize((tw, th), Image.LANCZOS)
349
+
350
+ packed_h = (th // VAE_SCALE_FACTOR) // 2
351
+ packed_w = (tw // VAE_SCALE_FACTOR) // 2
352
+
353
+ img_t = torch.from_numpy(np.array(source)).permute(2, 0, 1).float() / 127.5 - 1.0
354
+ img_t = img_t.unsqueeze(0).to(device)
355
+ condition_latents = encode_condition_image(vae, img_t)
356
+
357
+ # dynamic-shift mu from the condition sequence length
358
+ mu = (condition_latents.shape[1] / (256 * 256 / 16 / 16)) ** 0.5
359
+ if supports_sigmas:
360
+ scheduler.set_timesteps(sigmas=np.linspace(1.0, 0, args.steps + 1)[:-1],
361
+ device=device, mu=mu)
362
+ else:
363
+ scheduler.set_timesteps(num_inference_steps=args.steps, device=device)
364
+
365
+ img_shapes = build_img_shapes(args.num_layers, packed_h, packed_w)
366
+ seq_len = (args.num_layers + 1) * packed_h * packed_w
367
+
368
+ gen = torch.Generator(device=device).manual_seed(args.seed + idx)
369
+ latents = torch.randn(1, seq_len, in_channels, device=device,
370
+ dtype=torch.bfloat16, generator=gen)
371
+
372
+ latents = denoise(transformer, scheduler, latents, scheduler.timesteps,
373
+ prompt_embeds, prompt_mask, img_shapes, condition_latents,
374
+ args.guidance_scale, neg_embeds, neg_mask, additional_t_cond)
375
+
376
+ decoded = decode_layers(vae, latents, th, tw, args.num_layers)
377
+ composite = composite_layers(decoded)
378
+
379
+ source.save(out_dir / "source.png")
380
+ tensor_to_pil(composite[0]).save(out_dir / "composite.png")
381
+ for li in range(args.num_layers):
382
+ layer = decoded[0, li]
383
+ pil = layer_to_pil_rgba(layer) if args.transparent else layer_to_pil_white_bg(layer)
384
+ pil.save(out_dir / f"layer_{li}.png")
385
+
386
+ print(f"\nDone -> {args.output}/<name>/{{source,composite,layer_0..{args.num_layers - 1}}}.png")
387
+
388
+
389
+ if __name__ == "__main__":
390
+ main()
model/adapter_config.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "alora_invocation_tokens": null,
3
+ "alpha_pattern": {},
4
+ "arrow_config": null,
5
+ "auto_mapping": {
6
+ "base_model_class": "QwenImageTransformer2DModel",
7
+ "parent_library": "diffusers.models.transformers.transformer_qwenimage"
8
+ },
9
+ "base_model_name_or_path": null,
10
+ "bias": "none",
11
+ "corda_config": null,
12
+ "ensure_weight_tying": false,
13
+ "eva_config": null,
14
+ "exclude_modules": null,
15
+ "fan_in_fan_out": false,
16
+ "inference_mode": true,
17
+ "init_lora_weights": true,
18
+ "layer_replication": null,
19
+ "layers_pattern": null,
20
+ "layers_to_transform": null,
21
+ "loftq_config": {},
22
+ "lora_alpha": 64,
23
+ "lora_bias": false,
24
+ "lora_dropout": 0.0,
25
+ "megatron_config": null,
26
+ "megatron_core": "megatron.core",
27
+ "modules_to_save": null,
28
+ "peft_type": "LORA",
29
+ "peft_version": "0.18.1",
30
+ "qalora_group_size": 16,
31
+ "r": 32,
32
+ "rank_pattern": {},
33
+ "revision": null,
34
+ "target_modules": [
35
+ "add_q_proj",
36
+ "add_v_proj",
37
+ "to_q",
38
+ "to_v",
39
+ "add_k_proj",
40
+ "to_k",
41
+ "to_add_out"
42
+ ],
43
+ "target_parameters": null,
44
+ "task_type": null,
45
+ "trainable_token_indices": null,
46
+ "use_dora": false,
47
+ "use_qalora": false,
48
+ "use_rslora": false
49
+ }
model/adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9264c5447d55317a1a3deca6b739990344dc68fa7d0c99792c669c26a5d5050e
3
+ size 330417896