maitri01 commited on
Commit
40f7f9c
·
verified ·
1 Parent(s): 0481b33

Update RAR/1d-tokenizer/generate_rar_images.py

Browse files
RAR/1d-tokenizer/generate_rar_images.py CHANGED
@@ -2,98 +2,18 @@
2
  RAR IMAGE GENERATION + LIKELIHOOD EVALUATION
3
  ===========================================
4
 
5
- This script performs image generation and white-box likelihood analysis
6
- using a pretrained RAR (Reconstruction-Aware Autoregressive) generator
7
- with a MaskGit-VQ tokenizer.
8
 
9
- The script supports:
10
- - Conditional image generation on ImageNet classes
11
- - Automatic configuration based on the selected RAR checkpoint
12
- - Token-level white-box access (tokens, logits, loss, probabilities)
13
- - Teacher-forced likelihood computation (NLL)
14
- - Saving images, CSV summaries, and NumPy artifacts
15
-
16
- ------------------------------------------------
17
- REQUIREMENTS
18
- ------------------------------------------------
19
- Before running, ensure the following files exist:
20
-
21
- 1. RAR generator checkpoint (one of):
22
- - checkpoints/rar_b.bin
23
- - checkpoints/rar_l.bin
24
- - checkpoints/rar_xl.bin
25
- - checkpoints/rar_xxl.bin
26
-
27
- 2. MaskGit-VQ tokenizer checkpoint:
28
- - checkpoints/maskgit-vqgan-imagenet-f16-256.bin
29
-
30
- 3. The repository must include:
31
- - demo_util.py (patched to support return_tokens and teacher-forced logits)
32
- - modeling/rar.py
33
- - utils/train_utils.py
34
-
35
- ------------------------------------------------
36
- BASIC USAGE
37
- ------------------------------------------------
38
- Run the script directly:
39
 
 
40
  python generate_rar_images.py
41
-
42
- By default, the script:
43
- - Generates one image per class label
44
- - Uses the RAR-B checkpoint
45
- - Saves outputs to the folder: outputs_rar/
46
-
47
- ------------------------------------------------
48
- CHANGING THE RAR MODEL SIZE
49
- ------------------------------------------------
50
- To switch between RAR model variants, change ONLY this line:
51
-
52
- RAR_CKPT = os.path.join(CHECKPOINT_DIR, "rar_b.bin")
53
-
54
- Supported options:
55
- - rar_b.bin (smallest, fastest)
56
- - rar_l.bin
57
- - rar_xl.bin
58
- - rar_xxl.bin (largest, most expressive)
59
-
60
- The script automatically infers and applies the correct architecture
61
- (hidden size, depth, MLP size) from the checkpoint name.
62
- Manual configuration is NOT required and NOT recommended.
63
-
64
- ------------------------------------------------
65
- CHANGING CLASS LABELS / NUMBER OF IMAGES
66
- ------------------------------------------------
67
- Images are generated conditionally using ImageNet-1k class labels.
68
-
69
- Edit the following line:
70
-
71
- class_labels = [980, 437, 22, 562]
72
-
73
- Rules:
74
- - Each entry produces one image
75
- - Duplicate labels generate multiple images from the same class
76
- - Total number of images = len(class_labels)
77
-
78
- Examples:
79
- - Single image:
80
- class_labels = [980]
81
-
82
- - Multiple images from the same class:
83
- class_labels = [980, 980, 980]
84
-
85
- - Mixed classes:
86
- class_labels = [22, 437, 562]
87
-
88
- ------------------------------------------------
89
- CONTROLLING RANDOMNESS
90
- ------------------------------------------------
91
- Sampling randomness is controlled by the global seed:
92
-
93
- seed = 0
94
-
95
- Changing the seed will generate different images for the same class labels.
96
-
97
  ------------------------------------------------
98
  WHAT THE SCRIPT OUTPUTS
99
  ------------------------------------------------
@@ -106,13 +26,8 @@ WHAT THE SCRIPT OUTPUTS
106
  Columns:
107
  - image_id
108
  - class_label
109
- - sequence_nll
110
  - mean_token_nll
111
- - min_token_nll
112
- - max_token_nll
113
  - mean_token_prob
114
- - min_token_prob
115
- - max_token_prob
116
 
117
  3. NumPy archive (framework-agnostic):
118
  - outputs_rar/details.npz
@@ -125,31 +40,11 @@ WHAT THE SCRIPT OUTPUTS
125
  - outputs_rar/metadata.json
126
  Records model size, checkpoint, sampling parameters, and seed.
127
 
