YFanwang commited on
Commit
6c450d7
·
verified ·
1 Parent(s): 8635827

Upload residual heatmap guide asset: build_object_requirement_credit_payloads.py

Browse files
Reward_finetuning/SAGE-GRPO/scripts/build_object_requirement_credit_payloads.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build renderer payloads from saved rl_samples reward JSON files.
3
+
4
+ The visualization renderer expects records shaped like the rerun VLM JSONL
5
+ payloads: a ``source`` block plus a ``rerun_record`` containing ``credit_map``.
6
+ Training ``*_rewards.json`` files save the same credit maps, but nested under
7
+ per-sample reward records. This script converts those saved records into a
8
+ JSONL pool and filters for object-specific questions.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import csv
15
+ import json
16
+ import re
17
+ from pathlib import Path
18
+ from typing import Dict, Iterable, List, Sequence, Tuple
19
+
20
+ from select_spatial_two_object_credit_examples import (
21
+ object_count,
22
+ normalize_text,
23
+ spatial_prompt_score,
24
+ )
25
+
26
+
27
+ DEFAULT_EXCLUDE_MANIFESTS = (
28
+ "outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500_filled/candidate_manifest.csv",
29
+ "outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_500/candidate_manifest.csv",
30
+ "outputs/rerun_vlm_same_gradient_window_smoothing/spatial_two_object_credit_examples_selected_12/selected_manifest.csv",
31
+ )
32
+
33
+ QUESTION_EXCLUDE_PATTERNS = re.compile(
34
+ r"\b("
35
+ r"camera|shot|view|static|handheld|pans?|tilts?|zooms?|slow[- ]motion|"
36
+ r"motion blur|fade|lighting|style|anime|cinematic|close[- ]up|level angle"
37
+ r")\b",
38
+ re.I,
39
+ )
40
+
41
+ QUESTION_JSON_RE = re.compile(r'"question"\s*:\s*"((?:\\.|[^"\\])*)"')
42
+
43
+
44
+ def parse_args() -> argparse.Namespace:
45
+ parser = argparse.ArgumentParser(description=__doc__)
46
+ parser.add_argument(
47
+ "--repo-root",
48
+ type=Path,
49
+ default=Path.cwd(),
50
+ help="SAGE-GRPO repository root. Relative paths are resolved from here.",
51
+ )
52
+ parser.add_argument(
53
+ "--rl-samples-root",
54
+ type=Path,
55
+ default=Path("outputs/yw006-4-sage-qwen35-9b-token-credit-video-adv-window3/rl_samples"),
56
+ help="Directory containing step/group/*_rewards.json files.",
57
+ )
58
+ parser.add_argument("--output-jsonl", type=Path, required=True)
59
+ parser.add_argument("--manifest-csv", type=Path, required=True)
60
+ parser.add_argument(
61
+ "--exclude-manifest",
62
+ type=Path,
63
+ action="append",
64
+ default=[],
65
+ help="Candidate/selected manifest whose step/group/sample_idx/question_id keys should be excluded.",
66
+ )
67
+ parser.add_argument("--use-default-excludes", action="store_true")
68
+ parser.add_argument("--min-question-object-count", type=int, default=1)
69
+ parser.add_argument("--min-prompt-object-count", type=int, default=2)
70
+ parser.add_argument(
71
+ "--top-k",
72
+ type=int,
73
+ default=0,
74
+ help="If positive, write only the top K records by object/spatial prompt score.",
75
+ )
76
+ return parser.parse_args()
77
+
78
+
79
+ def resolve_path(repo_root: Path, path: Path) -> Path:
80
+ return path if path.is_absolute() else repo_root / path
81
+
82
+
83
+ def manifest_key(row: Dict[str, str]) -> Tuple[str, str, str, str]:
84
+ return (
85
+ str(row.get("step", "")),
86
+ str(row.get("group", "")),
87
+ str(row.get("sample_idx", "")),
88
+ str(row.get("question_id", "")),
89
+ )
90
+
91
+
92
+ def load_excluded_keys(paths: Sequence[Path]) -> set[Tuple[str, str, str, str]]:
93
+ keys: set[Tuple[str, str, str, str]] = set()
94
+ for path in paths:
95
+ if not path.exists():
96
+ continue
97
+ with path.open("r", encoding="utf-8", newline="") as f:
98
+ for row in csv.DictReader(f):
99
+ keys.add(manifest_key(row))
100
+ return keys
101
+
102
+
103
+ def extract_atomic_question(full_prompt: object, question_id: object) -> str:
104
+ text = str(full_prompt or "")
105
+ qid = str(question_id or "")
106
+ for line in text.splitlines():
107
+ if f'"id": "{qid}"' not in line and f'"id":"{qid}"' not in line:
108
+ continue
109
+ match = QUESTION_JSON_RE.search(line)
110
+ if match:
111
+ return json.loads(f'"{match.group(1)}"')
112
+ match = QUESTION_JSON_RE.search(text)
113
+ if match:
114
+ return json.loads(f'"{match.group(1)}"')
115
+ return normalize_text(text)
116
+
117
+
118
+ def has_credit_map(record: Dict) -> bool:
119
+ values = record.get("credit_map")
120
+ shape = record.get("credit_map_shape")
121
+ if not isinstance(values, list) or not isinstance(shape, list) or len(shape) != 3:
122
+ return False
123
+ try:
124
+ expected = int(shape[0]) * int(shape[1]) * int(shape[2])
125
+ except Exception:
126
+ return False
127
+ return len(values) == expected
128
+
129
+
130
+ def reward_json_files(root: Path) -> Iterable[Path]:
131
+ yield from sorted(root.rglob("*_rewards.json"))
132
+
133
+
134
+ def read_reward_file(path: Path) -> List[Dict]:
135
+ with path.open("r", encoding="utf-8") as f:
136
+ data = json.load(f)
137
+ if not isinstance(data, list):
138
+ raise ValueError(f"expected list in {path}")
139
+ return data
140
+
141
+
142
+ def candidate_sort_key(item: Dict) -> Tuple[float, int, int, str, str, str, str]:
143
+ source = item["payload"]["source"]
144
+ prompt = normalize_text(source.get("prompt", ""))
145
+ question = normalize_text(source.get("question", ""))
146
+ spatial_score, _phrase_type, _obj_count = spatial_prompt_score(prompt, question)
147
+ return (
148
+ float(spatial_score),
149
+ int(item["prompt_object_count"]),
150
+ int(item["question_object_count"]),
151
+ str(source.get("step", "")),
152
+ str(source.get("group", "")),
153
+ str(source.get("sample_idx", "")),
154
+ str(source.get("question_id", "")),
155
+ )
156
+
157
+
158
+ def main() -> None:
159
+ args = parse_args()
160
+ repo_root = args.repo_root.resolve()
161
+ rl_samples_root = resolve_path(repo_root, args.rl_samples_root)
162
+ output_jsonl = resolve_path(repo_root, args.output_jsonl)
163
+ manifest_csv = resolve_path(repo_root, args.manifest_csv)
164
+
165
+ exclude_paths = [resolve_path(repo_root, path) for path in args.exclude_manifest]
166
+ if args.use_default_excludes:
167
+ exclude_paths.extend(resolve_path(repo_root, Path(path)) for path in DEFAULT_EXCLUDE_MANIFESTS)
168
+ excluded = load_excluded_keys(exclude_paths)
169
+
170
+ scanned_records = 0
171
+ has_map = 0
172
+ object_q = 0
173
+ excluded_prev = 0
174
+ candidates: List[Dict] = []
175
+
176
+ for reward_path in reward_json_files(rl_samples_root):
177
+ step = reward_path.parent.parent.name
178
+ group = reward_path.parent.name
179
+ try:
180
+ samples = read_reward_file(reward_path)
181
+ except Exception as exc:
182
+ print(f"skip unreadable {reward_path}: {exc}", flush=True)
183
+ continue
184
+ for sample in samples:
185
+ if not isinstance(sample, dict):
186
+ continue
187
+ prompt = normalize_text(sample.get("prompt", ""))
188
+ prompt_obj_count = object_count(prompt)
189
+ for record in sample.get("reward_records", []):
190
+ if not isinstance(record, dict):
191
+ continue
192
+ scanned_records += 1
193
+ if not has_credit_map(record):
194
+ continue
195
+ has_map += 1
196
+
197
+ qid = str(record.get("question_id", ""))
198
+ atomic_question = extract_atomic_question(record.get("question", ""), qid)
199
+ question_obj_count = object_count(atomic_question)
200
+ if question_obj_count < args.min_question_object_count:
201
+ continue
202
+ if prompt_obj_count < args.min_prompt_object_count:
203
+ continue
204
+ if QUESTION_EXCLUDE_PATTERNS.search(atomic_question):
205
+ continue
206
+ object_q += 1
207
+
208
+ key = (str(step), str(group), str(sample.get("sample_idx", "")), qid)
209
+ if key in excluded:
210
+ excluded_prev += 1
211
+ continue
212
+
213
+ payload = {
214
+ "source": {
215
+ "step": step,
216
+ "group": group,
217
+ "sample_idx": sample.get("sample_idx"),
218
+ "question_id": qid,
219
+ "prompt": prompt,
220
+ "question": atomic_question,
221
+ "target_answer": record.get("target_answer"),
222
+ "source_pred": record.get("pred_sentence"),
223
+ "video_path": sample.get("video_path"),
224
+ "reward_json_path": str(reward_path),
225
+ },
226
+ "rerun_record": record,
227
+ }
228
+ candidates.append(
229
+ {
230
+ "payload": payload,
231
+ "reward_json_path": str(reward_path),
232
+ "prompt_object_count": prompt_obj_count,
233
+ "question_object_count": question_obj_count,
234
+ }
235
+ )
236
+
237
+ candidates.sort(key=candidate_sort_key, reverse=True)
238
+ if args.top_k > 0:
239
+ candidates = candidates[: args.top_k]
240
+
241
+ output_jsonl.parent.mkdir(parents=True, exist_ok=True)
242
+ manifest_csv.parent.mkdir(parents=True, exist_ok=True)
243
+
244
+ with output_jsonl.open("w", encoding="utf-8") as f:
245
+ for item in candidates:
246
+ f.write(json.dumps(item["payload"], ensure_ascii=False) + "\n")
247
+
248
+ fieldnames = [
249
+ "step",
250
+ "group",
251
+ "sample_idx",
252
+ "question_id",
253
+ "prompt_object_count",
254
+ "question_object_count",
255
+ "target_answer",
256
+ "source_pred",
257
+ "question",
258
+ "prompt",
259
+ "video_path",
260
+ "reward_json_path",
261
+ ]
262
+ with manifest_csv.open("w", encoding="utf-8", newline="") as f:
263
+ writer = csv.DictWriter(f, fieldnames=fieldnames)
264
+ writer.writeheader()
265
+ for item in candidates:
266
+ source = item["payload"]["source"]
267
+ writer.writerow(
268
+ {
269
+ "step": source.get("step"),
270
+ "group": source.get("group"),
271
+ "sample_idx": source.get("sample_idx"),
272
+ "question_id": source.get("question_id"),
273
+ "prompt_object_count": item["prompt_object_count"],
274
+ "question_object_count": item["question_object_count"],
275
+ "target_answer": source.get("target_answer"),
276
+ "source_pred": source.get("source_pred"),
277
+ "question": source.get("question"),
278
+ "prompt": source.get("prompt"),
279
+ "video_path": source.get("video_path"),
280
+ "reward_json_path": item["reward_json_path"],
281
+ }
282
+ )
283
+
284
+ print(
285
+ " ".join(
286
+ [
287
+ f"scanned={scanned_records}",
288
+ f"has_map={has_map}",
289
+ f"object_q={object_q}",
290
+ f"excluded_prev={excluded_prev}",
291
+ f"written={len(candidates)}",
292
+ ]
293
+ )
294
+ )
295
+ print(output_jsonl)
296
+ print(manifest_csv)
297
+
298
+
299
+ if __name__ == "__main__":
300
+ main()