maitri01 commited on
Commit
27315df
·
verified ·
1 Parent(s): 40f7f9c

Update VAR/generate_var_images.py

Browse files
Files changed (1) hide show
  1. VAR/generate_var_images.py +37 -158
VAR/generate_var_images.py CHANGED
@@ -1,99 +1,19 @@
1
  """
2
  VAR White-Box Image Generation and Likelihood Analysis
3
- =====================================================
4
-
5
  USAGE
6
  -----
7
- This script performs three things:
8
- 1. Generates class-conditional images using a pretrained VAR + VQ-VAE model.
9
- 2. Extracts the full discrete VQ token sequence used to generate each image.
10
- 3. Computes teacher-forced negative log-likelihood (NLL) and token probabilities,
11
- exposing white-box model confidence signals.
12
 
13
  Run:
14
  python generate_var_images.py
15
 
16
  Outputs (saved in ./outputs/):
17
  - sample_<id>_class_<label>.png : generated images
18
- - summary.csv : per-image likelihood and probability statistics
19
- - details.npz : per-token loss and probabilities (NumPy arrays)
20
  - metadata.json : run configuration
21
-
22
- All likelihoods and probabilities are computed using teacher forcing and are
23
- NOT affected by top-k, top-p, or classifier-free guidance truncation.
24
-
25
-
26
- CHANGING MODEL DEPTH
27
- --------------------
28
- The model depth MUST match the checkpoint being loaded.
29
-
30
- To change depth:
31
- 1. Set MODEL_DEPTH below to one of: {16, 20, 24, 30}
32
- 2. Ensure the corresponding checkpoint exists:
33
- checkpoints/var_d<MODEL_DEPTH>.pth
34
-
35
- Example:
36
- MODEL_DEPTH = 20
37
- -> loads checkpoints/var_d20.pth
38
-
39
- Using a mismatched depth will cause incorrect loading or silent errors.
40
-
41
- CHANGING CLASSES AND NUMBER OF IMAGES
42
- ------------------------------------
43
- Images are generated conditionally based on ImageNet class labels.
44
-
45
- To change which images are generated, edit:
46
- class_labels = [980, 437, 22, 562]
47
-
48
- Each entry corresponds to one generated image. Duplicate labels will generate
49
- multiple images from the same class.
50
-
51
- Examples:
52
- - Generate one image from a single class:
53
- class_labels = [980]
54
-
55
- - Generate multiple images from the same class:
56
- class_labels = [980, 980, 980]
57
-
58
- - Generate images from multiple classes:
59
- class_labels = [22, 437, 562]
60
-
61
- The total number of generated images equals:
62
- B = len(class_labels)
63
-
64
- Randomness is controlled by the global seed. To generate different images for
65
- the same class labels, change the `seed` value at the top of the file.
66
-
67
-
68
- ABOUT LOSS AND TOKEN PROBABILITIES (IMPORTANT)
69
- ----------------------------------------------
70
- For each generated image, we compute per-token negative log-likelihood (NLL):
71
-
72
- NLL_t = -log p(x_t | x_<t)
73
-
74
- From this, token probabilities are derived as:
75
-
76
- p_t = exp(-NLL_t)
77
-
78
- We report BOTH:
79
- - mean_token_nll = mean_t(NLL_t)
80
- - mean_token_prob = mean_t(p_t)
81
-
82
- Interpretation:
83
- - mean_token_nll measures average surprise in log-space (theoretically clean).
84
- - mean_token_prob measures average confidence in probability-space (intuitive).
85
- - Differences between them capture variance in token difficulty across the image.
86
-
87
- WHITE-BOX ACCESS GUARANTEE
88
- --------------------------
89
- This script provides full white-box access to the model by exposing:
90
- - discrete VQ tokens
91
- - per-token NLL
92
- - per-token probabilities
93
- - aggregate confidence statistics
94
-
95
- All outputs are saved in framework-agnostic formats (PNG, CSV, NPZ, JSON),
96
- allowing participants to analyze model behavior without modifying the model.
97
  """
98
 