128
- ------------------------------------------------
129
- ABOUT LIKELIHOOD AND TOKEN PROBABILITIES
130
- ------------------------------------------------
131
- RAR does NOT expose logits during autoregressive sampling.
132
-
133
- Therefore, token-level loss and probabilities are computed via a
134
- separate teacher-forced evaluation step:
135
-
136
- 1. Tokens are first generated using the official RAR sampling API.
137
- 2. The generator is then re-run in teacher-forced mode on the generated
138
- token sequence.
139
- 3. Logits are aligned to exclude prefix/control tokens.
140
- 4. Per-token negative log-likelihood (NLL) and probabilities are computed.
141
-
142
- This yields true model likelihoods, not sampling-time heuristics.
143
-
144
  ------------------------------------------------
145
  NOTES
146
  ------------------------------------------------
147
- - Sampling logic is unchanged from the official RAR implementation.
148
  - No retraining or weight modification is performed.
149
- - This script provides full white-box access suitable for auditing,
150
- analysis, and research tasks.
151
-
152
- ------------------------------------------------
153
  """
154
 
155
  import os
@@ -162,11 +57,31 @@ from PIL import Image
162
  import demo_util
163
  from utils.train_utils import create_pretrained_tokenizer
164
 
165
- # -------------------------------------------------
166
- # Configuration
167
- # -------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  CHECKPOINT_DIR = "checkpoints"
169
  OUT_DIR = "outputs_rar"
 
 
170
  os.makedirs(OUT_DIR, exist_ok=True)
171
 
172
  MASKGIT_CKPT = os.path.join(
@@ -187,9 +102,6 @@ np.random.seed(seed)
187
  class_labels = [980, 437, 22, 562]
188
  B = len(class_labels)
189
 
190
- # -------------------------------------------------
191
- # RAR checkpoint → architecture mapping
192
- # -------------------------------------------------
193
  RAR_CONFIGS = {
194
  "rar_b": {
195
  "hidden_size": 768,
@@ -231,35 +143,33 @@ rar_cfg = RAR_CONFIGS[ckpt_key]
231
  print(f"Using RAR checkpoint: {ckpt_name}")
232
  print(f"Auto-configured architecture: {ckpt_key}")
233
 
234
- # -------------------------------------------------
235
- # Load config and apply inferred architecture
236
- # -------------------------------------------------
237
  config = demo_util.get_config("configs/training/generator/rar.yaml")
238
-
239
  config.experiment.generator_checkpoint = RAR_CKPT
240
  config.model.vq_model.pretrained_tokenizer_weight = MASKGIT_CKPT
241
-
242
  config.model.generator.hidden_size = rar_cfg["hidden_size"]
243
  config.model.generator.num_hidden_layers = rar_cfg["num_hidden_layers"]
244
  config.model.generator.num_attention_heads = rar_cfg["num_attention_heads"]
245
  config.model.generator.intermediate_size = rar_cfg["intermediate_size"]
246
 
247
- # -------------------------------------------------
248
- # Build tokenizer and generator
249
- # -------------------------------------------------
250
  tokenizer = create_pretrained_tokenizer(config).to(device)
 
 
 
 
 
 
 
 
 
251
  generator = demo_util.get_rar_generator(config).to(device)
252
  generator.eval()
253
 
254
  print("RAR tokenizer and generator loaded.")
255
 
256
- # -------------------------------------------------
257
- # Generate images + tokens (official sampling)
258
- # -------------------------------------------------
259
  labels = torch.tensor(class_labels, device=device)
260
 
261
  with torch.no_grad():
262
- images, tokens = demo_util.sample_fn(
263
  generator=generator,
264
  tokenizer=tokenizer,
265
  labels=labels,
@@ -267,12 +177,8 @@ with torch.no_grad():
267
  guidance_scale_pow=0.0,
268
  randomize_temperature=1.0,
269
  device=device,
270
- return_tokens=True,
271
  )
272
 
273
- # -------------------------------------------------
274
- # Save images
275
- # -------------------------------------------------
276
  for i, sample in enumerate(images):
277
  Image.fromarray(sample).save(
278
  f"{OUT_DIR}/rar_sample_{i}_class_{class_labels[i]}.png"
@@ -280,74 +186,49 @@ for i, sample in enumerate(images):
280
 
281
  print("Images saved.")
282
 
283
- # -------------------------------------------------
284
- # Teacher-forced likelihood computation (RAR)
285
- # -------------------------------------------------
286
  with torch.no_grad():
287
- logits = demo_util.rar_teacher_forced_logits(
288
- generator=generator,
289
- tokens=tokens,
290
- labels=labels,
291
  )
292
 
293
- # tokens: (B, T)
294
- # logits: (B, L, V) where L >= T
 
295
 
296
- targets = tokens[:, 1:] # (B, T-1)
297
- # Align logits to targets length from the END
298
- logits = logits[:, -targets.shape[1]:, :] # (B, T-1, V)
299
 
300
  loss_per_token = torch.nn.functional.cross_entropy(
301
  logits.reshape(-1, logits.size(-1)),
302
- targets.reshape(-1),
303
  reduction="none",
304
- ).reshape(targets.shape)
305
-
306
 
307
- sequence_nll = loss_per_token.sum(dim=1)
308
  mean_token_nll = loss_per_token.mean(dim=1)
309
-
310
  token_probs = torch.exp(-loss_per_token)
311
  mean_token_prob = token_probs.mean(dim=1)
312
- min_token_prob = token_probs.min(dim=1).values
313
- max_token_prob = token_probs.max(dim=1).values
314
 
315
- # -------------------------------------------------
316
- # Save CSV summary
317
- # -------------------------------------------------
318
  csv_path = os.path.join(OUT_DIR, "summary.csv")
319
  with open(csv_path, "w", newline="") as f:
320
  writer = csv.writer(f)
321
  writer.writerow([
322
  "image_id",
323
  "class_label",
324
- "sequence_nll",
325
  "mean_token_nll",
326
- "min_token_nll",
327
- "max_token_nll",
328
  "mean_token_prob",
329
- "min_token_prob",
330
- "max_token_prob",
331
  ])
332
 
333
  for i in range(B):
334
  writer.writerow([
335
  i,
336
  class_labels[i],
337
- sequence_nll[i].item(),
338
  mean_token_nll[i].item(),
339
- loss_per_token[i].min().item(),
340
- loss_per_token[i].max().item(),
341
  mean_token_prob[i].item(),
342
- min_token_prob[i].item(),
343
- max_token_prob[i].item(),
344
  ])
345
 
346
  print("CSV summary saved.")
347
 
348
- # -------------------------------------------------
349
- # Save detailed arrays (framework-agnostic)
350
- # -------------------------------------------------
351
  np.savez(
352
  os.path.join(OUT_DIR, "details.npz"),
353
  tokens=tokens.cpu().numpy(),
@@ -355,9 +236,6 @@ np.savez(
355
  token_probs=token_probs.cpu().numpy(),
356
  )
357
 
358
- # -------------------------------------------------
359
- # Save metadata
360
- # -------------------------------------------------
361
  with open(os.path.join(OUT_DIR, "metadata.json"), "w") as f:
362
  json.dump(
363
  {
 
2
  RAR IMAGE GENERATION + LIKELIHOOD EVALUATION
3
  ===========================================
4
 
5
+ This script generates class-conditional images using a pretrained RAR
6
+ (Reconstruction-Aware Autoregressive) generator with a MaskGit-VQ tokenizer,
7
+ then computes token-level loss and probability on the generated images.
8
 
9
+ Key steps:
10
+ 1. Generate images with the RAR sampler (no logits returned during sampling).
11
+ 2. Re-tokenize the generated images using the tokenizer.
12
+ 3. Run the generator on those tokens to get logits and labels.
13
+ 4. Compute per-token NLL and mean token probability.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ Run from model_tracer/RAR/1d-tokenizer as -
16
  python generate_rar_images.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  ------------------------------------------------
18
  WHAT THE SCRIPT OUTPUTS
19
  ------------------------------------------------
 
26
  Columns:
27
  - image_id
28
  - class_label
 
29
  - mean_token_nll
 
 
30
  - mean_token_prob
 
 
31
 
32
  3. NumPy archive (framework-agnostic):
33
  - outputs_rar/details.npz
 
40
  - outputs_rar/metadata.json
41
  Records model size, checkpoint, sampling parameters, and seed.
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  ------------------------------------------------
44
  NOTES
45
  ------------------------------------------------
46
+ - Token-level losses are computed on the generated images, not on ground-truth.
47
  - No retraining or weight modification is performed.
 
 
 
 
48
  """
