Elea Zhong commited on
Commit
26db3f0
·
1 Parent(s): d786862

add training (lora, foundation, data)

Browse files
qwenimage/datamodels.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+
4
+ from diffusers.image_processor import PipelineImageInput
5
+ from pydantic import BaseModel, ConfigDict, Field
6
+ import torch
7
+
8
+ from wandml.foundation.datamodels import FluxInputs
9
+ from wandml.trainers.datamodels import ExperimentTrainerParameters
10
+
11
+
12
+ class QwenInputs(BaseModel):
13
+ image: PipelineImageInput | None = None
14
+ prompt: str| list[str] | None = None
15
+ height: int|None = None
16
+ width: int|None = None
17
+ negative_prompt: str| list[str] | None = None
18
+ true_cfg_scale: float = 1.0
19
+ num_inference_steps: int = 50
20
+ generator: torch.Generator | list[torch.Generator] | None = None
21
+ max_sequence_length: int = 512
22
+ vae_image_override: int | None = 512 * 512
23
+
24
+ model_config = ConfigDict(
25
+ arbitrary_types_allowed=True,
26
+ # extra="allow",
27
+ )
28
+
29
+
30
+ class QwenConfig(ExperimentTrainerParameters):
31
+ load_multi_view_lora: bool = False
32
+ train_max_sequence_length: int = 512
33
+ train_dist: str = "linear" # "logit-normal"
34
+ train_shift: bool = True
35
+ inference_dist: str = "linear"
36
+ inference_shift: bool = True
37
+ static_mu: float | None = None
38
+ loss_weight_dist: str | None = None # "scaled_clipped_gaussian", "logit-normal"
39
+
40
+ vae_image_size: int = 1024 * 1024
qwenimage/datasets.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ from pathlib import Path
4
+ import random
5
+
6
+ from PIL import Image
7
+ from wandml.core.datamodels import SourceDataType
8
+ from wandml.core.source import Source
9
+
10
+ class StyleSource(Source):
11
+ _data_types = [
12
+ SourceDataType(name="image", type=Image.Image),
13
+ SourceDataType(name="text", type=str),
14
+ ]
15
+ def __init__(self, data_dir, prompt, set_len=None):
16
+ data_dir = Path(data_dir)
17
+ self.images = list(data_dir.iterdir())
18
+ self.prompt = prompt
19
+ self.set_len = set_len
20
+
21
+ def __len__(self):
22
+ if self.set_len is not None:
23
+ return self.set_len
24
+ else:
25
+ return len(self.images)
26
+
27
+ def __getitem__(self, idx):
28
+ idx = idx % len(self.images)
29
+ im_pil = Image.open(self.images[idx]).convert("RGB")
30
+ return im_pil, self.prompt
31
+
32
+ class StyleSourceWithRandomRef(Source):
33
+ _data_types = [
34
+ SourceDataType(name="image", type=Image.Image),
35
+ SourceDataType(name="text", type=str),
36
+ SourceDataType(name="reference", type=Image.Image),
37
+ ]
38
+ def __init__(self, data_dir, prompt, ref_dir, set_len=None):
39
+ data_dir = Path(data_dir)
40
+ self.images = list(data_dir.iterdir())
41
+ self.ref_images = list(Path(ref_dir).iterdir())
42
+ self.prompt = prompt
43
+ self.set_len = set_len
44
+
45
+ def __len__(self):
46
+ if self.set_len is not None:
47
+ return self.set_len
48
+ else:
49
+ return len(self.images)
50
+
51
+ def __getitem__(self, idx):
52
+ idx = idx % len(self.images)
53
+ im_pil = Image.open(self.images[idx]).convert("RGB")
54
+ rand_ref = random.choice(self.ref_images)
55
+ ref_pil = Image.open(rand_ref).convert("RGB")
56
+ return im_pil, self.prompt, ref_pil
qwenimage/finetuner.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Optional
3
+ import uuid
4
+ import hashlib
5
+
6
+ from peft import LoraConfig
7
+
8
+ from wandml.utils.debug import ftimed
9
+ from wandml.finetune.lora.lora import LoraFinetuner
10
+
11
+ class QwenLoraFinetuner(LoraFinetuner):
12
+
13
+ @ftimed
14
+ def load(self, load_path, lora_rank=16, lora_config:Optional[LoraConfig]=None):
15
+ """
16
+ Loads new lora on flux transformer if not loaded. Loads lora safetensors from load_path. Specify specific lora config using lora_rank or lora_config.
17
+ """
18
+ if "transformer" in self.modules:
19
+ return super().load(load_path)
20
+
21
+ if lora_config:
22
+ self.foundation.transformer = self.add_module(
23
+ "transformer",
24
+ self.foundation.transformer,
25
+ lora_config=lora_config
26
+ )
27
+ else:
28
+ target_modules = [
29
+ 'to_q',
30
+ 'to_k',
31
+ 'to_v',
32
+ 'to_qkv',
33
+
34
+ 'add_q_proj',
35
+ 'add_k_proj',
36
+ 'add_v_proj',
37
+ 'to_added_qkv',
38
+
39
+ 'proj',
40
+ 'txt_in',
41
+ 'img_in',
42
+ 'txt_mod.1',
43
+ 'img_mod.1',
44
+ 'proj_out',
45
+ 'to_add_out',
46
+ 'to_out.0'
47
+ 'net.2',
48
+ 'linear',
49
+ 'linear_2',
50
+ 'linear_1',
51
+ ]
52
+ self.foundation.transformer = self.add_module(
53
+ "transformer",
54
+ self.foundation.transformer,
55
+ target_modules=target_modules,
56
+ lora_rank=lora_rank,
57
+ )
58
+ self.foundation.transformer.to(dtype=self.foundation.dtype)
59
+
60
+ return super().load(load_path)
qwenimage/foundation.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ from pathlib import Path
4
+ import warnings
5
+
6
+ from PIL import Image
7
+ from diffusers.pipelines.qwenimage.pipeline_qwenimage import QwenImagePipeline
8
+ import torch
9
+ from safetensors.torch import load_file, save_model
10
+ import torch.nn.functional as F
11
+ from einops import rearrange
12
+
13
+ from qwenimage.datamodels import QwenConfig, QwenInputs
14
+ from qwenimage.debug import print_gpu_memory
15
+ from qwenimage.models.encode_prompt import encode_prompt
16
+ from qwenimage.models.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline
17
+ from qwenimage.models.transformer_qwenimage import QwenImageTransformer2DModel
18
+ from qwenimage.sampling import TimestepDistUtils
19
+ from wandml import WandModel
20
+
21
+
22
+ class QwenImageFoundation(WandModel):
23
+ SOURCE = "Qwen/Qwen-Image-Edit-2509"
24
+ INPUT_MODEL = QwenInputs
25
+ CACHE_DIR = "qwen_image_edit_2509"
26
+ PIPELINE = QwenImageEditPlusPipeline
27
+
28
+ serialize_modules = ["transformer"]
29
+
30
+ def __init__(self, config:QwenConfig, device=None):
31
+ super().__init__()
32
+ self.config:QwenConfig = config
33
+ self.dtype = torch.bfloat16
34
+ if device is None:
35
+ default_device = "cuda" if torch.cuda.is_available() else "cpu"
36
+ self.device = default_device
37
+ else:
38
+ self.device = device
39
+ print(f"{self.device=}")
40
+
41
+ pipe = self.PIPELINE.from_pretrained(
42
+ "Qwen/Qwen-Image-Edit-2509",
43
+ transformer=QwenImageTransformer2DModel.from_pretrained(
44
+ "Qwen/Qwen-Image-Edit-2509",
45
+ subfolder='transformer',
46
+ torch_dtype=self.dtype,
47
+ device_map=self.device
48
+ ),
49
+ torch_dtype=self.dtype,
50
+ )
51
+ pipe = pipe.to(device=self.device, dtype=self.dtype)
52
+
53
+
54
+ if config.load_multi_view_lora:
55
+ pipe.load_lora_weights(
56
+ "dx8152/Qwen-Edit-2509-Multiple-angles",
57
+ weight_name="镜头转换.safetensors", adapter_name="angles"
58
+ )
59
+ pipe.set_adapters(["angles"], adapter_weights=[1.])
60
+ pipe.fuse_lora(adapter_names=["angles"], lora_scale=1.25)
61
+ pipe.unload_lora_weights()
62
+
63
+ self.pipe = pipe
64
+ self.vae = self.pipe.vae
65
+ self.transformer = self.pipe.transformer
66
+ self.text_encoder = self.pipe.text_encoder
67
+ self.scheduler = self.pipe.scheduler
68
+
69
+ self.vae.to(self.dtype)
70
+ self.vae.eval()
71
+ self.vae.requires_grad_(False)
72
+ self.text_encoder.eval()
73
+ self.text_encoder.requires_grad_(False)
74
+ self.text_encoder_device = None
75
+ self.transformer.eval()
76
+ self.transformer.requires_grad_(False)
77
+
78
+ self.timestep_dist_utils = TimestepDistUtils(
79
+ min_seq_len=self.scheduler.config.base_image_seq_len,
80
+ max_seq_len=self.scheduler.config.max_image_seq_len,
81
+ min_mu=self.scheduler.config.base_shift,
82
+ max_mu=self.scheduler.config.max_shift,
83
+ train_dist=self.config.train_dist,
84
+ train_shift=self.config.train_shift,
85
+ inference_dist=self.config.inference_dist,
86
+ inference_shift=self.config.inference_shift,
87
+ static_mu=self.config.static_mu,
88
+ loss_weight_dist=self.config.loss_weight_dist,
89
+ )
90
+ self.static_prompt_embeds = None
91
+
92
+ def load(self, load_path):
93
+ if not isinstance(load_path, Path):
94
+ load_path = Path(load_path)
95
+ if not load_path.is_dir():
96
+ raise ValueError(f"Expected {load_path=} to be a directory")
97
+ for module_name in self.serialize_modules:
98
+ model_state_dict = load_file(load_path / f"{module_name}.safetensors")
99
+ missing, unexpected = getattr(self, module_name).load_state_dict(model_state_dict, strict=False, assign=True)
100
+ if missing:
101
+ warnings.warn(f"{module_name} missing {missing}")
102
+ if unexpected:
103
+ warnings.warn(f"{module_name} unexpected {unexpected}")
104
+
105
+ def save(self, save_path, skip=False):
106
+ if skip: return
107
+
108
+ if not isinstance(save_path, Path):
109
+ save_path = Path(save_path)
110
+ if not save_path.is_dir():
111
+ raise ValueError(f"Expected {save_path=} to be a directory")
112
+
113
+ save_path.mkdir(parents=True, exist_ok=True)
114
+
115
+ for module_name in self.serialize_modules:
116
+ save_model(getattr(self, module_name), save_path / f"{module_name}.safetensors")
117
+ print(f"Saved {module_name} to {save_path}")
118
+
119
+ def get_train_params(self):
120
+ return [{"params": [p for p in self.transformer.parameters() if p.requires_grad]}]
121
+
122
+ def pil_to_latents(self, images):
123
+ image = self.pipe.image_processor.preprocess(images)
124
+ image = image.unsqueeze(2) # N, C, F=1, H, W
125
+ image = image.to(device=self.device, dtype=self.dtype)
126
+ latents = self.pipe.vae.encode(image).latent_dist.mode() # argmax
127
+
128
+ latents_mean = (
129
+ torch.tensor(self.pipe.vae.config.latents_mean)
130
+ .view(1, self.pipe.vae.config.z_dim, 1, 1, 1)
131
+ .to(latents.device, latents.dtype)
132
+ )
133
+ latents_std = (
134
+ torch.tensor(self.pipe.vae.config.latents_std)
135
+ .view(1, self.pipe.vae.config.z_dim, 1, 1, 1)
136
+ .to(latents.device, latents.dtype)
137
+ )
138
+ latents = (latents - latents_mean) / latents_std
139
+ latents = latents.squeeze(2)
140
+ return latents.to(dtype=self.dtype)
141
+
142
+ def latents_to_pil(self, latents):
143
+ latents = latents.clone().detach()
144
+ latents = latents.unsqueeze(2)
145
+
146
+ latents = latents.to(self.dtype)
147
+ latents_mean = (
148
+ torch.tensor(self.pipe.vae.config.latents_mean)
149
+ .view(1, self.pipe.vae.config.z_dim, 1, 1, 1)
150
+ .to(latents.device, latents.dtype)
151
+ )
152
+ latents_std = (
153
+ torch.tensor(self.pipe.vae.config.latents_std)
154
+ .view(1, self.pipe.vae.config.z_dim, 1, 1, 1)
155
+ .to(latents.device, latents.dtype)
156
+ )
157
+ latents = latents * latents_std + latents_mean
158
+
159
+ latents = latents.to(device=self.device, dtype=self.dtype)
160
+ image = self.pipe.vae.decode(latents, return_dict=False)[0][:, :, 0] # F = 1
161
+ image = self.pipe.image_processor.postprocess(image)
162
+ return image
163
+
164
+ @staticmethod
165
+ def pack_latents(latents):
166
+ packed = rearrange(latents, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
167
+ return packed
168
+
169
+ @staticmethod
170
+ def unpack_latents(packed, h, w):
171
+ latents = rearrange(packed, "b (h w) (c ph pw) -> b c (h ph) (w pw)", ph=2, pw=2, h=h, w=w)
172
+ return latents
173
+
174
+ def set_static_prompt(self, prompt:str):
175
+ self.text_encoder.to(device=self.device)
176
+ if self.text_encoder_device != "cuda":
177
+ self.text_encoder_device = "cuda"
178
+ with torch.no_grad():
179
+ prompt_embeds, prompt_embeds_mask = encode_prompt(
180
+ self.text_encoder,
181
+ self.pipe.tokenizer,
182
+ prompt,
183
+ device=self.device,
184
+ dtype=self.dtype,
185
+ max_sequence_length = self.config.train_max_sequence_length,
186
+ )
187
+ prompt_embeds = prompt_embeds.cpu().clone().detach()
188
+ prompt_embeds_mask = prompt_embeds_mask.cpu().clone().detach()
189
+ self.static_prompt_embeds = (prompt_embeds, prompt_embeds_mask)
190
+
191
+
192
+ def preprocess_batch(self, batch):
193
+ prompts = batch["text"]
194
+
195
+ if self.static_prompt_embeds is not None:
196
+ prompt_embeds, prompt_embeds_mask = self.static_prompt_embeds
197
+
198
+ self.text_encoder.to(device=self.device)
199
+ if self.text_encoder_device != "cuda":
200
+ self.text_encoder_device = "cuda"
201
+
202
+ with torch.no_grad():
203
+ prompt_embeds, prompt_embeds_mask = encode_prompt(
204
+ self.text_encoder,
205
+ self.pipe.tokenizer,
206
+ prompts,
207
+ device=self.device,
208
+ dtype=self.dtype,
209
+ max_sequence_length = self.config.train_max_sequence_length,
210
+ )
211
+ prompt_embeds = prompt_embeds.cpu().clone().detach()
212
+ prompt_embeds_mask = prompt_embeds_mask.cpu().clone().detach()
213
+
214
+
215
+ batch["prompt_embeds"] = (prompt_embeds, prompt_embeds_mask)
216
+
217
+ return batch
218
+
219
+ def single_step(self, batch) -> torch.Tensor:
220
+ self.text_encoder.to(device="cpu") # offload
221
+ if self.text_encoder_device != "cpu":
222
+ self.text_encoder_device = "cpu"
223
+ print_gpu_memory()
224
+
225
+ if "prompt_embeds" not in batch:
226
+ batch = self.preprocess_batch(batch)
227
+ prompt_embeds, prompt_embeds_mask = batch["prompt_embeds"]
228
+ prompt_embeds = prompt_embeds.to(device=self.device)
229
+ prompt_embeds_mask = prompt_embeds_mask.to(device=self.device)
230
+
231
+ images = batch["image"]
232
+ x_0 = self.pil_to_latents(images).to(device=self.device, dtype=self.dtype)
233
+ x_1 = torch.randn_like(x_0).to(device=self.device, dtype=self.dtype)
234
+ seq_len = self.timestep_dist_utils.get_seq_len(x_0)
235
+ batch_size = x_0.shape[0]
236
+ t = self.timestep_dist_utils.get_train_t([batch_size], seq_len=seq_len).to(device=self.device, dtype=self.dtype)
237
+ x_t = (1.0 - t) * x_0 + t * x_1
238
+
239
+ x_t_1d = self.pack_latents(x_t)
240
+
241
+ l_height, l_width = x_0.shape[-2:]
242
+ img_shapes = [
243
+ [(1, l_height // 2, l_width // 2), ]
244
+ ] * batch_size
245
+ txt_seq_lens = prompt_embeds_mask.sum(dim=1).tolist()
246
+ image_rotary_emb = self.transformer.pos_embed(img_shapes, txt_seq_lens, device=x_0.device)
247
+
248
+ v_pred_1d = self.transformer(
249
+ hidden_states=x_t_1d,
250
+ encoder_hidden_states=prompt_embeds,
251
+ encoder_hidden_states_mask=prompt_embeds_mask,
252
+ timestep=t,
253
+ image_rotary_emb=image_rotary_emb,
254
+ return_dict=False,
255
+ )[0]
256
+
257
+ v_pred_2d = self.unpack_latents(v_pred_1d, h=l_height//2, w=l_width//2)
258
+ v_gt_2d = x_1 - x_0
259
+
260
+ if self.config.loss_weight_dist is not None:
261
+ loss = F.mse_loss(v_pred_2d, v_gt_2d, reduction="none").mean(dim=[1,2,3])
262
+ weights = self.timestep_dist_utils.get_loss_weighting(t)
263
+ loss = torch.mean(loss * weights)
264
+ else:
265
+ loss = F.mse_loss(v_pred_2d, v_gt_2d, reduction="mean")
266
+
267
+ return loss
268
+
269
+
270
+ def base_pipe(self, inputs: QwenInputs) -> list[Image]:
271
+ self.text_encoder.to(device=self.device)
272
+ if self.text_encoder_device != "cuda":
273
+ self.text_encoder_device = "cuda"
274
+ return self.pipe(**inputs.model_dump()).images
275
+
276
+
277
+
qwenimage/models/encode_prompt.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2Tokenizer
3
+
4
+ tokenizer_max_length = 1024
5
+ prompt_template_encode = "<|im_start|>system\nDescribe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n"
6
+ prompt_template_encode_start_idx = 34
7
+ default_sample_size = 128
8
+
9
+ def _extract_masked_hidden(hidden_states: torch.Tensor, mask: torch.Tensor):
10
+ bool_mask = mask.bool()
11
+ valid_lengths = bool_mask.sum(dim=1)
12
+ selected = hidden_states[bool_mask]
13
+ split_result = torch.split(selected, valid_lengths.tolist(), dim=0)
14
+
15
+ return split_result
16
+
17
+
18
+ def encode_prompt(
19
+ text_encoder: Qwen2_5_VLForConditionalGeneration,
20
+ tokenizer: Qwen2Tokenizer,
21
+ prompt: str | list[str],
22
+ device: torch.device | None = None,
23
+ dtype: torch.dtype | None = None,
24
+ max_sequence_length: int|None = 1024,
25
+ ):
26
+
27
+
28
+ prompt = [prompt] if isinstance(prompt, str) else prompt
29
+
30
+ template = prompt_template_encode
31
+ drop_idx = prompt_template_encode_start_idx
32
+ txt = [template.format(e) for e in prompt]
33
+ txt_tokens = tokenizer(
34
+ txt, max_length=tokenizer_max_length + drop_idx, padding=True, truncation=True, return_tensors="pt"
35
+ ).to(device)
36
+ encoder_hidden_states = text_encoder(
37
+ input_ids=txt_tokens.input_ids,
38
+ attention_mask=txt_tokens.attention_mask,
39
+ output_hidden_states=True,
40
+ )
41
+ hidden_states = encoder_hidden_states.hidden_states[-1]
42
+ split_hidden_states = _extract_masked_hidden(hidden_states, txt_tokens.attention_mask)
43
+ split_hidden_states = [e[drop_idx:] for e in split_hidden_states]
44
+ attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states]
45
+ max_seq_len = max([e.size(0) for e in split_hidden_states])
46
+ prompt_embeds = torch.stack(
47
+ [torch.cat([u, u.new_zeros(max_seq_len - u.size(0), u.size(1))]) for u in split_hidden_states]
48
+ )
49
+ prompt_embeds_mask = torch.stack(
50
+ [torch.cat([u, u.new_zeros(max_seq_len - u.size(0))]) for u in attn_mask_list]
51
+ )
52
+
53
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
54
+
55
+ if max_sequence_length is not None:
56
+ prompt_embeds = prompt_embeds[:, :max_sequence_length]
57
+ prompt_embeds_mask = prompt_embeds_mask[:, :max_sequence_length]
58
+
59
+ return prompt_embeds, prompt_embeds_mask
qwenimage/models/pipeline_qwenimage_edit_plus.py CHANGED
@@ -763,6 +763,7 @@ class QwenImageEditPlusPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
763
  # 5. Prepare timesteps
764
  sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
765
  image_seq_len = latents.shape[1]
 
766
  mu = calculate_shift(
767
  image_seq_len,
768
  self.scheduler.config.get("base_image_seq_len", 256),
@@ -770,6 +771,7 @@ class QwenImageEditPlusPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
770
  self.scheduler.config.get("base_shift", 0.5),
771
  self.scheduler.config.get("max_shift", 1.15),
772
  )
 
773
  timesteps, num_inference_steps = retrieve_timesteps(
774
  self.scheduler,
775
  num_inference_steps,
@@ -777,6 +779,7 @@ class QwenImageEditPlusPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
777
  sigmas=sigmas,
778
  mu=mu,
779
  )
 
780
  num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
781
  self._num_timesteps = len(timesteps)
782
 
 
763
  # 5. Prepare timesteps
764
  sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
765
  image_seq_len = latents.shape[1]
766
+ print(f"{image_seq_len=}")
767
  mu = calculate_shift(
768
  image_seq_len,
769
  self.scheduler.config.get("base_image_seq_len", 256),
 
771
  self.scheduler.config.get("base_shift", 0.5),
772
  self.scheduler.config.get("max_shift", 1.15),
773
  )
774
+ print(f"{mu=}")
775
  timesteps, num_inference_steps = retrieve_timesteps(
776
  self.scheduler,
777
  num_inference_steps,
 
779
  sigmas=sigmas,
780
  mu=mu,
781
  )
782
+ print(f"{timesteps=}")
783
  num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
784
  self._num_timesteps = len(timesteps)
785
 
qwenimage/sampling.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+
4
+ # math functions for sampling schedule
5
+ import math
6
+ from typing import Callable, Literal
7
+
8
+ import torch
9
+
10
+
11
+
12
+ class TimestepDistUtils:
13
+
14
+ @staticmethod
15
+ def t_shift(mu: float, sigma: float, t: torch.Tensor):
16
+ """
17
+ see eq.(12) of https://arxiv.org/abs/2506.15742 Black Forest Labs (2025)
18
+ t' = \frac{e^{\mu}}{e^{\mu} + (1/t - 1)^{\sigma}}
19
+ """
20
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
21
+
22
+ @staticmethod
23
+ def lerp_mu( # qwen params
24
+ seq_len,
25
+ min_seq_len: int = 256,
26
+ max_seq_len: int = 8192,
27
+ min_mu: float = 0.5,
28
+ max_mu: float = 0.9,
29
+ train_dist: str = "linear",
30
+ ):
31
+ """
32
+ Resolution-dependent shifting of timestep schedules
33
+ from Esser et al. https://arxiv.org/abs/2403.03206
34
+ updated with default params for Qwen
35
+ """
36
+ m = (max_mu - min_mu) / (max_seq_len - min_seq_len)
37
+ b = min_mu - m * min_seq_len
38
+ mu = seq_len * m + b
39
+ return mu
40
+
41
+ @staticmethod
42
+ def logit_normal(t, mu=0.0, sigma=1.0):
43
+ """
44
+ Logit normal PDF, as in logistic(randn(mu, sigma))
45
+ """
46
+ pdf = torch.zeros_like(t)
47
+ z = (torch.logit(t) - mu) / sigma
48
+ coef = 1.0 / (sigma * torch.sqrt(torch.tensor(2.0 * torch.pi)))
49
+ pdf = coef * torch.exp(-0.5 * z**2) / (t * (1.0 - t))
50
+ return pdf
51
+
52
+ @staticmethod
53
+ def scaled_clipped_gaussian(t):
54
+ """
55
+ Heuristic distribution for gaussian wuth mu = 0.5 and sigma=0.5,
56
+ clipped to [0,1], with int_0^1dt =1.0
57
+ """
58
+ y = torch.exp(-2 * (t - 0.5) ** 2)
59
+ y = (y - 0.606) * 4.02
60
+ return y
61
+
62
+ @staticmethod
63
+ def get_seq_len(latents):
64
+ if latents.dim() == 4 or latents.dim() == 5:
65
+ h,w = latents.shape[-2:]
66
+ seq_len = (h//2)*(w//2)
67
+ elif latents.dim() == 3:
68
+ seq_len = latents.shape[1] # [B, L=h*w, C]
69
+ else:
70
+ raise ValueError(f"{latents.dim()=} not in 3,4,5")
71
+ return seq_len
72
+
73
+ def __init__(
74
+ self,
75
+ min_seq_len=256,
76
+ max_seq_len=8192,
77
+ min_mu=0.5,
78
+ max_mu=0.9,
79
+ train_dist:Literal["logit-normal", "linear"]="linear",
80
+ train_shift:bool=True,
81
+ inference_dist:Literal["logit-normal", "linear"]="linear",
82
+ inference_shift:bool=True,
83
+ static_mu:float|None=None,
84
+ loss_weight_dist: Literal["scaled_clipped_gaussian", "logit-normal"] | None = None,
85
+ ):
86
+ self.min_seq_len = min_seq_len
87
+ self.max_seq_len = max_seq_len
88
+ self.min_mu = min_mu
89
+ self.max_mu = max_mu
90
+ self.train_dist = train_dist
91
+ self.train_shift = train_shift
92
+ self.inference_dist = inference_dist
93
+ self.inference_shift = inference_shift
94
+ self.static_mu = static_mu
95
+ self.loss_weight_dist = loss_weight_dist
96
+
97
+ def lin_t_to_dist(self, t, seq_len=None):
98
+ if self.train_dist == "logit-normal":
99
+ t = self.logit_normal_pdf(t)
100
+ elif self.train_dist == "linear":
101
+ pass
102
+ else:
103
+ raise ValueError()
104
+
105
+ if self.train_shift:
106
+ if self.static_mu:
107
+ mu = self.static_mu
108
+ elif seq_len:
109
+ mu = self.lerp_mu(seq_len, self.min_seq_len, self.max_seq_len, self.min_mu, self.max_mu)
110
+ else:
111
+ raise ValueError()
112
+ t = self.t_shift(mu, 1.0, t)
113
+ return t
114
+
115
+ def get_train_t(self, size, seq_len=None):
116
+ t = torch.rand(size)
117
+ t = self.lin_t_to_dist(t, seq_len=seq_len)
118
+ return t
119
+
120
+ def get_loss_weighting(self, t):
121
+ if self.loss_weight_dist == "scaled_clipped_gaussian":
122
+ w = self.scaled_clipped_gaussian(t)
123
+ elif self.loss_weight_dist == "logit-normal":
124
+ w = self.logit_normal_pdf(t)
125
+ elif self.loss_weight_dist is None:
126
+ w = torch.ones_like(t)
127
+ else:
128
+ raise ValueError()
129
+ return w
130
+
131
+
132
+ def get_inference_t(self, steps, strength=1.0, seq_len=None, clip_by_strength=True):
133
+ if clip_by_strength:
134
+ true_steps = max(1, int(strength * steps)) + 1
135
+ else:
136
+ true_steps = max(1, steps) + 1
137
+ t = torch.linspace(strength, 0.0, true_steps)
138
+ t = self.lin_t_to_dist(t, seq_len=seq_len)
139
+ return t
140
+
141
+ def inference_ode_step(self, noise_pred: torch.Tensor, latents: torch.Tensor, index: int, t_schedule: torch.Tensor):
142
+ t = t_schedule[index]
143
+ t_next = t_schedule[index + 1]
144
+ d_t = t_next - t
145
+ latents = latents + d_t * noise_pred
146
+ return latents
qwenimage/task.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import torch
3
+ from torchvision.transforms import v2 as T
4
+
5
+ from wandml.core.datamodels import SourceDataType
6
+ from wandml.core.task import Task
7
+ from wandml.data.transforms import RemoveAlphaTransform, RandomDownsize
8
+
9
+
10
+ image_transforms = T.Compose([
11
+ RemoveAlphaTransform(bg_color_rgb=(34, 34, 34)),
12
+ T.ToImage(),
13
+ T.RGB(),
14
+ RandomDownsize(sizes=(384, 512, 768)),
15
+ T.ToDtype(torch.float, scale=True),
16
+ ])
17
+
18
+ class TextToImageTask(Task):
19
+ data_types = [
20
+ SourceDataType(name="text", type=str),
21
+ SourceDataType(name="image", type=Image.Image),
22
+ ]
23
+ type_transforms = [
24
+ Task.identity,
25
+ image_transforms,
26
+ ]
27
+ sample_input_dict = {
28
+ "prompt": SourceDataType(name="text", type=str),
29
+ }
30
+
31
+
32
+ class TextToImageWithRefTask(Task):
33
+ data_types = [
34
+ SourceDataType(name="text", type=str),
35
+ SourceDataType(name="image", type=Image.Image),
36
+ SourceDataType(name="reference", type=Image.Image),
37
+ ]
38
+ type_transforms = [
39
+ Task.identity,
40
+ image_transforms,
41
+ image_transforms,
42
+ ]
43
+ sample_input_dict = {
44
+ "prompt": SourceDataType(name="text", type=str),
45
+ "image": SourceDataType(name="reference", type=Image.Image),
46
+ }
requirements.txt CHANGED
@@ -10,7 +10,7 @@ dashscope
10
  kernels
11
  torchvision
12
  peft
13
- torchao==0.11.0
14
  pydantic
15
  pandas
16
  modal
 
10
  kernels
11
  torchvision
12
  peft
13
+ torchao==0.14.1
14
  pydantic
15
  pandas
16
  modal
scripts/logit_normal_dist.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
scripts/scratch.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
scripts/train.ipynb ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "faf9556d",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "name": "stdout",
11
+ "output_type": "stream",
12
+ "text": [
13
+ "/home/ubuntu/Qwen-Image-Edit-Angles\n"
14
+ ]
15
+ }
16
+ ],
17
+ "source": [
18
+ "%cd /home/ubuntu/Qwen-Image-Edit-Angles"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": 2,
24
+ "id": "d74b1b7e",
25
+ "metadata": {},
26
+ "outputs": [
27
+ {
28
+ "name": "stderr",
29
+ "output_type": "stream",
30
+ "text": [
31
+ "/usr/lib/python3/dist-packages/sklearn/utils/fixes.py:25: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81.\n",
32
+ " from pkg_resources import parse_version # type: ignore\n",
33
+ "2025-11-22 18:13:10.673389: I tensorflow/core/util/port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n",
34
+ "2025-11-22 18:13:10.687858: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:467] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
35
+ "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
36
+ "E0000 00:00:1763835190.705243 2236633 cuda_dnn.cc:8579] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
37
+ "E0000 00:00:1763835190.710795 2236633 cuda_blas.cc:1407] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
38
+ "W0000 00:00:1763835190.724588 2236633 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n",
39
+ "W0000 00:00:1763835190.724603 2236633 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n",
40
+ "W0000 00:00:1763835190.724605 2236633 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n",
41
+ "W0000 00:00:1763835190.724607 2236633 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n",
42
+ "2025-11-22 18:13:10.729261: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
43
+ "To enable the following instructions: AVX512F AVX512_VNNI AVX512_BF16 AVX512_FP16 AVX_VNNI, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n"
44
+ ]
45
+ },
46
+ {
47
+ "ename": "AttributeError",
48
+ "evalue": "'MessageFactory' object has no attribute 'GetPrototype'",
49
+ "output_type": "error",
50
+ "traceback": [
51
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
52
+ "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
53
+ "\u001b[0;31mAttributeError\u001b[0m: 'MessageFactory' object has no attribute 'GetPrototype'"
54
+ ]
55
+ },
56
+ {
57
+ "ename": "AttributeError",
58
+ "evalue": "'MessageFactory' object has no attribute 'GetPrototype'",
59
+ "output_type": "error",
60
+ "traceback": [
61
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
62
+ "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
63
+ "\u001b[0;31mAttributeError\u001b[0m: 'MessageFactory' object has no attribute 'GetPrototype'"
64
+ ]
65
+ },
66
+ {
67
+ "ename": "AttributeError",
68
+ "evalue": "'MessageFactory' object has no attribute 'GetPrototype'",
69
+ "output_type": "error",
70
+ "traceback": [
71
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
72
+ "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
73
+ "\u001b[0;31mAttributeError\u001b[0m: 'MessageFactory' object has no attribute 'GetPrototype'"
74
+ ]
75
+ },
76
+ {
77
+ "name": "stderr",
78
+ "output_type": "stream",
79
+ "text": [
80
+ "/home/ubuntu/.local/lib/python3.10/site-packages/google/api_core/_python_version_support.py:266: FutureWarning: You are using a Python version (3.10.12) which Google will stop supporting in new releases of google.api_core once it reaches its end of life (2026-10-04). Please upgrade to the latest Python version, or at least Python 3.11, to continue receiving updates for google.api_core past that date.\n",
81
+ " warnings.warn(message, FutureWarning)\n"
82
+ ]
83
+ },
84
+ {
85
+ "ename": "AttributeError",
86
+ "evalue": "'MessageFactory' object has no attribute 'GetPrototype'",
87
+ "output_type": "error",
88
+ "traceback": [
89
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
90
+ "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
91
+ "\u001b[0;31mAttributeError\u001b[0m: 'MessageFactory' object has no attribute 'GetPrototype'"
92
+ ]
93
+ },
94
+ {
95
+ "ename": "AttributeError",
96
+ "evalue": "'MessageFactory' object has no attribute 'GetPrototype'",
97
+ "output_type": "error",
98
+ "traceback": [
99
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
100
+ "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
101
+ "\u001b[0;31mAttributeError\u001b[0m: 'MessageFactory' object has no attribute 'GetPrototype'"
102
+ ]
103
+ },
104
+ {
105
+ "name": "stderr",
106
+ "output_type": "stream",
107
+ "text": [
108
+ "Skipping import of cpp extensions due to incompatible torch version 2.9.1+cu128 for torchao version 0.14.1 Please see https://github.com/pytorch/ao/issues/2919 for more info\n",
109
+ "TMA benchmarks will be running without grid constant TMA descriptor.\n",
110
+ "WARNING:bitsandbytes.cextension:Could not find the bitsandbytes CUDA binary at PosixPath('/usr/local/lib/python3.10/dist-packages/bitsandbytes/libbitsandbytes_cuda128.so')\n",
111
+ "ERROR:bitsandbytes.cextension:Could not load bitsandbytes native library: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.32' not found (required by /usr/local/lib/python3.10/dist-packages/bitsandbytes/libbitsandbytes_cpu.so)\n",
112
+ "Traceback (most recent call last):\n",
113
+ " File \"/usr/local/lib/python3.10/dist-packages/bitsandbytes/cextension.py\", line 85, in <module>\n",
114
+ " lib = get_native_library()\n",
115
+ " File \"/usr/local/lib/python3.10/dist-packages/bitsandbytes/cextension.py\", line 72, in get_native_library\n",
116
+ " dll = ct.cdll.LoadLibrary(str(binary_path))\n",
117
+ " File \"/usr/lib/python3.10/ctypes/__init__.py\", line 452, in LoadLibrary\n",
118
+ " return self._dlltype(name)\n",
119
+ " File \"/usr/lib/python3.10/ctypes/__init__.py\", line 374, in __init__\n",
120
+ " self._handle = _dlopen(self._name, mode)\n",
121
+ "OSError: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.32' not found (required by /usr/local/lib/python3.10/dist-packages/bitsandbytes/libbitsandbytes_cpu.so)\n",
122
+ "WARNING:bitsandbytes.cextension:\n",
123
+ "CUDA Setup failed despite CUDA being available. Please run the following command to get more information:\n",
124
+ "\n",
125
+ "python -m bitsandbytes\n",
126
+ "\n",
127
+ "Inspect the output of the command and see if you can locate CUDA libraries. You might need to add them\n",
128
+ "to your LD_LIBRARY_PATH. If you suspect a bug, please take the information from python -m bitsandbytes\n",
129
+ "and open an issue at: https://github.com/bitsandbytes-foundation/bitsandbytes/issues\n",
130
+ "\n"
131
+ ]
132
+ }
133
+ ],
134
+ "source": [
135
+ "import os\n",
136
+ "import subprocess\n",
137
+ "from pathlib import Path\n",
138
+ "import argparse\n",
139
+ "\n",
140
+ "from ruamel.yaml import YAML\n",
141
+ "import diffusers\n",
142
+ "\n",
143
+ "\n",
144
+ "from wandml.trainers.experiment_trainer import ExperimentTrainer\n",
145
+ "from wandml import WandDataPipe\n",
146
+ "import wandml\n",
147
+ "\n",
148
+ "from qwenimage.finetuner import QwenLoraFinetuner\n"
149
+ ]
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "execution_count": null,
154
+ "id": "b7b70d58",
155
+ "metadata": {},
156
+ "outputs": [],
157
+ "source": []
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "execution_count": 3,
162
+ "id": "ba2e8778",
163
+ "metadata": {},
164
+ "outputs": [],
165
+ "source": [
166
+ "\n",
167
+ "\n",
168
+ "from qwenimage.datasets import StyleSource\n",
169
+ "\n",
170
+ "\n",
171
+ "src = StyleSource(\"/data/styles-finetune-data-artistic/tarot\", \"<0001>\")"
172
+ ]
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "execution_count": 4,
177
+ "id": "eda50bdf",
178
+ "metadata": {},
179
+ "outputs": [],
180
+ "source": [
181
+ "from wandml.data.tasks.text_to_image import TextToImageTask\n",
182
+ "\n",
183
+ "task = TextToImageTask()"
184
+ ]
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "execution_count": 5,
189
+ "metadata": {},
190
+ "outputs": [
191
+ {
192
+ "name": "stderr",
193
+ "output_type": "stream",
194
+ "text": [
195
+ "/home/ubuntu/wand-ml/wandml/core/source.py:14: UserWarning: Deprecated: Use data_types instead of _data_types\n",
196
+ " warnings.warn(\"Deprecated: Use data_types instead of _data_types\")\n"
197
+ ]
198
+ }
199
+ ],
200
+ "source": [
201
+ "dp = WandDataPipe()\n",
202
+ "dp.add_source(src)\n",
203
+ "dp.set_task(task)"
204
+ ]
205
+ },
206
+ {
207
+ "cell_type": "code",
208
+ "execution_count": 6,
209
+ "id": "b98b9368",
210
+ "metadata": {},
211
+ "outputs": [
212
+ {
213
+ "data": {
214
+ "application/vnd.jupyter.widget-view+json": {
215
+ "model_id": "c4aecbbe70e8441c8f7f7a15ff5a95f6",
216
+ "version_major": 2,
217
+ "version_minor": 0
218
+ },
219
+ "text/plain": [
220
+ "Fetching 7 files: 0%| | 0/7 [00:00<?, ?it/s]"
221
+ ]
222
+ },
223
+ "metadata": {},
224
+ "output_type": "display_data"
225
+ },
226
+ {
227
+ "name": "stdout",
228
+ "output_type": "stream",
229
+ "text": [
230
+ "self.device='cuda'\n"
231
+ ]
232
+ },
233
+ {
234
+ "data": {
235
+ "application/vnd.jupyter.widget-view+json": {
236
+ "model_id": "94340bbd1c674a88ba287f7154815d6b",
237
+ "version_major": 2,
238
+ "version_minor": 0
239
+ },
240
+ "text/plain": [
241
+ "Fetching 5 files: 0%| | 0/5 [00:00<?, ?it/s]"
242
+ ]
243
+ },
244
+ "metadata": {},
245
+ "output_type": "display_data"
246
+ },
247
+ {
248
+ "data": {
249
+ "application/vnd.jupyter.widget-view+json": {
250
+ "model_id": "44febcb836804a969fd7c2571f7830be",
251
+ "version_major": 2,
252
+ "version_minor": 0
253
+ },
254
+ "text/plain": [
255
+ "Loading checkpoint shards: 0%| | 0/5 [00:00<?, ?it/s]"
256
+ ]
257
+ },
258
+ "metadata": {},
259
+ "output_type": "display_data"
260
+ },
261
+ {
262
+ "data": {
263
+ "application/vnd.jupyter.widget-view+json": {
264
+ "model_id": "379bfa34f1cb46ef9aa6c06b94a5437f",
265
+ "version_major": 2,
266
+ "version_minor": 0
267
+ },
268
+ "text/plain": [
269
+ "Loading pipeline components...: 0%| | 0/6 [00:00<?, ?it/s]"
270
+ ]
271
+ },
272
+ "metadata": {},
273
+ "output_type": "display_data"
274
+ },
275
+ {
276
+ "name": "stderr",
277
+ "output_type": "stream",
278
+ "text": [
279
+ "`torch_dtype` is deprecated! Use `dtype` instead!\n"
280
+ ]
281
+ },
282
+ {
283
+ "data": {
284
+ "application/vnd.jupyter.widget-view+json": {
285
+ "model_id": "963f6022ee8c46ce9d36a02aad4bc739",
286
+ "version_major": 2,
287
+ "version_minor": 0
288
+ },
289
+ "text/plain": [
290
+ "Loading checkpoint shards: 0%| | 0/4 [00:00<?, ?it/s]"
291
+ ]
292
+ },
293
+ "metadata": {},
294
+ "output_type": "display_data"
295
+ }
296
+ ],
297
+ "source": [
298
+ "from qwenimage.datamodels import QwenConfig\n",
299
+ "from qwenimage.foundation import QwenImageFoundation\n",
300
+ "\n",
301
+ "config = QwenConfig()\n",
302
+ "foundation = QwenImageFoundation(config=config)"
303
+ ]
304
+ },
305
+ {
306
+ "cell_type": "code",
307
+ "execution_count": 7,
308
+ "id": "7646e8ce",
309
+ "metadata": {},
310
+ "outputs": [
311
+ {
312
+ "name": "stdout",
313
+ "output_type": "stream",
314
+ "text": [
315
+ "Loading Lora from None\n"
316
+ ]
317
+ }
318
+ ],
319
+ "source": [
320
+ "finetuner = QwenLoraFinetuner(foundation, config)\n",
321
+ "finetuner.load(None)"
322
+ ]
323
+ },
324
+ {
325
+ "cell_type": "code",
326
+ "execution_count": 8,
327
+ "id": "47bcba68",
328
+ "metadata": {},
329
+ "outputs": [
330
+ {
331
+ "name": "stdout",
332
+ "output_type": "stream",
333
+ "text": [
334
+ "foundation=<FoundationEnum.FLUX: 'flux'> instance_data_dir=None class_data_dir=None instance_prompt=None class_prompt=None num_class_images=10 output_dir='output' seed=None size=1024 center_crop=False train_batch_size=1 num_train_epochs=1 max_train_steps=None save_steps=1000 save_path=None gradient_accumulation_steps=1 learning_rate=0.001 learning_rate_1d=1e-06 scale_lr=False lr_scheduler='constant' lr_warmup_steps=0 base_lr=1e-05 max_lr=0.001 step_size_up=2000 cyclic_lr_mode=<CyclicLRMode.TRIANGULAR2: 'triangular2'> cyclic_lr_cycle_momentum=False optim=<OptimizerType.ADAMW: 'adamw'> adam_beta1=0.9 adam_beta2=0.999 adam_weight_decay=0.01 adam_epsilon=1e-08 max_grad_norm=1.0 mixed_precision='bf16' concepts_list=None modifier_tokens=None initializer_tokens=None checkpointing_steps=9999 resume_from_checkpoint=None train_text_encoder=True gcs_bucket=None topic_id='finetune-complete' concepts=None global_step=0 prior_loss_weight=1.0 wand_user_id='test' wand_model_id='testing' wand_model_bucket='wand-finetune' wand_project_name='wand-finetune' num_sample_images=5 prodigy_beta3=None prodigy_decouple=True prodigy_use_bias_correction=False prodigy_safeguard_warmup=False base_cache_dir=PosixPath('/data/wand_cache') num_validation_images=30 log_batch_steps=100 run_name=None record_training=True validation_steps=500 train_sigma_distribution='linear' inference_sigma_distribution='shift' quantize=False gradient_checkpointing=False compile=False lora_map_save_params=False log_model_steps=None resume_optimizer=False sample_steps=500 upload_optimizer=False early_stop=False preprocessing_epoch_len=128 train_regional=False preprocessing_epoch_repetitions=1 lora_rank=16 ema=False composite_reference=False train_color_fix=False num_workers=None wandb_entity='wand-tech' warmup_start_lr=0.0 lr_T_mult=1 lr_T_0=None logger_service='wandb' clearml_task_type='training' load_multi_view_lora=False train_max_sequence_length=512 train_dist='linear' train_shift=True inference_dist='linear' inference_shift=True static_mu=None loss_weight_dist=None\n"
335
+ ]
336
+ }
337
+ ],
338
+ "source": [
339
+ "trainer = ExperimentTrainer(foundation,dp,config)"
340
+ ]
341
+ },
342
+ {
343
+ "cell_type": "code",
344
+ "execution_count": 9,
345
+ "id": "d92855c1",
346
+ "metadata": {},
347
+ "outputs": [
348
+ {
349
+ "name": "stderr",
350
+ "output_type": "stream",
351
+ "text": [
352
+ "\u001b[34m\u001b[1mwandb\u001b[0m: Currently logged in as: \u001b[33meleazhong\u001b[0m to \u001b[32mhttps://api.wandb.ai\u001b[0m. Use \u001b[1m`wandb login --relogin`\u001b[0m to force relogin\n"
353
+ ]
354
+ },
355
+ {
356
+ "name": "stdout",
357
+ "output_type": "stream",
358
+ "text": [
359
+ "wandb.init called with:\n",
360
+ " project: wand-finetune\n",
361
+ " entity: wand-tech\n",
362
+ " name: None\n",
363
+ " config: {'foundation': <FoundationEnum.FLUX: 'flux'>, 'instance_data_dir': None, 'class_data_dir': None, 'instance_prompt': None, 'class_prompt': None, 'num_class_images': 10, 'output_dir': 'output', 'seed': None, 'size': 1024, 'center_crop': False, 'train_batch_size': 1, 'num_train_epochs': 1, 'max_train_steps': None, 'save_steps': 1000, 'save_path': None, 'gradient_accumulation_steps': 1, 'learning_rate': 0.001, 'learning_rate_1d': 1e-06, 'scale_lr': False, 'lr_scheduler': 'constant', 'lr_warmup_steps': 0, 'base_lr': 1e-05, 'max_lr': 0.001, 'step_size_up': 2000, 'cyclic_lr_mode': <CyclicLRMode.TRIANGULAR2: 'triangular2'>, 'cyclic_lr_cycle_momentum': False, 'optim': <OptimizerType.ADAMW: 'adamw'>, 'adam_beta1': 0.9, 'adam_beta2': 0.999, 'adam_weight_decay': 0.01, 'adam_epsilon': 1e-08, 'max_grad_norm': 1.0, 'mixed_precision': 'bf16', 'concepts_list': None, 'modifier_tokens': None, 'initializer_tokens': None, 'checkpointing_steps': 9999, 'resume_from_checkpoint': None, 'train_text_encoder': True, 'gcs_bucket': None, 'topic_id': 'finetune-complete', 'concepts': None, 'global_step': 0, 'prior_loss_weight': 1.0, 'wand_user_id': 'test', 'wand_model_id': 'testing', 'wand_model_bucket': 'wand-finetune', 'wand_project_name': 'wand-finetune', 'num_sample_images': 5, 'prodigy_beta3': None, 'prodigy_decouple': True, 'prodigy_use_bias_correction': False, 'prodigy_safeguard_warmup': False, 'base_cache_dir': PosixPath('/data/wand_cache'), 'num_validation_images': 30, 'log_batch_steps': 100, 'run_name': None, 'record_training': True, 'validation_steps': 500, 'train_sigma_distribution': 'linear', 'inference_sigma_distribution': 'shift', 'quantize': False, 'gradient_checkpointing': False, 'compile': False, 'lora_map_save_params': False, 'log_model_steps': None, 'resume_optimizer': False, 'sample_steps': 500, 'upload_optimizer': False, 'early_stop': False, 'preprocessing_epoch_len': 128, 'train_regional': False, 'preprocessing_epoch_repetitions': 1, 'lora_rank': 16, 'ema': False, 'composite_reference': False, 'train_color_fix': False, 'num_workers': None, 'wandb_entity': 'wand-tech', 'warmup_start_lr': 0.0, 'lr_T_mult': 1, 'lr_T_0': None, 'logger_service': 'wandb', 'clearml_task_type': 'training', 'load_multi_view_lora': False, 'train_max_sequence_length': 512, 'train_dist': 'linear', 'train_shift': True, 'inference_dist': 'linear', 'inference_shift': True, 'static_mu': None, 'loss_weight_dist': None}\n",
364
+ " tags: None\n",
365
+ " kwargs: {'save_code': True}\n"
366
+ ]
367
+ },
368
+ {
369
+ "data": {
370
+ "text/html": [],
371
+ "text/plain": [
372
+ "<IPython.core.display.HTML object>"
373
+ ]
374
+ },
375
+ "metadata": {},
376
+ "output_type": "display_data"
377
+ },
378
+ {
379
+ "data": {
380
+ "text/html": [
381
+ "Tracking run with wandb version 0.23.0"
382
+ ],
383
+ "text/plain": [
384
+ "<IPython.core.display.HTML object>"
385
+ ]
386
+ },
387
+ "metadata": {},
388
+ "output_type": "display_data"
389
+ },
390
+ {
391
+ "data": {
392
+ "text/html": [
393
+ "Run data is saved locally in <code>/home/ubuntu/Qwen-Image-Edit-Angles/wandb/run-20251122_181330-lg6f3z2h</code>"
394
+ ],
395
+ "text/plain": [
396
+ "<IPython.core.display.HTML object>"
397
+ ]
398
+ },
399
+ "metadata": {},
400
+ "output_type": "display_data"
401
+ },
402
+ {
403
+ "data": {
404
+ "text/html": [
405
+ "Syncing run <strong><a href='https://wandb.ai/wand-tech/wand-finetune/runs/lg6f3z2h' target=\"_blank\">graceful-galaxy-731</a></strong> to <a href='https://wandb.ai/wand-tech/wand-finetune' target=\"_blank\">Weights & Biases</a> (<a href='https://wandb.me/developer-guide' target=\"_blank\">docs</a>)<br>"
406
+ ],
407
+ "text/plain": [
408
+ "<IPython.core.display.HTML object>"
409
+ ]
410
+ },
411
+ "metadata": {},
412
+ "output_type": "display_data"
413
+ },
414
+ {
415
+ "data": {
416
+ "text/html": [
417
+ " View project at <a href='https://wandb.ai/wand-tech/wand-finetune' target=\"_blank\">https://wandb.ai/wand-tech/wand-finetune</a>"
418
+ ],
419
+ "text/plain": [
420
+ "<IPython.core.display.HTML object>"
421
+ ]
422
+ },
423
+ "metadata": {},
424
+ "output_type": "display_data"
425
+ },
426
+ {
427
+ "data": {
428
+ "text/html": [
429
+ " View run at <a href='https://wandb.ai/wand-tech/wand-finetune/runs/lg6f3z2h' target=\"_blank\">https://wandb.ai/wand-tech/wand-finetune/runs/lg6f3z2h</a>"
430
+ ],
431
+ "text/plain": [
432
+ "<IPython.core.display.HTML object>"
433
+ ]
434
+ },
435
+ "metadata": {},
436
+ "output_type": "display_data"
437
+ },
438
+ {
439
+ "name": "stdout",
440
+ "output_type": "stream",
441
+ "text": [
442
+ "Using suggested max workers 26\n"
443
+ ]
444
+ },
445
+ {
446
+ "name": "stderr",
447
+ "output_type": "stream",
448
+ "text": [
449
+ "Train: 0%| | 0/6 [00:00<?, ?it/s]"
450
+ ]
451
+ },
452
+ {
453
+ "name": "stdout",
454
+ "output_type": "stream",
455
+ "text": [
456
+ "Memory allocated: 55297.20 MB\n",
457
+ "Memory reserved: 55616.00 MB\n",
458
+ "Total memory: 81089.88 MB\n"
459
+ ]
460
+ },
461
+ {
462
+ "name": "stderr",
463
+ "output_type": "stream",
464
+ "text": [
465
+ "Preprocess Batch: 100%|██████████| 128/128 [00:16<00:00, 7.73it/s]\n"
466
+ ]
467
+ },
468
+ {
469
+ "name": "stdout",
470
+ "output_type": "stream",
471
+ "text": [
472
+ "Memory allocated: 56371.81 MB\n",
473
+ "Memory reserved: 56676.00 MB\n",
474
+ "Total memory: 81089.88 MB\n",
475
+ "Repetition: 0\n"
476
+ ]
477
+ },
478
+ {
479
+ "ename": "RuntimeError",
480
+ "evalue": "Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!",
481
+ "output_type": "error",
482
+ "traceback": [
483
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
484
+ "\u001b[0;31mRuntimeError\u001b[0m Traceback (most recent call last)",
485
+ "\u001b[0;32m/tmp/ipykernel_2236633/4032920361.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mtrainer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtrain\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
486
+ "\u001b[0;32m~/wand-ml/wandml/utils/debug.py\u001b[0m in \u001b[0;36mwrapper\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m 20\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mwrapper\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 21\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mDEBUG\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 22\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfunc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 23\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 24\u001b[0m \u001b[0mstart_time\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtime\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mperf_counter\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
487
+ "\u001b[0;32m~/wand-ml/wandml/trainers/experiment_trainer.py\u001b[0m in \u001b[0;36mtrain\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 295\u001b[0m \u001b[0mbatch\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"epoch\"\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mepoch\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 296\u001b[0m \u001b[0mbatch\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"split\"\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"train\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 297\u001b[0;31m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msingle_step\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mbatch\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 298\u001b[0m \u001b[0mbatch_num\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 299\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mglobal_step\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
488
+ "\u001b[0;32m~/wand-ml/wandml/trainers/experiment_trainer.py\u001b[0m in \u001b[0;36msingle_step\u001b[0;34m(self, batch)\u001b[0m\n\u001b[1;32m 334\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0maccelerator\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0maccumulate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodel\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 335\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0maccelerator\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mautocast\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 336\u001b[0;31m \u001b[0mloss\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodel\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msingle_step\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mbatch\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 337\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mctimed\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"accelerator.backward(loss)\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 338\u001b[0m \u001b[0maccelerator\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbackward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mloss\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
489
+ "\u001b[0;32m~/wand-ml/wandml/core/hooks.py\u001b[0m in \u001b[0;36mwrapper\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mresult\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 13\u001b[0m \u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkwargs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmanager\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun_pre_hooks\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 14\u001b[0;31m \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmethod\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 15\u001b[0m \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmanager\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun_post_hooks\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mresult\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 16\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mresult\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
490
+ "\u001b[0;32m~/Qwen-Image-Edit-Angles/qwenimage/foundation.py\u001b[0m in \u001b[0;36msingle_step\u001b[0;34m(self, batch)\u001b[0m\n\u001b[1;32m 190\u001b[0m \u001b[0mbatch_size\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx_0\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshape\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 191\u001b[0m \u001b[0mt\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtimestep_dist_utils\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_train_t\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mbatch_size\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mseq_len\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mseq_len\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 192\u001b[0;31m \u001b[0mx_t\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m1.0\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mt\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0mx_0\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mt\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0mx_1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 193\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 194\u001b[0m \u001b[0ml_channels\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtransformer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mconfig\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0min_channels\u001b[0m \u001b[0;34m//\u001b[0m \u001b[0;36m4\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
491
+ "\u001b[0;31mRuntimeError\u001b[0m: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!"
492
+ ]
493
+ }
494
+ ],
495
+ "source": [
496
+ "trainer.train()"
497
+ ]
498
+ },
499
+ {
500
+ "cell_type": "code",
501
+ "execution_count": null,
502
+ "id": "0eea7b23",
503
+ "metadata": {},
504
+ "outputs": [],
505
+ "source": []
506
+ }
507
+ ],
508
+ "metadata": {
509
+ "kernelspec": {
510
+ "display_name": "Python 3",
511
+ "language": "python",
512
+ "name": "python3"
513
+ },
514
+ "language_info": {
515
+ "codemirror_mode": {
516
+ "name": "ipython",
517
+ "version": 3
518
+ },
519
+ "file_extension": ".py",
520
+ "mimetype": "text/x-python",
521
+ "name": "python",
522
+ "nbconvert_exporter": "python",
523
+ "pygments_lexer": "ipython3",
524
+ "version": "3.10.12"
525
+ }
526
+ },
527
+ "nbformat": 4,
528
+ "nbformat_minor": 5
529
+ }
scripts/train.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # %%
2
+ # %cd /home/ubuntu/Qwen-Image-Edit-Angles
3
+
4
+ # %%
5
+ import os
6
+ import subprocess
7
+ from pathlib import Path
8
+ import argparse
9
+
10
+ from ruamel.yaml import YAML
11
+ import diffusers
12
+
13
+
14
+ from wandml.trainers.experiment_trainer import ExperimentTrainer
15
+ from wandml import WandDataPipe
16
+ import wandml
17
+
18
+ from qwenimage.finetuner import QwenLoraFinetuner
19
+
20
+
21
+ # %%
22
+
23
+
24
+ # %%
25
+
26
+
27
+ from qwenimage.datasets import StyleSourceWithRandomRef
28
+
29
+
30
+ src = StyleSourceWithRandomRef("/data/styles-finetune-data-artistic/tarot", "<0001>", "/data/image", set_len=1000)
31
+
32
+ # %%
33
+ from qwenimage.task import TextToImageWithRefTask
34
+
35
+ task = TextToImageWithRefTask()
36
+
37
+ # %%
38
+ dp = WandDataPipe()
39
+ dp.add_source(src)
40
+ dp.set_task(task)
41
+
42
+ # %%
43
+ from qwenimage.datamodels import QwenConfig
44
+ from qwenimage.foundation import QwenImageFoundation
45
+
46
+ config = QwenConfig(
47
+ # preprocessing_epoch_len=0,
48
+ )
49
+ foundation = QwenImageFoundation(config=config)
50
+
51
+ # %%
52
+ finetuner = QwenLoraFinetuner(foundation, config)
53
+ finetuner.load(None)
54
+
55
+ # %%
56
+ trainer = ExperimentTrainer(foundation,dp,config)
57
+
58
+ # %%
59
+ trainer.train()
60
+
61
+ # %%
62
+
63
+
64
+