99
  import os
@@ -103,11 +23,9 @@ import json
103
  import csv
104
  import numpy as np
105
  import torch
 
106
  from PIL import Image
107
 
108
- # -------------------------------------------------
109
- # Reproducibility and performance
110
- # -------------------------------------------------
111
  seed = 0
112
  torch.manual_seed(seed)
113
  random.seed(seed)
@@ -119,30 +37,30 @@ torch.backends.cuda.matmul.allow_tf32 = True
119
  torch.backends.cudnn.allow_tf32 = True
120
  torch.set_float32_matmul_precision("high")
121
 
122
- # Disable default init (speed)
123
  setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
124
  setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
125
 
126
- # -------------------------------------------------
127
- # Imports from VAR repo
128
- # -------------------------------------------------
129
  from models import build_vae_var
130
 
131
- # -------------------------------------------------
132
- # Configuration
133
- # -------------------------------------------------
134
  MODEL_DEPTH = 16 # must match checkpoint
135
  CHECKPOINT_DIR = "checkpoints"
136
  OUT_DIR = "outputs"
 
 
137
  os.makedirs(OUT_DIR, exist_ok=True)
138
 
139
- VAE_CKPT = osp.join(CHECKPOINT_DIR, "vae_ch160v4096z32.pth")
 
 
 
 
 
140
  VAR_CKPT = osp.join(CHECKPOINT_DIR, f"var_d{MODEL_DEPTH}.pth")
141
 
142
  device = "cuda" if torch.cuda.is_available() else "cpu"
143
 
144
  # ImageNet class labels to generate
145
- class_labels = [12, 12, 14] # Example: 'golden retriever'
146
 
147
  # Sampling parameters
148
  cfg_scale = 3.0
@@ -150,9 +68,6 @@ top_k = 900
150
  top_p = 0.95
151
  more_smooth = False
152
 
153
- # -------------------------------------------------
154
- # Build models
155
- # -------------------------------------------------
156
  patch_nums = (1, 2, 3, 4, 5, 6, 8, 10, 13, 16)
157
 