49
 
50
  import os
 
57
  import demo_util
58
  from utils.train_utils import create_pretrained_tokenizer
59
 
60
+ def update_weights(model, ckpt_path, delta=True):
61
+ state_dict = torch.load(ckpt_path, map_location="cpu", weights_only=False)
62
+ if "state_dict" in state_dict:
63
+ state_dict = state_dict["state_dict"]
64
+
65
+ if delta:
66
+ state_dict_to_apply = model.state_dict().copy()
67
+ for key in state_dict:
68
+ if key in state_dict_to_apply:
69
+ state_dict_to_apply[key] = state_dict_to_apply[key] + state_dict[key].to(
70
+ state_dict_to_apply[key].device
71
+ )
72
+ else:
73
+ state_dict_to_apply[key] = state_dict[key]
74
+ else:
75
+ state_dict_to_apply = state_dict
76
+
77
+ missing, unexpected = model.load_state_dict(state_dict_to_apply, strict=False)
78
+ print(f"Missing: {missing}")
79
+ print(f"Unexpected: {unexpected}")
80
+
81
  CHECKPOINT_DIR = "checkpoints"
82
  OUT_DIR = "outputs_rar"
83
+ enc_name = "orig_enc"
84
+ ft_enc_path = "checkpoints/rar_ae_ft_delta.pth"
85
  os.makedirs(OUT_DIR, exist_ok=True)
