YFanwang commited on
Commit
8635827
·
verified ·
1 Parent(s): 2ed4708

Upload residual heatmap guide asset: residual_heatmap_generation_and_upload.md

Browse files
Reward_finetuning/SAGE-GRPO/docs/residual_heatmap_generation_and_upload.md ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Residual / Heatmap Visualization and HF Upload Guide
2
+
3
+ This guide documents how the token-credit heatmap and residual examples were generated and uploaded to `YFanwang/Backup`.
4
+
5
+ Run all commands from the SAGE-GRPO repo root:
6
+
7
+ ```bash
8
+ cd /nfs/ywang29/Reward_finetuning/SAGE-GRPO
9
+ ```
10
+
11
+ ## 1. What Is Being Visualized
12
+
13
+ The input signal is the saved VLM visual-gradient credit map in each reward record:
14
+
15
+ - `credit_map`: flattened visual credit values.
16
+ - `credit_map_shape`: `[T, H, W]`.
17
+ - In the current saved samples, a common native shape is `10 x 2 x 4`.
18
+
19
+ The renderer normalizes this credit map, upsamples it spatially, and then compares three aggregation levels:
20
+
21
+ - `Fine-map`: normalized `credit_map`, resized to `spatial_bins x spatial_bins` per frame. We usually use `32 x 32`.
22
+ - `Window3`: `Fine-map` averaged with a `3 x 3` spatial window independently per frame, then renormalized.
23
+ - `Window7`: `Fine-map` averaged with a `7 x 7` spatial window independently per frame, then renormalized.
24
+
25
+ The heatmap rows are overlays of `Fine-map`, `Window3`, and `Window7` on the selected video frame. They use the same color scale within a panel:
26
+
27
+ ```text
28
+ vmin = 0
29
+ vmax = 98.5th percentile over [fine, window3, window7]
30
+ colormap = turbo
31
+ alpha = 0.60
32
+ ```
33
+
34
+ The residual rows show positive differences:
35
+
36
+ ```text
37
+ Fine > Window3 = max(Fine-map - Window3, 0)
38
+ Window3 > Window7 = max(Window3 - Window7, 0)
39
+ ```
40
+
41
+ Interpretation:
42
+
43
+ - `Fine > Window3` highlights extra local fine-map credit that the `3 x 3` window suppresses. This is useful for showing fine-map noise or overly local sensitivity.
44
+ - `Window3 > Window7` highlights local detail preserved by `3 x 3` but washed out by `7 x 7`. This is useful for arguing why `3 x 3` can be empirically better than a coarser window.
45
+
46
+ The representative frame is selected by residual mass:
47
+
48
+ ```text
49
+ top_frame = argmax_t sum_pixels(max(Fine - Window3, 0) + 1.5 * max(Window3 - Window7, 0))
50
+ ```
51
+
52
+ The main script implementing this is:
53
+
54
+ ```text
55
+ scripts/select_spatial_two_object_credit_examples.py
56
+ ```
57
+
58
+ Its map construction comes from:
59
+
60
+ ```text
61
+ scripts/visualize_finemap_noise_tradeoff_examples.py
62
+ ```
63
+
64
+ ## 2. Generate Panels From Existing `rerun_records.jsonl`
65
+
66
+ Use this when you already have rerun payloads under:
67
+
68
+ ```text
69
+ outputs/rerun_vlm_same_gradient_window_smoothing/*/rerun_records.jsonl
70
+ ```
71
+
72
+ Example:
73
+
74
+ ```bash
75
+ python scripts/select_spatial_two_object_credit_examples.py \
76
+ --input-jsonl outputs/rerun_vlm_same_gradient_window_smoothing/window3_no_pred_first100_maxpix200704/rerun_records.jsonl \
77
+ outputs/rerun_vlm_same_gradient_window_smoothing/window3_no_pred_next200_maxpix200704/rerun_records.jsonl \
78
+ outputs/rerun_vlm_same_gradient_window_smoothing/window3_no_pred_remaining195_maxpix200704/rerun_records.jsonl \
79
+ --output-dir outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled \
80
+ --num-candidates 500 \
81
+ --tile-width 260 \
82
+ --contact-page-size 10 \
83
+ --contact-thumb-width 1700 \
84
+ --heat-blur 4 \
85
+ --residual-blur 7 \
86
+ --fill-mode object \
87
+ --min-object-count 2 \
88
+ --title-prefix "Spatial two-object prompt"
89
+ ```
90
+
91
+ Important outputs:
92
+
93
+ ```text
94
+ <output-dir>/comparison_panels/
95
+ <output-dir>/by_category_top1/original/
96
+ <output-dir>/by_category_top1/fine-map/
97
+ <output-dir>/by_category_top1/window3/
98
+ <output-dir>/by_category_top1/window7/
99
+ <output-dir>/by_category_top1/fine_gt_window3/
100
+ <output-dir>/by_category_top1/window3_gt_window7/
101
+ <output-dir>/candidate_manifest.csv
102
+ <output-dir>/candidate_contact_page_*.png
103
+ ```
104
+
105
+ For the previously generated batch, expected counts were:
106
+
107
+ ```bash
108
+ find outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled/comparison_panels -type f -name '*.png' | wc -l
109
+ find outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled -maxdepth 1 -type f -name 'candidate_contact_page_*.png' | wc -l
110
+ ```
111
+
112
+ Expected:
113
+
114
+ ```text
115
+ 500
116
+ 50
117
+ ```
118
+
119
+ ## 3. Generate Object-Specific Payloads From `rl_samples`
120
+
121
+ Use this when the rerun pool is too small and you want more examples with explicit object requirements. This route reads saved training reward files, so it does not rerun the VLM.
122
+
123
+ Source directory:
124
+
125
+ ```text
126
+ outputs/yw006-4-sage-qwen35-9b-token-credit-video-adv-window3/rl_samples
127
+ ```
128
+
129
+ Each `*_rewards.json` file is a list of samples. Each sample contains:
130
+
131
+ ```text
132
+ prompt
133
+ video_path
134
+ sample_idx
135
+ reward_records
136
+ ```
137
+
138
+ Each reward record contains:
139
+
140
+ ```text
141
+ question_id
142
+ question
143
+ target_answer
144
+ pred_sentence
145
+ credit_map
146
+ credit_map_shape
147
+ ```
148
+
149
+ Build a renderer-ready payload pool:
150
+
151
+ ```bash
152
+ python scripts/build_object_requirement_credit_payloads.py \
153
+ --repo-root . \
154
+ --rl-samples-root outputs/yw006-4-sage-qwen35-9b-token-credit-video-adv-window3/rl_samples \
155
+ --output-jsonl outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500/object_requirement_payloads.jsonl \
156
+ --manifest-csv outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500/object_requirement_payload_manifest.csv \
157
+ --use-default-excludes \
158
+ --min-question-object-count 1 \
159
+ --min-prompt-object-count 2
160
+ ```
161
+
162
+ This filters for:
163
+
164
+ - reward records that contain valid `credit_map` and `credit_map_shape`;
165
+ - atomic questions with at least one object term;
166
+ - source prompts with at least two object terms;
167
+ - non-camera-only questions, excluding obvious camera/style/lighting questions;
168
+ - keys not already used in earlier selected manifests when `--use-default-excludes` is set.
169
+
170
+ If the payload pool is very large, take a high-scoring subset before rendering:
171
+
172
+ ```bash
173
+ python scripts/build_object_requirement_credit_payloads.py \
174
+ --repo-root . \
175
+ --rl-samples-root outputs/yw006-4-sage-qwen35-9b-token-credit-video-adv-window3/rl_samples \
176
+ --output-jsonl outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object/object_requirement_payloads_top5000.jsonl \
177
+ --manifest-csv outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object/object_requirement_payloads_top5000_manifest.csv \
178
+ --use-default-excludes \
179
+ --min-question-object-count 1 \
180
+ --min-prompt-object-count 2 \
181
+ --top-k 5000
182
+ ```
183
+
184
+ Then render 500 panels from that payload subset:
185
+
186
+ ```bash
187
+ python scripts/select_spatial_two_object_credit_examples.py \
188
+ --input-jsonl outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object/object_requirement_payloads_top5000.jsonl \
189
+ --output-dir outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object \
190
+ --num-candidates 500 \
191
+ --tile-width 260 \
192
+ --contact-page-size 10 \
193
+ --contact-thumb-width 1700 \
194
+ --heat-blur 4 \
195
+ --residual-blur 7 \
196
+ --fill-mode object \
197
+ --min-object-count 2 \
198
+ --title-prefix "Object-specific prompt"
199
+ ```
200
+
201
+ Expected final checks:
202
+
203
+ ```bash
204
+ find outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object/comparison_panels -type f -name '*.png' | wc -l
205
+ find outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object -maxdepth 1 -type f -name 'candidate_contact_page_*.png' | wc -l
206
+
207
+ for d in outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object/by_category_top1/*; do
208
+ [ -d "$d" ] || continue
209
+ printf '%s ' "$(basename "$d")"
210
+ find "$d" -type f -name '*.png' | wc -l
211
+ done
212
+ ```
213
+
214
+ Expected:
215
+
216
+ ```text
217
+ comparison panels: 500
218
+ contact pages: 50
219
+ each by_category_top1 category: 500
220
+ ```
221
+
222
+ ## 4. Visual Settings to Adjust
223
+
224
+ The most useful knobs are:
225
+
226
+ - `--spatial-bins 32`: display resolution for credit maps. Larger values make overlays look finer but do not create new gradient information.
227
+ - `--heat-blur 4`: visual blur on `Fine-map`, `Window3`, and `Window7` overlay rows.
228
+ - `--residual-blur 7`: visual blur on residual rows. Increase slightly if residual blocks look too square.
229
+ - `--residual-smooth-window 1`: optional pre-display smoothing on residual maps. Keep this at `1` if you want residuals to stay local.
230
+ - `--tile-width 260`: width of each tile in a comparison panel.
231
+ - `--contact-page-size 10`: number of panels per contact sheet.
232
+
233
+ Use `--fill-mode none` if you want only strict spatial prompts. Use `--fill-mode object` if you want to fill the batch with object-specific prompts when explicit left/right or foreground/background language is not enough.
234
+
235
+ ## 5. Upload to Hugging Face
236
+
237
+ The target used here is the Hugging Face dataset repo:
238
+
239
+ ```text
240
+ YFanwang/Backup
241
+ ```
242
+
243
+ The token is read from:
244
+
245
+ ```text
246
+ /nfs/ywang29/hf_token.txt
247
+ ```
248
+
249
+ Do not print the token. Read it inside Python:
250
+
251
+ ```python
252
+ token = Path("/nfs/ywang29/hf_token.txt").read_text().strip()
253
+ ```
254
+
255
+ For small directories, `upload_folder` is enough:
256
+
257
+ ```bash
258
+ python - <<'PY'
259
+ from pathlib import Path
260
+ from huggingface_hub import HfApi
261
+
262
+ repo_id = "YFanwang/Backup"
263
+ repo_type = "dataset"
264
+ token = Path("/nfs/ywang29/hf_token.txt").read_text().strip()
265
+ api = HfApi(token=token)
266
+
267
+ local = Path("/nfs/ywang29/Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object")
268
+ remote = "Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object"
269
+
270
+ info = api.upload_folder(
271
+ repo_id=repo_id,
272
+ repo_type=repo_type,
273
+ folder_path=str(local),
274
+ path_in_repo=remote,
275
+ commit_message=f"Upload {local.name}",
276
+ token=token,
277
+ ignore_patterns=[".DS_Store", "__pycache__/*", "*.pyc"],
278
+ )
279
+ print(info.commit_url)
280
+ PY
281
+ ```
282
+
283
+ For large directories or many small PNGs, use chunked commits. This avoids the `504 Gateway Time-out` that can happen when one commit contains thousands of files.
284
+
285
+ ```bash
286
+ python - <<'PY'
287
+ from pathlib import Path
288
+ from huggingface_hub import HfApi, CommitOperationAdd
289
+ from huggingface_hub.utils import disable_progress_bars
290
+ import hashlib
291
+ import json
292
+ import os
293
+ import time
294
+
295
+ os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
296
+ disable_progress_bars()
297
+
298
+ repo_id = "YFanwang/Backup"
299
+ repo_type = "dataset"
300
+ token = Path("/nfs/ywang29/hf_token.txt").read_text().strip()
301
+ api = HfApi(token=token)
302
+
303
+ state_path = Path("/nfs/ywang29/Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/hf_backup_upload_state_manual.json")
304
+
305
+ items = [
306
+ (
307
+ Path("/nfs/ywang29/Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled"),
308
+ "Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled",
309
+ ),
310
+ (
311
+ Path("/nfs/ywang29/Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object"),
312
+ "Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object",
313
+ ),
314
+ ]
315
+
316
+ def load_state():
317
+ return json.loads(state_path.read_text()) if state_path.exists() else {"done": {}}
318
+
319
+ def save_state(state):
320
+ state_path.parent.mkdir(parents=True, exist_ok=True)
321
+ tmp = state_path.with_suffix(".tmp")
322
+ tmp.write_text(json.dumps(state, indent=2, sort_keys=True))
323
+ tmp.replace(state_path)
324
+
325
+ def iter_files(root):
326
+ for path in sorted(root.rglob("*")):
327
+ if not path.is_file():
328
+ continue
329
+ if "__pycache__" in path.parts or path.name == ".DS_Store" or path.suffix == ".pyc":
330
+ continue
331
+ yield path, path.relative_to(root).as_posix(), path.stat().st_size
332
+
333
+ def make_chunks(files, max_files=500, max_bytes=120 * 1024 * 1024):
334
+ chunk, size = [], 0
335
+ for item in files:
336
+ if chunk and (len(chunk) >= max_files or size + item[2] > max_bytes):
337
+ yield chunk
338
+ chunk, size = [], 0
339
+ chunk.append(item)
340
+ size += item[2]
341
+ if chunk:
342
+ yield chunk
343
+
344
+ def chunk_id(remote_root, chunk):
345
+ h = hashlib.sha1(remote_root.encode())
346
+ for _path, rel, size in chunk:
347
+ h.update(rel.encode())
348
+ h.update(str(size).encode())
349
+ return h.hexdigest()[:16]
350
+
351
+ state = load_state()
352
+ done = state.setdefault("done", {})
353
+
354
+ for local_root, remote_root in items:
355
+ chunks = list(make_chunks(list(iter_files(local_root))))
356
+ print(f"{local_root} -> {remote_root}: {len(chunks)} chunks")
357
+ for idx, chunk in enumerate(chunks, start=1):
358
+ cid = chunk_id(remote_root, chunk)
359
+ if done.get(cid):
360
+ print(f"skip {remote_root} {idx}/{len(chunks)}")
361
+ continue
362
+ ops = [
363
+ CommitOperationAdd(
364
+ path_in_repo=f"{remote_root}/{rel}",
365
+ path_or_fileobj=str(path),
366
+ )
367
+ for path, rel, _size in chunk
368
+ ]
369
+ print(f"upload {remote_root} {idx}/{len(chunks)} files={len(chunk)}")
370
+ last_error = None
371
+ for attempt in range(1, 4):
372
+ try:
373
+ info = api.create_commit(
374
+ repo_id=repo_id,
375
+ repo_type=repo_type,
376
+ operations=ops,
377
+ commit_message=f"Upload backup chunk {idx}/{len(chunks)}: {Path(remote_root).name}",
378
+ token=token,
379
+ )
380
+ done[cid] = {"commit": info.oid, "files": len(chunk), "remote_root": remote_root}
381
+ save_state(state)
382
+ print(f"done {remote_root} {idx}/{len(chunks)} {info.oid}")
383
+ break
384
+ except Exception as exc:
385
+ last_error = repr(exc)
386
+ print(f"retry {remote_root} {idx}/{len(chunks)} attempt={attempt}: {type(exc).__name__}")
387
+ time.sleep(15 * attempt)
388
+ else:
389
+ raise RuntimeError(last_error)
390
+ PY
391
+ ```
392
+
393
+ ## 6. Verify Upload
394
+
395
+ Avoid listing the whole repo if it is large. Verify only the uploaded subpath:
396
+
397
+ ```bash
398
+ python - <<'PY'
399
+ from pathlib import Path
400
+ from huggingface_hub import HfApi
401
+
402
+ repo_id = "YFanwang/Backup"
403
+ repo_type = "dataset"
404
+ token = Path("/nfs/ywang29/hf_token.txt").read_text().strip()
405
+ api = HfApi(token=token)
406
+
407
+ paths = [
408
+ "Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled",
409
+ "Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object",
410
+ "YFanwang",
411
+ ]
412
+
413
+ for path in paths:
414
+ items = list(api.list_repo_tree(
415
+ repo_id=repo_id,
416
+ repo_type=repo_type,
417
+ token=token,
418
+ path_in_repo=path,
419
+ recursive=True,
420
+ ))
421
+ files = [item for item in items if item.__class__.__name__ == "RepoFile"]
422
+ print(path, len(files))
423
+ PY
424
+ ```
425
+
426
+ For the completed upload, the verified counts were:
427
+
428
+ ```text
429
+ spatial_two_object_credit_examples_500_filled: 3551
430
+ object_requirement_credit_examples_more500_strict_object: 3552
431
+ YFanwang: 897
432
+ ```
433
+
434
+ ## 7. Remote Locations Used
435
+
436
+ The uploaded files are under:
437
+
438
+ ```text
439
+ https://huggingface.co/datasets/YFanwang/Backup/tree/main
440
+ ```
441
+
442
+ Repo paths:
443
+
444
+ ```text
445
+ Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled
446
+ Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object
447
+ YFanwang
448
+ ```