158
  vae, var = build_vae_var(
@@ -179,15 +94,15 @@ for p in var.parameters():
179
 
180
  print("Models loaded.")
181
 
182
- # -------------------------------------------------
183
- # Generate images (official API)
184
- # -------------------------------------------------
185
  label_B = torch.tensor(class_labels, device=device)
186
  B = len(class_labels)
187
 
188
  with torch.inference_mode():
189
  with torch.autocast("cuda", enabled=(device == "cuda"), dtype=torch.float16):
190
- images, tokens = var.autoregressive_infer_cfg(
191
  B=B,
192
  label_B=label_B,
193
  cfg=cfg_scale,
@@ -195,12 +110,8 @@ with torch.inference_mode():
195
  top_p=top_p,
196
  g_seed=seed,
197
  more_smooth=more_smooth,
198
- return_tokens=True, # <<< requires small repo patch (see note below)
199
  )
200
 
201
- # -------------------------------------------------
202
- # Save standalone images
203
- # -------------------------------------------------
204
  for i, img in enumerate(images):
205
  img = (
206
  img.permute(1, 2, 0)
@@ -216,87 +127,55 @@ for i, img in enumerate(images):
216
 
217
  print("Images saved.")
218
 
219
- # -------------------------------------------------
220
- # Teacher-forced likelihood computation
221
- # -------------------------------------------------
222
  with torch.inference_mode():
223
- # Convert tokens -> VQ embeddings
224
- token_embeddings = var.vae_quant_proxy[0].embedding(tokens) # (B, T, Cvae)
225
 
226
- # Remove first-level tokens (teacher forcing protocol)
227
- x_BLCv_wo_first_l = token_embeddings[:, var.first_l:, :] # (B, L-first_l, Cvae)
 
 
228
 
229
- # Forward pass (correct argument order)
230
- logits = var(label_B, x_BLCv_wo_first_l) # (B, L, V)
231
-
232
- # Targets are next-token indices
233
- targets = tokens[:, 1:] # (B, L)
234
-
235
- # Align logits with targets
236
- logits = logits[:, :-1, :] # (B, L-1, V)
237
- targets = targets[:, -logits.shape[1]:] # safety align
238
-
239
- # Cross-entropy per token
240
- loss_per_token = torch.nn.functional.cross_entropy(
241
- logits.reshape(-1, logits.size(-1)),
242
- targets.reshape(-1),
243
  reduction="none",
244
- ).reshape(targets.shape)
245
 
246
- sequence_nll = loss_per_token.sum(dim=1)
247
- mean_token_nll = loss_per_token.mean(dim=1)
248
 
249
- # Token probabilities from NLL
250
- token_probs = torch.exp(-loss_per_token)
251
  mean_token_prob = token_probs.mean(dim=1)
252
- min_token_prob = token_probs.min(dim=1).values
253
 
254
-
255
- # -------------------------------------------------
256
- # Save CSV summary (human-readable)
257
- # -------------------------------------------------
258
  csv_path = osp.join(OUT_DIR, "summary.csv")
259
  with open(csv_path, "w", newline="") as f:
260
  writer = csv.writer(f)
261
  writer.writerow([
262
  "image_id",
263
  "class_label",
264
- "sequence_nll",
265
- "mean_token_nll",
266
- "min_token_nll",
267
- "max_token_nll",
268
  "mean_token_prob",
269
- "min_token_prob",
270
  ])
271
 
272
  for i in range(B):
273
  writer.writerow([
274
  i,
275
  class_labels[i],
276
- sequence_nll[i].item(),
277
- mean_token_nll[i].item(),
278
- loss_per_token[i].min().item(),
279
- loss_per_token[i].max().item(),
280
  mean_token_prob[i].item(),
281
- min_token_prob[i].item(),
282
  ])
283
 
284
  print("CSV summary saved.")
285
 
286
- # -------------------------------------------------
287
- # Save detailed arrays (NumPy, framework-agnostic)
288
- # -------------------------------------------------
289
  np.savez(
290
  osp.join(OUT_DIR, "details.npz"),
291
- tokens=tokens.cpu().numpy(),
292
- loss_per_token=loss_per_token.cpu().numpy(),
293
  token_probs=token_probs.cpu().numpy(),
294
-
295
  )
296
 
297
- # -------------------------------------------------
298
- # Save metadata
299
- # -------------------------------------------------
300
  with open(osp.join(OUT_DIR, "metadata.json"), "w") as f:
301
  json.dump(
302
  {
 
1
  """
2
  VAR White-Box Image Generation and Likelihood Analysis
 
 
3
  USAGE
4
  -----
5
+ This script generates class-conditional images using a pretrained VAR + VQ-VAE model
6
+ and computes token-level cross-entropy and token probabilities.
7
+
 
 
8
 
9
  Run:
10
  python generate_var_images.py
11
 
12
  Outputs (saved in ./outputs/):
13
  - sample_<id>_class_<label>.png : generated images
14
+ - summary.csv : per-image loss/probability statistics
15
+ - details.npz : per-token losses/probabilities and tokens (NumPy arrays)
16
  - metadata.json : run configuration
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  """
18
 
19
  import os
 
23
  import csv
24
  import numpy as np
25
  import torch
26
+ from torch.nn import functional as F
27
  from PIL import Image
28
 
 
 
 
29
  seed = 0
30
  torch.manual_seed(seed)
31
  random.seed(seed)
 
37
  torch.backends.cudnn.allow_tf32 = True
38
  torch.set_float32_matmul_precision("high")
39
 
 
40
  setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
41
  setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
42
 
 
 
 
43
  from models import build_vae_var
44
 
 
 
 
45
  MODEL_DEPTH = 16 # must match checkpoint
46
  CHECKPOINT_DIR = "checkpoints"
47
  OUT_DIR = "outputs"
48
+ ENC_NAME = "orig_enc"
49
+ FT_VAE_CKPT = "checkpoints/var_ae_ft.pth"
50
  os.makedirs(OUT_DIR, exist_ok=True)
51
 
52
+ if ENC_NAME == "orig_enc":
53
+ VAE_CKPT = osp.join(CHECKPOINT_DIR, "vae_ch160v4096z32.pth")
54
+ elif ENC_NAME == "ft_enc":
55
+ VAE_CKPT = FT_VAE_CKPT
56
+ else:
57
+ raise ValueError(f"Unknown encoder name: {ENC_NAME}")
58
  VAR_CKPT = osp.join(CHECKPOINT_DIR, f"var_d{MODEL_DEPTH}.pth")
59
 
60
  device = "cuda" if torch.cuda.is_available() else "cpu"
61
 
62
  # ImageNet class labels to generate
63
+ class_labels = [120, 120, 140] # Example: 'golden retriever'
64
 
65
  # Sampling parameters
66
  cfg_scale = 3.0
 
68
  top_p = 0.95
69
  more_smooth = False
70
 
 
 
 
71
  patch_nums = (1, 2, 3, 4, 5, 6, 8, 10, 13, 16)
72
 
73
  vae, var = build_vae_var(
 
94
 
95
  print("Models loaded.")
96
 
97
+ def get_token_list(images):
98
+ return vae.img_to_idxBl(images, v_patch_nums=patch_nums)
99
+
100
  label_B = torch.tensor(class_labels, device=device)
101
  B = len(class_labels)
102
 
103
  with torch.inference_mode():
104
  with torch.autocast("cuda", enabled=(device == "cuda"), dtype=torch.float16):
105
+ images = var.autoregressive_infer_cfg(
106
  B=B,
107
  label_B=label_B,
108
  cfg=cfg_scale,
 
110
  top_p=top_p,
111
  g_seed=seed,
112
  more_smooth=more_smooth,
 
113
  )
114
 
 
 
 
115
  for i, img in enumerate(images):
116
  img = (
117
  img.permute(1, 2, 0)
 
127
 
128
  print("Images saved.")
129
 
 
 
 
130
  with torch.inference_mode():
131
+ # VQ-VAE expects float inputs in [-1, 1]
132
+ images_for_loss = images.float().mul(2.0).sub(1.0)
133
 
134
+ token_list = get_token_list(images_for_loss)
135
+ gt_BL = torch.cat(token_list, dim=1)
136
+ var_input = vae.quantize.idxBl_to_var_input(token_list)
137
+ logits = var(label_B, var_input)
138
 
139
+ loss_per_token_ce = F.cross_entropy(
140
+ logits.permute(0, 2, 1),
141
+ gt_BL,
 
 
 
 
 
 
 
 
 
 
 
142
  reduction="none",
143
+ )
144
 
145
+ token_probs = torch.exp(-loss_per_token_ce)
 
146
 
147
+ mean_token_ce = loss_per_token_ce.mean(dim=1)
 
148
  mean_token_prob = token_probs.mean(dim=1)
 
149
 
 
 
 
 
150
  csv_path = osp.join(OUT_DIR, "summary.csv")
151
  with open(csv_path, "w", newline="") as f:
152
  writer = csv.writer(f)
153
  writer.writerow([
154
  "image_id",
155
  "class_label",
156
+ "mean_token_ce",
 
 
 
157
  "mean_token_prob",
 
158
  ])
159
 
160
  for i in range(B):
161
  writer.writerow([
162
  i,
163
  class_labels[i],
164
+ mean_token_ce[i].item(),
 
 
 
165
  mean_token_prob[i].item(),
 
166
  ])
167
 
168
  print("CSV summary saved.")
169
 
170
+
 
 
171
  np.savez(
172
  osp.join(OUT_DIR, "details.npz"),
173
+ tokens=gt_BL.cpu().numpy(),
174
+ loss_per_token_ce=loss_per_token_ce.cpu().numpy(),
175
  token_probs=token_probs.cpu().numpy(),
 
176
  )
177
 
178
+
 
 
179
  with open(osp.join(OUT_DIR, "metadata.json"), "w") as f:
180
  json.dump(
181
  {