86
 
87
  MASKGIT_CKPT = os.path.join(
 
102
  class_labels = [980, 437, 22, 562]
103
  B = len(class_labels)
104
 
 
 
 
105
  RAR_CONFIGS = {
106
  "rar_b": {
107
  "hidden_size": 768,
 
143
  print(f"Using RAR checkpoint: {ckpt_name}")
144
  print(f"Auto-configured architecture: {ckpt_key}")
145
 
 
 
 
146
  config = demo_util.get_config("configs/training/generator/rar.yaml")
 
147
  config.experiment.generator_checkpoint = RAR_CKPT
148
  config.model.vq_model.pretrained_tokenizer_weight = MASKGIT_CKPT
 
149
  config.model.generator.hidden_size = rar_cfg["hidden_size"]
150
  config.model.generator.num_hidden_layers = rar_cfg["num_hidden_layers"]
151
  config.model.generator.num_attention_heads = rar_cfg["num_attention_heads"]
152
  config.model.generator.intermediate_size = rar_cfg["intermediate_size"]
153
 
 
 
 
154
  tokenizer = create_pretrained_tokenizer(config).to(device)
155
+
156
+ match enc_name:
157
+ case "orig_enc":
158
+ pass
159
+ case "ft_enc":
160
+ update_weights(tokenizer.encoder, ft_enc_path)
161
+ print("Loaded finetuned tokenizer encoder (delta).")
162
+ case _:
163
+ raise ValueError(f"Unknown encoder name: {enc_name}")
164
  generator = demo_util.get_rar_generator(config).to(device)
165
  generator.eval()
166
 
167
  print("RAR tokenizer and generator loaded.")
168
 
 
 
 
169
  labels = torch.tensor(class_labels, device=device)
170
 
171
  with torch.no_grad():
172
+ images = demo_util.sample_fn(
173
  generator=generator,
174
  tokenizer=tokenizer,
175
  labels=labels,
 
177
  guidance_scale_pow=0.0,
178
  randomize_temperature=1.0,
179
  device=device,
 
180
  )
181
 
 
 
 
182
  for i, sample in enumerate(images):
183
  Image.fromarray(sample).save(
184
  f"{OUT_DIR}/rar_sample_{i}_class_{class_labels[i]}.png"
 
186
 
187
  print("Images saved.")
188
 
189
+ # Tokenize generated images for loss computation
 
 
190
  with torch.no_grad():
191
+ tokens = tokenizer.encode(
192
+ torch.from_numpy(images).to(device).permute(0, 3, 1, 2).float() / 255.0
 
 
193
  )
194
 
195
+ with torch.no_grad():
196
+ cond = generator.preprocess_condition(labels)
197
+ logits, labels_tf = generator(tokens, cond, return_labels=True)
198
 
199
+ # logits: (B, N_tokens + 1, V), labels_tf: (B, N_tokens)
200
+ logits = logits[:, :-1]
 
201
 
202
  loss_per_token = torch.nn.functional.cross_entropy(
203
  logits.reshape(-1, logits.size(-1)),
204
+ labels_tf.reshape(-1),
205
  reduction="none",
206
+ ).reshape(labels_tf.shape)
 
207
 
 
208
  mean_token_nll = loss_per_token.mean(dim=1)
 
209
  token_probs = torch.exp(-loss_per_token)
210
  mean_token_prob = token_probs.mean(dim=1)
 
 
211
 
 
 
 
212
  csv_path = os.path.join(OUT_DIR, "summary.csv")
213
  with open(csv_path, "w", newline="") as f:
214
  writer = csv.writer(f)
215
  writer.writerow([
216
  "image_id",
217
  "class_label",
 
218
  "mean_token_nll",
 
 
219
  "mean_token_prob",
 
 
220
  ])
221
 
222
  for i in range(B):
223
  writer.writerow([
224
  i,
225
  class_labels[i],
 
226
  mean_token_nll[i].item(),
 
 
227
  mean_token_prob[i].item(),
 
 
228
  ])
229
 
230
  print("CSV summary saved.")
231
 
 
 
 
232
  np.savez(
233
  os.path.join(OUT_DIR, "details.npz"),
234
  tokens=tokens.cpu().numpy(),
 
236
  token_probs=token_probs.cpu().numpy(),
237
  )
238
 
 
 
 
239
  with open(os.path.join(OUT_DIR, "metadata.json"), "w") as f:
240
  json.dump(
241
  {