akhaliq HF Staff commited on
Commit
9b58924
·
verified ·
1 Parent(s): 6144131

Upload 22 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ examples/image.png filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
4
+
5
+ import gradio as gr
6
+ import torch
7
+ import math
8
+ from PIL import Image
9
+ from transformers import AutoTokenizer
10
+ from model import LLaDAForMultiModalGeneration
11
+ from utils.image_utils import (
12
+ decode_vq_to_image, calculate_vq_params,
13
+ generate_crop_size_list, var_center_crop, add_break_line,
14
+ encode_img_with_breaks, encode_img_with_paint
15
+ )
16
+ from utils.prompt_utils import generate_text_image_to_text_image_prompt
17
+ import torch.nn.functional as F
18
+
19
+ MODEL = None
20
+ TOKENIZER = None
21
+ VQVAE = None
22
+ DEVICE = None
23
+ CURRENT_MODEL_PATH = None
24
+
25
+ SPECIAL_TOKENS = {
26
+ "mask_token": 126336,
27
+ "newline_token": 126084,
28
+ "image_token_offset": 126356,
29
+ "answer_start": 126354,
30
+ "answer_end": 126355,
31
+ "boi": 126349,
32
+ "eoi": 126350,
33
+ "uncondition": 126351
34
+ }
35
+
36
+ SYSTEM_PROMPT = "Generate an image applying the following editing instruction based on the original image."
37
+
38
+ def cosine_schedule(t):
39
+ return torch.cos(t * math.pi / 2)
40
+
41
+ def add_gumbel_noise(logits, temperature=1.0, generator=None):
42
+ if temperature == 0:
43
+ return logits
44
+
45
+ if generator is not None:
46
+ uniform_noise = torch.rand(logits.shape, dtype=logits.dtype, device=logits.device, generator=generator)
47
+ else:
48
+ uniform_noise = torch.rand_like(logits)
49
+
50
+ gumbel_noise = -torch.log(-torch.log(uniform_noise + 1e-10) + 1e-10)
51
+ return logits + temperature * gumbel_noise
52
+
53
+ def mask_by_random_topk(mask_len, probs, temperature=1.0, generator=None):
54
+ if generator is not None:
55
+ noise = torch.randn(probs.shape, dtype=probs.dtype, device=probs.device, generator=generator)
56
+ else:
57
+ noise = torch.randn_like(probs)
58
+
59
+ confidence = torch.log(probs + 1e-10) + temperature * noise
60
+ sorted_confidence, sorted_indices = torch.sort(confidence, dim=-1, descending=False)
61
+
62
+ if isinstance(mask_len, torch.Tensor):
63
+ mask_len_clamped = torch.clamp(mask_len, 0, probs.shape[-1] - 1)
64
+ mask_len_clamped = mask_len_clamped.long().squeeze(-1)
65
+ else:
66
+ mask_len_clamped = int(mask_len)
67
+
68
+ if isinstance(mask_len_clamped, torch.Tensor):
69
+ batch = probs.shape[0]
70
+ masking = torch.zeros_like(probs, dtype=torch.bool, device=probs.device)
71
+ for b in range(batch):
72
+ k = mask_len_clamped[b].item()
73
+ if k <= 0:
74
+ continue
75
+ low_idx = sorted_indices[b, :k]
76
+ masking[b, low_idx] = True
77
+ else:
78
+ k = mask_len_clamped
79
+ if k <= 0:
80
+ masking = torch.zeros_like(probs, dtype=torch.bool, device=probs.device)
81
+ else:
82
+ low_idx = sorted_indices[:, :k]
83
+ masking = torch.zeros_like(probs, dtype=torch.bool, device=probs.device)
84
+ batch = probs.shape[0]
85
+ for b in range(batch):
86
+ masking[b, low_idx[b]] = True
87
+
88
+ return masking
89
+
90
+ def get_num_transfer_tokens(text_masked_indices, text_steps):
91
+ batch_size = text_masked_indices.shape[0]
92
+ initial_masks = text_masked_indices.sum(dim=1)
93
+
94
+ num_transfer = torch.zeros(batch_size, text_steps, dtype=torch.long, device=text_masked_indices.device)
95
+
96
+ for b in range(batch_size):
97
+ total_masks = initial_masks[b].item()
98
+ remaining = total_masks
99
+
100
+ for step in range(text_steps):
101
+ ratio = (step + 1) / text_steps
102
+ target_remaining = int(total_masks * (1 - ratio))
103
+ tokens_to_unmask = max(0, remaining - target_remaining)
104
+ num_transfer[b, step] = tokens_to_unmask
105
+ remaining -= tokens_to_unmask
106
+
107
+ return num_transfer
108
+
109
+ @torch.no_grad()
110
+ def decode_text_with_masks(combined_input_ids, text_start, text_end, tokenizer, mask_token):
111
+ text_ids = combined_input_ids[0, text_start:text_end].cpu().tolist()
112
+
113
+ result_parts = []
114
+ consecutive_masks = 0
115
+
116
+ for token_id in text_ids:
117
+ if token_id == mask_token:
118
+ consecutive_masks += 1
119
+ else:
120
+ if consecutive_masks > 0:
121
+ if consecutive_masks <= 10:
122
+ result_parts.append("▓" * consecutive_masks)
123
+ else:
124
+ result_parts.append(f"▓▓▓▓▓[...{consecutive_masks - 5} more]")
125
+ consecutive_masks = 0
126
+
127
+ try:
128
+ token_text = tokenizer.decode([token_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)
129
+ if token_text.strip() or token_text in [' ', '\n', '\t']:
130
+ result_parts.append(token_text)
131
+ except:
132
+ result_parts.append(f"[{token_id}]")
133
+
134
+ if consecutive_masks > 0:
135
+ if consecutive_masks <= 10:
136
+ result_parts.append("▓" * consecutive_masks)
137
+ else:
138
+ result_parts.append(f"▓▓▓▓▓[...{consecutive_masks - 5} more]")
139
+
140
+ return "".join(result_parts)
141
+
142
+ @torch.no_grad()
143
+ def generate_ti2ti_stepwise(
144
+ model, input_ids, text_start, text_end, image_start, seq_len, newline_every,
145
+ text_steps=100, temperature=1.0, text_temperature=0.7, cfg_scale=0.0, cfg_img=4.0,
146
+ uncon_text=None, uncon_image=None, tokenizer=None, remasking='low_confidence',
147
+ noise_schedule=cosine_schedule, generator=None, text_vocab_size=126356,
148
+ codebook_size=8192, vqvae=None, image_height=512, image_width=512,
149
+ ):
150
+ device = input_ids.device
151
+ MASK_TOKEN = SPECIAL_TOKENS["mask_token"]
152
+ NEW_LINE = SPECIAL_TOKENS["newline_token"]
153
+
154
+ combined_input_ids = input_ids.clone()
155
+ num_vq_tokens = seq_len
156
+ total_image_len = seq_len + seq_len // newline_every
157
+ image_end = image_start + total_image_len
158
+
159
+ text_masked_indices = combined_input_ids[:, text_start:text_end] == MASK_TOKEN
160
+ num_transfer_tokens = get_num_transfer_tokens(text_masked_indices, text_steps)
161
+
162
+ image_generation_step_indices = torch.linspace(
163
+ 0, text_steps - 1, int(text_steps * 0.3)
164
+ ).round().int().tolist()
165
+
166
+ image_position_mapping = []
167
+ for i in range(image_start, image_end):
168
+ if combined_input_ids[0, i] != NEW_LINE:
169
+ image_position_mapping.append(i)
170
+
171
+ batch_size = combined_input_ids.shape[0]
172
+ initial_text_display = decode_text_with_masks(combined_input_ids, text_start, text_end, tokenizer, MASK_TOKEN)
173
+ last_generated_image = None
174
+
175
+ yield 0, initial_text_display, None, f"Step 0/{text_steps}"
176
+
177
+ for step in range(text_steps):
178
+ cond_logits = model(combined_input_ids, infer=True, use_cache=False).logits
179
+
180
+ text_masked_indices = combined_input_ids[:, text_start:text_end] == MASK_TOKEN
181
+
182
+ if text_masked_indices.sum() > 0:
183
+ text_logits = cond_logits[:, text_start:text_end, :]
184
+ logits_with_noise = add_gumbel_noise(text_logits, temperature=text_temperature, generator=generator)
185
+ x0 = torch.argmax(logits_with_noise, dim=-1)
186
+
187
+ if remasking == 'low_confidence':
188
+ p = F.softmax(text_logits.to(torch.float64), dim=-1)
189
+ x0_p = torch.squeeze(torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1)
190
+ elif remasking == 'random':
191
+ if generator is not None:
192
+ x0_p = torch.rand(x0.shape, dtype=x0.dtype, device=x0.device, generator=generator)
193
+ else:
194
+ x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
195
+ else:
196
+ x0_p = torch.ones_like(x0, dtype=torch.float)
197
+
198
+ x0 = torch.where(text_masked_indices, x0, combined_input_ids[:, text_start:text_end])
199
+ confidence = torch.where(text_masked_indices, x0_p, float('-inf'))
200
+
201
+ transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
202
+ for j in range(confidence.shape[0]):
203
+ k = num_transfer_tokens[j, step].item()
204
+ if k > 0:
205
+ _, select_index = torch.topk(confidence[j], k=k)
206
+ transfer_index[j, select_index] = True
207
+
208
+ combined_input_ids[:, text_start:text_end][transfer_index] = x0[transfer_index]
209
+
210
+ if step in image_generation_step_indices:
211
+ vq_tokens_list = []
212
+ mask_positions = []
213
+ for idx, pos in enumerate(image_position_mapping):
214
+ token = combined_input_ids[0, pos].item()
215
+ if token == MASK_TOKEN:
216
+ vq_tokens_list.append(-1)
217
+ mask_positions.append(idx)
218
+ else:
219
+ vq_token = token - text_vocab_size
220
+ vq_token = max(0, min(vq_token, codebook_size - 1))
221
+ vq_tokens_list.append(vq_token)
222
+
223
+ vq_tokens_tensor = torch.tensor(vq_tokens_list, device=device).unsqueeze(0)
224
+ unknown_map = vq_tokens_tensor == -1
225
+
226
+ cond_image_logits_list = []
227
+ for pos in image_position_mapping:
228
+ cond_image_logits_list.append(
229
+ cond_logits[:, pos:pos+1, text_vocab_size:text_vocab_size+codebook_size]
230
+ )
231
+ cond_vq_logits = torch.cat(cond_image_logits_list, dim=1)
232
+
233
+ if (cfg_scale > 0.0 and uncon_text is not None) or (cfg_img > 0.0 and uncon_image is not None):
234
+ if uncon_text is None:
235
+ combined_uncond_text = combined_input_ids.clone()
236
+ else:
237
+ combined_uncond_text = combined_input_ids.clone()
238
+ prefix_len = uncon_text.shape[1]
239
+ combined_uncond_text[:, :prefix_len] = uncon_text.to(device)
240
+
241
+ if uncon_image is None:
242
+ combined_uncond_img = combined_input_ids.clone()
243
+ else:
244
+ combined_uncond_img = combined_input_ids.clone()
245
+ prefix_len_img = uncon_image.shape[1]
246
+ combined_uncond_img[:, :prefix_len_img] = uncon_image.to(device)
247
+
248
+ uncond_text_logits_full = model(combined_uncond_text, infer=True, use_cache=False).logits
249
+ uncond_img_logits_full = model(combined_uncond_img, infer=True, use_cache=False).logits
250
+
251
+ uncond_text_vq_list = []
252
+ uncond_img_vq_list = []
253
+ for pos in image_position_mapping:
254
+ uncond_text_vq_list.append(
255
+ uncond_text_logits_full[:, pos:pos+1, text_vocab_size:text_vocab_size+codebook_size]
256
+ )
257
+ uncond_img_vq_list.append(
258
+ uncond_img_logits_full[:, pos:pos+1, text_vocab_size:text_vocab_size+codebook_size]
259
+ )
260
+
261
+ uncond_text_vq_logits = torch.cat(uncond_text_vq_list, dim=1)
262
+ uncond_img_vq_logits = torch.cat(uncond_img_vq_list, dim=1)
263
+ else:
264
+ uncond_text_vq_logits = torch.zeros_like(cond_vq_logits)
265
+ uncond_img_vq_logits = torch.zeros_like(cond_vq_logits)
266
+
267
+ image_logits = cond_vq_logits
268
+ if cfg_scale != 0.0:
269
+ image_logits = image_logits + cfg_scale * (cond_vq_logits - uncond_text_vq_logits)
270
+ if cfg_img != 0.0:
271
+ image_logits = image_logits + cfg_img * (cond_vq_logits - uncond_img_vq_logits)
272
+
273
+ probs = F.softmax(image_logits, dim=-1)
274
+
275
+ if temperature == 0:
276
+ sampled_ids = probs.argmax(dim=-1)
277
+ else:
278
+ sampled = probs.reshape(-1, image_logits.size(-1))
279
+ if generator is not None:
280
+ sampled_ids = torch.multinomial(sampled, 1, generator=generator)[:, 0].view(*image_logits.shape[:-1])
281
+ else:
282
+ sampled_ids = torch.multinomial(sampled, 1)[:, 0].view(*image_logits.shape[:-1])
283
+
284
+ sampled_ids = torch.where(unknown_map, sampled_ids, vq_tokens_tensor)
285
+ sampled_ids = torch.clamp(sampled_ids, 0, codebook_size - 1)
286
+
287
+ selected_probs = torch.gather(probs, -1, sampled_ids.long()[..., None]).squeeze(-1)
288
+ high_val = torch.finfo(selected_probs.dtype).max
289
+ selected_probs = torch.where(unknown_map, selected_probs, high_val)
290
+
291
+ ratio = 1.0 * (step + 1) / text_steps
292
+ mask_ratio = noise_schedule(torch.tensor(ratio, device=device))
293
+ unknown_counts = unknown_map.sum(dim=-1, keepdim=True)
294
+ mask_len = (num_vq_tokens * mask_ratio).floor().unsqueeze(0).to(device)
295
+ mask_len = torch.max(torch.tensor([1], device=device), torch.min(unknown_counts - 1, mask_len.to(device).long()))
296
+ if mask_len.ndim == 1:
297
+ mask_len = mask_len.unsqueeze(1)
298
+
299
+ img_temp = temperature * (1.0 - ratio)
300
+ masking = mask_by_random_topk(mask_len, selected_probs, img_temp, generator=generator)
301
+ final_vq_tokens = torch.where(masking, torch.tensor(-1, device=device), sampled_ids)
302
+
303
+ for idx, pos in enumerate(image_position_mapping):
304
+ v = final_vq_tokens[0, idx].item()
305
+ if v == -1:
306
+ combined_input_ids[0, pos] = MASK_TOKEN
307
+ else:
308
+ combined_input_ids[0, pos] = int(v + text_vocab_size)
309
+
310
+ try:
311
+ decoded_image = decode_vq_to_image(
312
+ sampled_ids, None, None, image_height, image_width, vqvae
313
+ )
314
+
315
+ masked_positions_bool = masking[0]
316
+ if masked_positions_bool.sum() > 0:
317
+ from PIL import ImageDraw
318
+ decoded_image = decoded_image.copy()
319
+ draw = ImageDraw.Draw(decoded_image, 'RGBA')
320
+
321
+ vae_scale = 2 ** (len(VQVAE.config.block_out_channels) - 1)
322
+ token_h = image_height // vae_scale
323
+ token_w = image_width // vae_scale
324
+ pixel_h = image_height // token_h
325
+ pixel_w = image_width // token_w
326
+
327
+ masked_indices = torch.where(masked_positions_bool)[0].cpu().tolist()
328
+ for masked_idx in masked_indices:
329
+ token_row = masked_idx // token_w
330
+ token_col = masked_idx % token_w
331
+
332
+ y1 = token_row * pixel_h
333
+ x1 = token_col * pixel_w
334
+ y2 = y1 + pixel_h
335
+ x2 = x1 + pixel_w
336
+
337
+ draw.rectangle([x1, y1, x2, y2], fill=(128, 128, 128, 120))
338
+
339
+ last_generated_image = decoded_image
340
+ except Exception as e:
341
+ pass
342
+
343
+ text_display = decode_text_with_masks(combined_input_ids, text_start, text_end, tokenizer, MASK_TOKEN)
344
+ text_masks_remaining = (combined_input_ids[:, text_start:text_end] == MASK_TOKEN).sum().item()
345
+ text_progress = (1 - text_masks_remaining / (text_end - text_start)) * 100
346
+
347
+ status_msg = f"Step {step + 1}/{text_steps} | Text: {text_progress:.1f}%"
348
+ if step in image_generation_step_indices:
349
+ image_masks_remaining = sum(1 for pos in image_position_mapping if combined_input_ids[0, pos] == MASK_TOKEN)
350
+ image_progress = (1 - image_masks_remaining / num_vq_tokens) * 100
351
+ status_msg += f" | Image: {image_progress:.1f}%"
352
+
353
+ if step % 5 == 0 or step in image_generation_step_indices or step == text_steps - 1:
354
+ yield step + 1, text_display, last_generated_image, status_msg
355
+
356
+ final_text_display = decode_text_with_masks(combined_input_ids, text_start, text_end, tokenizer, MASK_TOKEN)
357
+
358
+ if last_generated_image is not None:
359
+ final_image = last_generated_image
360
+ else:
361
+ final_vq_tokens = []
362
+ final_mask_positions = []
363
+ for idx, pos in enumerate(image_position_mapping):
364
+ token = combined_input_ids[0, pos].item()
365
+ if token != MASK_TOKEN:
366
+ vq_token = token - text_vocab_size
367
+ vq_token = max(0, min(vq_token, codebook_size - 1))
368
+ final_vq_tokens.append(vq_token)
369
+ else:
370
+ final_vq_tokens.append(codebook_size // 2)
371
+ final_mask_positions.append(idx)
372
+
373
+ vq_tensor = torch.tensor(final_vq_tokens, dtype=torch.long, device=device).unsqueeze(0)
374
+ final_image = decode_vq_to_image(vq_tensor, None, None, image_height, image_width, vqvae)
375
+
376
+ if final_mask_positions:
377
+ from PIL import ImageDraw
378
+ final_image = final_image.copy()
379
+ draw = ImageDraw.Draw(final_image, 'RGBA')
380
+
381
+ vae_scale = 2 ** (len(VQVAE.config.block_out_channels) - 1)
382
+ token_h = image_height // vae_scale
383
+ token_w = image_width // vae_scale
384
+ pixel_h = image_height // token_h
385
+ pixel_w = image_width // token_w
386
+
387
+ for masked_idx in final_mask_positions:
388
+ token_row = masked_idx // token_w
389
+ token_col = masked_idx % token_w
390
+
391
+ y1 = token_row * pixel_h
392
+ x1 = token_col * pixel_w
393
+ y2 = y1 + pixel_h
394
+ x2 = x1 + pixel_w
395
+
396
+ draw.rectangle([x1, y1, x2, y2], fill=(128, 128, 128, 120))
397
+
398
+ yield text_steps, final_text_display, final_image, "✓ Complete"
399
+
400
+ def load_model_and_vae(model_path, vae_path):
401
+ global MODEL, TOKENIZER, VQVAE, DEVICE, CURRENT_MODEL_PATH
402
+
403
+ if MODEL is not None and CURRENT_MODEL_PATH == model_path:
404
+ return f"Model already loaded: {model_path}"
405
+
406
+ try:
407
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
408
+
409
+ TOKENIZER = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
410
+ MODEL = LLaDAForMultiModalGeneration.from_pretrained(
411
+ model_path, torch_dtype=torch.bfloat16, device_map="auto"
412
+ )
413
+ MODEL.eval()
414
+
415
+ from diffusers import VQModel
416
+ VQVAE = VQModel.from_pretrained(vae_path, subfolder="vqvae").to(DEVICE)
417
+
418
+ CURRENT_MODEL_PATH = model_path
419
+
420
+ return f"✓ Model loaded | Device: {DEVICE}"
421
+ except Exception as e:
422
+ MODEL = None
423
+ TOKENIZER = None
424
+ VQVAE = None
425
+ CURRENT_MODEL_PATH = None
426
+ return f"✗ Failed: {str(e)}"
427
+
428
+ def generate_wrapper(
429
+ input_image, prompt_text, model_path, vae_path, height, width,
430
+ text_steps, text_gen_length, text_block_length, cfg_scale, cfg_img,
431
+ temperature, text_temperature, remasking_strategy, painting_mode,
432
+ mask_h_ratio, mask_w_ratio, seed,
433
+ ):
434
+ global MODEL, TOKENIZER, VQVAE, DEVICE
435
+
436
+ if MODEL is None or TOKENIZER is None or VQVAE is None:
437
+ load_status = load_model_and_vae(model_path, vae_path)
438
+ if "Failed" in load_status:
439
+ yield "", None, load_status
440
+ return
441
+
442
+ if input_image is None:
443
+ yield "", None, "✗ No input image"
444
+ return
445
+
446
+ if seed != 0:
447
+ torch.manual_seed(seed)
448
+ generator = torch.Generator(device=DEVICE).manual_seed(seed)
449
+ else:
450
+ generator = None
451
+
452
+ MASK = SPECIAL_TOKENS["mask_token"]
453
+ NEW_LINE = SPECIAL_TOKENS["newline_token"]
454
+ BOA = SPECIAL_TOKENS["answer_start"]
455
+ EOA = SPECIAL_TOKENS["answer_end"]
456
+ BOI = SPECIAL_TOKENS["boi"]
457
+ EOI = SPECIAL_TOKENS["eoi"]
458
+
459
+ try:
460
+ input_prompt, uncon_text = generate_text_image_to_text_image_prompt(
461
+ prompt_text, SYSTEM_PROMPT
462
+ )
463
+
464
+ prompt_ids = TOKENIZER(input_prompt)["input_ids"]
465
+ uncon_text_ids = TOKENIZER(uncon_text)["input_ids"]
466
+
467
+ img = input_image.convert("RGB")
468
+ crop_size_list = generate_crop_size_list((512 // 32) ** 2, 32)
469
+ img = var_center_crop(img, crop_size_list=crop_size_list)
470
+
471
+ input_img_token = encode_img_with_breaks(img, VQVAE)
472
+
473
+ con_input_list = prompt_ids[:-1] + input_img_token + prompt_ids[-1:]
474
+ uncon_input_text = uncon_text_ids[:-1] + input_img_token + uncon_text_ids[-1:]
475
+ uncon_input_image = prompt_ids
476
+
477
+ vae_scale = 2 ** (len(VQVAE.config.block_out_channels) - 1)
478
+ seq_len, newline_every, token_grid_height, token_grid_width = calculate_vq_params(
479
+ height, width, vae_scale
480
+ )
481
+
482
+ text_mask_tokens = [MASK] * text_gen_length
483
+
484
+ if painting_mode:
485
+ img_mask_token, img_vis = encode_img_with_paint(
486
+ img, vqvae=VQVAE, mask_h_ratio=mask_h_ratio,
487
+ mask_w_ratio=mask_w_ratio, mask_mode=painting_mode
488
+ )
489
+ else:
490
+ img_mask_token = add_break_line(
491
+ [MASK] * seq_len, token_grid_height, token_grid_width,
492
+ new_number=NEW_LINE
493
+ )
494
+
495
+ end_token_ids = TOKENIZER("</answer>", add_special_tokens=False).input_ids
496
+ pred_token = [BOA] + [BOI] + img_mask_token + [EOI] + text_mask_tokens + end_token_ids
497
+
498
+ code_start = len(con_input_list)
499
+ image_start = len(con_input_list) + 2
500
+ image_end = image_start + len(img_mask_token)
501
+ text_start = image_end + 1
502
+ text_end = text_start + text_gen_length
503
+
504
+ full_input_ids = con_input_list + pred_token
505
+ con_input = torch.tensor(full_input_ids, device=DEVICE).unsqueeze(0)
506
+ uncon_input_text_tensor = torch.tensor(uncon_input_text, device=DEVICE).unsqueeze(0)
507
+ uncon_input_image_tensor = torch.tensor(uncon_input_image, device=DEVICE).unsqueeze(0)
508
+
509
+ config = MODEL.config
510
+ text_vocab_size = getattr(config, 'text_vocab_size', 126356)
511
+ codebook_size = getattr(config, 'codebook_size', 8192)
512
+
513
+ for step, text_display, image, status in generate_ti2ti_stepwise(
514
+ model=MODEL, input_ids=con_input, text_start=text_start, text_end=text_end,
515
+ image_start=image_start, seq_len=seq_len, newline_every=newline_every,
516
+ text_steps=text_steps, temperature=temperature, text_temperature=text_temperature,
517
+ cfg_scale=cfg_scale, cfg_img=cfg_img, uncon_text=uncon_input_text_tensor,
518
+ uncon_image=uncon_input_image_tensor, tokenizer=TOKENIZER,
519
+ remasking=remasking_strategy, noise_schedule=cosine_schedule,
520
+ generator=generator, text_vocab_size=text_vocab_size,
521
+ codebook_size=codebook_size, vqvae=VQVAE,
522
+ image_height=height, image_width=width,
523
+ ):
524
+ yield text_display, image, status
525
+
526
+ except Exception as e:
527
+ import traceback
528
+ yield "", None, f"✗ Error: {str(e)}"
529
+
530
+ css_styles = """
531
+ .gradio-container {
532
+ font-family: 'IBM Plex Sans', sans-serif;
533
+ max-width: 1400px !important;
534
+ margin: auto;
535
+ }
536
+ .gr-button-primary {
537
+ background: linear-gradient(90deg, #7c3aed 0%, #a855f7 100%) !important;
538
+ border: none !important;
539
+ color: white !important;
540
+ }
541
+ .gr-button-primary:hover {
542
+ transform: scale(1.02);
543
+ box-shadow: 0 4px 12px rgba(124, 58, 237, 0.4) !important;
544
+ }
545
+ .output-markdown {
546
+ min-height: 400px !important;
547
+ max-height: 600px !important;
548
+ overflow-y: auto !important;
549
+ padding: 12px !important;
550
+ background: #fafafa !important;
551
+ border-radius: 8px !important;
552
+ border: 1px solid #e0e0e0 !important;
553
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace !important;
554
+ font-size: 13px !important;
555
+ line-height: 1.5 !important;
556
+ }
557
+ .output-markdown .prose,
558
+ .output-markdown .prose * {
559
+ font-size: 10px !important;
560
+ line-height: 1.4 !important;
561
+ }
562
+ .output-markdown h1 {
563
+ font-size: 1.4em !important;
564
+ margin-top: 0.8em !important;
565
+ margin-bottom: 0.4em !important;
566
+ color: #333 !important;
567
+ }
568
+ .output-markdown h2 {
569
+ font-size: 1.2em !important;
570
+ margin-top: 0.8em !important;
571
+ margin-bottom: 0.4em !important;
572
+ color: #333 !important;
573
+ }
574
+ .output-markdown h3 {
575
+ font-size: 1.1em !important;
576
+ margin-top: 0.8em !important;
577
+ margin-bottom: 0.4em !important;
578
+ color: #333 !important;
579
+ }
580
+ .output-markdown code {
581
+ background: #f0f0f0 !important;
582
+ padding: 2px 4px !important;
583
+ border-radius: 3px !important;
584
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace !important;
585
+ font-size: 12px !important;
586
+ }
587
+ .output-markdown pre {
588
+ background: #f5f5f5 !important;
589
+ padding: 8px !important;
590
+ border-radius: 5px !important;
591
+ overflow-x: auto !important;
592
+ font-size: 12px !important;
593
+ }
594
+ .output-markdown ul, .output-markdown ol {
595
+ padding-left: 18px !important;
596
+ margin: 8px 0 !important;
597
+ }
598
+ .output-markdown li {
599
+ margin: 4px 0 !important;
600
+ }
601
+ .output-markdown p {
602
+ margin: 6px 0 !important;
603
+ }
604
+ .output-markdown strong {
605
+ font-weight: 600 !important;
606
+ }
607
+ footer {display: none !important}
608
+ """
609
+
610
+ with gr.Blocks(css=css_styles, theme=gr.themes.Soft(primary_hue="purple")) as demo:
611
+ gr.Markdown(
612
+ """
613
+ # 🎨 MMaDA-Parallel: Text+Image to Text+Image Generation
614
+
615
+ Real-time parallel generation with step-by-step visualization.
616
+
617
+ **Github:** [tyfeld/MMaDA-Parallel-A](https://github.com/tyfeld/MMaDA-Parallel-A)
618
+ """
619
+ )
620
+
621
+ with gr.Row():
622
+ with gr.Column(scale=1):
623
+ gr.Markdown("### Input")
624
+
625
+ input_image = gr.Image(type="pil", label="Input Image")
626
+ prompt_text = gr.Textbox(
627
+ label="Editing Instruction",
628
+ lines=3,
629
+ value="Make the sky more dramatic with sunset colors",
630
+ placeholder="Enter your editing instruction..."
631
+ )
632
+
633
+ with gr.Accordion("Model", open=False):
634
+ model_path = gr.Textbox(
635
+ label="Model Path",
636
+ value="tyfeld/MMaDA-Parallel-A",
637
+ info="HuggingFace path or local directory"
638
+ )
639
+ vae_path = gr.Textbox(
640
+ label="VAE Path",
641
+ value="tyfeld/MMaDA-Parallel-A",
642
+ info="VQ-VAE checkpoint path"
643
+ )
644
+
645
+ with gr.Accordion("Parameters", open=False):
646
+ with gr.Row():
647
+ height = gr.Slider(256, 768, value=512, step=64, label="Height")
648
+ width = gr.Slider(256, 768, value=512, step=64, label="Width")
649
+
650
+ text_steps = gr.Slider(32, 512, value=128, step=32, label="Steps")
651
+ text_gen_length = gr.Slider(64, 512, value=256, step=32, label="Text Length")
652
+ text_block_length = gr.Slider(16, 128, value=32, step=16, label="Block Length")
653
+
654
+ with gr.Row():
655
+ cfg_scale = gr.Slider(0, 5, value=2.5, step=0.5, label="Text CFG")
656
+ cfg_img = gr.Slider(0, 8, value=4.0, step=0.5, label="Image CFG")
657
+
658
+ with gr.Row():
659
+ temperature = gr.Slider(0, 2, value=1.0, step=0.1, label="Image Temp")
660
+ text_temperature = gr.Slider(0, 2, value=0.7, step=0.1, label="Text Temp")
661
+
662
+ remasking_strategy = gr.Dropdown(
663
+ choices=["low_confidence", "random"],
664
+ value="low_confidence",
665
+ label="Remasking"
666
+ )
667
+
668
+ seed = gr.Slider(0, 10000, value=0, step=1, label="Seed (0=random)")
669
+
670
+ with gr.Accordion("Painting Mode", open=False):
671
+ painting_mode = gr.Dropdown(
672
+ choices=[None, "inpainting", "outpainting"],
673
+ value=None,
674
+ label="Mode"
675
+ )
676
+ with gr.Row():
677
+ mask_h_ratio = gr.Slider(0.1, 1.0, value=0.5, step=0.1, label="Mask H")
678
+ mask_w_ratio = gr.Slider(0.1, 1.0, value=0.5, step=0.1, label="Mask W")
679
+
680
+ generate_btn = gr.Button("🚀 Generate", variant="primary", size="lg")
681
+
682
+ with gr.Column(scale=2):
683
+ gr.Markdown("### Output")
684
+
685
+ status_text = gr.Textbox(label="Status", lines=2, interactive=False)
686
+
687
+ with gr.Row():
688
+ with gr.Column(scale=1.2):
689
+ output_text = gr.Markdown(
690
+ value="*Waiting...*",
691
+ label="Generated Text (▓ = masked)",
692
+ show_label=True,
693
+ container=True,
694
+ elem_classes=["output-markdown"]
695
+ )
696
+
697
+ with gr.Column(scale=1):
698
+ output_image = gr.Image(label="Generated Image", type="pil", interactive=False)
699
+
700
+ generate_btn.click(
701
+ fn=generate_wrapper,
702
+ inputs=[
703
+ input_image, prompt_text, model_path, vae_path,
704
+ height, width, text_steps, text_gen_length, text_block_length,
705
+ cfg_scale, cfg_img, temperature, text_temperature,
706
+ remasking_strategy, painting_mode, mask_h_ratio, mask_w_ratio, seed
707
+ ],
708
+ outputs=[output_text, output_image, status_text]
709
+ )
710
+
711
+ if __name__ == "__main__":
712
+ import argparse
713
+ parser = argparse.ArgumentParser(description="MMaDA-Parallel Gradio Demo")
714
+ parser.add_argument("--model_path", type=str, default="tyfeld/MMaDA-Parallel-A")
715
+ parser.add_argument("--vae_path", type=str, default="tyfeld/MMaDA-Parallel-A")
716
+ parser.add_argument("--share", action="store_true")
717
+ parser.add_argument("--port", type=int, default=7860)
718
+ args = parser.parse_args()
719
+
720
+ print("Loading model...")
721
+ load_status = load_model_and_vae(args.model_path, args.vae_path)
722
+ print(load_status)
723
+
724
+ demo.launch(share=args.share, server_name="0.0.0.0", server_port=args.port)
examples/image.png ADDED

Git LFS Details

  • SHA256: 526888582775ba2878424e37824b5e0e21ec80d2e631af0fd26b8f0dc1e00dfd
  • Pointer size: 131 Bytes
  • Size of remote file: 264 kB
generators/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Generator modules
4
+ """
generators/image_generation_generator.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Image generation generator (with optional debug prints/saving)
4
+ """
5
+ import torch
6
+ import math
7
+ import os
8
+ import numpy as np
9
+ from typing import Callable, Optional
10
+ from utils.generation_utils import cosine_schedule, gumbel_max_sample, mask_by_random_topk
11
+ from model import LLaDAForMultiModalGeneration
12
+
13
+
14
+ @torch.no_grad()
15
+ def generate_image(
16
+ model,
17
+ prompt: torch.LongTensor,
18
+ *,
19
+ seq_len: int = 1024,
20
+ newline_every: int = 16,
21
+ timesteps: int = 18,
22
+ mask_token_id: int = 126336,
23
+ newline_id: int = 126084,
24
+ temperature: float = 1.0,
25
+ cfg_scale: float = 0.0,
26
+ uncon_ids: torch.LongTensor = None,
27
+ code_start: Optional[int] = None,
28
+ codebook_size: int = 8192,
29
+ noise_schedule: Callable[[torch.Tensor], torch.Tensor] = cosine_schedule,
30
+ text_vocab_size: Optional[int] = None,
31
+ generator: Optional[torch.Generator] = None,
32
+ use_cache=False,
33
+ cache_ratio=0.9,
34
+ refresh_interval=5,
35
+ warmup_ratio=0.3,
36
+ debug: bool = True,
37
+ debug_log_dir: Optional[str] = None,
38
+ max_print_tokens: int = 100
39
+ ) -> torch.LongTensor:
40
+ """
41
+ MaskGit parallel decoding to generate VQ tokens
42
+
43
+ Added debug=True to print shapes and token samples per step. Optional debug_log_dir to save numpy dumps.
44
+
45
+ Args:
46
+ debug: when True, print detailed info each step.
47
+ debug_log_dir: directory to save per-step npy dumps (x, vq_mask, logits, sampled_full)
48
+ max_print_tokens: maximum number of tokens/logits to print for arrays (prevents terminal spam)
49
+ """
50
+
51
+ if debug and debug_log_dir:
52
+ os.makedirs(debug_log_dir, exist_ok=True)
53
+
54
+ device = next(model.parameters()).device
55
+ prompt = prompt.to(device)
56
+ B, P = prompt.shape
57
+ assert B == 1, "batch>1 not supported – wrap in loop if needed"
58
+
59
+ x = prompt.clone()
60
+
61
+ vq_mask = x == mask_token_id
62
+ unknown_cnt = vq_mask.sum(dim=1, keepdim=True)
63
+ vq_len = unknown_cnt
64
+
65
+ if isinstance(model, LLaDAForMultiModalGeneration):
66
+ model.caching(use_cache)
67
+ else: # DDP
68
+ model.module.caching(use_cache)
69
+
70
+ warmup_step = int(timesteps * warmup_ratio)
71
+ refresh_steps = torch.zeros(timesteps, dtype=torch.bool)
72
+ for step in range(timesteps):
73
+ if not use_cache or step <= warmup_step or (step-warmup_step) % refresh_interval == 0:
74
+ refresh_steps[step] = True
75
+ compute_ratio = 1 - cache_ratio
76
+
77
+ # Infer text vocabulary size
78
+ if text_vocab_size is None:
79
+ # call with a minimal input to get logits size
80
+ vocab_total = model(torch.zeros(1, 1, dtype=torch.long, device=device), infer=True).logits.size(-1)
81
+ text_vocab_size = vocab_total - codebook_size
82
+ vocab_offset = text_vocab_size
83
+
84
+ if debug:
85
+ print("=== generate_image debug start ===")
86
+ print(f"device={device}, seq_len={seq_len}, code_start={code_start}, codebook_size={codebook_size}")
87
+ print(f"text_vocab_size={text_vocab_size}, vocab_offset={vocab_offset}")
88
+ print(f"Initial x.shape={x.shape}, initial unknown_cnt={int(unknown_cnt.item())}")
89
+ print("==================================")
90
+
91
+ for step in range(timesteps):
92
+ if unknown_cnt.item() == 0:
93
+ if debug:
94
+ print(f"[step {step}] All tokens filled, breaking early.")
95
+ break
96
+
97
+ # Calculate number of tokens to keep (continue masking) this round
98
+ if step < timesteps - 1:
99
+ frac = noise_schedule(torch.tensor([(step + 1) / timesteps], device=device))
100
+ keep_n = (vq_len.float() * frac).floor().clamp_min(1).long()
101
+ else:
102
+ keep_n = torch.zeros_like(unknown_cnt)
103
+
104
+ if use_cache and step and refresh_steps[step]:
105
+ if isinstance(model, LLaDAForMultiModalGeneration):
106
+ model.empty_cache()
107
+ else: # DDP
108
+ model.module.empty_cache()
109
+
110
+ if debug:
111
+ print(f"\n--- step {step} ---")
112
+ print(f"unknown_cnt={int(unknown_cnt.item())}, keep_n={int(keep_n.item())}, refresh_step={bool(refresh_steps[step])}")
113
+ print(f"x.shape={x.shape}, vq_mask.sum()={int(vq_mask.sum().item())}")
114
+ # print a slice of tokens around code_start for visibility if code_start is set
115
+ if code_start is not None:
116
+ cs = code_start
117
+ sample_slice = x[0, cs:cs+min(50, x.shape[1]-cs)].detach().cpu().numpy().tolist()
118
+ print(f"x tokens at code_start (first 50): {sample_slice[:min(len(sample_slice), max_print_tokens)]}")
119
+
120
+ # Forward pass (with/without CFG)
121
+ if cfg_scale > 0:
122
+ # build uncond sequence
123
+ uncond = torch.cat((uncon_ids.to(x.device), x[:, code_start-2:]), axis=1)
124
+ uncond_vq_mask = torch.cat((torch.zeros((1, uncon_ids.size()[1]), dtype=torch.bool).to(x.device), vq_mask[:, code_start-2:]), axis=1)
125
+
126
+ # conditional logits
127
+ cond_out = model(x, infer=True, use_cache=use_cache)
128
+ cond_logits = cond_out.logits[..., vocab_offset : vocab_offset + codebook_size]
129
+ if debug:
130
+ print(f"cond_logits shape: {cond_logits.shape}")
131
+ cond_mask_logits = cond_logits[vq_mask].view(B, -1, codebook_size)
132
+ """
133
+ if debug:
134
+ print(f"cond_mask_logits shape (after vq_mask): {tuple(cond_mask_logits.shape)}")
135
+ # print few values
136
+ tmp = cond_mask_logits.detach().cpu().numpy()
137
+ flat_tmp = tmp.reshape(-1, tmp.shape[-1])
138
+ if flat_tmp.shape[0] > 0:
139
+ print("cond_mask_logits[first_row, first_10]:", flat_tmp[0, :min(10, flat_tmp.shape[1])].tolist())
140
+ """
141
+ # unconditional logits
142
+ uncond_out = model(uncond, infer=True, use_cache=use_cache)
143
+ uncond_logits = uncond_out.logits[..., vocab_offset : vocab_offset + codebook_size]
144
+ if debug:
145
+ print(f"uncond_logits shape: {uncond_logits.shape}")
146
+ uncond_mask_logits = uncond_logits[uncond_vq_mask].view(B, -1, codebook_size)
147
+ """
148
+ if debug:
149
+ print(f"uncond_mask_logits shape: {tuple(uncond_mask_logits.shape)}")
150
+ tmpu = uncond_mask_logits.detach().cpu().numpy()
151
+ if tmpu.size:
152
+ print("uncond_mask_logits[first_row, first_10]:", tmpu.reshape(-1, tmpu.shape[-1])[0, :min(10, tmpu.shape[-1])].tolist())
153
+ """
154
+ logits = (1 + cfg_scale) * cond_mask_logits - cfg_scale * uncond_mask_logits
155
+ if debug:
156
+ print(f"combined logits shape: {logits.shape}")
157
+
158
+ else:
159
+ out = model(x, infer=True)
160
+ # logits for masked positions: (B, num_masked, codebook_size)
161
+ # here we index directly by boolean mask along sequence dim
162
+ logits = out.logits[:, vq_mask[0], vocab_offset : vocab_offset + codebook_size]
163
+ if debug:
164
+ print(f"logits shape (no-cfg): {logits.shape}")
165
+ ltmp = logits.detach().cpu().numpy()
166
+ if ltmp.size:
167
+ print("logits[first_pos, first_10]:", ltmp[0, :min(10, ltmp.shape[1])].tolist() if ltmp.ndim == 2 else ltmp.reshape(-1, ltmp.shape[-1])[0, :min(10, ltmp.shape[-1])].tolist())
168
+
169
+ # sample
170
+ sampled = gumbel_max_sample(logits, temperature, generator=generator)
171
+ sampled_full = sampled + vocab_offset # bring to full token space
172
+ probs = torch.softmax(logits, dim=-1)
173
+ conf = probs.gather(-1, sampled.unsqueeze(-1)).squeeze(-1)
174
+
175
+ if debug:
176
+ print(f"sampled.shape={sampled.shape}, sampled_full.shape={sampled_full.shape}, conf.shape={conf.shape}")
177
+ # print some sampled tokens
178
+ sf_np = sampled_full.detach().cpu().numpy().reshape(-1).tolist()
179
+ print(f"sampled_full(first {min(len(sf_np), max_print_tokens)}): {sf_np[:min(len(sf_np), max_print_tokens)]}")
180
+
181
+ # write sampled tokens into x at masked positions
182
+ flat_idx = vq_mask.nonzero(as_tuple=False)[:, 1]
183
+ if debug:
184
+ print(f"flat_idx (masked positions indices) length={flat_idx.shape[0]}")
185
+ if flat_idx.numel() > 0:
186
+ print(f"flat_idx first 30: {flat_idx[:min(30, flat_idx.shape[0])].detach().cpu().numpy().tolist()}")
187
+
188
+ x.view(-1)[flat_idx] = sampled_full.view(-1)
189
+
190
+ # confidence map (for display / selection)
191
+ conf_map = torch.full_like(x, -math.inf, dtype=probs.dtype)
192
+ conf_map.view(-1)[flat_idx] = conf.view(-1)
193
+
194
+ if debug:
195
+ # show some stats of conf_map in code region
196
+ try:
197
+ conf_np = conf.detach().cpu().numpy().reshape(-1)
198
+ print(f"conf stats (min/mean/max): {float(conf_np.min()):.6f}/{float(conf_np.mean()):.6f}/{float(conf_np.max()):.6f}")
199
+ except Exception:
200
+ pass
201
+
202
+ # mask selection -> re-mask some tokens for next step
203
+ mask_sel = mask_by_random_topk(keep_n.squeeze(1), conf, temperature=temperature, generator=generator)
204
+ if debug:
205
+ print(f"mask_sel.shape={mask_sel.shape}, mask_sel.sum()={int(mask_sel.sum().item())}")
206
+ x.view(-1)[flat_idx[mask_sel.view(-1)]] = mask_token_id
207
+ vq_mask = x == mask_token_id
208
+ unknown_cnt = vq_mask.sum(dim=1, keepdim=True)
209
+
210
+ if debug:
211
+ print(f"after masking, vq_mask.sum()={int(vq_mask.sum().item())}, unknown_cnt={int(unknown_cnt.item())}")
212
+
213
+ # Save debug artifacts if requested
214
+ if debug and debug_log_dir:
215
+ step_base = os.path.join(debug_log_dir, f"step_{step}")
216
+ try:
217
+ np.save(step_base + "_x.npy", x.detach().cpu().numpy())
218
+ np.save(step_base + "_vq_mask.npy", vq_mask.detach().cpu().numpy())
219
+ # logits may be large; save as float32
220
+ np.save(step_base + "_logits.npy", logits.detach().cpu().numpy().astype(np.float32))
221
+ np.save(step_base + "_sampled_full.npy", sampled_full.detach().cpu().numpy())
222
+ except Exception as e:
223
+ print(f"[debug] failed to save debug npy at step {step}: {e}")
224
+
225
+ # Update cond/uncond compute masks for caching only if cfg_scale>0
226
+ if use_cache and step < timesteps - 1 and not refresh_steps[step+1] and cfg_scale > 0:
227
+ cond_conf = cond_logits.max(dim=-1)[0]
228
+ cond_conf_threshold = torch.quantile(cond_conf.to(torch.float), compute_ratio, dim=-1, keepdim=True)
229
+ cond_to_compute_mask = cond_conf <= cond_conf_threshold
230
+
231
+ uncond_conf = uncond_logits.max(dim=-1)[0]
232
+ uncond_conf_threshold = torch.quantile(uncond_conf.to(torch.float), compute_ratio, dim=-1, keepdim=True)
233
+ uncond_to_compute_mask = uncond_conf <= uncond_conf_threshold
234
+
235
+ if debug:
236
+ print(f"cond_conf shape: {cond_conf.shape}, threshold: {cond_conf_threshold.detach().cpu().numpy().tolist()}")
237
+ print(f"uncond_conf shape: {uncond_conf.shape}, threshold: {uncond_conf_threshold.detach().cpu().numpy().tolist()}")
238
+
239
+ # Remove newline tokens and shape properly
240
+ vq_ids = x[0, code_start:-2]
241
+ vq_ids = vq_ids[vq_ids != newline_id].view(1, seq_len)
242
+
243
+ if debug:
244
+ print("=== generate_image debug end ===")
245
+ print(f"final vq_ids.shape={vq_ids.shape}")
246
+ try:
247
+ print("final vq_ids first 100:", vq_ids.detach().cpu().numpy().reshape(-1)[:min(max_print_tokens, vq_ids.numel())].tolist())
248
+ except Exception:
249
+ pass
250
+
251
+ return vq_ids
generators/parallel_generator.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from tqdm import tqdm
4
+ import math
5
+ import numpy as np
6
+
7
+
8
+ def add_gumbel_noise(logits, temperature=1.0, generator=None):
9
+ """Add Gumbel noise to logits for sampling"""
10
+ if temperature == 0:
11
+ return logits
12
+
13
+ if generator is not None:
14
+ uniform_noise = torch.rand(logits.shape, dtype=logits.dtype, device=logits.device, generator=generator)
15
+ else:
16
+ uniform_noise = torch.rand_like(logits)
17
+
18
+ gumbel_noise = -torch.log(-torch.log(uniform_noise + 1e-10) + 1e-10)
19
+
20
+ return logits + temperature * gumbel_noise
21
+
22
+
23
+ def mask_by_random_topk(mask_len, probs, temperature=1.0, generator=None):
24
+ """
25
+ Mask tokens by random top-k selection based on confidence
26
+ probs: [batch, L] confidence scores (higher = more confident)
27
+ mask_len: tensor shape [batch, 1] or scalar, number of tokens to keep masked (lowest-confidence)
28
+ returns: boolean mask [batch, L] True where token should REMAIN masked
29
+ """
30
+ if generator is not None:
31
+ noise = torch.randn(probs.shape, dtype=probs.dtype, device=probs.device, generator=generator)
32
+ else:
33
+ noise = torch.randn_like(probs)
34
+
35
+ # Add small noise to jitter confidences according to temperature
36
+ confidence = torch.log(probs + 1e-10) + temperature * noise # higher = more confident
37
+
38
+ # We want to mask lowest-confidence tokens -> find cutoff
39
+ sorted_confidence, sorted_indices = torch.sort(confidence, dim=-1, descending=False) # ascending
40
+
41
+ # mask_len may be float or tensor; ensure integer per-batch
42
+ if isinstance(mask_len, torch.Tensor):
43
+ mask_len_clamped = torch.clamp(mask_len, 0, probs.shape[-1] - 1)
44
+ mask_len_clamped = mask_len_clamped.long().squeeze(-1) # shape [batch]
45
+ else:
46
+ mask_len_clamped = int(mask_len)
47
+
48
+ # Build boolean mask: True for tokens to KEEP masked (lowest confidence)
49
+ if isinstance(mask_len_clamped, torch.Tensor):
50
+ batch = probs.shape[0]
51
+ masking = torch.zeros_like(probs, dtype=torch.bool, device=probs.device)
52
+ for b in range(batch):
53
+ k = mask_len_clamped[b].item()
54
+ if k <= 0:
55
+ continue
56
+ low_idx = sorted_indices[b, :k] # indices of lowest k confidences
57
+ masking[b, low_idx] = True
58
+ else:
59
+ # scalar k
60
+ k = mask_len_clamped
61
+ if k <= 0:
62
+ masking = torch.zeros_like(probs, dtype=torch.bool, device=probs.device)
63
+ else:
64
+ low_idx = sorted_indices[:, :k]
65
+ masking = torch.zeros_like(probs, dtype=torch.bool, device=probs.device)
66
+ batch = probs.shape[0]
67
+ for b in range(batch):
68
+ masking[b, low_idx[b]] = True
69
+
70
+ return masking
71
+
72
+
73
+ def cosine_schedule(t):
74
+ """Cosine noise schedule"""
75
+ return torch.cos(t * math.pi / 2)
76
+
77
+
78
+ def get_num_transfer_tokens(text_masked_indices, text_steps):
79
+ """
80
+ Calculate number of tokens to unmask at each step
81
+ Returns: [batch_size, text_steps]
82
+ """
83
+ batch_size = text_masked_indices.shape[0]
84
+ initial_masks = text_masked_indices.sum(dim=1) # [batch_size]
85
+
86
+ num_transfer = torch.zeros(batch_size, text_steps, dtype=torch.long, device=text_masked_indices.device)
87
+
88
+ for b in range(batch_size):
89
+ total_masks = initial_masks[b].item()
90
+ remaining = total_masks
91
+
92
+ for step in range(text_steps):
93
+ ratio = (step + 1) / text_steps
94
+ target_remaining = int(total_masks * (1 - ratio))
95
+ tokens_to_unmask = max(0, remaining - target_remaining)
96
+ num_transfer[b, step] = tokens_to_unmask
97
+ remaining -= tokens_to_unmask
98
+
99
+ return num_transfer
100
+
101
+
102
+ def generate_ti2ti(
103
+ model,
104
+ input_ids,
105
+ text_start,
106
+ text_end,
107
+ image_start,
108
+ seq_len,
109
+ newline_every,
110
+ text_steps=100,
111
+ text_gen_length=256,
112
+ text_block_length=64,
113
+ timesteps=100,
114
+ temperature=1.0,
115
+ text_temperature=0.7,
116
+ cfg_scale=0.0,
117
+ cfg_img=4.0,
118
+ uncon_text=None,
119
+ uncon_image=None,
120
+ tokenizer=None,
121
+ remasking='low_confidence',
122
+ noise_schedule=cosine_schedule,
123
+ generator=None,
124
+ text_vocab_size=126356,
125
+ codebook_size=8192,
126
+ ):
127
+ """
128
+ Generate text and image jointly with interleaved generation.
129
+ Text generation uses cond logits only (text_cfg assumed 0).
130
+ Image generation (at scheduled steps) uses two CFGs:
131
+ - uncond_text (if provided) : guidance that relates to text part
132
+ - uncond_image (if provided): guidance that relates to image part
133
+ """
134
+
135
+ device = input_ids.device
136
+ MASK_TOKEN = 126336
137
+ NEW_LINE = 126084
138
+
139
+ # Clone input for modification
140
+ combined_input_ids = input_ids.clone()
141
+
142
+ # Calculate total image region length (including newlines)
143
+ num_vq_tokens = seq_len
144
+ total_image_len = seq_len + seq_len // newline_every
145
+ image_end = image_start + total_image_len
146
+
147
+ print(f"Interleaved generation: {text_steps} total steps")
148
+ print(f" - Text generation range: [{text_start}, {text_end})")
149
+ print(f" - Image generation range: [{image_start}, {image_end}) (total {total_image_len} including newlines)")
150
+ print(f" - VQ tokens: {num_vq_tokens}")
151
+
152
+ # Calculate number of tokens to unmask at each step for text
153
+ text_masked_indices = combined_input_ids[:, text_start:text_end] == MASK_TOKEN
154
+ num_transfer_tokens = get_num_transfer_tokens(text_masked_indices, text_steps)
155
+
156
+ # Schedule: when to perform image generation steps
157
+ image_generation_step_indices = torch.linspace(
158
+ text_steps // 4, text_steps - 1, timesteps
159
+ ).round().int().tolist()
160
+
161
+ print(f" - Image generation at steps: {image_generation_step_indices[:5]}...{image_generation_step_indices[-5:]}")
162
+
163
+ # Build position mapping for image (excluding newlines)
164
+ image_position_mapping = []
165
+ for i in range(image_start, image_end):
166
+ if combined_input_ids[0, i] != NEW_LINE:
167
+ image_position_mapping.append(i)
168
+
169
+ assert len(image_position_mapping) == num_vq_tokens, f"Expected {num_vq_tokens} VQ tokens, got {len(image_position_mapping)}"
170
+
171
+ batch_size = combined_input_ids.shape[0]
172
+
173
+ # ========== Interleaved Generation Loop ==========
174
+ for step in tqdm(range(text_steps), desc="Interleaved generation"):
175
+
176
+ # ===== Forward pass: compute conditional logits once per step =====
177
+ with torch.no_grad():
178
+ cond_logits = model(combined_input_ids, infer=True, use_cache=False).logits # [B, L, V]
179
+
180
+ # ===== Text Generation Step (no CFG for text; use cond_logits directly) =====
181
+ text_masked_indices = combined_input_ids[:, text_start:text_end] == MASK_TOKEN
182
+
183
+ if text_masked_indices.sum() > 0:
184
+ # Extract text logits from cond (no guidance)
185
+ text_logits = cond_logits[:, text_start:text_end, :]
186
+
187
+ # Apply temperature & gumbel
188
+ logits_with_noise = add_gumbel_noise(text_logits, temperature=text_temperature, generator=generator)
189
+ x0 = torch.argmax(logits_with_noise, dim=-1) # [B, text_len]
190
+
191
+ # Compute confidence for remasking
192
+ if remasking == 'low_confidence':
193
+ p = F.softmax(text_logits.to(torch.float64), dim=-1)
194
+ x0_p = torch.squeeze(torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # [B, text_len]
195
+ elif remasking == 'random':
196
+ if generator is not None:
197
+ x0_p = torch.rand(x0.shape, dtype=x0.dtype, device=x0.device, generator=generator)
198
+ else:
199
+ x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
200
+ else:
201
+ raise NotImplementedError(remasking)
202
+
203
+ # keep already-unmasked tokens
204
+ x0 = torch.where(text_masked_indices, x0, combined_input_ids[:, text_start:text_end])
205
+ confidence = torch.where(text_masked_indices, x0_p, -np.inf)
206
+
207
+ # Select tokens to unmask based on confidence (top-k per batch element)
208
+ transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
209
+ for j in range(confidence.shape[0]):
210
+ k = num_transfer_tokens[j, step].item()
211
+ if k > 0:
212
+ _, select_index = torch.topk(confidence[j], k=k)
213
+ transfer_index[j, select_index] = True
214
+
215
+ # Unmask selected tokens into combined_input_ids
216
+ # Note: transfer_index is [B, text_len] boolean; place into full combined_input_ids
217
+ combined_input_ids[:, text_start:text_end][transfer_index] = x0[transfer_index]
218
+
219
+ # ===== Image Generation Step (scheduled) =====
220
+ if step in image_generation_step_indices:
221
+ # Build vq token list from current combined_input_ids (placeholder -1 for masked)
222
+ vq_tokens_list = []
223
+ for pos in image_position_mapping:
224
+ token = combined_input_ids[0, pos].item()
225
+ if token == MASK_TOKEN:
226
+ vq_tokens_list.append(-1)
227
+ else:
228
+ vq_token = token - text_vocab_size
229
+ vq_token = max(0, min(vq_token, codebook_size - 1))
230
+ vq_tokens_list.append(vq_token)
231
+
232
+ vq_tokens_tensor = torch.tensor(vq_tokens_list, device=device).unsqueeze(0) # [1, num_vq_tokens]
233
+ unknown_map = vq_tokens_tensor == -1 # True where masked
234
+
235
+ # Extract cond_vq_logits from cond_logits (for VQ positions and vocab offset)
236
+ cond_image_logits_list = []
237
+ for pos in image_position_mapping:
238
+ cond_image_logits_list.append(cond_logits[:, pos:pos+1, text_vocab_size:text_vocab_size+codebook_size])
239
+ cond_vq_logits = torch.cat(cond_image_logits_list, dim=1) # [B, num_vq_tokens, codebook_size]
240
+
241
+ # Prepare uncond logits only when needed (for image CFG)
242
+ # Create combined_uncond_text and combined_uncond_img by replacing prefix with uncon_text/uncon_image
243
+ if (cfg_scale > 0.0 and uncon_text is not None) or (cfg_img > 0.0 and uncon_image is not None):
244
+ # clone base input
245
+ # IMPORTANT: uncon_text/uncon_image expected to be on the same device or will be moved
246
+ # If uncon_text / uncon_image is None, create copies to avoid errors
247
+ if uncon_text is None:
248
+ combined_uncond_text = combined_input_ids.clone()
249
+ else:
250
+ combined_uncond_text = combined_input_ids.clone()
251
+ prefix_len = uncon_text.shape[1]
252
+ combined_uncond_text[:, :prefix_len] = uncon_text.to(device)
253
+
254
+ if uncon_image is None:
255
+ combined_uncond_img = combined_input_ids.clone()
256
+ else:
257
+ combined_uncond_img = combined_input_ids.clone()
258
+ prefix_len_img = uncon_image.shape[1]
259
+ combined_uncond_img[:, :prefix_len_img] = uncon_image.to(device)
260
+
261
+ # Forward for unconds
262
+ with torch.no_grad():
263
+ uncond_text_logits_full = model(combined_uncond_text, infer=True, use_cache=False).logits
264
+ uncond_img_logits_full = model(combined_uncond_img, infer=True, use_cache=False).logits
265
+
266
+ # Extract VQ ranges for each image position
267
+ uncond_text_vq_list = []
268
+ uncond_img_vq_list = []
269
+ for pos in image_position_mapping:
270
+ uncond_text_vq_list.append(uncond_text_logits_full[:, pos:pos+1, text_vocab_size:text_vocab_size+codebook_size])
271
+ uncond_img_vq_list.append(uncond_img_logits_full[:, pos:pos+1, text_vocab_size:text_vocab_size+codebook_size])
272
+
273
+ uncond_text_vq_logits = torch.cat(uncond_text_vq_list, dim=1) # [B, num_vq_tokens, codebook_size]
274
+ uncond_img_vq_logits = torch.cat(uncond_img_vq_list, dim=1) # [B, num_vq_tokens, codebook_size]
275
+ else:
276
+ # no unconds provided or scales are zero -> set uncond logits to zeros so (cond - 0) works if used
277
+ uncond_text_vq_logits = torch.zeros_like(cond_vq_logits)
278
+ uncond_img_vq_logits = torch.zeros_like(cond_vq_logits)
279
+
280
+ # Compose guided image logits:
281
+ # image_logits = cond_vq + cfg_scale * (cond_vq - uncond_text_vq) + cfg_img * (cond_vq - uncond_img_vq)
282
+ if cfg_scale == 0.0 and cfg_img == 0.0:
283
+ image_logits = cond_vq_logits
284
+ else:
285
+ image_logits = cond_vq_logits
286
+ if cfg_scale != 0.0:
287
+ image_logits = image_logits + cfg_scale * (cond_vq_logits - uncond_text_vq_logits)
288
+ if cfg_img != 0.0:
289
+ image_logits = image_logits + cfg_img * (cond_vq_logits - uncond_img_vq_logits)
290
+
291
+ # Sample from image_logits
292
+ probs = F.softmax(image_logits, dim=-1) # [B, num_vq, codebook]
293
+
294
+ if temperature == 0:
295
+ sampled_ids = probs.argmax(dim=-1)
296
+ else:
297
+ # flatten batch*num_vq x vocab for multinomial
298
+ sampled = probs.reshape(-1, image_logits.size(-1))
299
+ if generator is not None:
300
+ sampled_ids = torch.multinomial(sampled, 1, generator=generator)[:, 0].view(*image_logits.shape[:-1])
301
+ else:
302
+ sampled_ids = torch.multinomial(sampled, 1)[:, 0].view(*image_logits.shape[:-1])
303
+
304
+ # Keep already-unmasked tokens unchanged
305
+ sampled_ids = torch.where(unknown_map, sampled_ids, vq_tokens_tensor)
306
+
307
+ # Clamp safety
308
+ sampled_ids = torch.clamp(sampled_ids, 0, codebook_size - 1)
309
+
310
+ # Confidence for sampled tokens
311
+ selected_probs = torch.gather(probs, -1, sampled_ids.long()[..., None]).squeeze(-1) # [B, num_vq]
312
+
313
+ # If token was previously unmasked, give it very high confidence so we don't remask it
314
+ high_val = torch.finfo(selected_probs.dtype).max
315
+ selected_probs = torch.where(unknown_map, selected_probs, high_val)
316
+
317
+ # Masking ratio and mask_len calculation
318
+ ratio = 1.0 * (step + 1) / text_steps
319
+ mask_ratio = noise_schedule(torch.tensor(ratio, device=device))
320
+ # compute how many tokens to keep masked (lowest confidences)
321
+ unknown_counts = unknown_map.sum(dim=-1, keepdim=True) # [B,1]
322
+ mask_len = (num_vq_tokens * mask_ratio).floor().unsqueeze(0).to(device) # shape [1,] maybe
323
+ # clamp mask_len to [1, unknown_counts-1]
324
+ mask_len = torch.max(torch.tensor([1], device=device), torch.min(unknown_counts - 1, mask_len.to(device).long()))
325
+ # ensure shape [B,1]
326
+ if mask_len.ndim == 1:
327
+ mask_len = mask_len.unsqueeze(1)
328
+
329
+ # temperature decay for image sampling (optional)
330
+ img_temp = temperature * (1.0 - ratio)
331
+
332
+ # masking boolean: True where should remain masked
333
+ masking = mask_by_random_topk(mask_len, selected_probs, img_temp, generator=generator)
334
+
335
+ # final_vq_tokens: -1 means remain masked, else sampled id
336
+ final_vq_tokens = torch.where(masking, torch.tensor(-1, device=device), sampled_ids)
337
+
338
+ # Write back into combined_input_ids (convert vq id -> full vocab id by adding offset)
339
+ for idx, pos in enumerate(image_position_mapping):
340
+ v = final_vq_tokens[0, idx].item()
341
+ if v == -1:
342
+ combined_input_ids[0, pos] = MASK_TOKEN
343
+ else:
344
+ combined_input_ids[0, pos] = int(v + text_vocab_size)
345
+
346
+ # ===== Extract final results =====
347
+ # Extract text tokens
348
+ text_tokens = combined_input_ids[0, text_start:text_end].cpu().tolist()
349
+ text_tokens = [t for t in text_tokens if t != MASK_TOKEN]
350
+ generated_text = tokenizer.decode(text_tokens, skip_special_tokens=True) if tokenizer is not None else text_tokens
351
+
352
+ # Extract image VQ tokens
353
+ image_tokens = []
354
+ for pos in image_position_mapping:
355
+ token = combined_input_ids[0, pos].item()
356
+ if token != MASK_TOKEN:
357
+ vq_token = token - text_vocab_size
358
+ vq_token = max(0, min(vq_token, codebook_size - 1))
359
+ image_tokens.append(vq_token)
360
+ else:
361
+ # still masked -> sample randomly
362
+ image_tokens.append(int(torch.randint(0, codebook_size, (1,)).item()))
363
+
364
+ print(f"Interleaved generation complete.")
365
+ print(f" - Generated text: {len(text_tokens)} tokens")
366
+ print(f" - Generated image: {len(image_tokens)} VQ tokens (range [0, {codebook_size}))")
367
+
368
+ return image_tokens, generated_text
inference.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
5
+
6
+ import argparse
7
+ import time
8
+ import math
9
+ from PIL import Image
10
+ import torch
11
+ from transformers import AutoTokenizer
12
+ from model import LLaDAForMultiModalGeneration
13
+ from utils.generation_utils import setup_seed
14
+ from utils.image_utils import (
15
+ preprocess_image, decode_vq_to_image, calculate_vq_params,
16
+ generate_crop_size_list, var_center_crop, add_break_line, encode_img_with_breaks,
17
+ encode_img_with_paint
18
+ )
19
+ from generators.parallel_generator import generate_ti2ti
20
+ from utils.prompt_utils import generate_text_image_to_text_image_prompt
21
+
22
+ SPECIAL_TOKENS = {
23
+ "mask_token": 126336,
24
+ "newline_token": 126084,
25
+ "image_token_offset": 126356,
26
+ "answer_start": 126354,
27
+ "answer_end": 126355,
28
+ "boi": 126349,
29
+ "eoi": 126350,
30
+ "uncondition": 126351
31
+ }
32
+ SYSTEM_PROMPT = (
33
+ "Generate an image applying the following editing instruction based on the original image."
34
+ )
35
+
36
+
37
+ def cosine_schedule(t):
38
+ return torch.cos(t * math.pi / 2)
39
+
40
+
41
+ def main():
42
+ parser = argparse.ArgumentParser(description="Text+Image to Text+Image inference (TI2TI)")
43
+ parser.add_argument("--checkpoint", type=str, required=True, help="Fine-tuned checkpoint path")
44
+ parser.add_argument("--prompt", type=str, required=True, help="Text prompt for editing")
45
+ parser.add_argument("--image_path", type=str, required=True, help="Input image path")
46
+ parser.add_argument("--height", type=int, default=512, help="Output image height")
47
+ parser.add_argument("--width", type=int, default=512, help="Output image width")
48
+ parser.add_argument("--timesteps", type=int, default=64, help="Number of diffusion timesteps")
49
+ parser.add_argument("--text_steps", type=int, default=256, help="Number of text generation steps")
50
+ parser.add_argument("--text_gen_length", type=int, default=256, help="Maximum text generation length")
51
+ parser.add_argument("--text_block_length", type=int, default=32, help="Text generation block length")
52
+ parser.add_argument("--cfg_scale", type=float, default=2.5, help="CFG scale for text")
53
+ parser.add_argument("--cfg_img", type=float, default=4.0, help="CFG scale for image")
54
+ parser.add_argument("--temperature", type=float, default=1.0, help="Sampling temperature")
55
+ parser.add_argument("--text_temperature", type=float, default=0.7, help="Text generation temperature")
56
+ parser.add_argument("--seed", type=int, default=0, help="Random seed")
57
+ parser.add_argument("--vae_ckpt", type=str, required=True, help="VAE checkpoint path")
58
+ parser.add_argument("--output_dir", type=str, default="results_ti2ti", help="Output directory")
59
+ parser.add_argument("--remasking", type=str, default="low_confidence",
60
+ choices=["low_confidence", "random"],
61
+ help="Remasking strategy")
62
+ parser.add_argument("--painting_mode", type=str, default=None, help="If set, use painting-mode encoding")
63
+ parser.add_argument("--mask_h_ratio", type=float, default=0.5, help="mask height ratio for painting mode")
64
+ parser.add_argument("--mask_w_ratio", type=float, default=0.5, help="mask width ratio for painting mode")
65
+ parser.add_argument("--debug_tokens", action="store_true", help="Print token debug info to verify sequence layout")
66
+ args = parser.parse_args()
67
+
68
+ MASK = SPECIAL_TOKENS["mask_token"]
69
+ NEW_LINE = SPECIAL_TOKENS["newline_token"]
70
+ BOA = SPECIAL_TOKENS["answer_start"]
71
+ EOA = SPECIAL_TOKENS["answer_end"]
72
+ BOI = SPECIAL_TOKENS["boi"]
73
+ EOI = SPECIAL_TOKENS["eoi"]
74
+
75
+ if args.seed != 0:
76
+ setup_seed(args.seed)
77
+
78
+ os.makedirs(args.output_dir, exist_ok=True)
79
+
80
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
81
+ print(f"Loading model from {args.checkpoint}...")
82
+ tokenizer = AutoTokenizer.from_pretrained(args.checkpoint, trust_remote_code=True)
83
+ model = LLaDAForMultiModalGeneration.from_pretrained(
84
+ args.checkpoint, torch_dtype=torch.bfloat16, device_map="auto",
85
+ )
86
+
87
+ config = model.config
88
+ text_vocab_size = getattr(config, 'text_vocab_size', 126356)
89
+ codebook_size = getattr(config, 'codebook_size', 8192)
90
+
91
+ print(f"Vocabulary config: text_vocab_size={text_vocab_size}, codebook_size={codebook_size}")
92
+
93
+ print(f"Loading VQ-VAE from {args.vae_ckpt}...")
94
+ from diffusers import VQModel
95
+ vqvae = VQModel.from_pretrained(args.vae_ckpt, subfolder="vqvae").to(device)
96
+ vae_scale = 2 ** (len(vqvae.config.block_out_channels) - 1)
97
+
98
+ prompt_text = args.prompt
99
+ input_image_path = args.image_path
100
+
101
+ print(f"\n{'='*80}")
102
+ print(f"TI2TI Generation")
103
+ print(f"{'='*80}")
104
+ print(f"Input image: {input_image_path}")
105
+ print(f"Prompt: {prompt_text}")
106
+ print(f"Output size: {args.height}x{args.width}")
107
+ print(f"{'='*80}\n")
108
+
109
+ input_prompt, uncon_text = generate_text_image_to_text_image_prompt(
110
+ prompt_text, SYSTEM_PROMPT
111
+ )
112
+
113
+ print("Conditioning prompt:\n", input_prompt)
114
+ if args.debug_tokens:
115
+ print("Unconditional text prompt (first 200 chars):", uncon_text[:200])
116
+
117
+ prompt_ids = tokenizer(input_prompt)["input_ids"]
118
+ uncon_text_ids = tokenizer(uncon_text)["input_ids"]
119
+
120
+ img = Image.open(input_image_path).convert("RGB")
121
+ crop_size_list = generate_crop_size_list((512 // 32) ** 2, 32)
122
+ img = var_center_crop(img, crop_size_list=crop_size_list)
123
+
124
+ input_image_width, input_image_height = img.size
125
+
126
+ print("Encoding input image for conditioning...")
127
+ input_img_token = encode_img_with_breaks(img, vqvae)
128
+
129
+ con_input_list = prompt_ids[:-1] + input_img_token + prompt_ids[-1:]
130
+ uncon_input_text = uncon_text_ids[:-1] + input_img_token + uncon_text_ids[-1:]
131
+ uncon_input_image = prompt_ids
132
+
133
+ output_image_height = args.height
134
+ output_image_width = args.width
135
+ seq_len, newline_every, token_grid_height, token_grid_width = calculate_vq_params(
136
+ output_image_height, output_image_width, vae_scale
137
+ )
138
+
139
+ text_mask_tokens = [MASK] * args.text_gen_length
140
+
141
+ if args.painting_mode:
142
+ img_mask_token, img_vis = encode_img_with_paint(
143
+ img, vqvae=vqvae, mask_h_ratio=args.mask_h_ratio, mask_w_ratio=args.mask_w_ratio, mask_mode=args.painting_mode
144
+ )
145
+ else:
146
+ img_mask_token = add_break_line([MASK] * seq_len, token_grid_height, token_grid_width, new_number=NEW_LINE)
147
+
148
+ end_token_ids = tokenizer("</answer>", add_special_tokens=False).input_ids
149
+
150
+ pred_token = [BOA] + [BOI] + img_mask_token + [EOI] + text_mask_tokens + end_token_ids
151
+
152
+ code_start = len(con_input_list)
153
+ image_start = len(con_input_list) + 2
154
+ image_end = image_start + len(img_mask_token)
155
+ text_start = image_end + 1
156
+ text_end = text_start + args.text_gen_length
157
+
158
+ full_input_ids = con_input_list + pred_token
159
+ con_input = torch.tensor(full_input_ids, device=device).unsqueeze(0)
160
+ uncon_input_text = torch.tensor(uncon_input_text, device=device).unsqueeze(0)
161
+ uncon_input_image = torch.tensor(uncon_input_image, device=device).unsqueeze(0)
162
+ start_time = time.time()
163
+
164
+ if args.seed != 0:
165
+ generator = torch.Generator(device=device).manual_seed(args.seed)
166
+ else:
167
+ generator = None
168
+
169
+ output_tokens, generated_text = generate_ti2ti(
170
+ model=model,
171
+ input_ids=con_input,
172
+ text_start=text_start,
173
+ text_end=text_end,
174
+ image_start=image_start,
175
+ seq_len=seq_len,
176
+ newline_every=newline_every,
177
+ text_steps=args.text_steps,
178
+ text_gen_length=args.text_gen_length,
179
+ text_block_length=args.text_block_length,
180
+ timesteps=args.timesteps,
181
+ temperature=args.temperature,
182
+ text_temperature=args.text_temperature,
183
+ cfg_scale=args.cfg_scale,
184
+ cfg_img=args.cfg_img,
185
+ uncon_text=uncon_input_text,
186
+ uncon_image=uncon_input_image,
187
+ tokenizer=tokenizer,
188
+ remasking=args.remasking,
189
+ noise_schedule=cosine_schedule,
190
+ generator=generator,
191
+ text_vocab_size=text_vocab_size,
192
+ codebook_size=codebook_size,
193
+ )
194
+
195
+ end_time = time.time()
196
+ elapsed_time = end_time - start_time
197
+
198
+ print(f"\n{'='*80}")
199
+ print(f"Generated thinking/text output:")
200
+ print(f"{'='*80}")
201
+ print(generated_text)
202
+ print(f"{'='*80}\n")
203
+
204
+ print(f"Converting {len(output_tokens)} VQ tokens to tensor...")
205
+ output_tokens_tensor = torch.tensor(output_tokens, dtype=torch.long, device=device).unsqueeze(0)
206
+
207
+ print(f"VQ tokens range: [{min(output_tokens)}, {max(output_tokens)}]")
208
+
209
+ words = (prompt_text or "").split()
210
+ filename_words = words[:10] if len(words) > 10 else words
211
+ filename = "_".join(filename_words)
212
+ filename = "".join(c for c in filename if c.isalnum() or c in ('_', '-'))
213
+ filename = f"{filename}_{output_image_height}x{output_image_width}_t{args.timesteps}_cfg{args.cfg_scale}_ti2ti.png"
214
+
215
+ save_path = os.path.join(args.output_dir, filename)
216
+
217
+ print("Decoding image...")
218
+ out_img = decode_vq_to_image(
219
+ output_tokens_tensor,
220
+ save_path,
221
+ vae_ckpt=args.vae_ckpt,
222
+ image_height=output_image_height,
223
+ image_width=output_image_width,
224
+ vqvae=vqvae
225
+ )
226
+
227
+ w1, h1 = img.size
228
+ w2, h2 = out_img.size
229
+ canvas = Image.new("RGB", (w1 + w2, max(h1, h2)), "white")
230
+ canvas.paste(img, (0, 0))
231
+ canvas.paste(out_img, (w1, 0))
232
+ concat_path = save_path.replace(".png", "_concat.png")
233
+ canvas.save(concat_path)
234
+
235
+ text_path = save_path.replace(".png", "_thinking.txt")
236
+ with open(text_path, "w", encoding="utf-8") as f:
237
+ f.write(f"{generated_text}\n")
238
+
239
+ print(f"\n[✓] Image saved to: {concat_path}")
240
+ print(f"[✓] Text saved to: {text_path}")
241
+ print(f"[✓] Total time: {elapsed_time:.2f}s")
242
+
243
+
244
+ if __name__ == '__main__':
245
+ main()
model/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .modeling_xllmx_dimoo import LLaDAForMultiModalGeneration
model/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (271 Bytes). View file
 
model/__pycache__/configuration_llada.cpython-311.pyc ADDED
Binary file (9.27 kB). View file
 
model/__pycache__/modeling_llada.cpython-311.pyc ADDED
Binary file (78.2 kB). View file
 
model/__pycache__/modeling_xllmx_dimoo.cpython-311.pyc ADDED
Binary file (11.8 kB). View file
 
model/configuration_llada.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LLaDA configuration
3
+ """
4
+ from transformers import AutoConfig, PretrainedConfig
5
+
6
+ from enum import Enum
7
+ from os import PathLike
8
+ from typing import Union
9
+ from dataclasses import asdict, dataclass, field
10
+ from glob import glob
11
+ from pathlib import Path
12
+ from typing import (
13
+ Any,
14
+ Dict,
15
+ Iterable,
16
+ List,
17
+ Optional,
18
+ Tuple,
19
+ Type,
20
+ TypeVar,
21
+ Union,
22
+ cast,
23
+ )
24
+
25
+
26
+ __all__ = [
27
+ "ActivationType",
28
+ "ActivationCheckpointingStrategy",
29
+ "BlockType",
30
+ "LayerNormType",
31
+ "InitFnType",
32
+ "ModelConfig",
33
+ ]
34
+
35
+ PathOrStr = Union[str, PathLike]
36
+
37
+
38
+ class StrEnum(str, Enum):
39
+ """
40
+ This is equivalent to Python's :class:`enum.StrEnum` since version 3.11.
41
+ We include this here for compatibility with older version of Python.
42
+ """
43
+
44
+ def __str__(self) -> str:
45
+ return self.value
46
+
47
+ def __repr__(self) -> str:
48
+ return f"'{str(self)}'"
49
+
50
+
51
+ class LayerNormType(StrEnum):
52
+ default = "default"
53
+ """
54
+ The default LayerNorm implementation, equivalent to PyTorch's built-in version.
55
+ """
56
+
57
+ low_precision = "low_precision"
58
+ """
59
+ A low-precision version of the default LayerNorm.
60
+ """
61
+
62
+ rms = "rms"
63
+ """
64
+ An RMSNorm implementation. When using ``torch.compile`` this is
65
+ probably the fastest implementation.
66
+ """
67
+
68
+ gemma_rms = "gemma_rms"
69
+ """
70
+ An RMSNorm implementation by gemmma. When using ``torch.compile`` this is
71
+ probably the fastest implementation.
72
+ """
73
+
74
+ amd_compatible = "amd_compatible"
75
+ """
76
+ LayerNorm implemented manually to work around an issue with ROCm.
77
+ """
78
+
79
+
80
+ class ActivationType(StrEnum):
81
+ gelu = "gelu"
82
+ relu = "relu"
83
+ silu = "silu"
84
+ swiglu = "swiglu"
85
+
86
+
87
+ class BlockType(StrEnum):
88
+ sequential = "sequential"
89
+ parallel = "parallel"
90
+
91
+ llama = "llama"
92
+ """
93
+ A block similar to the sequential block with slightly different
94
+ implementations of operations like attention to imitate the behavior of Llama.
95
+ """
96
+
97
+
98
+ class InitFnType(StrEnum):
99
+ mitchell = "mitchell"
100
+ """
101
+ The strategy suggested to us by Mitchell Wortsman from UW.
102
+ This uses a truncated normal distribution with an adaptive standard deviation that depends
103
+ on the size of the weights as well as the depth of the layer.
104
+ """
105
+
106
+ normal = "normal"
107
+ """
108
+ All weights are initialized from the same normal distribution.
109
+ """
110
+
111
+ kaiming_normal = "kaiming_normal"
112
+ """
113
+ All weights are initialized with the Kaiming method from a normal distribution.
114
+ Note this currently won't work with FSDP.
115
+ """
116
+
117
+ fan_in = "fan_in"
118
+ """
119
+ "Fan-in variance scaling", i.e. normal with a standard deviation of ``1/sqrt(d_in)`` where ``d_in``
120
+ is the input dimensionality of the kernel.
121
+ """
122
+
123
+ full_megatron = "full_megatron"
124
+ """
125
+ This is what metaseq calls "full megatron init". It is the init used for Llama 2.
126
+ """
127
+
128
+
129
+ @dataclass
130
+ class ModelConfig():
131
+ """
132
+ LLaDA (model) configuration.
133
+ """
134
+
135
+ # Note that the defaults for these attributes are equivalent to the base GPT2 model.
136
+
137
+ d_model: int = 768
138
+ """
139
+ The hidden size of the model.
140
+ """
141
+
142
+ n_heads: int = 12
143
+ """
144
+ The number of self-attention heads.
145
+ """
146
+
147
+ n_kv_heads: Optional[int] = None
148
+ """
149
+ The number of heads to use for keys and values. Defaults to `n_heads`.
150
+ Set this to ``None`` or ``n_heads`` for normal multi-head attention.
151
+ Set this to 1 for multi-query attention.
152
+ Set it to some in-between value for Llama2-style grouped query attention.
153
+ """
154
+
155
+ n_layers: int = 12
156
+ """
157
+ The number of layers/blocks.
158
+ """
159
+
160
+ mlp_ratio: int = 4
161
+ """
162
+ The ratio of the inner MLP dimensionality to ``d_model``.
163
+ This is only used when ``mlp_hidden_size`` is not set.
164
+ """
165
+
166
+ mlp_hidden_size: Optional[int] = None
167
+ """
168
+ Set the exact hidden size for the MLP. Otherwise the inner MLP hidden size will be set to `mlp_ratio * d_model`.
169
+ """
170
+
171
+ activation_type: ActivationType = ActivationType.swiglu
172
+ """
173
+ The activation function to use within the MLP layers.
174
+ """
175
+
176
+ block_type: BlockType = BlockType.sequential
177
+ """
178
+ The transformer block implementation.
179
+ """
180
+
181
+ block_group_size: int = 1
182
+ """
183
+ The number of blocks to group together into a single parent block.
184
+ This has no affect on the number of parameters in the model and is only used to wrap groups
185
+ of blocks together with a single FSDP wrapper during training.
186
+ """
187
+
188
+ alibi: bool = False
189
+ """
190
+ If ``True``, use ALiBi embeddings. Mutually exclusive with ``rope``.
191
+ """
192
+
193
+ alibi_bias_max: float = 8.0
194
+ """
195
+ Maximum absolute value of ALiBi bias.
196
+ """
197
+
198
+ rope: bool = False
199
+ """
200
+ Use rotary positional embeddings (RoPE). Mutually exclusive with ``alibi``.
201
+ """
202
+
203
+ rope_full_precision: bool = True
204
+ """
205
+ If ``True``, apply RoPE embeddings at full precision regardless of the input type. Otherwise,
206
+ apply RoPE at the precision of the input.
207
+ """
208
+
209
+ flash_attention: bool = False
210
+ """
211
+ If ``True``, use ``FlashAttention``.
212
+ """
213
+
214
+ attention_dropout: float = 0.1
215
+ """
216
+ The dropout probability within the attention modules.
217
+ """
218
+
219
+ multi_query_attention: Optional[bool] = None
220
+ """
221
+ Use the Multi-Query formulation of attention used in PaLM. This reduces the number of parameters
222
+ and is more efficient during inference.
223
+ """
224
+
225
+ attention_layer_norm: bool = False
226
+ """
227
+ Apply layer norm to the keys and queries within the attention mechanism.
228
+ This can help stabilize training.
229
+ """
230
+
231
+ residual_dropout: float = 0.1
232
+ """
233
+ The dropout probability for the MLP and attention output within each block.
234
+ """
235
+
236
+ embedding_dropout: float = 0.1
237
+ """
238
+ The dropout probability for embeddings.
239
+ """
240
+
241
+ input_emb_norm: bool = False
242
+ """
243
+ An input hidden_states norm implementation by gemmma.
244
+ """
245
+
246
+ layer_norm_type: LayerNormType = LayerNormType.default
247
+ """
248
+ The layernorm implementation to use.
249
+ """
250
+
251
+ layer_norm_with_affine: bool = True
252
+ """
253
+ Whether to include bias and weight parameters for the layer norms.
254
+ This only affects layer norms that are immediately followed by a linear layer in the forward pass,
255
+ so everything except QK-norms. To turn off affines for QK norms as well, set :attr:`attention_layer_norm_with_affine`
256
+ to ``False``.
257
+ """
258
+
259
+ rms_norm_eps: float = 1e-05
260
+ """
261
+ The rms layernorm eps param.
262
+ """
263
+
264
+ attention_layer_norm_with_affine: bool = True
265
+ """
266
+ Toggle affine transform for the QK norms.
267
+ """
268
+
269
+ max_sequence_length: int = 1024
270
+ """
271
+ The maximum input sequence length supported by the model.
272
+ """
273
+
274
+ rope_theta: float = 10000.0
275
+ """
276
+ The rope base param.
277
+ """
278
+
279
+ include_qkv_bias: Optional[bool] = False
280
+ """
281
+ Whether or not to include bias parameters in qkv linear layers.
282
+ """
283
+
284
+ include_bias: bool = False
285
+ """
286
+ Whether or not to include bias parameters in linear layers.
287
+ In PaLM, they got rid of all bias terms because they found that large
288
+ models tend to have near 0 bias terms anyway.
289
+ """
290
+
291
+ bias_for_layer_norm: Optional[bool] = None
292
+ """
293
+ Whether or not to include bias parameters in layer norm.
294
+ This is separate from the include_bias parameter, because of a ROCm crash when biases are disabled in
295
+ layer norm.
296
+ When this is None (the default), it inherits the setting from include_bias.
297
+ """
298
+
299
+ scale_logits: bool = False
300
+ """
301
+ If ``True``, scale the output logits by ``1 / sqrt(d_model)``.
302
+ """
303
+
304
+ vocab_size: int = 50257
305
+ """
306
+ Vocabulary size of the model.
307
+ """
308
+
309
+ embedding_size: Optional[int] = 50304
310
+ """
311
+ The number of embeddings, i.e. the number of tokens. If set to ``None`` it will default
312
+ to ``vocab_size``. If ``vocab_size`` is not a multiple of 128, setting this to the
313
+ next multiple of 128 that's greater than ``vocab_size`` can improve throughput
314
+ substantially.
315
+ """
316
+
317
+ weight_tying: bool = True
318
+ """
319
+ Whether to tie output linear weights to the input embedding.
320
+ """
321
+
322
+ eos_token_id: int = 50256
323
+ """
324
+ The ID of the end-of-sentence special token.
325
+ """
326
+
327
+ pad_token_id: int = 50256
328
+ """
329
+ The ID of the token to use for padding. Defaults to the ID of the EOS token.
330
+ """
331
+
332
+ mask_token_id: Optional[int] = 50256
333
+ """
334
+ The ID of the token to use for mask token. Defaults to the ID of the EOS token.
335
+ """
336
+
337
+ init_device: Optional[str] = None
338
+ """
339
+ The torch device to use when initializing the model parameters, e.g. "cpu", "cuda:0", "meta".
340
+ """
341
+
342
+ init_fn: InitFnType = InitFnType.normal
343
+ """
344
+ The weight initialization strategy.
345
+ """
346
+
347
+ init_std: float = 0.02
348
+ """
349
+ The standard deviation to use when initializing weights with a "fixed distribution" ``init_fn``, such
350
+ as "normal".
351
+ """
352
+
353
+ init_cutoff_factor: Optional[float] = None
354
+ """
355
+ A positive factor used to scale the cutoff values when initializing weights with a "fixed distribution" ``init_fn``, such
356
+ as "normal". Setting this to None means values are not cutoff.
357
+ """
358
+
359
+ precision: Optional[str] = None
360
+ """
361
+ Precision used to train/evaluate with. You shouldn't set this directly.
362
+ See :data:`TrainConfig.precision` instead.
363
+ """
364
+
365
+ @property
366
+ def effective_n_kv_heads(self) -> int:
367
+ if self.n_kv_heads is None:
368
+ if self.multi_query_attention is True:
369
+ return 1
370
+ else:
371
+ return self.n_heads
372
+ else:
373
+ if self.multi_query_attention is None:
374
+ return self.n_kv_heads
375
+ if self.multi_query_attention:
376
+ n_kv_heads_should_be = 1
377
+ else:
378
+ n_kv_heads_should_be = self.n_heads
379
+ if self.n_kv_heads == n_kv_heads_should_be:
380
+ return n_kv_heads_should_be
381
+ else:
382
+ raise Exception(
383
+ "You can't set `multi_query_attention` and `n_kv_heads` at the same time."
384
+ )
385
+
386
+ class ActivationCheckpointingStrategy(StrEnum):
387
+ whole_layer = "whole_layer"
388
+ """
389
+ Checkpoint every transformer layer.
390
+ """
391
+
392
+ one_in_two = "one_in_two"
393
+ """
394
+ Checkpoint one in two transformer layers.
395
+ """
396
+
397
+ one_in_three = "one_in_three"
398
+ """
399
+ Checkpoint one in three transformer layers.
400
+ """
401
+
402
+ one_in_four = "one_in_four"
403
+ """
404
+ Checkpoint one in four transformer layers.
405
+ """
406
+
407
+ two_in_three = "two_in_three"
408
+ """
409
+ Checkpoint two out of every three transformer layers.
410
+ """
411
+
412
+ three_in_four = "three_in_four"
413
+ """
414
+ Checkpoint three out of four of every transformer layers.
415
+ """
416
+
417
+ four_in_five = "four_in_five"
418
+ """
419
+ Checkpoint four out of five of every transformer layers.
420
+ """
421
+
422
+ nine_in_ten = "nine_in_ten"
423
+ """
424
+ Checkpoint nine out of ten of every transformer layers.
425
+ """
426
+
427
+ fine_grained = "fine_grained"
428
+ """
429
+ Focus checkpointing on where it is cheap to recompute and saves most memory.
430
+ """
431
+
432
+
433
+ class LLaDAConfig(PretrainedConfig):
434
+ model_type = "llada"
435
+ keys_to_ignore_at_inference = ["past_key_values"] # TODO: confirm
436
+
437
+ def __init__(self, use_cache: bool = False, **kwargs):
438
+ model_config = ModelConfig()
439
+ all_kwargs = model_config.__dict__
440
+ all_kwargs.update(kwargs)
441
+ all_kwargs.update({"use_cache": use_cache})
442
+ all_kwargs.update(
443
+ {
444
+ "architectures": all_kwargs.get("architectures", ["LLaDAModelLM"])
445
+ }
446
+ )
447
+ super().__init__(**all_kwargs)
448
+
449
+ @property
450
+ def num_attention_heads(self):
451
+ return self.n_heads
452
+
453
+ @property
454
+ def num_hidden_layers(self):
455
+ return self.n_layers
456
+
457
+ @property
458
+ def hidden_size(self):
459
+ return self.d_model
460
+
461
+
462
+ # Register the config class so that it is available for transformer pipelines, auto-loading etc.
463
+ AutoConfig.register("llada", LLaDAConfig)
model/modeling_llada.py ADDED
@@ -0,0 +1,1567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import math
5
+ import sys
6
+ from abc import abstractmethod
7
+ from collections import defaultdict
8
+ from functools import partial
9
+ from typing import (
10
+ Callable,
11
+ Dict,
12
+ Iterable,
13
+ List,
14
+ NamedTuple,
15
+ Optional,
16
+ Sequence,
17
+ Set,
18
+ Tuple,
19
+ cast,
20
+ )
21
+ from dataclasses import fields
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.backends.cuda
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+ from torch import einsum
29
+ from transformers import PreTrainedModel
30
+ from transformers.modeling_outputs import CausalLMOutputWithPast
31
+ from transformers.models.auto import AutoModel
32
+ from transformers.cache_utils import Cache
33
+
34
+ from .configuration_llada import (
35
+ LLaDAConfig,
36
+ StrEnum,
37
+ InitFnType,
38
+ ActivationType,
39
+ BlockType,
40
+ LayerNormType,
41
+ ModelConfig,
42
+ ActivationCheckpointingStrategy,
43
+ )
44
+
45
+ if sys.version_info.minor > 8:
46
+ from collections.abc import MutableMapping
47
+ elif sys.version_info.minor == 8:
48
+ from typing import MutableMapping
49
+ else:
50
+ raise SystemExit("This script supports Python 3.8 or higher")
51
+
52
+ __all__ = [
53
+ "LayerNormBase",
54
+ "LayerNorm",
55
+ "RMSLayerNorm",
56
+ "GemmaRMSLayerNorm",
57
+ "RotaryEmbedding",
58
+ "Activation",
59
+ "GELU",
60
+ "ReLU",
61
+ "SwiGLU",
62
+ "LLaDABlock",
63
+ "LLaDASequentialBlock",
64
+ "LLaDAModel",
65
+ "LLaDAOutput",
66
+ "LLaDAGenerateOutput",
67
+ ]
68
+
69
+
70
+ log = logging.getLogger(__name__)
71
+
72
+
73
+ class ModuleType(StrEnum):
74
+ in_module = "in"
75
+ out_module = "out"
76
+ emb = "emb"
77
+ final_out = "final_out"
78
+
79
+
80
+ def init_weights(
81
+ config: ModelConfig,
82
+ module: Union[nn.Linear, nn.Embedding],
83
+ d: Optional[int] = None,
84
+ layer_id: Optional[int] = None,
85
+ std_factor: float = 1.0,
86
+ type_of_module: Optional[ModuleType] = None,
87
+ ) -> None:
88
+ """
89
+ Initialize weights of a linear or embedding module.
90
+
91
+ :param config: The model config.
92
+ :param module: The linear or embedding submodule to initialize.
93
+ :param d: The effective input dimensionality of the weights. This could be smaller than the actual dimensions
94
+ for fused layers.
95
+ :param layer_id: When set, the standard deviation for the "mitchell" method will be adjusted by
96
+ ``1 / sqrt(2 * (layer_id + 1))``.
97
+ """
98
+ d = d if d is not None else config.d_model
99
+ if config.init_fn == InitFnType.normal:
100
+ std = config.init_std * std_factor
101
+ if config.init_cutoff_factor is not None:
102
+ cutoff_value = config.init_cutoff_factor * std
103
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-cutoff_value, b=cutoff_value)
104
+ else:
105
+ nn.init.normal_(module.weight, mean=0.0, std=std)
106
+ elif config.init_fn == InitFnType.mitchell:
107
+ std = std_factor / math.sqrt(d)
108
+ if layer_id is not None:
109
+ std = std / math.sqrt(2 * (layer_id + 1))
110
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-3 * std, b=3 * std)
111
+ elif config.init_fn == InitFnType.kaiming_normal:
112
+ nn.init.kaiming_normal_(module.weight, nonlinearity="relu")
113
+ elif config.init_fn == InitFnType.fan_in:
114
+ std = std_factor / math.sqrt(d)
115
+ nn.init.normal_(module.weight, mean=0.0, std=std)
116
+ elif config.init_fn == InitFnType.full_megatron:
117
+ if type_of_module is None:
118
+ raise RuntimeError(f"When using the {InitFnType.full_megatron} init, every module must have a type.")
119
+
120
+ cutoff_factor = config.init_cutoff_factor
121
+ if cutoff_factor is None:
122
+ cutoff_factor = 3
123
+
124
+ if type_of_module == ModuleType.in_module:
125
+ # for att_proj (same as QKV), ff_proj
126
+ std = config.init_std
127
+ elif type_of_module == ModuleType.out_module:
128
+ # for attn_out, ff_out
129
+ std = config.init_std / math.sqrt(2.0 * config.n_layers)
130
+ elif type_of_module == ModuleType.emb:
131
+ # positional embeddings (wpe)
132
+ # token embeddings (wte)
133
+ std = config.init_std
134
+ elif type_of_module == ModuleType.final_out:
135
+ # final output (ff_out)
136
+ std = config.d_model**-0.5
137
+ else:
138
+ raise RuntimeError(f"Unknown module type '{type_of_module}'")
139
+ nn.init.trunc_normal_(
140
+ module.weight,
141
+ mean=0.0,
142
+ std=std,
143
+ a=-cutoff_factor * std,
144
+ b=cutoff_factor * std,
145
+ )
146
+ else:
147
+ raise NotImplementedError(config.init_fn)
148
+
149
+ if isinstance(module, nn.Linear):
150
+ if module.bias is not None:
151
+ nn.init.zeros_(module.bias)
152
+
153
+ if config.init_fn == InitFnType.normal and getattr(module, "_is_residual", False):
154
+ with torch.no_grad():
155
+ module.weight.div_(math.sqrt(2 * config.n_layers))
156
+
157
+
158
+ def ensure_finite_(x: torch.Tensor, check_neg_inf: bool = True, check_pos_inf: bool = False):
159
+ """
160
+ Modify ``x`` in place to replace ``float("-inf")`` with the minimum value of the dtype when ``check_neg_inf``
161
+ is ``True`` and to replace ``float("inf")`` with the maximum value of the dtype when ``check_pos_inf`` is ``True``.
162
+ """
163
+ if check_neg_inf:
164
+ x.masked_fill_(x == float("-inf"), torch.finfo(x.dtype).min)
165
+ if check_pos_inf:
166
+ x.masked_fill_(x == float("inf"), torch.finfo(x.dtype).max)
167
+
168
+
169
+ def activation_checkpoint_function(cfg: ModelConfig):
170
+ preserve_rng_state = (
171
+ (cfg.attention_dropout == 0.0) and (cfg.embedding_dropout == 0.0) and (cfg.residual_dropout == 0.0)
172
+ )
173
+ from torch.utils.checkpoint import checkpoint
174
+
175
+ return partial(
176
+ checkpoint,
177
+ preserve_rng_state=preserve_rng_state,
178
+ use_reentrant=False,
179
+ )
180
+
181
+
182
+ class BufferCache(dict, MutableMapping[str, torch.Tensor]):
183
+ """
184
+ Cache for attention biases and other things that would normally be stored as buffers.
185
+ We avoid using buffers because we've run into various issues doing so with FSDP.
186
+ In general it appears the way FSDP handles buffers is not well-defined.
187
+ It doesn't shard them but apparently it does synchronize them across processes, which we want to avoid
188
+ since (A) it isn't necessary, and (B) we sometimes have `-inf` in these biases which might get turned into
189
+ NaNs when they're synchronized due to casting or some other issue.
190
+ """
191
+
192
+
193
+ def _non_meta_init_device(config: ModelConfig) -> torch.device:
194
+ if config.init_device is not None and config.init_device != "meta":
195
+ return torch.device(config.init_device)
196
+ else:
197
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
198
+
199
+
200
+ class Dropout(nn.Dropout):
201
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
202
+ if self.p == 0.0:
203
+ return input
204
+ else:
205
+ return F.dropout(input, self.p, self.training, self.inplace)
206
+
207
+
208
+ class LayerNormBase(nn.Module):
209
+ def __init__(
210
+ self,
211
+ config: ModelConfig,
212
+ *,
213
+ size: Optional[int] = None,
214
+ elementwise_affine: Optional[bool] = True,
215
+ eps: float = 1e-05,
216
+ ):
217
+ super().__init__()
218
+ self.config = config
219
+ self.eps = eps
220
+ self.normalized_shape = (size or config.d_model,)
221
+ if elementwise_affine or (elementwise_affine is None and self.config.layer_norm_with_affine):
222
+ self.weight = nn.Parameter(torch.ones(self.normalized_shape, device=config.init_device))
223
+ use_bias = self.config.bias_for_layer_norm
224
+ if use_bias is None:
225
+ use_bias = self.config.include_bias
226
+ if use_bias:
227
+ self.bias = nn.Parameter(torch.zeros(self.normalized_shape, device=config.init_device))
228
+ else:
229
+ self.register_parameter("bias", None)
230
+ else:
231
+ self.register_parameter("bias", None)
232
+ self.register_parameter("weight", None)
233
+
234
+ @abstractmethod
235
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
236
+ raise NotImplementedError
237
+
238
+ @classmethod
239
+ def build(cls, config: ModelConfig, size: Optional[int] = None, **kwargs) -> LayerNormBase:
240
+ if config.layer_norm_type == LayerNormType.default:
241
+ return LayerNorm(config, size=size, low_precision=False, **kwargs)
242
+ elif config.layer_norm_type == LayerNormType.low_precision:
243
+ return LayerNorm(config, size=size, low_precision=True, **kwargs)
244
+ elif config.layer_norm_type == LayerNormType.rms:
245
+ return RMSLayerNorm(config, size=size, **kwargs)
246
+ elif config.layer_norm_type == LayerNormType.gemma_rms:
247
+ return GemmaRMSLayerNorm(config, size=size, **kwargs)
248
+ else:
249
+ raise NotImplementedError(f"Unknown LayerNorm type: '{config.layer_norm_type}'")
250
+
251
+ def _cast_if_autocast_enabled(self, tensor: torch.Tensor, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
252
+ # NOTE: `is_autocast_enabled()` only checks for CUDA autocast, so we use the separate function
253
+ # `is_autocast_cpu_enabled()` for CPU autocast.
254
+ # See https://github.com/pytorch/pytorch/issues/110966.
255
+ if tensor.device.type == "cuda" and torch.is_autocast_enabled():
256
+ return tensor.to(dtype=dtype if dtype is not None else torch.get_autocast_gpu_dtype())
257
+ elif tensor.device.type == "cpu" and torch.is_autocast_cpu_enabled():
258
+ return tensor.to(dtype=dtype if dtype is not None else torch.get_autocast_cpu_dtype())
259
+ else:
260
+ return tensor
261
+
262
+ def reset_parameters(self):
263
+ if self.weight is not None:
264
+ torch.nn.init.ones_(self.weight) # type: ignore
265
+ if self.bias is not None:
266
+ torch.nn.init.zeros_(self.bias) # type: ignore
267
+
268
+
269
+ class LayerNorm(LayerNormBase):
270
+ """
271
+ The default :class:`LayerNorm` implementation which can optionally run in low precision.
272
+ """
273
+
274
+ def __init__(
275
+ self,
276
+ config: ModelConfig,
277
+ size: Optional[int] = None,
278
+ low_precision: bool = False,
279
+ elementwise_affine: Optional[bool] = None,
280
+ eps: float = 1e-05,
281
+ ):
282
+ super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=eps)
283
+ self.low_precision = low_precision
284
+
285
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
286
+ if self.low_precision:
287
+ module_device = x.device
288
+ downcast_x = self._cast_if_autocast_enabled(x)
289
+ downcast_weight = (
290
+ self._cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
291
+ )
292
+ downcast_bias = self._cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias
293
+ with torch.autocast(enabled=False, device_type=module_device.type):
294
+ return F.layer_norm(
295
+ downcast_x, self.normalized_shape, weight=downcast_weight, bias=downcast_bias, eps=self.eps
296
+ )
297
+ else:
298
+ return F.layer_norm(x, self.normalized_shape, weight=self.weight, bias=self.bias, eps=self.eps)
299
+
300
+
301
+ class RMSLayerNorm(LayerNormBase):
302
+ """
303
+ RMS layer norm, a simplified :class:`LayerNorm` implementation
304
+ """
305
+
306
+ def __init__(
307
+ self,
308
+ config: ModelConfig,
309
+ size: Optional[int] = None,
310
+ elementwise_affine: Optional[bool] = None,
311
+ eps: float = 1e-5,
312
+ ):
313
+ super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=config.rms_norm_eps)
314
+
315
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
316
+ with torch.autocast(enabled=False, device_type=x.device.type):
317
+ og_dtype = x.dtype
318
+ x = x.to(torch.float32)
319
+ variance = x.pow(2).mean(-1, keepdim=True)
320
+ x = x * torch.rsqrt(variance + self.eps)
321
+ x = x.to(og_dtype)
322
+
323
+ if self.weight is not None:
324
+ if self.bias is not None:
325
+ return self.weight * x + self.bias
326
+ else:
327
+ return self.weight * x
328
+ else:
329
+ return x
330
+
331
+
332
+ class GemmaRMSLayerNorm(LayerNormBase):
333
+ """
334
+ Gemma RMS layer norm, a simplified :class:`LayerNorm` implementation
335
+ """
336
+
337
+ def __init__(
338
+ self,
339
+ config: ModelConfig,
340
+ size: Optional[int] = None,
341
+ elementwise_affine: Optional[bool] = None,
342
+ eps: float = 1e-5,
343
+ ):
344
+ super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=config.rms_norm_eps)
345
+
346
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
347
+ with torch.autocast(enabled=False, device_type=x.device.type):
348
+ og_dtype = x.dtype
349
+ x = x.to(torch.float32)
350
+ variance = x.pow(2).mean(-1, keepdim=True)
351
+ x = x * torch.rsqrt(variance + self.eps)
352
+ x = x.to(og_dtype)
353
+
354
+ if self.weight is not None:
355
+ if self.bias is not None:
356
+ return x * (1 + self.weight) + self.bias
357
+ else:
358
+ return x * (1 + self.weight)
359
+ else:
360
+ return x
361
+
362
+
363
+ class RotaryEmbedding(nn.Module):
364
+ """
365
+ [Rotary positional embeddings (RoPE)](https://arxiv.org/abs/2104.09864).
366
+ """
367
+
368
+ def __init__(self, config: ModelConfig, cache: BufferCache):
369
+ super().__init__()
370
+ self.config = config
371
+ self.__cache = cache
372
+ # Warm up cache.
373
+ self.rope_theta = config.rope_theta
374
+ self.get_rotary_embedding(config.max_sequence_length, _non_meta_init_device(config))
375
+
376
+ def get_rotary_embedding(self, seq_len: int, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:
377
+ if (
378
+ (pos_sin := self.__cache.get("rope_pos_sin")) is not None
379
+ and (pos_cos := self.__cache.get("rope_pos_cos")) is not None
380
+ and pos_sin.shape[-2] >= seq_len
381
+ and pos_cos.shape[-2] >= seq_len
382
+ ):
383
+ if pos_sin.device != device:
384
+ pos_sin = pos_sin.to(device)
385
+ self.__cache["rope_pos_sin"] = pos_sin
386
+ if pos_cos.device != device:
387
+ pos_cos = pos_cos.to(device)
388
+ self.__cache["rope_pos_cos"] = pos_cos
389
+ return pos_sin[:, :, :seq_len, :], pos_cos[:, :, :seq_len, :]
390
+
391
+ with torch.autocast(device.type, enabled=False):
392
+ dim = self.config.d_model // self.config.n_heads
393
+ inv_freq = 1.0 / (self.rope_theta ** (torch.arange(0, dim, 2, device=device, dtype=torch.float) / dim))
394
+ seq = torch.arange(seq_len, device=device, dtype=torch.float)
395
+ freqs = einsum("i , j -> i j", seq, inv_freq)
396
+ positions = torch.cat((freqs, freqs), dim=-1)
397
+ pos_sin, pos_cos = positions.sin()[None, None, :, :], positions.cos()[None, None, :, :]
398
+ self.__cache["rope_pos_sin"] = pos_sin
399
+ self.__cache["rope_pos_cos"] = pos_cos
400
+ return pos_sin, pos_cos
401
+
402
+ def rotate_half(self, x: torch.Tensor) -> torch.Tensor:
403
+ B, nh, T, hs = x.size()
404
+ x = x.view(B, nh, T, 2, hs // 2)
405
+ x1, x2 = x.unbind(dim=-2)
406
+ return torch.cat((-x2, x1), dim=-1)
407
+
408
+ def apply_rotary_pos_emb(self, pos_sin: torch.Tensor, pos_cos: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
409
+ return ((t * pos_cos) + (self.rotate_half(t) * pos_sin)).to(t.dtype)
410
+
411
+ def forward(self, q: torch.Tensor, k: torch.Tensor, q_mask=None) -> Tuple[torch.Tensor, torch.Tensor]:
412
+ if self.config.rope_full_precision:
413
+ q_, k_ = q.float(), k.float()
414
+ else:
415
+ q_, k_ = q, k
416
+
417
+ with torch.autocast(q.device.type, enabled=False):
418
+ query_len, key_len = q_.shape[-2], k_.shape[-2] # could be different if layer_past not None
419
+ pos_sin, pos_cos = self.get_rotary_embedding(key_len, q_.device)
420
+ pos_sin = pos_sin.type_as(q_)
421
+ pos_cos = pos_cos.type_as(q_)
422
+ if q_mask is None:
423
+ q_ = self.apply_rotary_pos_emb(
424
+ pos_sin[:, :, key_len - query_len : key_len, :],
425
+ pos_cos[:, :, key_len - query_len : key_len, :],
426
+ q_,
427
+ )
428
+ else:
429
+ q_ = self.apply_rotary_pos_emb(
430
+ pos_sin[:, :, q_mask, :],
431
+ pos_cos[:, :, q_mask, :],
432
+ q_,
433
+ )
434
+ k_ = self.apply_rotary_pos_emb(pos_sin, pos_cos, k_)
435
+ return q_.type_as(q), k_.type_as(k)
436
+
437
+
438
+ class Activation(nn.Module):
439
+ def __init__(self, config: ModelConfig):
440
+ super().__init__()
441
+ self.config = config
442
+
443
+ @abstractmethod
444
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
445
+ raise NotImplementedError
446
+
447
+ @property
448
+ @abstractmethod
449
+ def output_multiplier(self) -> float:
450
+ raise NotImplementedError
451
+
452
+ @classmethod
453
+ def build(cls, config: ModelConfig) -> Activation:
454
+ if config.activation_type == ActivationType.gelu:
455
+ return cast(Activation, GELU(approximate="none"))
456
+ elif config.activation_type == ActivationType.relu:
457
+ return cast(Activation, ReLU(inplace=False))
458
+ elif config.activation_type == ActivationType.silu:
459
+ return cast(Activation, SiLU(inplace=False))
460
+ elif config.activation_type == ActivationType.swiglu:
461
+ return SwiGLU(config)
462
+ else:
463
+ raise NotImplementedError(f"Unknown activation: '{config.activation_type}'")
464
+
465
+
466
+ class GELU(nn.GELU):
467
+ @property
468
+ def output_multiplier(self) -> float:
469
+ return 1.0
470
+
471
+
472
+ class ReLU(nn.ReLU):
473
+ @property
474
+ def output_multiplier(self) -> float:
475
+ return 1.0
476
+
477
+ class SiLU(nn.SiLU):
478
+ @property
479
+ def output_multiplier(self) -> float:
480
+ return 1.0
481
+
482
+ class SwiGLU(Activation):
483
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
484
+ x, gate = x.chunk(2, dim=-1)
485
+ return F.silu(gate) * x
486
+
487
+ @property
488
+ def output_multiplier(self) -> float:
489
+ return 0.5
490
+
491
+
492
+ def causal_attention_bias(seq_len: int, device: torch.device) -> torch.FloatTensor:
493
+ att_bias = torch.triu(
494
+ torch.ones(seq_len, seq_len, device=device, dtype=torch.float),
495
+ diagonal=1,
496
+ )
497
+ att_bias.masked_fill_(att_bias == 1, torch.finfo(att_bias.dtype).min)
498
+ return att_bias.view(1, 1, seq_len, seq_len) # type: ignore
499
+
500
+
501
+ def get_causal_attention_bias(cache: BufferCache, seq_len: int, device: torch.device) -> torch.Tensor:
502
+ if (causal_bias := cache.get("causal_attention_bias")) is not None and causal_bias.shape[-1] >= seq_len:
503
+ if causal_bias.device != device:
504
+ causal_bias = causal_bias.to(device)
505
+ cache["causal_attention_bias"] = causal_bias
506
+ return causal_bias
507
+ with torch.autocast(device.type, enabled=False):
508
+ causal_bias = causal_attention_bias(seq_len, device)
509
+ cache["causal_attention_bias"] = causal_bias
510
+ return causal_bias
511
+
512
+
513
+ def alibi_attention_bias(seq_len: int, config: ModelConfig, device: torch.device) -> torch.FloatTensor:
514
+ alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.float, device=device).view(1, 1, 1, seq_len)
515
+
516
+ # shape: (1, 1, seq_len, seq_len)
517
+ alibi_bias = alibi_bias - torch.arange(1 - seq_len, 1, dtype=torch.float, device=device).view(1, 1, seq_len, 1)
518
+ alibi_bias.abs_().mul_(-1)
519
+
520
+ # shape: (n_heads,)
521
+ m = torch.arange(1, config.n_heads + 1, dtype=torch.float, device=device)
522
+ m.mul_(config.alibi_bias_max / config.n_heads)
523
+
524
+ # shape: (1, n_heads, seq_len, seq_len)
525
+ return alibi_bias * (1.0 / (2 ** m.view(1, config.n_heads, 1, 1))) # type: ignore
526
+
527
+
528
+ class LLaDABlock(nn.Module):
529
+ """
530
+ A base class for transformer block implementations.
531
+ """
532
+
533
+ def __init__(self, layer_id: int, config: ModelConfig, cache: BufferCache):
534
+ super().__init__()
535
+ self.layer_id = layer_id
536
+ self.config = config
537
+ self.hidden_size = (
538
+ config.mlp_hidden_size if config.mlp_hidden_size is not None else config.mlp_ratio * config.d_model
539
+ )
540
+ self.__cache = cache
541
+ assert config.d_model % config.n_heads == 0
542
+
543
+ self._activation_checkpoint_fn = None
544
+
545
+ # Dropout.
546
+ self.dropout = Dropout(config.residual_dropout)
547
+
548
+ # Layer norms.
549
+ self.k_norm: Optional[LayerNormBase] = None
550
+ self.q_norm: Optional[LayerNormBase] = None
551
+ if config.attention_layer_norm:
552
+ self.k_norm = LayerNormBase.build(
553
+ config,
554
+ size=(config.d_model // config.n_heads) * config.effective_n_kv_heads,
555
+ elementwise_affine=config.attention_layer_norm_with_affine,
556
+ )
557
+ self.q_norm = LayerNormBase.build(config, elementwise_affine=config.attention_layer_norm_with_affine)
558
+
559
+ # Activation function.
560
+ self.act = Activation.build(config)
561
+ assert (self.act.output_multiplier * self.hidden_size) % 1 == 0
562
+
563
+ # Attention output projection.
564
+ self.attn_out = nn.Linear(
565
+ config.d_model, config.d_model, bias=config.include_bias, device=config.init_device
566
+ )
567
+
568
+ # Feed-forward output projection.
569
+ self.ff_out = nn.Linear(
570
+ int(self.act.output_multiplier * self.hidden_size),
571
+ config.d_model,
572
+ bias=config.include_bias,
573
+ device=config.init_device,
574
+ )
575
+ self.ff_out._is_residual = True # type: ignore
576
+
577
+ # Rotary embeddings.
578
+ if self.config.rope:
579
+ self.rotary_emb = RotaryEmbedding(config, self.__cache)
580
+
581
+ self.flash_attn_func = None
582
+ if config.flash_attention:
583
+ try:
584
+ from flash_attn import flash_attn_func # type: ignore
585
+
586
+ self.flash_attn_func = flash_attn_func
587
+ except ModuleNotFoundError:
588
+ pass
589
+
590
+ self.use_cache = False
591
+ self.init_cache()
592
+
593
+ def init_cache(self):
594
+ self.cache = {
595
+ 'k': {}, 'v': {}, 'out': {}
596
+ }
597
+
598
+ def caching(self, enable: bool = True):
599
+ self.use_cache = enable
600
+ self.init_cache()
601
+
602
+ def reset_parameters(self):
603
+ if self.k_norm is not None:
604
+ self.k_norm.reset_parameters()
605
+ if self.q_norm is not None:
606
+ self.q_norm.reset_parameters()
607
+ init_weights(
608
+ self.config,
609
+ self.attn_out,
610
+ d=self.config.d_model,
611
+ layer_id=self.layer_id,
612
+ type_of_module=ModuleType.out_module,
613
+ )
614
+ init_weights(
615
+ self.config,
616
+ self.ff_out,
617
+ d=self.ff_out.in_features,
618
+ layer_id=self.layer_id,
619
+ type_of_module=ModuleType.out_module,
620
+ )
621
+
622
+ def set_activation_checkpointing(self, strategy: Optional[ActivationCheckpointingStrategy]):
623
+ if strategy == ActivationCheckpointingStrategy.fine_grained:
624
+ self._activation_checkpoint_fn = activation_checkpoint_function(self.config)
625
+ else:
626
+ self._activation_checkpoint_fn = None
627
+
628
+ @classmethod
629
+ def _cast_attn_bias(cls, bias: torch.Tensor, input_dtype: torch.dtype) -> torch.Tensor:
630
+ target_dtype = input_dtype
631
+ # NOTE: `is_autocast_enabled()` only checks for CUDA autocast, so we use the separate function
632
+ # `is_autocast_cpu_enabled()` for CPU autocast.
633
+ # See https://github.com/pytorch/pytorch/issues/110966.
634
+ if bias.device.type == "cuda" and torch.is_autocast_enabled():
635
+ target_dtype = torch.get_autocast_gpu_dtype()
636
+ elif bias.device.type == "cpu" and torch.is_autocast_cpu_enabled():
637
+ target_dtype = torch.get_autocast_cpu_dtype()
638
+ if bias.dtype != target_dtype:
639
+ bias = bias.to(target_dtype)
640
+ ensure_finite_(bias, check_neg_inf=True, check_pos_inf=False)
641
+ return bias
642
+
643
+ def _scaled_dot_product_attention(
644
+ self,
645
+ q: torch.Tensor,
646
+ k: torch.Tensor,
647
+ v: torch.Tensor,
648
+ attn_mask: Optional[torch.Tensor] = None,
649
+ dropout_p: float = 0.0,
650
+ is_causal: bool = False,
651
+ ) -> torch.Tensor:
652
+ """
653
+ Computes scaled dot product attention on query, key and value tensors, using an optional
654
+ attention mask if passed, and applying dropout if a probability greater than 0.0 is specified.
655
+ """
656
+ if self.flash_attn_func is not None and attn_mask is None:
657
+ r = self.flash_attn_func(
658
+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), dropout_p=dropout_p, causal=False
659
+ )
660
+ return r.transpose(1, 2)
661
+ else:
662
+ # torch's sdpa doesn't support GQA, so we're doing this
663
+ assert k.size(1) == v.size(1)
664
+ num_kv_heads = k.size(1)
665
+ num_q_heads = q.size(1)
666
+ if num_q_heads != num_kv_heads:
667
+ assert num_q_heads % num_kv_heads == 0
668
+ k = k.repeat_interleave(num_q_heads // num_kv_heads, dim=1, output_size=num_q_heads)
669
+ v = v.repeat_interleave(num_q_heads // num_kv_heads, dim=1, output_size=num_q_heads)
670
+
671
+ # Modify: MDM set causal to False, and with no attn_mask.
672
+ return F.scaled_dot_product_attention(
673
+ q,
674
+ k,
675
+ v,
676
+ attn_mask=None,
677
+ dropout_p=dropout_p,
678
+ is_causal=False,
679
+ )
680
+
681
+ def attention(
682
+ self,
683
+ q: torch.Tensor,
684
+ k: torch.Tensor,
685
+ v: torch.Tensor,
686
+ attention_bias: Optional[torch.Tensor] = None,
687
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
688
+ to_compute_mask = None,
689
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
690
+ B, T, C = q.size() # batch size, sequence length, d_model
691
+ dtype = k.dtype
692
+
693
+ # Optionally apply layer norm to keys and queries.
694
+ if self.q_norm is not None and self.k_norm is not None:
695
+ q = self.q_norm(q).to(dtype=dtype)
696
+ k = self.k_norm(k).to(dtype=dtype)
697
+
698
+ # Move head forward to be next to the batch dim.
699
+ # shape: (B, nh, T, hs)
700
+ q = q.view(B, -1, self.config.n_heads, C // self.config.n_heads).transpose(1, 2)
701
+ # shape: (B, n_kv_h, T, hs)
702
+ k = k.view(B, -1, self.config.effective_n_kv_heads, C // self.config.n_heads).transpose(1, 2)
703
+ # shape: (B, n_kv_h, T, hs)
704
+ v = v.view(B, -1, self.config.effective_n_kv_heads, C // self.config.n_heads).transpose(1, 2)
705
+
706
+ if layer_past is not None:
707
+ past_key, past_value = layer_past
708
+ k = torch.cat((past_key, k), dim=-2)
709
+ v = torch.cat((past_value, v), dim=-2)
710
+
711
+ # present = (k, v) if use_cache else None
712
+ # query_len, key_len = q.shape[-2], k.shape[-2] # could be different if layer_past not None
713
+
714
+ if self.config.rope:
715
+ to_compute_index = to_compute_mask.nonzero(as_tuple=True)[1] if self.use_cache and to_compute_mask is not None else None
716
+ q, k = self.rotary_emb(q, k, q_mask=to_compute_index)
717
+
718
+ if attention_bias is not None:
719
+ # Resize and cast attention bias.
720
+ # The current dtype of the attention bias might not match the dtype that the SDP attn function will
721
+ # run in if AMP is enabled, and this can be a problem if some tokens are masked out due to padding
722
+ # as down-casting the attention bias to the autocast precision will result in -infs, which will
723
+ # cause the SDP attn function to produce NaNs.
724
+ attention_bias = self._cast_attn_bias(
725
+ # attention_bias[:, :, key_len - query_len : key_len, :key_len], dtype
726
+ attention_bias, dtype
727
+ )
728
+
729
+ # Get the attention scores.
730
+ # shape: (B, nh, T, hs)
731
+ att = self._scaled_dot_product_attention(
732
+ q,
733
+ k,
734
+ v,
735
+ attn_mask=None,
736
+ dropout_p=0.0 if not self.training else self.config.attention_dropout,
737
+ is_causal=False,
738
+ )
739
+
740
+ # Re-assemble all head outputs side-by-side.
741
+ att = att.transpose(1, 2).contiguous().view(B, T, C)
742
+
743
+ # Apply output projection.
744
+ return self.attn_out(att), None
745
+
746
+ @abstractmethod
747
+ def forward(
748
+ self,
749
+ x: torch.Tensor,
750
+ attention_bias: Optional[torch.FloatTensor] = None,
751
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
752
+ use_cache: bool = False,
753
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
754
+ raise NotImplementedError
755
+
756
+ @classmethod
757
+ def build(cls, layer_id: int, config: ModelConfig, cache: BufferCache) -> LLaDABlock:
758
+ if config.block_type == BlockType.sequential:
759
+ return LLaDASequentialBlock(layer_id, config, cache)
760
+ elif config.block_type == BlockType.llama:
761
+ return LLaDALlamaBlock(layer_id, config, cache)
762
+ else:
763
+ raise NotImplementedError(f"Unknown block type: '{config.block_type}'")
764
+
765
+
766
+ class LLaDASequentialBlock(LLaDABlock):
767
+ """
768
+ This is a typical transformer block where the output is computed as ``MLP(LN(x + Attention(LN(x))))``
769
+ (plus another skip connection).
770
+ """
771
+
772
+ def __init__(self, layer_id: int, config: ModelConfig, cache: BufferCache):
773
+ super().__init__(layer_id, config, cache)
774
+ # Layer norms.
775
+ self.attn_norm = LayerNorm.build(config)
776
+ self.ff_norm = LayerNorm.build(config)
777
+ # Attention input projection. Projects x -> (q, k, v)
778
+ head_dim = config.d_model // config.n_heads
779
+ self.fused_dims = (
780
+ config.d_model,
781
+ config.effective_n_kv_heads * head_dim,
782
+ config.effective_n_kv_heads * head_dim,
783
+ )
784
+ self.att_proj = nn.Linear(
785
+ config.d_model, sum(self.fused_dims), bias=config.include_bias | config.include_qkv_bias, device=config.init_device
786
+ )
787
+ # Feed-forward input projection.
788
+ self.ff_proj = nn.Linear(
789
+ config.d_model, self.hidden_size, bias=config.include_bias, device=config.init_device
790
+ )
791
+
792
+ def reset_parameters(self):
793
+ super().reset_parameters()
794
+ self.attn_norm.reset_parameters()
795
+ self.ff_norm.reset_parameters()
796
+ # NOTE: the standard deviation for these weights does not depend on the layer.
797
+ init_weights(
798
+ self.config, self.att_proj, d=self.config.d_model, layer_id=None, type_of_module=ModuleType.in_module
799
+ )
800
+ init_weights(
801
+ self.config, self.ff_proj, d=self.config.d_model, layer_id=None, type_of_module=ModuleType.in_module
802
+ )
803
+
804
+ def forward(
805
+ self,
806
+ x: torch.Tensor,
807
+ attention_bias: Optional[torch.Tensor] = None,
808
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
809
+ use_cache: bool = False,
810
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
811
+ # Get query, key, value projections.
812
+ # shape:
813
+ # - for regular attn q, k, v: (batch_size, seq_len, d_model)
814
+ # - for multi-query attn q: (batch_size, seq_len, d_model)
815
+ # k, v: (batch_size, seq_len, d_model // n_heads)
816
+ # - for group query attn q: (batch_size, seq_len, d_model)
817
+ # k, v: (batch_size, seq_len, d_model // n_kv_heads)
818
+ if self._activation_checkpoint_fn is not None:
819
+ q, k, v = self.att_proj(self._activation_checkpoint_fn(self.attn_norm, x)).split(
820
+ self.fused_dims, dim=-1
821
+ )
822
+ else:
823
+ q, k, v = self.att_proj(self.attn_norm(x)).split(self.fused_dims, dim=-1)
824
+
825
+ # Get attention scores.
826
+ if self._activation_checkpoint_fn is not None:
827
+ att, cache = self._activation_checkpoint_fn( # type: ignore
828
+ self.attention, q, k, v, attention_bias, layer_past=layer_past, use_cache=use_cache
829
+ )
830
+ else:
831
+ att, cache = self.attention(q, k, v, attention_bias, layer_past=layer_past, use_cache=use_cache)
832
+
833
+ # Add attention scores.
834
+ # shape: (B, T, C)
835
+ x = x + self.dropout(att)
836
+
837
+ # Add feed-forward projection.
838
+ # shape: (batch_size, seq_len, d_model)
839
+ og_x = x
840
+ if self._activation_checkpoint_fn is not None:
841
+ x = self._activation_checkpoint_fn(self.ff_norm, x) # type: ignore
842
+ else:
843
+ x = self.ff_norm(x)
844
+ x = self.ff_proj(x)
845
+ if self._activation_checkpoint_fn is not None:
846
+ x = self._activation_checkpoint_fn(self.act, x) # type: ignore
847
+ else:
848
+ x = self.act(x)
849
+ x = self.ff_out(x)
850
+ x = self.dropout(x)
851
+ x = og_x + x
852
+
853
+ return x, cache
854
+
855
+
856
+ class LLaDALlamaBlock(LLaDABlock):
857
+ """
858
+ This is a transformer block where the output is computed as ``MLP(LN(x + Attention(LN(x))))``
859
+ (plus another skip connection). This block is similar to `LLaDASequentialBlock`
860
+ but some operations have slightly different implementations to imitate the
861
+ behavior of Llama.
862
+ """
863
+
864
+ def __init__(self, layer_id: int, config: ModelConfig, cache: BufferCache):
865
+ super().__init__(layer_id, config, cache)
866
+ # Layer norms.
867
+ self.attn_norm = LayerNorm.build(config)
868
+ self.ff_norm = LayerNorm.build(config)
869
+ self.__cache = cache
870
+
871
+ # Attention input projection. Projects x -> (q, k, v)
872
+ head_dim = config.d_model // config.n_heads
873
+ q_proj_out_dim = config.d_model
874
+ k_proj_out_dim = config.effective_n_kv_heads * head_dim
875
+ v_proj_out_dim = config.effective_n_kv_heads * head_dim
876
+ self.q_proj = nn.Linear(
877
+ config.d_model, q_proj_out_dim, bias=config.include_bias | config.include_qkv_bias, device=config.init_device
878
+ )
879
+ self.k_proj = nn.Linear(
880
+ config.d_model, k_proj_out_dim, bias=config.include_bias | config.include_qkv_bias, device=config.init_device
881
+ )
882
+ self.v_proj = nn.Linear(
883
+ config.d_model, v_proj_out_dim, bias=config.include_bias | config.include_qkv_bias, device=config.init_device
884
+ )
885
+
886
+ # Feed-forward input projection.
887
+ self.ff_proj = nn.Linear(
888
+ config.d_model, self.hidden_size, bias=config.include_bias, device=config.init_device
889
+ )
890
+ # new add
891
+ self.up_proj = nn.Linear(
892
+ config.d_model, self.hidden_size, bias=config.include_bias, device=config.init_device
893
+ )
894
+
895
+ def reset_parameters(self):
896
+ super().reset_parameters()
897
+ self.attn_norm.reset_parameters()
898
+ self.ff_norm.reset_parameters()
899
+ # NOTE: the standard deviation for these weights does not depend on the layer.
900
+ init_weights(self.config, self.q_proj, d=self.config.d_model, layer_id=None)
901
+ init_weights(self.config, self.k_proj, d=self.config.d_model, layer_id=None)
902
+ init_weights(self.config, self.v_proj, d=self.config.d_model, layer_id=None)
903
+ init_weights(self.config, self.ff_proj, d=self.config.d_model, layer_id=None)
904
+ init_weights(self.config, self.up_proj, d=self.config.d_model, layer_id=None) # new add
905
+
906
+ def forward(
907
+ self,
908
+ x: torch.Tensor,
909
+ attention_bias: Optional[torch.Tensor] = None,
910
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
911
+ use_cache: bool = False,
912
+ cat = 'cond',
913
+ to_compute_mask = None,
914
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
915
+ # Get query, key, value projections.
916
+ # shape:
917
+ # - for regular attn q, k, v: (batch_size, seq_len, d_model)
918
+ # - for multi-query attn q: (batch_size, seq_len, d_model)
919
+ # k, v: (batch_size, seq_len, d_model // n_heads)
920
+ # - for group query attn q: (batch_size, seq_len, d_model)
921
+ # k, v: (batch_size, seq_len, d_model // n_kv_heads)
922
+ B, T, D = x.shape
923
+
924
+ x_normed = self.attn_norm(x)
925
+ q = self.q_proj(x_normed)
926
+ k = self.k_proj(x_normed)
927
+ v = self.v_proj(x_normed)
928
+
929
+ if use_cache:
930
+ if cat not in self.cache['k']:
931
+ self.cache['k'][cat] = torch.zeros_like(x)
932
+ self.cache['v'][cat] = torch.zeros_like(x)
933
+ if to_compute_mask is not None:
934
+ self.cache['k'][cat][to_compute_mask] = k.view(-1, D)
935
+ self.cache['v'][cat][to_compute_mask] = v.view(-1, D)
936
+ k = self.cache['k'][cat]
937
+ v = self.cache['v'][cat]
938
+ else:
939
+ self.cache['k'][cat] = k
940
+ self.cache['v'][cat] = v
941
+
942
+ # Get attention scores.
943
+ if self._activation_checkpoint_fn is not None:
944
+ att, cache = self._activation_checkpoint_fn( # type: ignore
945
+ self.attention, q, k, v, attention_bias, layer_past=layer_past, use_cache=use_cache
946
+ )
947
+ else:
948
+ att, cache = self.attention(q, k, v, attention_bias, layer_past=layer_past,
949
+ to_compute_mask=to_compute_mask)
950
+
951
+ # Add attention scores.
952
+ # shape: (B, T, C)
953
+ x = x + self.dropout(att)
954
+
955
+ # Add feed-forward projection.
956
+ # shape: (batch_size, seq_len, d_model)
957
+ og_x = x
958
+ if self._activation_checkpoint_fn is not None:
959
+ x = self._activation_checkpoint_fn(self.ff_norm, x) # type: ignore
960
+ else:
961
+ x = self.ff_norm(x)
962
+ x, x_up = self.ff_proj(x), self.up_proj(x) # new add
963
+ if self._activation_checkpoint_fn is not None:
964
+ x = self._activation_checkpoint_fn(self.act, x) # type: ignore
965
+ else:
966
+ x = self.act(x)
967
+ x = x * x_up # new add
968
+ x = self.ff_out(x)
969
+ x = self.dropout(x)
970
+ x = og_x + x
971
+
972
+ return x, cache
973
+
974
+
975
+ class LLaDAOutput(NamedTuple):
976
+ logits: torch.FloatTensor
977
+ """
978
+ A tensor of shape `(batch_size, seq_len, vocab_size)` representing the log probabilities
979
+ for the next token *before* normalization via (log) softmax.
980
+ """
981
+
982
+ attn_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]]
983
+ """
984
+ Attention keys and values from each block.
985
+ """
986
+
987
+ hidden_states: Optional[Tuple[torch.Tensor]]
988
+ """
989
+ Hidden states from each block.
990
+ """
991
+
992
+
993
+ class LLaDAGenerateOutput(NamedTuple):
994
+ token_ids: torch.LongTensor
995
+ """
996
+ The generated token IDs, a tensor of shape `(batch_size, beam_size, max_steps)`.
997
+ These do *not* include the original input IDs.
998
+ """
999
+
1000
+ scores: torch.FloatTensor
1001
+ """
1002
+ The scores of the generated sequences, a tensor of shape `(batch_size, beam_size)`.
1003
+ """
1004
+
1005
+
1006
+ class LLaDABlockGroup(nn.ModuleList):
1007
+ def __init__(self, config: ModelConfig, layer_offset: int, modules: Optional[Iterable[nn.Module]] = None):
1008
+ super().__init__(modules)
1009
+ self.config = config
1010
+ self.layer_offset = layer_offset
1011
+ self.activation_checkpointing_strategy: Optional[ActivationCheckpointingStrategy] = None
1012
+ self._activation_checkpoint_fn = activation_checkpoint_function(self.config)
1013
+
1014
+ def forward(
1015
+ self,
1016
+ x: torch.Tensor,
1017
+ attention_bias: Optional[torch.FloatTensor] = None,
1018
+ layers_past: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
1019
+ use_cache: bool = False,
1020
+ ) -> Tuple[torch.Tensor, Optional[List[Tuple[torch.Tensor, torch.Tensor]]]]:
1021
+ attn_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = [] if use_cache else None
1022
+ for block_idx, block in enumerate(self):
1023
+ layer_past = None if layers_past is None else layers_past[block_idx]
1024
+ block_idx += self.layer_offset
1025
+ if (
1026
+ (self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.whole_layer)
1027
+ or (
1028
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_two
1029
+ and block_idx % 2 == 0
1030
+ )
1031
+ or (
1032
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_three
1033
+ and block_idx % 3 == 0
1034
+ )
1035
+ or (
1036
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_four
1037
+ and block_idx % 4 == 0
1038
+ )
1039
+ ):
1040
+ # shape: (batch_size, seq_len, d_model)
1041
+ x, cache = self._activation_checkpoint_fn( # type: ignore
1042
+ block, x, attention_bias=attention_bias, layer_past=layer_past, use_cache=use_cache
1043
+ )
1044
+ else:
1045
+ # shape: (batch_size, seq_len, d_model)
1046
+ x, cache = block(x, attention_bias=attention_bias, layer_past=layer_past, use_cache=use_cache)
1047
+ if attn_key_values is not None:
1048
+ assert cache is not None
1049
+ attn_key_values.append(cache)
1050
+ return x, attn_key_values
1051
+
1052
+ def reset_parameters(self):
1053
+ for block in self:
1054
+ block.reset_parameters()
1055
+
1056
+ def set_activation_checkpointing(self, strategy: Optional[ActivationCheckpointingStrategy]):
1057
+ self.activation_checkpointing_strategy = strategy
1058
+ for block in self:
1059
+ block.set_activation_checkpointing(strategy)
1060
+
1061
+
1062
+ class LLaDAModel(nn.Module):
1063
+ def __init__(self, config: ModelConfig, init_params: bool = True):
1064
+ super().__init__()
1065
+ self.config = config
1066
+ self.__cache = BufferCache()
1067
+
1068
+ # Validate config.
1069
+ if self.config.alibi and self.config.flash_attention:
1070
+ raise Exception("ALiBi is currently not supported with FlashAttention")
1071
+
1072
+ if self.config.alibi and self.config.rope:
1073
+ raise Exception("ALiBi and RoPE are mutually exclusive")
1074
+
1075
+ if self.config.embedding_size is not None and self.config.embedding_size != self.config.vocab_size:
1076
+ if self.config.embedding_size < self.config.vocab_size:
1077
+ raise Exception("embedding size should be at least as big as vocab size")
1078
+ elif self.config.embedding_size % 128 != 0:
1079
+ import warnings
1080
+
1081
+ warnings.warn(
1082
+ "Embedding size is not a multiple of 128! This could hurt throughput performance.", UserWarning
1083
+ )
1084
+
1085
+ self.activation_checkpointing_strategy: Optional[ActivationCheckpointingStrategy] = None
1086
+ self._activation_checkpoint_fn: Callable = activation_checkpoint_function(self.config)
1087
+
1088
+ if not (
1089
+ 0 < self.config.block_group_size <= self.config.n_layers
1090
+ and self.config.n_layers % self.config.block_group_size == 0
1091
+ ):
1092
+ raise Exception("n layers must be divisible by block group size")
1093
+
1094
+ torch.backends.cuda.enable_flash_sdp(True)
1095
+ torch.backends.cuda.enable_mem_efficient_sdp(False) # this is super slow so make sure torch won't use it
1096
+
1097
+ self.transformer = nn.ModuleDict(
1098
+ dict(
1099
+ wte=nn.Embedding(
1100
+ config.embedding_size or config.vocab_size, config.d_model, device=config.init_device
1101
+ ),
1102
+ emb_drop=Dropout(config.embedding_dropout),
1103
+ ln_f=LayerNorm.build(config),
1104
+ )
1105
+ )
1106
+
1107
+ blocks = [LLaDABlock.build(i, config, self.__cache) for i in range(config.n_layers)]
1108
+ if self.config.block_group_size > 1:
1109
+ block_groups = [
1110
+ LLaDABlockGroup(config, i, blocks[i : i + config.block_group_size])
1111
+ for i in range(0, config.n_layers, config.block_group_size)
1112
+ ]
1113
+ self.transformer.update({"block_groups": nn.ModuleList(block_groups)})
1114
+ else:
1115
+ self.transformer.update({"blocks": nn.ModuleList(blocks)})
1116
+
1117
+ if not (self.config.alibi or self.config.rope):
1118
+ self.transformer.update(
1119
+ {"wpe": nn.Embedding(config.max_sequence_length, config.d_model, device=config.init_device)}
1120
+ )
1121
+ if not config.weight_tying:
1122
+ self.transformer.update(
1123
+ {
1124
+ "ff_out": nn.Linear(
1125
+ config.d_model,
1126
+ config.embedding_size or config.vocab_size,
1127
+ bias=config.include_bias,
1128
+ device=config.init_device,
1129
+ )
1130
+ }
1131
+ )
1132
+ # When `init_device="meta"` FSDP will call `reset_parameters()` to initialize weights.
1133
+ if init_params and self.config.init_device != "meta":
1134
+ self.reset_parameters()
1135
+ self.__num_fwd_flops: Optional[int] = None
1136
+
1137
+ # Warm up cache.
1138
+ if self.config.alibi:
1139
+ get_causal_attention_bias(self.__cache, config.max_sequence_length, _non_meta_init_device(config))
1140
+ self.get_alibi_attention_bias(config.max_sequence_length, _non_meta_init_device(config))
1141
+
1142
+ self.logit_cache = {}
1143
+
1144
+ def set_activation_checkpointing(self, strategy: Optional[ActivationCheckpointingStrategy]):
1145
+ self.activation_checkpointing_strategy = strategy
1146
+ if self.config.block_group_size != 1:
1147
+ for block_group in self.transformer.block_groups:
1148
+ block_group.set_activation_checkpointing(strategy)
1149
+ else:
1150
+ for block in self.transformer.blocks:
1151
+ block.set_activation_checkpointing(strategy)
1152
+
1153
+ @property
1154
+ def device(self) -> torch.device:
1155
+ device: torch.device = self.transformer.wte.weight.device # type: ignore
1156
+ if device.type == "meta":
1157
+ return _non_meta_init_device(self.config)
1158
+ else:
1159
+ return device
1160
+
1161
+ def reset_parameters(self):
1162
+ log.info("Initializing model parameters...")
1163
+ # Top-level embeddings / linear layers.
1164
+ init_weights(
1165
+ self.config,
1166
+ self.transformer.wte, # type: ignore
1167
+ std_factor=(0.5 * math.sqrt(self.config.d_model)) if self.config.scale_logits else 1.0,
1168
+ type_of_module=ModuleType.emb,
1169
+ )
1170
+ if hasattr(self.transformer, "wpe"):
1171
+ init_weights(self.config, self.transformer.wpe, type_of_module=ModuleType.emb) # type: ignore
1172
+
1173
+ # Top-level layer norm.
1174
+ self.transformer.ln_f.reset_parameters() # type: ignore
1175
+
1176
+ # Output weights.
1177
+ if hasattr(self.transformer, "ff_out"):
1178
+ init_weights(self.config, self.transformer.ff_out, type_of_module=ModuleType.final_out) # type: ignore
1179
+
1180
+ # Let the blocks handle themselves.
1181
+ if self.config.block_group_size == 1:
1182
+ for block in self.transformer.blocks:
1183
+ block.reset_parameters()
1184
+ else:
1185
+ for block_group in self.transformer.block_groups:
1186
+ block_group.reset_parameters()
1187
+
1188
+ def get_alibi_attention_bias(self, seq_len: int, device: torch.device) -> torch.Tensor:
1189
+ if (alibi_bias := self.__cache.get("alibi_attention_bias")) is not None and alibi_bias.shape[
1190
+ -1
1191
+ ] >= seq_len:
1192
+ if alibi_bias.device != device:
1193
+ alibi_bias = alibi_bias.to(device)
1194
+ self.__cache["alibi_attention_bias"] = alibi_bias
1195
+ return alibi_bias
1196
+ with torch.autocast(device.type, enabled=False):
1197
+ alibi_bias = alibi_attention_bias(seq_len, self.config, device)
1198
+ self.__cache["alibi_attention_bias"] = alibi_bias
1199
+ return alibi_bias
1200
+
1201
+ def forward(
1202
+ self,
1203
+ input_ids: torch.LongTensor,
1204
+ input_embeddings: Optional[torch.FloatTensor] = None,
1205
+ attention_mask: Optional[torch.Tensor] = None,
1206
+ attention_bias: Optional[torch.Tensor] = None,
1207
+ past_key_values: Optional[Sequence[Tuple[torch.Tensor, torch.Tensor]]] = None,
1208
+ last_logits_only: bool = False,
1209
+ output_hidden_states: Optional[bool] = None,
1210
+ use_cache = False,
1211
+ to_compute_mask = None,
1212
+ cat = '',
1213
+ ) -> LLaDAOutput:
1214
+ """
1215
+ :param input_ids: A tensor of shape `(batch_size, seq_len)`.
1216
+ :param input_embeddings: A tensor of shape `(batch_size, seq_len, d_model)` with input
1217
+ embeddings. When provided, it is treated as the output of the input embedding layer.
1218
+ :param attention_mask: A tensor of shape `(batch_size, seq_len)` that indicates
1219
+ which input IDs are masked. A `1` value in the mask means that
1220
+ the corresponding input ID should *not* be ignored. A `0` means
1221
+ that the corresponding input ID is masked.
1222
+
1223
+ This has the same meaning as the `attention_mask` in HuggingFace's `transformers`
1224
+ library.
1225
+ :param attention_bias: A tensor of shape `(batch_size, 1, seq_len, seq_len)`,
1226
+ `(1, 1, seq_len, seq_len)`, or `(seq_len, seq_len)`. This is used
1227
+ to introduce causal or other biases.
1228
+
1229
+ If the tensor is a bool or byte tensor, a `True` or `1` at `attention_bias[:, :, i, j]`
1230
+ indicates that the i-th element in the sequence is allowed to attend to the j-th
1231
+ element in the sequence.
1232
+
1233
+ If the tensor is a float tensor, it will just be added to the attention
1234
+ scores before the softmax.
1235
+
1236
+ The default is causal, which corresponds to a lower-diagonal byte matrix of ones.
1237
+ :param past_key_values: Pre-computed keys and values for each attention block.
1238
+ Can be used to speed up sequential decoding. The `input_ids` which have
1239
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
1240
+ :param use_cache: If `True`, return key and value tensors for each block.
1241
+ :param last_logits_only: If `True`, only compute the logits for the last token of each sequence.
1242
+ This can speed up decoding when you only care about the next token.
1243
+ """
1244
+ if use_cache and to_compute_mask is not None:
1245
+ input_ids = input_ids[to_compute_mask].view(input_ids.shape[0], -1)
1246
+
1247
+ # Add Basic MDM Model config check
1248
+ assert not self.config.alibi, "Alibi length extrapolation is not supported for MDM."
1249
+ assert self.config.rope, "Rope must be used in Llama-Encoder for MDM."
1250
+ # assert (past_key_values is None and not use_cache), "The kvcache is not suppotred for MDM."
1251
+
1252
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else False
1253
+
1254
+ if past_key_values:
1255
+ assert len(past_key_values) == self.config.n_layers
1256
+
1257
+ batch_size, seq_len = input_ids.size() if input_embeddings is None else input_embeddings.size()[:2]
1258
+ if past_key_values is None:
1259
+ past_length = 0
1260
+ else:
1261
+ past_length = past_key_values[0][0].size(-2)
1262
+
1263
+ # Get embeddings of input.
1264
+ # shape: (batch_size, seq_len, d_model)
1265
+ x = self.transformer.wte(input_ids) if input_embeddings is None else input_embeddings # type: ignore
1266
+
1267
+ if self.config.input_emb_norm:
1268
+ x = x * (self.config.d_model**0.5)
1269
+
1270
+ if not (self.config.alibi or self.config.rope):
1271
+ # Get positional embeddings.
1272
+ # shape: (1, seq_len)
1273
+ pos = torch.arange(past_length, past_length + seq_len, dtype=torch.long, device=x.device).unsqueeze(0)
1274
+ # shape: (1, seq_len, d_model)
1275
+ pos_emb = self.transformer.wpe(pos) # type: ignore
1276
+ x = pos_emb + x
1277
+
1278
+ # Add input + positional embeddings and apply dropout.
1279
+ # shape: (batch_size, seq_len, d_model)
1280
+ x = self.transformer.emb_drop(x) # type: ignore
1281
+
1282
+ # Transform the attention mask into what the blocks expect.
1283
+ if attention_mask is not None and 0.0 in attention_mask:
1284
+ # shape: (batch_size, 1, 1, seq_len)
1285
+ attention_mask = attention_mask.to(dtype=torch.float).view(batch_size, -1)[:, None, None, :]
1286
+ attention_mask = (1.0 - attention_mask) * torch.finfo(attention_mask.dtype).min
1287
+ else:
1288
+ attention_mask = None
1289
+
1290
+ # Merge attention mask with attention bias.
1291
+ if (
1292
+ attention_bias is not None
1293
+ or attention_mask is not None
1294
+ or self.config.alibi
1295
+ # NOTE (epwalsh): we need to initialize the attn bias in order for attn to work properly
1296
+ # with key+value cache. Otherwise `F.scaled_dot_product_attention()` doesn't seem to compute
1297
+ # scores correctly.
1298
+ or past_key_values is not None
1299
+ ):
1300
+ if attention_bias is None and self.config.alibi:
1301
+ attention_bias = get_causal_attention_bias(
1302
+ self.__cache, past_length + seq_len, x.device
1303
+ ) + self.get_alibi_attention_bias(past_length + seq_len, x.device)
1304
+ elif attention_bias is None:
1305
+ attention_bias = get_causal_attention_bias(self.__cache, past_length + seq_len, x.device)
1306
+ elif attention_bias.dtype in (torch.int8, torch.bool):
1307
+ attention_bias = attention_bias.to(dtype=torch.float)
1308
+ attention_bias.masked_fill_(attention_bias == 0.0, torch.finfo(attention_bias.dtype).min)
1309
+
1310
+ # Transform to the right shape and data type.
1311
+ mask_len = seq_len
1312
+ if attention_mask is not None:
1313
+ mask_len = attention_mask.shape[-1]
1314
+ elif past_key_values is not None:
1315
+ mask_len = past_key_values[0][0].shape[-2] + seq_len
1316
+ attention_bias = attention_bias[:, :, :mask_len, :mask_len].to(dtype=torch.float)
1317
+
1318
+ # Add in the masking bias.
1319
+ if attention_mask is not None:
1320
+ attention_bias = attention_bias + attention_mask
1321
+ # Might get -infs after adding attention mask, since dtype.min + dtype.min = -inf.
1322
+ # `F.scaled_dot_product_attention()` doesn't handle -inf like you'd expect, instead
1323
+ # it can produce NaNs.
1324
+ ensure_finite_(attention_bias, check_neg_inf=True, check_pos_inf=False)
1325
+
1326
+ attn_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = [] if use_cache else None
1327
+
1328
+ # decoder layers
1329
+ all_hidden_states = []
1330
+
1331
+ # Apply blocks one-by-one.
1332
+ if self.config.block_group_size == 1:
1333
+ for block_idx, block in enumerate(self.transformer.blocks):
1334
+ if output_hidden_states:
1335
+ # add hidden states
1336
+ all_hidden_states.append(x)
1337
+
1338
+ layer_past = None if past_key_values is None else past_key_values[block_idx]
1339
+ if (
1340
+ (self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.whole_layer)
1341
+ or (
1342
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_two
1343
+ and block_idx % 2 == 0
1344
+ )
1345
+ or (
1346
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_three
1347
+ and block_idx % 3 == 0
1348
+ )
1349
+ or (
1350
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_four
1351
+ and block_idx % 4 == 0
1352
+ )
1353
+ ):
1354
+ # shape: (batch_size, seq_len, d_model)
1355
+ x, _ = self._activation_checkpoint_fn(
1356
+ block, x, attention_bias=attention_bias, layer_past=layer_past,
1357
+ to_compute_mask=to_compute_mask, use_cache=use_cache, cat=cat
1358
+ )
1359
+ else:
1360
+ # shape: (batch_size, seq_len, d_model)
1361
+ LLaDALlamaBlock.forward
1362
+ x, _ = block(x, attention_bias=attention_bias, layer_past=layer_past,
1363
+ to_compute_mask=to_compute_mask, use_cache=use_cache, cat=cat
1364
+ )
1365
+ else:
1366
+ for group_idx, block_group in enumerate(self.transformer.block_groups):
1367
+ if output_hidden_states:
1368
+ # add hidden states
1369
+ all_hidden_states.append(x)
1370
+
1371
+ layers_past = (
1372
+ None
1373
+ if past_key_values is None
1374
+ else past_key_values[
1375
+ group_idx * self.config.block_group_size : (group_idx + 1) * self.config.block_group_size
1376
+ ]
1377
+ )
1378
+ x, _ = block_group(
1379
+ x, attention_bias=attention_bias, layers_past=layers_past,
1380
+ to_compute_mask=to_compute_mask, use_cache=use_cache, cat=cat
1381
+ )
1382
+ # if attn_key_values is not None:
1383
+ # assert cache is not None
1384
+ # attn_key_values.extend(cache)
1385
+
1386
+ if last_logits_only:
1387
+ # shape: (batch_size, 1, d_model)
1388
+ x = x[:, -1, :].unsqueeze(1)
1389
+
1390
+ # Apply final layer norm.
1391
+ # shape: (batch_size, seq_len or 1, d_model)
1392
+ x = self.transformer.ln_f(x) # type: ignore
1393
+ if output_hidden_states:
1394
+ # add final hidden state post-final-layernorm, following HuggingFace's convention
1395
+ all_hidden_states.append(x)
1396
+
1397
+ # Get logits.
1398
+ # shape: (batch_size, seq_len or 1, vocab_size)
1399
+ if self.config.weight_tying:
1400
+ logits = F.linear(x, self.transformer.wte.weight, None) # type: ignore
1401
+ else:
1402
+ logits = self.transformer.ff_out(x) # type: ignore
1403
+ if self.config.scale_logits:
1404
+ logits.mul_(1 / math.sqrt(self.config.d_model))
1405
+
1406
+ if use_cache:
1407
+ if cat not in self.logit_cache:
1408
+ self.logit_cache[cat] = torch.zeros_like(logits)
1409
+ if to_compute_mask is not None:
1410
+ self.logit_cache[cat][to_compute_mask] = logits.view(-1, logits.shape[-1])
1411
+ logits = self.logit_cache[cat]
1412
+ else:
1413
+ self.logit_cache[cat] = logits
1414
+
1415
+ return LLaDAOutput(logits=logits, attn_key_values=attn_key_values, hidden_states=tuple(all_hidden_states) if output_hidden_states else None) # type: ignore[arg-type]
1416
+
1417
+ def caching(self, enable: bool = True):
1418
+ LLaDABlock.caching
1419
+ for block in self.transformer.blocks:
1420
+ block.caching(enable)
1421
+ self.logit_cache = {}
1422
+
1423
+ def empty_cache(self):
1424
+ for block in self.transformer.blocks:
1425
+ block.init_cache()
1426
+ self.logit_cache = {}
1427
+
1428
+
1429
+ def create_model_config_from_pretrained_config(config: LLaDAConfig):
1430
+ """
1431
+ Utility function
1432
+ """
1433
+
1434
+ kwargs = {}
1435
+ for field in fields(ModelConfig):
1436
+ kwargs[field.name] = getattr(config, field.name)
1437
+
1438
+ model_config = ModelConfig(**kwargs)
1439
+ return model_config
1440
+
1441
+
1442
+ class LLaDAModelLM(PreTrainedModel):
1443
+ """
1444
+ Extremely barebones HF model wrapper.
1445
+ """
1446
+
1447
+ config_class = LLaDAConfig
1448
+ base_model_prefix = "model"
1449
+ _no_split_modules = ["LLaDABlock", "LLaDASequentialBlock", "LLaDALlamaBlock"]
1450
+
1451
+ def __init__(self, config: LLaDAConfig, model: Optional[LLaDAModel] = None, init_params: bool = False):
1452
+ super().__init__(config)
1453
+
1454
+ if not model:
1455
+ model_config = create_model_config_from_pretrained_config(config)
1456
+ # Initialize model (always on CPU to start with so we don't run out of GPU memory).
1457
+ model_config.init_device = "cpu"
1458
+ self.model = LLaDAModel(model_config, init_params=init_params)
1459
+ else:
1460
+ self.model = model
1461
+
1462
+ def forward(
1463
+ self,
1464
+ input_ids: torch.LongTensor = None,
1465
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1466
+ attention_mask: Optional[torch.Tensor] = None,
1467
+ attention_bias: Optional[torch.Tensor] = None,
1468
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1469
+ labels: Optional[torch.LongTensor] = None,
1470
+ output_attentions: Optional[bool] = None,
1471
+ output_hidden_states: Optional[bool] = None,
1472
+ return_dict: Optional[bool] = None,
1473
+ cache_position: Optional[Cache] = None, # This is a hack mitigation of an issue in transformers `4.39.x`
1474
+ use_cache = False,
1475
+ to_compute_mask = None,
1476
+ cat = '',
1477
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1478
+ if output_attentions:
1479
+ raise ValueError("output_attentions is not yet supported in LLaDA")
1480
+
1481
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1482
+
1483
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1484
+ outputs = self.model.forward(
1485
+ input_ids=input_ids,
1486
+ input_embeddings=inputs_embeds,
1487
+ attention_mask=attention_mask,
1488
+ attention_bias=attention_bias,
1489
+ past_key_values=past_key_values,
1490
+ output_hidden_states=output_hidden_states,
1491
+ use_cache=use_cache,
1492
+ to_compute_mask=to_compute_mask,
1493
+ cat=cat,
1494
+ )
1495
+
1496
+ logits = outputs.logits
1497
+ hidden_states = outputs.hidden_states
1498
+
1499
+ loss = None
1500
+ if labels is not None:
1501
+ import warnings
1502
+ warnings.warn("Note that for LLaDA, you cannot calculate the loss here.", UserWarning)
1503
+ if not return_dict:
1504
+ output = (logits,) + outputs[1:]
1505
+ return (loss,) + output if loss is not None else output
1506
+
1507
+ return CausalLMOutputWithPast(
1508
+ logits=logits,
1509
+ past_key_values=outputs.attn_key_values,
1510
+ hidden_states=hidden_states,
1511
+ )
1512
+
1513
+ def can_generate(self) -> bool:
1514
+ return True
1515
+
1516
+ def prepare_inputs_for_generation(
1517
+ self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple]] = None, **kwargs
1518
+ ):
1519
+ if past_key_values:
1520
+ # This is because we want the model to only process the last generated token.
1521
+ input_ids = input_ids[:, -1:]
1522
+ model_inputs = {"input_ids": input_ids, "past_key_values": past_key_values}
1523
+
1524
+ model_inputs.update(kwargs)
1525
+ model_inputs["use_cache"] = kwargs.pop("use_cache", self.config.use_cache)
1526
+ return model_inputs
1527
+
1528
+ # TODO: these are required to make the implementation complete.
1529
+ # def resize_position_embeddings(self, new_num_position_embeddings: int):
1530
+ # pass
1531
+ #
1532
+ # def get_position_embeddings(self) -> Union[nn.Embedding, Tuple[nn.Embedding]]:
1533
+ # pass
1534
+ #
1535
+ # def _reorder_cache(self, past_key_values, beam_idx):
1536
+ # pass
1537
+
1538
+ def get_input_embeddings(self) -> torch.nn.Module:
1539
+ return self.model.transformer.wte
1540
+
1541
+ def set_input_embeddings(self, value: torch.nn.Module):
1542
+ self.model.transformer.wte = value
1543
+
1544
+ def get_output_embeddings(self):
1545
+ if self.config.weight_tying:
1546
+ return self.model.transformer.wte
1547
+ else:
1548
+ return self.model.transformer.ff_out
1549
+
1550
+ def set_output_embeddings(self, value: torch.nn.Module):
1551
+ if self.config.weight_tying:
1552
+ self.model.transformer.wte = value
1553
+ else:
1554
+ self.model.transformer.ff_out = value
1555
+
1556
+ def tie_weights(self):
1557
+ if self.config.weight_tying:
1558
+ self.model.transformer.ff_out = self.model.transformer.wte
1559
+
1560
+ def caching(self, enable: bool = True):
1561
+ self.model.caching(enable)
1562
+
1563
+ def empty_cache(self):
1564
+ self.model.empty_cache()
1565
+
1566
+ # Register the model so that it is available for transformer pipelines, auto-loading, etc.
1567
+ AutoModel.register(LLaDAConfig, LLaDAModelLM)
model/modeling_xllmx_dimoo.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import logging
3
+ import math
4
+ from typing import List, Dict, Tuple, Optional
5
+ import torch.nn.functional as F
6
+ import torch
7
+ from torch import nn
8
+ from transformers import AutoTokenizer, AutoConfig
9
+ from .modeling_llada import LLaDAModelLM
10
+ from .configuration_llada import LLaDAConfig
11
+ from transformers.modeling_outputs import CausalLMOutputWithPast
12
+
13
+ __all__ = ["LLaDAForMultiModalGeneration"]
14
+
15
+
16
+ def create_attention_mask(original_lengths, max_tokens, device):
17
+ batch_size = len(original_lengths)
18
+ attention_mask = torch.zeros(batch_size, max_tokens, dtype=torch.bool, device=device)
19
+ for i, length in enumerate(original_lengths):
20
+ attention_mask[i, :length] = 1
21
+ return attention_mask
22
+
23
+
24
+ class LLaDAForMultiModalGeneration(LLaDAModelLM):
25
+ config_class = LLaDAConfig
26
+ base_model_prefix = "model"
27
+
28
+ IMAGE_START_TOKEN = 126349
29
+ IMAGE_END_TOKEN = 126350
30
+ ANSWER_START_TOKEN = 126354
31
+ ANSWER_END_TOKEN = 126355
32
+ BREAKLINE_TOKEN = 126084
33
+ MASK_TOKEN = 126336
34
+ PAD_TOKEN = 126339
35
+
36
+ def __init__(self, config: LLaDAConfig, *args, **kwargs):
37
+ print(f"Initializing LLaDAForMultiModalGeneration with config: {config}")
38
+ super().__init__(config, *args, **kwargs)
39
+ self._debug_step = 0
40
+
41
+ def forward(
42
+ self,
43
+ input_ids=None,
44
+ labels=None,
45
+ infer=False,
46
+ use_cache=False,
47
+ return_dict=False,
48
+ compute_separate_losses=True,
49
+ t=None,
50
+ text_coeff=1.0,
51
+ image_coeff=1.0,
52
+ ):
53
+ if infer:
54
+ input_ids = input_ids.tolist()
55
+
56
+ max_tokens = max([len(_) for _ in input_ids])
57
+ original_lengths = [len(example) for example in input_ids]
58
+ input_ids = [example + [0] * (max_tokens - len(example)) for example in input_ids]
59
+ input_ids = torch.tensor(input_ids, dtype=torch.int64, device=self.device)
60
+
61
+ attention_mask = create_attention_mask(original_lengths, max_tokens, self.device)
62
+ attention_bias = (attention_mask[:, :, None] & attention_mask[:, None, :]).bool().unsqueeze(1)
63
+
64
+ output = LLaDAModelLM.forward(
65
+ self,
66
+ input_ids=input_ids,
67
+ attention_bias=attention_bias,
68
+ use_cache=use_cache
69
+ )
70
+
71
+ if infer:
72
+ return output
73
+
74
+ if labels is None:
75
+ if return_dict:
76
+ return {'logits': output.logits}
77
+ else:
78
+ return output.logits
79
+
80
+ labels = [label + [-100] * (max_tokens - len(label)) for label in labels]
81
+ labels = torch.tensor(labels, dtype=torch.int64, device=self.device)
82
+
83
+ logits = output.logits
84
+ batch_size = logits.shape[0]
85
+
86
+ unscaled_loss = F.cross_entropy(
87
+ logits.contiguous().view(-1, logits.shape[-1]),
88
+ labels.contiguous().view(-1),
89
+ ignore_index=-100,
90
+ reduction='none'
91
+ ).view(batch_size, -1)
92
+
93
+ valid_mask = (labels != -100)
94
+
95
+ if valid_mask.sum() > 0:
96
+ interleave_loss = unscaled_loss[valid_mask].mean()
97
+ else:
98
+ interleave_loss = torch.tensor(0.0, device=self.device)
99
+
100
+ if compute_separate_losses:
101
+ self._debug_step += 1
102
+ debug_this_step = (self._debug_step <= 3)
103
+
104
+ if debug_this_step:
105
+ print(f"\n{'='*80}")
106
+ print(f"DEBUG Step {self._debug_step}")
107
+ print(f"{'='*80}")
108
+
109
+ text_loss_list = []
110
+ image_loss_list = []
111
+
112
+ for b in range(batch_size):
113
+ answer_start_positions = (input_ids[b] == self.ANSWER_START_TOKEN).nonzero(as_tuple=True)[0]
114
+
115
+ if len(answer_start_positions) == 0:
116
+ continue
117
+
118
+ answer_start = answer_start_positions[0].item()
119
+
120
+ answer_end_in_search = (input_ids[b, answer_start:] == self.ANSWER_END_TOKEN).nonzero(as_tuple=True)[0]
121
+ if len(answer_end_in_search) > 0:
122
+ answer_end = answer_start + answer_end_in_search[0].item()
123
+ else:
124
+ answer_end = original_lengths[b]
125
+
126
+ answer_region_input = input_ids[b, answer_start:answer_end]
127
+ image_start_in_answer = (answer_region_input == self.IMAGE_START_TOKEN).nonzero(as_tuple=True)[0]
128
+
129
+ if len(image_start_in_answer) > 0:
130
+ image_start_pos = answer_start + image_start_in_answer[0].item()
131
+ image_end_search = input_ids[b, image_start_pos:]
132
+ image_end_in_search = (image_end_search == self.IMAGE_END_TOKEN).nonzero(as_tuple=True)[0]
133
+
134
+ if len(image_end_in_search) > 0 :
135
+ image_end_pos = image_start_pos + image_end_in_search[0].item()
136
+
137
+ for pos in range(image_start_pos + 1, image_end_pos):
138
+ if input_ids[b, pos] != self.BREAKLINE_TOKEN:
139
+ image_loss_list.append(unscaled_loss[b, pos])
140
+
141
+ for pos in range(image_end_pos + 1, answer_end):
142
+ if labels[b, pos] != -100:
143
+ text_loss_list.append(unscaled_loss[b, pos])
144
+ else:
145
+ for pos in range(answer_start + 1, answer_end):
146
+ if labels[b, pos] != -100:
147
+ text_loss_list.append(unscaled_loss[b, pos])
148
+
149
+ if debug_this_step:
150
+ print(f"Total text_loss_list length: {len(text_loss_list)}")
151
+ print(f"Total image_loss_list length: {len(image_loss_list)}")
152
+ if len(text_loss_list) > 0:
153
+ non_zero_text = [l.item() for l in text_loss_list if l.item() > 0]
154
+ print(f"Non-zero text losses count: {len(non_zero_text)}/{len(text_loss_list)}")
155
+ print(f"Sample non-zero text losses: {non_zero_text[:5]}")
156
+ if len(image_loss_list) > 0:
157
+ non_zero_image = [l.item() for l in image_loss_list if l.item() > 0]
158
+ print(f"Non-zero image losses count: {len(non_zero_image)}/{len(image_loss_list)}")
159
+ print(f"Sample non-zero image losses: {non_zero_image[:5]}")
160
+ print(f"{'='*80}\n")
161
+
162
+ if len(text_loss_list) > 0:
163
+ text_loss = torch.stack(text_loss_list).mean()
164
+ else:
165
+ text_loss = torch.tensor(0.0, device=self.device)
166
+
167
+ if len(image_loss_list) > 0:
168
+ image_loss = torch.stack(image_loss_list).mean()
169
+ else:
170
+ image_loss = torch.tensor(0.0, device=self.device)
171
+
172
+ if t is not None and len(text_loss_list) > 0:
173
+ text_loss = text_loss / t.mean().clamp(min=0.01)
174
+
175
+ if return_dict:
176
+ return {
177
+ 'logits': logits,
178
+ 'loss': interleave_loss,
179
+ 'interleave_loss': interleave_loss,
180
+ 'text_loss': text_loss,
181
+ 'image_loss': image_loss,
182
+ 'labels': labels,
183
+ }
184
+ else:
185
+ return interleave_loss, {
186
+ 'text_loss': text_loss,
187
+ 'image_loss': image_loss,
188
+ 'interleave_loss': interleave_loss,
189
+ }
190
+ else:
191
+ if return_dict:
192
+ return {'logits': logits, 'loss': interleave_loss, 'labels': labels}
193
+ else:
194
+ return interleave_loss
195
+
196
+ def get_fsdp_wrap_module_list(self) -> List:
197
+ modules = [*list(self.model.transformer.blocks), self.model.transformer.ff_out]
198
+ return modules
199
+
200
+
201
+ def get_checkpointing_wrap_module_list(self) -> List:
202
+ return list(self.model.transformer.blocks)
utils/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Utility modules
4
+ """
utils/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (223 Bytes). View file
 
utils/__pycache__/generation_utils.cpython-311.pyc ADDED
Binary file (5.68 kB). View file
 
utils/__pycache__/image_utils.cpython-311.pyc ADDED
Binary file (15.4 kB). View file
 
utils/__pycache__/prompt_utils.cpython-311.pyc ADDED
Binary file (7.9 kB). View file
 
utils/generation_utils.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Generation related utility functions
4
+ """
5
+ import math
6
+ import torch
7
+ import torch.nn.functional as F
8
+ import numpy as np
9
+ from typing import Callable, Optional
10
+
11
+
12
+ def add_gumbel_noise(logits, temperature):
13
+ """
14
+ Gumbel noise addition function
15
+ According to arXiv:2409.02908, for MDM, low-precision Gumbel Max improves perplexity score but reduces generation quality
16
+ Therefore using float64
17
+ """
18
+ if temperature == 0:
19
+ return logits
20
+ logits = logits.to(torch.float64)
21
+ noise = torch.rand_like(logits, dtype=torch.float64)
22
+ gumbel_noise = (- torch.log(noise)) ** temperature
23
+ return logits.exp() / gumbel_noise
24
+
25
+
26
+ def cosine_schedule(t: torch.Tensor) -> torch.Tensor:
27
+ """Cosine schedule function: m(t) = cos(π/2 · t) – MaskGit paper Eq.(3)"""
28
+ return torch.cos(0.5 * math.pi * t)
29
+
30
+
31
+ def gumbel_noise(t: torch.Tensor, *, generator: Optional[torch.Generator] = None) -> torch.Tensor:
32
+ """Return i.i.d. Gumbel(0,1) noise with same shape as t"""
33
+ if generator is None:
34
+ u = torch.rand_like(t)
35
+ else:
36
+ u = torch.rand(t.shape, device=t.device, dtype=t.dtype, generator=generator)
37
+ return -torch.log(-torch.log(u + 1e-20) + 1e-20)
38
+
39
+
40
+ def gumbel_max_sample(logits: torch.Tensor, tau: float = 1.0, *, generator: Optional[torch.Generator] = None) -> torch.Tensor:
41
+ """Sample from categorical(logits) via Gumbel-Max. τ=0 → greedy argmax"""
42
+ if tau == 0.0:
43
+ return logits.argmax(dim=-1)
44
+ g = gumbel_noise(logits, generator=generator)
45
+ return (logits / tau + g).argmax(dim=-1)
46
+
47
+
48
+ def mask_by_random_topk(
49
+ mask_len: torch.Tensor, # (B,) number of tokens to keep masked
50
+ probs: torch.Tensor, # (B, L) sampled token probability
51
+ *,
52
+ temperature: float = 1.0,
53
+ generator: Optional[torch.Generator] = None,
54
+ ) -> torch.BoolTensor:
55
+ """Return Boolean mask – True means *stay masked* for next step"""
56
+ g = gumbel_noise(probs, generator=generator)
57
+ confidence = torch.log(probs.clamp_min(1e-20)) + temperature * g # higher = more confident
58
+ sorted_conf = torch.sort(confidence, dim=-1).values # ascending
59
+ k = mask_len.long().unsqueeze(1).clamp_(0, probs.size(1) - 1)
60
+ cut_off = torch.gather(sorted_conf, 1, k) # (B,1)
61
+ return confidence < cut_off # (B,L)
62
+
63
+
64
+ def get_num_transfer_tokens(mask_index, steps):
65
+ """
66
+ In the reverse process, the interval [0, 1] is uniformly discretized into steps intervals
67
+ Since LLaDA employs a linear noise schedule (as defined in Eq.(8)),
68
+ the expected number of tokens transitioned at each step should be consistent
69
+
70
+ This function is designed to precompute the number of tokens that need to be transitioned at each step
71
+ """
72
+ mask_num = mask_index.sum(dim=1, keepdim=True)
73
+
74
+ base = mask_num // steps
75
+ remainder = mask_num % steps
76
+
77
+ num_transfer_tokens = torch.zeros(mask_num.size(0), steps, device=mask_index.device, dtype=torch.int64) + base
78
+
79
+ for i in range(mask_num.size(0)):
80
+ num_transfer_tokens[i, :remainder[i]] += 1
81
+
82
+ return num_transfer_tokens
83
+
84
+ def setup_seed(seed: int):
85
+ """Set random seed"""
86
+ import random
87
+ torch.manual_seed(seed)
88
+ torch.cuda.manual_seed_all(seed)
89
+ random.seed(seed)
utils/image_utils.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Image processing utilities
4
+ """
5
+ import torch
6
+ import PIL
7
+ import random
8
+ from PIL import Image, ImageDraw
9
+ from diffusers import VQModel
10
+ from diffusers.image_processor import VaeImageProcessor
11
+ import torch.nn.functional as F
12
+
13
+ def decode_vq_to_image(
14
+ vq_codes: torch.LongTensor,
15
+ save_path: str = None,
16
+ vae_ckpt: str = None,
17
+ image_height: int = 512,
18
+ image_width: int = 512,
19
+ vqvae: VQModel = None
20
+ ) -> Image.Image:
21
+ """
22
+ Decode VQ codes to image
23
+
24
+ Args:
25
+ vq_codes: VQ codes in range [0, codebook_size), shape [batch_size, seq_len]
26
+ save_path: Save path (optional, if None will not save to file)
27
+ vae_ckpt: VAE checkpoint path (optional if vqvae is provided)
28
+ image_height: Image height
29
+ image_width: Image width
30
+ vqvae: VQ-VAE model, if None will load from vae_ckpt
31
+
32
+ Returns:
33
+ PIL image
34
+ """
35
+ device = vq_codes.device
36
+ if vqvae is None:
37
+ vqvae = VQModel.from_pretrained(vae_ckpt, subfolder="vqvae").to(device)
38
+
39
+ scale = 2 ** (len(vqvae.config.block_out_channels) - 1)
40
+ img_proc = VaeImageProcessor(vae_scale_factor=scale, do_normalize=False)
41
+
42
+ # Calculate latent space grid size
43
+ latent_height = image_height // scale
44
+ latent_width = image_width // scale
45
+
46
+ # Ensure VQ codes length matches
47
+ expected_len = latent_height * latent_width
48
+ if vq_codes.shape[1] != expected_len:
49
+ raise ValueError(
50
+ f"VQ codes length mismatch: {vq_codes.shape[1]} != {expected_len} "
51
+ f"for image size ({image_height},{image_width}) with scale {scale}"
52
+ )
53
+
54
+ # Reshape to 2D grid: [batch_size, seq_len] -> [batch_size, latent_height, latent_width]
55
+ # vq_codes should already be in range [0, codebook_size), no offset needed
56
+
57
+
58
+ latents = vq_codes.view(vq_codes.shape[0], latent_height, latent_width).long()
59
+ # latents = (vq_codes.view(1, latent_height, latent_width) - 126356).long()
60
+
61
+ # Decode
62
+ recon = vqvae.decode(
63
+ latents,
64
+ force_not_quantize=True,
65
+ shape=(vq_codes.shape[0], latent_height, latent_width, vqvae.config.latent_channels),
66
+ ).sample.clip(0, 1)
67
+
68
+ # Post-process
69
+ img = img_proc.postprocess(recon.detach(), output_type="pil")[0]
70
+
71
+ # Save image (only if save_path is provided)
72
+ if save_path is not None:
73
+ img.save(save_path)
74
+
75
+ return img
76
+
77
+
78
+ def preprocess_image(image_path: str, target_size: tuple = (512, 512)):
79
+ """
80
+ Preprocess image: load, crop, resize
81
+
82
+ Args:
83
+ image_path: Image path
84
+ target_size: Target size (width, height)
85
+
86
+ Returns:
87
+ Processed PIL image
88
+ """
89
+ img = Image.open(image_path).convert("RGB")
90
+ crop_size_list = generate_crop_size_list((target_size[0] // 32) ** 2, 32)
91
+ processed_img = var_center_crop(img, crop_size_list=crop_size_list)
92
+ return processed_img
93
+
94
+
95
+ def calculate_vq_params(image_height: int, image_width: int, vae_scale: int = 16):
96
+ """
97
+ Calculate VQ related parameters
98
+
99
+ Args:
100
+ image_height: Image height
101
+ image_width: Image width
102
+ vae_scale: VAE scale factor
103
+
104
+ Returns:
105
+ seq_len, newline_every, token_grid_height, token_grid_width
106
+ """
107
+ token_grid_height = image_height // vae_scale
108
+ token_grid_width = image_width // vae_scale
109
+ seq_len = token_grid_height * token_grid_width
110
+ newline_every = token_grid_width
111
+ return seq_len, newline_every, token_grid_height, token_grid_width
112
+
113
+ def center_crop(pil_image, crop_size):
114
+ while pil_image.size[0] >= 2 * crop_size[0] and pil_image.size[1] >= 2 * crop_size[1]:
115
+ pil_image = pil_image.resize(tuple(x // 2 for x in pil_image.size), resample=Image.BOX)
116
+
117
+ scale = max(crop_size[0] / pil_image.size[0], crop_size[1] / pil_image.size[1])
118
+ pil_image = pil_image.resize(tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC)
119
+
120
+ crop_left = random.randint(0, pil_image.size[0] - crop_size[0])
121
+ crop_upper = random.randint(0, pil_image.size[1] - crop_size[1])
122
+ crop_right = crop_left + crop_size[0]
123
+ crop_lower = crop_upper + crop_size[1]
124
+ return pil_image.crop(box=(crop_left, crop_upper, crop_right, crop_lower))
125
+
126
+
127
+ def var_center_crop(pil_image, crop_size_list, random_top_k=1):
128
+ w, h = pil_image.size
129
+ rem_percent = [min(cw / w, ch / h) / max(cw / w, ch / h) for cw, ch in crop_size_list]
130
+ crop_size = random.choice(
131
+ sorted(((x, y) for x, y in zip(rem_percent, crop_size_list)), reverse=True)[:random_top_k]
132
+ )[1]
133
+ return center_crop(pil_image, crop_size)
134
+
135
+
136
+ def generate_crop_size_list(num_patches, patch_size, max_ratio=4.0):
137
+ assert max_ratio >= 1.0
138
+ crop_size_list = []
139
+ wp, hp = num_patches, 1
140
+ while wp > 0:
141
+ if max(wp, hp) / min(wp, hp) <= max_ratio:
142
+ crop_size_list.append((wp * patch_size, hp * patch_size))
143
+ if (hp + 1) * wp <= num_patches:
144
+ hp += 1
145
+ else:
146
+ wp -= 1
147
+ return crop_size_list
148
+
149
+ def add_break_line(sequence: list, H: int, W: int, new_number: int = 0) -> list:
150
+ """Add newline characters to sequence"""
151
+ result = []
152
+ for i in range(H):
153
+ start = i * W
154
+ end = start + W
155
+ row = sequence[start:end]
156
+ result.extend(row + [new_number])
157
+ return result
158
+
159
+ def encode_img_with_breaks(img, vqvae, vae_scale_factor: int = 16):
160
+ """Encode image and add newline characters"""
161
+ from diffusers.image_processor import VaeImageProcessor
162
+
163
+ orig = img.convert("RGB")
164
+ orig_resized = orig
165
+ image_processor = VaeImageProcessor(vae_scale_factor=vae_scale_factor, do_normalize=False)
166
+ x = image_processor.preprocess(orig_resized).to(vqvae.device)
167
+ latents = vqvae.encode(x).latents
168
+ latents_bsz, channels, lat_h, lat_w = latents.shape
169
+ quantized = vqvae.quantize(latents)[2][2] + 126356
170
+ quantized = quantized.reshape(latents_bsz, lat_h, lat_w).flatten().tolist()
171
+ img_token = add_break_line(quantized, lat_h, lat_w, new_number=126084)
172
+ img_token = [126349] + img_token + [126350]
173
+ return img_token
174
+
175
+ @torch.no_grad()
176
+ def encode_img_with_paint(
177
+ img: Image.Image,
178
+ vqvae: VQModel,
179
+ *,
180
+ mask_h_ratio: float = 1, # Height ratio
181
+ mask_w_ratio: float = 0.2, # Width ratio
182
+ gray_value: int = 127, # Visualization gray value
183
+ downsample_mode: str = "area",# Pixel mask alignment to latent grid
184
+ dilate_latent_k: int = 0, # Optional dilation on latent grid (grid count)
185
+ mask_mode: str = "inpainting", # "inpainting" | "outpainting"
186
+ ):
187
+ """
188
+ Encode image with mask for inpainting/outpainting tasks
189
+
190
+ Args:
191
+ img: Input PIL image
192
+ vqvae: VQ-VAE model for encoding
193
+ mask_h_ratio: Height ratio for mask region (default: 1.0)
194
+ mask_w_ratio: Width ratio for mask region (default: 0.2)
195
+ gray_value: Gray value for mask visualization (default: 127)
196
+ downsample_mode: Downsampling mode for mask alignment ("area", "nearest", "bilinear")
197
+ dilate_latent_k: Dilation kernel size for latent grid (default: 0)
198
+ mask_mode: Mask mode - "inpainting" (mask inside) or "outpainting" (mask outside)
199
+
200
+ Returns:
201
+ img_token: List[int] - Token sequence with newlines (126084) inserted at row ends;
202
+ masked positions = 126336, others = index + 126356
203
+ vis_img: PIL.Image - Gray mask visualization image (consistent with mask_mode)
204
+
205
+ Note:
206
+ * Encoding uses original image strictly; mask only maps to latent grid to determine
207
+ which tokens are set to MASK_TOKEN_ID.
208
+ * mask_mode="inpainting": mask inside rectangle; "outpainting": mask outside rectangle (inverse).
209
+ """
210
+ MASK_TOKEN_ID = 126336 # mask token
211
+ NEWLINE_TOKEN_ID = 126084 # newline token
212
+ VQ_OFFSET = 126356 # quantization index offset
213
+
214
+ assert mask_mode in ("inpainting", "outpainting"), "mask_mode must be 'inpainting' or 'outpainting'"
215
+
216
+ # --- 1) Calculate center rectangle and generate visualization ---
217
+ img = img.convert("RGB")
218
+ W, H = img.size
219
+ mh = int(round(H * mask_h_ratio))
220
+ mw = int(round(W * mask_w_ratio))
221
+ top = (H - mh) // 2
222
+ left = (W - mw) // 2
223
+ bottom = top + mh
224
+ right = left + mw
225
+
226
+ if mask_mode == "inpainting":
227
+ vis_img = img.copy()
228
+ draw = ImageDraw.Draw(vis_img)
229
+ draw.rectangle([left, top, right, bottom], fill=(gray_value, gray_value, gray_value))
230
+ elif mask_mode == "outpainting": # outpainting
231
+ bg = Image.new("RGB", (W, H), (gray_value, gray_value, gray_value))
232
+ crop = img.crop((left, top, right, bottom))
233
+ bg.paste(crop, (left, top))
234
+ vis_img = bg
235
+
236
+ # --- 2) VQ encoding using original image ---
237
+ vae_scale_factor = 2 ** (len(vqvae.config.block_out_channels) - 1)
238
+ image_processor = VaeImageProcessor(vae_scale_factor=vae_scale_factor, do_normalize=False)
239
+ x = image_processor.preprocess(img).to(vqvae.device) # 1 x 3 x H' x W'
240
+ latents = vqvae.encode(x).latents # 1 x C x h x w
241
+ _, _, lat_h, lat_w = latents.shape
242
+
243
+ # Quantization indices
244
+ quant_pack = vqvae.quantize(latents)
245
+ indices = quant_pack[2][2].view(1, lat_h, lat_w) # 1 x h x w, long
246
+
247
+ # --- 3) Pixel mask -> latent grid mask (aligned with encoding input size) ---
248
+ Hp, Wp = x.shape[-2:]
249
+ mask_px = torch.zeros((1, 1, Hp, Wp), dtype=torch.float32, device=vqvae.device)
250
+ # First generate mask where "rectangle inside=1, outside=0"
251
+ top_p = int(round(top * Hp / H))
252
+ left_p = int(round(left * Wp / W))
253
+ bh_p = int(round(mh * Hp / H))
254
+ bw_p = int(round(mw * Wp / W))
255
+ mask_px[:, :, top_p:top_p+bh_p, left_p:left_p+bw_p] = 1.0
256
+
257
+ # If outpainting, need to invert (outside=1, inside=0 is the masked region)
258
+ if mask_mode == "outpainting":
259
+ mask_px = 1.0 - mask_px
260
+
261
+ if downsample_mode not in ("nearest", "area", "bilinear"):
262
+ downsample_mode = "area"
263
+ mask_lat = F.interpolate(mask_px, size=(lat_h, lat_w), mode=downsample_mode)
264
+ mask_lat = (mask_lat > 0.5) if downsample_mode == "area" else (mask_lat >= 0.5)
265
+ mask_lat = mask_lat[0, 0] # h x w (bool)
266
+
267
+ # Optional: latent grid dilation (after inversion is applied)
268
+ if dilate_latent_k > 0:
269
+ m = mask_lat.float().unsqueeze(0).unsqueeze(0)
270
+ ker = 2 * dilate_latent_k + 1
271
+ m = F.max_pool2d(m, kernel_size=ker, stride=1, padding=dilate_latent_k)
272
+ mask_lat = (m[0, 0] > 0.5)
273
+
274
+ # --- 4) Generate tokens: masked positions=MASK_TOKEN_ID, others=indices+VQ_OFFSET ---
275
+ idx_flat = indices.view(-1)
276
+ mask_flat = mask_lat.view(-1)
277
+ tokens = torch.empty_like(idx_flat)
278
+ tokens[mask_flat] = MASK_TOKEN_ID
279
+ tokens[~mask_flat] = idx_flat[~mask_flat] + VQ_OFFSET
280
+ tokens_list = tokens.tolist()
281
+
282
+ # --- 5) Insert newlines (no longer wrapped in <boi>/<eoi>, consistent with current return) ---
283
+
284
+ img_token = add_break_line(tokens_list, lat_h, lat_w, NEWLINE_TOKEN_ID)
285
+ return img_token, vis_img
utils/prompt_utils.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Prompt generation utilities for different inference types
4
+ """
5
+ from typing import Dict, List, Tuple, Optional
6
+
7
+ def create_prompt_templates():
8
+ """Create prompt templates for various tasks"""
9
+ templates = {
10
+ "text_understanding": "You are a multimodal model that can process both text and images. Answer the following question based on the provided images. Analyze each image and combine relevant details to answer.",
11
+ "image_generation": "Generate an image according to the text prompt.",
12
+ "image_editing": "Generate an image applying the following editing instruction based on the original image.",
13
+ "dense_prediction": "Perform dense prediction on the given images.",
14
+ "control_generation": "Generate an image according to the text prompt and the given control image.",
15
+ "subject_generation": "Generate an image according to the text prompt and the given object image.",
16
+ "multi_view": "Generate a view-image based on the given image.",
17
+ "style_transfer": "Transform the current image into the style of the provided image."
18
+ }
19
+ return templates
20
+
21
+
22
+ def generate_text_to_image_prompt(prompt_text: str, templates: Optional[Dict] = None) -> Tuple[str, str]:
23
+ """
24
+ Generate prompt for text-to-image generation
25
+
26
+ Args:
27
+ prompt_text: User input text prompt
28
+ templates: Optional prompt templates dict
29
+
30
+ Returns:
31
+ Tuple of (input_prompt, unconditional_prompt)
32
+ """
33
+ if templates is None:
34
+ templates = create_prompt_templates()
35
+
36
+ system_prompt = templates["image_generation"]
37
+ input_prompt = "<system>" + system_prompt + "</system>" + "<user>" + prompt_text + "</user>"
38
+ uncon_prompt = "<system>" + system_prompt + "</system>" + "<user>" + "<uncondition>" + "</user>"
39
+
40
+ return input_prompt, uncon_prompt
41
+
42
+
43
+ def generate_image_to_image_prompt(
44
+ prompt_text: str,
45
+ edit_type: str,
46
+ templates: Optional[Dict] = None,
47
+ **kwargs
48
+ ) -> Tuple[str, str, str]:
49
+ """
50
+ Generate prompt for image-to-image generation
51
+
52
+ Args:
53
+ prompt_text: User input text prompt
54
+ edit_type: Type of editing operation
55
+ templates: Optional prompt templates dict
56
+ **kwargs: Additional parameters for specific edit types
57
+
58
+ Returns:
59
+ Tuple of (input_prompt, unconditional_prompt, system_prompt)
60
+ """
61
+ if templates is None:
62
+ templates = create_prompt_templates()
63
+
64
+ # Determine system prompt and processed prompt text based on edit type
65
+ if 'dense' in edit_type:
66
+ des = {
67
+ "canny": "canny edge map",
68
+ "hed": "hed edge map",
69
+ "normal": "normal map",
70
+ "sam2mask": "sam2 mask",
71
+ "depth": "depth map",
72
+ "openpose": "pose estimation map"
73
+ }
74
+ system_prompt = templates["dense_prediction"]
75
+ prompt_text_used = f"Generate a {des.get(edit_type.split('_')[0], 'dense map')} according to the image."
76
+
77
+ elif 'control' in edit_type:
78
+ system_prompt = templates["control_generation"]
79
+ prompt_text_used = prompt_text
80
+
81
+ elif 'subject' in edit_type:
82
+ system_prompt = templates["subject_generation"]
83
+ prompt_text_used = prompt_text
84
+
85
+ elif 'edit' in edit_type:
86
+ system_prompt = templates["image_editing"]
87
+ prompt_text_used = prompt_text
88
+
89
+ elif "ref_transfer" in edit_type:
90
+ system_prompt = templates["style_transfer"]
91
+ prompt_text_used = "Transform the current image into the style of the provided image."
92
+
93
+ elif 'multi_view' in edit_type:
94
+ system_prompt = templates["multi_view"]
95
+ prompt_text_used = f"Generate the {edit_type.split('_')[-1]} view based on the provided front view."
96
+
97
+ else:
98
+ system_prompt = "Generate an image according to the prompt and image."
99
+ prompt_text_used = prompt_text
100
+
101
+ # Build final prompts
102
+ input_prompt = "<system>" + system_prompt + "</system>" + "<user>" + prompt_text_used + "</user>"
103
+ uncon_prompt = "<system>" + system_prompt + "</system>" + "<user>" + "<uncondition>" + "</user>"
104
+
105
+ return input_prompt, uncon_prompt, system_prompt
106
+
107
+
108
+ def generate_multimodal_understanding_prompt(question: str, templates: Optional[Dict] = None) -> str:
109
+ """
110
+ Generate prompt for multimodal understanding (MMU)
111
+
112
+ Args:
113
+ question: User question about the image
114
+ templates: Optional prompt templates dict
115
+
116
+ Returns:
117
+ Formatted input prompt
118
+ """
119
+ if templates is None:
120
+ templates = create_prompt_templates()
121
+
122
+ system_prompt = "You are a multimodal model that can process both text and images. Answer the following question based on the provided images. Analyze each image and combine relevant details to answer."
123
+ input_prompt = "<system>" + system_prompt + "</system>" + "<user>" + question + "</user>"
124
+
125
+ return input_prompt
126
+
127
+
128
+ def get_edit_type_specific_prompt(edit_type: str, prompt_text: str, templates: Optional[Dict] = None) -> str:
129
+ """
130
+ Get edit type specific prompt text
131
+
132
+ Args:
133
+ edit_type: Type of editing operation
134
+ prompt_text: Original prompt text
135
+ templates: Optional prompt templates dict
136
+
137
+ Returns:
138
+ Processed prompt text for the specific edit type
139
+ """
140
+ if templates is None:
141
+ templates = create_prompt_templates()
142
+
143
+ if 'dense' in edit_type:
144
+ des = {
145
+ "canny": "canny edge map",
146
+ "hed": "hed edge map",
147
+ "normal": "normal map",
148
+ "sam2mask": "sam2 mask",
149
+ "depth": "depth map",
150
+ "openpose": "pose estimation map"
151
+ }
152
+ return f"Generate a {des.get(edit_type.split('_')[0], 'dense map')} according to the image."
153
+
154
+ elif 'control' in edit_type:
155
+ return prompt_text
156
+
157
+ elif 'subject' in edit_type:
158
+ return prompt_text
159
+
160
+ elif 'edit' in edit_type:
161
+ if "multiturn" in edit_type:
162
+ ids = int(edit_type.split("_")[-1])
163
+ if ids == 0:
164
+ return prompt_text[0] if isinstance(prompt_text, list) else prompt_text
165
+ else:
166
+ return prompt_text[ids][0] if isinstance(prompt_text[ids], list) else prompt_text[ids]
167
+ else:
168
+ return prompt_text
169
+
170
+ elif "ref_transfer" in edit_type:
171
+ return "Transform the current image into the style of the provided image."
172
+
173
+ elif 'multi_view' in edit_type:
174
+ return f"Generate the {edit_type.split('_')[-1]} view based on the provided front view."
175
+
176
+ else:
177
+ return prompt_text
178
+
179
+
180
+ def get_system_prompt_for_edit_type(edit_type: str, templates: Optional[Dict] = None) -> str:
181
+ """
182
+ Get system prompt for specific edit type
183
+
184
+ Args:
185
+ edit_type: Type of editing operation
186
+ templates: Optional prompt templates dict
187
+
188
+ Returns:
189
+ System prompt for the edit type
190
+ """
191
+ if templates is None:
192
+ templates = create_prompt_templates()
193
+
194
+ if 'dense' in edit_type:
195
+ return templates["dense_prediction"]
196
+ elif 'control' in edit_type:
197
+ return templates["control_generation"]
198
+ elif 'subject' in edit_type:
199
+ return templates["subject_generation"]
200
+ elif 'edit' in edit_type:
201
+ return templates["image_editing"]
202
+ elif "ref_transfer" in edit_type:
203
+ return templates["style_transfer"]
204
+ elif 'multi_view' in edit_type:
205
+ return templates["multi_view"]
206
+ else:
207
+ return "Generate an image according to the prompt and image."
208
+
209
+ def generate_text_image_to_text_image_prompt(prompt_text, system_prompt):
210
+ """
211
+ Generate prompts for TI2TI tasks
212
+
213
+ Args:
214
+ prompt_text: User's editing instruction
215
+ system_prompt: System prompt for the task
216
+
217
+ Returns:
218
+ input_prompt: Conditional prompt
219
+ uncon_text: Unconditional prompt
220
+ """
221
+ # Conditional prompt
222
+ input_prompt = (
223
+ f"<system>{system_prompt}</system>"
224
+ f"<user>{prompt_text}</user>"
225
+ )
226
+
227
+ # Unconditional prompt (for CFG)
228
+ uncon_text = (
229
+ f"<system>{system_prompt}</system>"
230
+ f"<user><uncondition></user>"
231
+ )
232
+
233
+ return input_prompt, uncon_text