Upload residual heatmap guide asset: residual_heatmap_generation_and_upload.md
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448# Residual / Heatmap Visualization and HF Upload Guide
This guide documents how the token-credit heatmap and residual examples were generated and uploaded to `YFanwang/Backup`.
Run all commands from the SAGE-GRPO repo root:
```bashcd /nfs/ywang29/Reward_finetuning/SAGE-GRPO```
## 1. What Is Being Visualized
The input signal is the saved VLM visual-gradient credit map in each reward record:
- `credit_map`: flattened visual credit values.- `credit_map_shape`: `[T, H, W]`.- In the current saved samples, a common native shape is `10 x 2 x 4`.
The renderer normalizes this credit map, upsamples it spatially, and then compares three aggregation levels:
- `Fine-map`: normalized `credit_map`, resized to `spatial_bins x spatial_bins` per frame. We usually use `32 x 32`.- `Window3`: `Fine-map` averaged with a `3 x 3` spatial window independently per frame, then renormalized.- `Window7`: `Fine-map` averaged with a `7 x 7` spatial window independently per frame, then renormalized.
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:
```textvmin = 0vmax = 98.5th percentile over [fine, window3, window7]colormap = turboalpha = 0.60```
The residual rows show positive differences:
```textFine > Window3 = max(Fine-map - Window3, 0)Window3 > Window7 = max(Window3 - Window7, 0)```
Interpretation:
- `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.- `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.
The representative frame is selected by residual mass:
```texttop_frame = argmax_t sum_pixels(max(Fine - Window3, 0) + 1.5 * max(Window3 - Window7, 0))```
The main script implementing this is:
```textscripts/select_spatial_two_object_credit_examples.py```
Its map construction comes from:
```textscripts/visualize_finemap_noise_tradeoff_examples.py```
## 2. Generate Panels From Existing `rerun_records.jsonl`
Use this when you already have rerun payloads under:
```textoutputs/rerun_vlm_same_gradient_window_smoothing/*/rerun_records.jsonl```
Example:
```bashpython scripts/select_spatial_two_object_credit_examples.py \ --input-jsonl outputs/rerun_vlm_same_gradient_window_smoothing/window3_no_pred_first100_maxpix200704/rerun_records.jsonl \ outputs/rerun_vlm_same_gradient_window_smoothing/window3_no_pred_next200_maxpix200704/rerun_records.jsonl \ outputs/rerun_vlm_same_gradient_window_smoothing/window3_no_pred_remaining195_maxpix200704/rerun_records.jsonl \ --output-dir outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled \ --num-candidates 500 \ --tile-width 260 \ --contact-page-size 10 \ --contact-thumb-width 1700 \ --heat-blur 4 \ --residual-blur 7 \ --fill-mode object \ --min-object-count 2 \ --title-prefix "Spatial two-object prompt"```
Important outputs:
```text<output-dir>/comparison_panels/<output-dir>/by_category_top1/original/<output-dir>/by_category_top1/fine-map/<output-dir>/by_category_top1/window3/<output-dir>/by_category_top1/window7/<output-dir>/by_category_top1/fine_gt_window3/<output-dir>/by_category_top1/window3_gt_window7/<output-dir>/candidate_manifest.csv<output-dir>/candidate_contact_page_*.png```
For the previously generated batch, expected counts were:
```bashfind outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled/comparison_panels -type f -name '*.png' | wc -lfind 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```
Expected:
```text50050```
## 3. Generate Object-Specific Payloads From `rl_samples`
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.
Source directory:
```textoutputs/yw006-4-sage-qwen35-9b-token-credit-video-adv-window3/rl_samples```
Each `*_rewards.json` file is a list of samples. Each sample contains:
```textpromptvideo_pathsample_idxreward_records```
Each reward record contains:
```textquestion_idquestiontarget_answerpred_sentencecredit_mapcredit_map_shape```
Build a renderer-ready payload pool:
```bashpython scripts/build_object_requirement_credit_payloads.py \ --repo-root . \ --rl-samples-root outputs/yw006-4-sage-qwen35-9b-token-credit-video-adv-window3/rl_samples \ --output-jsonl outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500/object_requirement_payloads.jsonl \ --manifest-csv outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500/object_requirement_payload_manifest.csv \ --use-default-excludes \ --min-question-object-count 1 \ --min-prompt-object-count 2```
This filters for:
- reward records that contain valid `credit_map` and `credit_map_shape`;- atomic questions with at least one object term;- source prompts with at least two object terms;- non-camera-only questions, excluding obvious camera/style/lighting questions;- keys not already used in earlier selected manifests when `--use-default-excludes` is set.
If the payload pool is very large, take a high-scoring subset before rendering:
```bashpython scripts/build_object_requirement_credit_payloads.py \ --repo-root . \ --rl-samples-root outputs/yw006-4-sage-qwen35-9b-token-credit-video-adv-window3/rl_samples \ --output-jsonl outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object/object_requirement_payloads_top5000.jsonl \ --manifest-csv outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object/object_requirement_payloads_top5000_manifest.csv \ --use-default-excludes \ --min-question-object-count 1 \ --min-prompt-object-count 2 \ --top-k 5000```
Then render 500 panels from that payload subset:
```bashpython scripts/select_spatial_two_object_credit_examples.py \ --input-jsonl outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object/object_requirement_payloads_top5000.jsonl \ --output-dir outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object \ --num-candidates 500 \ --tile-width 260 \ --contact-page-size 10 \ --contact-thumb-width 1700 \ --heat-blur 4 \ --residual-blur 7 \ --fill-mode object \ --min-object-count 2 \ --title-prefix "Object-specific prompt"```
Expected final checks:
```bashfind outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object/comparison_panels -type f -name '*.png' | wc -lfind 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
for d in outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object/by_category_top1/*; do [ -d "$d" ] || continue printf '%s ' "$(basename "$d")" find "$d" -type f -name '*.png' | wc -ldone```
Expected:
```textcomparison panels: 500contact pages: 50each by_category_top1 category: 500```
## 4. Visual Settings to Adjust
The most useful knobs are:
- `--spatial-bins 32`: display resolution for credit maps. Larger values make overlays look finer but do not create new gradient information.- `--heat-blur 4`: visual blur on `Fine-map`, `Window3`, and `Window7` overlay rows.- `--residual-blur 7`: visual blur on residual rows. Increase slightly if residual blocks look too square.- `--residual-smooth-window 1`: optional pre-display smoothing on residual maps. Keep this at `1` if you want residuals to stay local.- `--tile-width 260`: width of each tile in a comparison panel.- `--contact-page-size 10`: number of panels per contact sheet.
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.
## 5. Upload to Hugging Face
The target used here is the Hugging Face dataset repo:
```textYFanwang/Backup```
The token is read from:
```text/nfs/ywang29/hf_token.txt```
Do not print the token. Read it inside Python:
```pythontoken = Path("/nfs/ywang29/hf_token.txt").read_text().strip()```
For small directories, `upload_folder` is enough:
```bashpython - <<'PY'from pathlib import Pathfrom huggingface_hub import HfApi
repo_id = "YFanwang/Backup"repo_type = "dataset"token = Path("/nfs/ywang29/hf_token.txt").read_text().strip()api = HfApi(token=token)
local = Path("/nfs/ywang29/Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object")remote = "Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object"
info = api.upload_folder( repo_id=repo_id, repo_type=repo_type, folder_path=str(local), path_in_repo=remote, commit_message=f"Upload {local.name}", token=token, ignore_patterns=[".DS_Store", "__pycache__/*", "*.pyc"],)print(info.commit_url)PY```
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.
```bashpython - <<'PY'from pathlib import Pathfrom huggingface_hub import HfApi, CommitOperationAddfrom huggingface_hub.utils import disable_progress_barsimport hashlibimport jsonimport osimport time
os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"disable_progress_bars()
repo_id = "YFanwang/Backup"repo_type = "dataset"token = Path("/nfs/ywang29/hf_token.txt").read_text().strip()api = HfApi(token=token)
state_path = Path("/nfs/ywang29/Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/hf_backup_upload_state_manual.json")
items = [ ( Path("/nfs/ywang29/Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled"), "Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled", ), ( Path("/nfs/ywang29/Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object"), "Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object", ),]
def load_state(): return json.loads(state_path.read_text()) if state_path.exists() else {"done": {}}
def save_state(state): state_path.parent.mkdir(parents=True, exist_ok=True) tmp = state_path.with_suffix(".tmp") tmp.write_text(json.dumps(state, indent=2, sort_keys=True)) tmp.replace(state_path)
def iter_files(root): for path in sorted(root.rglob("*")): if not path.is_file(): continue if "__pycache__" in path.parts or path.name == ".DS_Store" or path.suffix == ".pyc": continue yield path, path.relative_to(root).as_posix(), path.stat().st_size
def make_chunks(files, max_files=500, max_bytes=120 * 1024 * 1024): chunk, size = [], 0 for item in files: if chunk and (len(chunk) >= max_files or size + item[2] > max_bytes): yield chunk chunk, size = [], 0 chunk.append(item) size += item[2] if chunk: yield chunk
def chunk_id(remote_root, chunk): h = hashlib.sha1(remote_root.encode()) for _path, rel, size in chunk: h.update(rel.encode()) h.update(str(size).encode()) return h.hexdigest()[:16]
state = load_state()done = state.setdefault("done", {})
for local_root, remote_root in items: chunks = list(make_chunks(list(iter_files(local_root)))) print(f"{local_root} -> {remote_root}: {len(chunks)} chunks") for idx, chunk in enumerate(chunks, start=1): cid = chunk_id(remote_root, chunk) if done.get(cid): print(f"skip {remote_root} {idx}/{len(chunks)}") continue ops = [ CommitOperationAdd( path_in_repo=f"{remote_root}/{rel}", path_or_fileobj=str(path), ) for path, rel, _size in chunk ] print(f"upload {remote_root} {idx}/{len(chunks)} files={len(chunk)}") last_error = None for attempt in range(1, 4): try: info = api.create_commit( repo_id=repo_id, repo_type=repo_type, operations=ops, commit_message=f"Upload backup chunk {idx}/{len(chunks)}: {Path(remote_root).name}", token=token, ) done[cid] = {"commit": info.oid, "files": len(chunk), "remote_root": remote_root} save_state(state) print(f"done {remote_root} {idx}/{len(chunks)} {info.oid}") break except Exception as exc: last_error = repr(exc) print(f"retry {remote_root} {idx}/{len(chunks)} attempt={attempt}: {type(exc).__name__}") time.sleep(15 * attempt) else: raise RuntimeError(last_error)PY```
## 6. Verify Upload
Avoid listing the whole repo if it is large. Verify only the uploaded subpath:
```bashpython - <<'PY'from pathlib import Pathfrom huggingface_hub import HfApi
repo_id = "YFanwang/Backup"repo_type = "dataset"token = Path("/nfs/ywang29/hf_token.txt").read_text().strip()api = HfApi(token=token)
paths = [ "Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled", "Reward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_object", "YFanwang",]
for path in paths: items = list(api.list_repo_tree( repo_id=repo_id, repo_type=repo_type, token=token, path_in_repo=path, recursive=True, )) files = [item for item in items if item.__class__.__name__ == "RepoFile"] print(path, len(files))PY```
For the completed upload, the verified counts were:
```textspatial_two_object_credit_examples_500_filled: 3551object_requirement_credit_examples_more500_strict_object: 3552YFanwang: 897```
## 7. Remote Locations Used
The uploaded files are under:
```texthttps://huggingface.co/datasets/YFanwang/Backup/tree/main```
Repo paths:
```textReward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filledReward_finetuning/SAGE-GRPO/outputs/rerun_vlm_same_gradient_window_smoothing/object_requirement_credit_examples_more500_strict_objectYFanwang```Reward_finetuning/SAGE-GRPO/docs/residual_heatmap_generation_and_upload.mdAdded+448