geminiDeveloper commited on
Commit
cbfbc9b
·
verified ·
1 Parent(s): 0eb5a18

Delete analyze_nanoclaw_mask_trajectories.py

Browse files
Files changed (1) hide show
  1. analyze_nanoclaw_mask_trajectories.py +0 -520
analyze_nanoclaw_mask_trajectories.py DELETED
@@ -1,520 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Offline NanoClaw mask-candidate and positive-advantage analysis.
3
-
4
- The script reads saved ``conversation_history.json`` files and the reward
5
- records written under ``step_N/_reward_logs``. It does not load a model, start
6
- Ray/vLLM, call a verifier, or modify the old rollout directories.
7
-
8
- For every step it reports eight primary quantities:
9
-
10
- 1. candidate turns for each of four bad-turn types;
11
- 2. candidate turns whose group-score advantage is positive for each type.
12
-
13
- Token counterparts are emitted as additional columns and plotted as well.
14
- The positive-advantage decision is reconstructed from the saved final reward
15
- score within each prompt/task group. If the historical run used KL-in-reward,
16
- the exact token-level KL contribution was not saved in conversation history;
17
- the output therefore labels this reconstruction as ``positive_by_group_score``
18
- and reports missing/incomplete groups explicitly.
19
- """
20
-
21
- from __future__ import annotations
22
-
23
- import argparse
24
- import csv
25
- import json
26
- import re
27
- import sys
28
- from collections import defaultdict
29
- from dataclasses import dataclass, field
30
- from pathlib import Path
31
- from statistics import fmean
32
- from typing import Any
33
-
34
-
35
- REASONS = (
36
- "looping_response",
37
- "budget_exhausted_last_turn",
38
- "duplicate_tool_result_turn",
39
- "error_tool_result_turn",
40
- )
41
- TERMINATION_REASONS = {"max_assistant_response_tokens", "max_response_tokens"}
42
- STEP_RE = re.compile(r"(?:^|/)step_(\d+)(?:/|$)")
43
- RESULT_DIR_RE = re.compile(r"^(?P<task>.+)_sample_(?P<sample>\d+)(?:_[A-Za-z0-9]+)?$")
44
-
45
-
46
- @dataclass
47
- class Sample:
48
- history_path: Path
49
- result_dir: Path
50
- step: int | None
51
- task_id: str
52
- rollout_n: int | None
53
- payload: dict[str, Any]
54
- candidate_turns: dict[str, int] = field(default_factory=dict)
55
- candidate_tokens: dict[str, int] = field(default_factory=dict)
56
- score: float | None = None
57
- score_source: str | None = None
58
- group_mean: float | None = None
59
- group_advantage: float | None = None
60
- positive_by_group_score: bool | None = None
61
- group_complete: bool = False
62
-
63
-
64
- def parse_args() -> argparse.Namespace:
65
- parser = argparse.ArgumentParser(description="Analyze saved NanoClaw mask candidates by step.")
66
- parser.add_argument("workplace_root", type=Path, help="nanoclaw_temp_workplace... root")
67
- parser.add_argument("--output-dir", type=Path, default=None, help="Defaults to <root>/mask_analysis")
68
- parser.add_argument(
69
- "--history-name",
70
- "--trajectory-name",
71
- dest="history_name",
72
- default="conversation_history.json",
73
- help="Saved event file to scan (default: conversation_history.json; trajectory.json is also supported)",
74
- )
75
- parser.add_argument(
76
- "--expected-group-size",
77
- type=int,
78
- default=None,
79
- help="Expected GRPO samples per prompt, e.g. 8. Incomplete groups are not used for positive classification.",
80
- )
81
- parser.add_argument("--no-plot", action="store_true", help="Write CSV/JSON only.")
82
- return parser.parse_args()
83
-
84
-
85
- def load_json(path: Path) -> dict[str, Any] | None:
86
- try:
87
- value = json.loads(path.read_text(encoding="utf-8"))
88
- except (OSError, UnicodeDecodeError, json.JSONDecodeError):
89
- return None
90
- return value if isinstance(value, dict) else None
91
-
92
-
93
- def number(value: Any) -> float | None:
94
- if isinstance(value, bool):
95
- return None
96
- try:
97
- result = float(value)
98
- except (TypeError, ValueError):
99
- return None
100
- return result if result == result else None
101
-
102
-
103
- def integer(*values: Any) -> int | None:
104
- for value in values:
105
- if isinstance(value, bool):
106
- continue
107
- try:
108
- return int(value)
109
- except (TypeError, ValueError):
110
- continue
111
- return None
112
-
113
-
114
- def events_from_history(payload: dict[str, Any]) -> list[dict[str, Any]]:
115
- events = payload.get("events")
116
- if isinstance(events, list):
117
- return [event for event in events if isinstance(event, dict)]
118
- nested = payload.get("conversation_history")
119
- if isinstance(nested, dict) and isinstance(nested.get("events"), list):
120
- return [event for event in nested["events"] if isinstance(event, dict)]
121
- return []
122
-
123
-
124
- def infer_step(path: Path, payload: dict[str, Any]) -> int | None:
125
- match = STEP_RE.search(path.as_posix())
126
- if match:
127
- return int(match.group(1))
128
- for container_key in ("rollout", "workspace"):
129
- container = payload.get(container_key)
130
- if isinstance(container, dict):
131
- value = integer(container.get("step"), container.get("rollout_step"))
132
- if value is not None:
133
- return value
134
- return integer(payload.get("rollout_step"), payload.get("step"))
135
-
136
-
137
- def result_dir_and_identity(history_path: Path, payload: dict[str, Any]) -> tuple[Path, str, int | None]:
138
- result_dir = history_path.parent
139
- task_id = payload.get("task_id")
140
- rollout_n = integer(payload.get("rollout_n"), payload.get("rollout_sample_index"))
141
- match = RESULT_DIR_RE.match(result_dir.name)
142
- if match:
143
- task_id = task_id or match.group("task")
144
- rollout_n = rollout_n if rollout_n is not None else int(match.group("sample"))
145
- if not isinstance(task_id, str) or not task_id:
146
- task_id = result_dir.name
147
- return result_dir, task_id, rollout_n
148
-
149
-
150
- def event_turn(event: dict[str, Any]) -> int | None:
151
- return integer(event.get("assistant_turn"), event.get("turn"))
152
-
153
-
154
- def assistant_events(events: list[dict[str, Any]]) -> dict[int, dict[str, Any]]:
155
- result: dict[int, dict[str, Any]] = {}
156
- for event in events:
157
- if event.get("type") == "assistant":
158
- turn = event_turn(event)
159
- if turn is not None:
160
- result[turn] = event
161
- return result
162
-
163
-
164
- def assistant_tokens(event: dict[str, Any] | None) -> int:
165
- if not isinstance(event, dict):
166
- return 0
167
- explicit = integer(event.get("token_count"))
168
- if explicit is not None and explicit >= 0:
169
- return explicit
170
- start = integer(event.get("response_start"))
171
- end = integer(event.get("response_end"))
172
- return max(0, end - start) if start is not None and end is not None else 0
173
-
174
-
175
- def text_parts(value: Any) -> list[str]:
176
- if isinstance(value, str):
177
- return [value]
178
- if isinstance(value, list):
179
- result: list[str] = []
180
- for item in value:
181
- result.extend(text_parts(item))
182
- return result
183
- if isinstance(value, dict):
184
- result: list[str] = []
185
- for key in ("text", "content"):
186
- if key in value:
187
- result.extend(text_parts(value[key]))
188
- return result
189
- return []
190
-
191
-
192
- def is_error_tool_result(event: dict[str, Any]) -> bool:
193
- response = event.get("response")
194
- content = response.get("content") if isinstance(response, dict) else response
195
- if any(re.match(r"^\s*error(?:\b|\s*:)", text, re.IGNORECASE) for text in text_parts(content)):
196
- return True
197
- result = event.get("result")
198
- if not isinstance(result, dict):
199
- return False
200
- error_value = result.get("error")
201
- if error_value is not None and error_value is not False and error_value != "":
202
- return True
203
- status = result.get("status")
204
- return isinstance(status, str) and status.strip().lower() in {"error", "failed", "failure"}
205
-
206
-
207
- def canonical_key(value: Any) -> str:
208
- try:
209
- return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=repr)
210
- except (TypeError, ValueError):
211
- return repr(value)
212
-
213
-
214
- def duplicate_turns(events: list[dict[str, Any]]) -> set[int]:
215
- seen: set[str] = set()
216
- result: set[int] = set()
217
- for event in events:
218
- if event.get("type") != "tool":
219
- continue
220
- key = canonical_key({key: event.get(key) for key in ("tool", "arguments", "response", "result")})
221
- turn = event_turn(event)
222
- if key in seen and turn is not None:
223
- result.add(turn)
224
- seen.add(key)
225
- return result
226
-
227
-
228
- def candidate_counts(payload: dict[str, Any]) -> tuple[dict[str, int], dict[str, int]]:
229
- events = events_from_history(payload)
230
- assistants = assistant_events(events)
231
- turns: dict[str, set[int]] = {reason: set() for reason in REASONS}
232
-
233
- for turn, event in assistants.items():
234
- repeats = integer(event.get("looping_repeat_count"), event.get("repeat_count")) or 0
235
- if repeats > 0 or event.get("looping_response_mask_candidate") is True:
236
- turns["looping_response"].add(turn)
237
-
238
- termination = payload.get("termination_reason")
239
- if not isinstance(termination, str) and isinstance(payload.get("summary"), dict):
240
- termination = payload["summary"].get("termination_reason")
241
- if termination in TERMINATION_REASONS and assistants:
242
- turns["budget_exhausted_last_turn"].add(max(assistants))
243
-
244
- turns["duplicate_tool_result_turn"] = duplicate_turns(events)
245
- for event in events:
246
- if event.get("type") == "tool" and is_error_tool_result(event):
247
- turn = event_turn(event)
248
- if turn is not None:
249
- turns["error_tool_result_turn"].add(turn)
250
-
251
- token_counts = {
252
- reason: sum(assistant_tokens(assistants.get(turn)) for turn in reason_turns)
253
- for reason, reason_turns in turns.items()
254
- }
255
- return {reason: len(reason_turns) for reason, reason_turns in turns.items()}, token_counts
256
-
257
-
258
- def score_from_obj(obj: dict[str, Any]) -> tuple[float | None, str | None]:
259
- # Training reward logs contain the final reward under score. Prefer it over
260
- # verifier-only score_ratio because it includes configured bonuses/penalties.
261
- for key in ("score", "reward_score", "nanoclaw_score"):
262
- value = number(obj.get(key))
263
- if value is not None:
264
- return value, key
265
- summary = obj.get("score_summary")
266
- if isinstance(summary, dict):
267
- for key in ("score", "score_ratio"):
268
- value = number(summary.get(key))
269
- if value is not None:
270
- return value, f"score_summary.{key}"
271
- return None, None
272
-
273
-
274
- def build_reward_index(root: Path) -> dict[str, list[tuple[float, str, Path]]]:
275
- index: dict[str, list[tuple[float, str, Path]]] = defaultdict(list)
276
- for path in root.rglob("*.reward.json"):
277
- obj = load_json(path)
278
- if not obj:
279
- continue
280
- score, source = score_from_obj(obj)
281
- result_dir = obj.get("result_dir")
282
- if score is None or not isinstance(result_dir, str):
283
- continue
284
- index[Path(result_dir).name].append((score, f"reward_log.{source}", path))
285
- return index
286
-
287
-
288
- def load_sample_score(sample: Sample, reward_index: dict[str, list[tuple[float, str, Path]]]) -> None:
289
- result_name = sample.result_dir.name
290
- candidates = reward_index.get(result_name, [])
291
- if candidates:
292
- sample.score, sample.score_source, _ = candidates[-1]
293
- return
294
-
295
- # Useful when the run was rescored after training or reward logs were moved.
296
- for filename in ("score_summary.json", "verifier_result.json"):
297
- obj = load_json(sample.result_dir / filename)
298
- if obj:
299
- sample.score, sample.score_source = score_from_obj(obj)
300
- if sample.score is not None:
301
- return
302
- for container_key in ("score_summary", "verifier"):
303
- obj = sample.payload.get(container_key)
304
- if isinstance(obj, dict):
305
- sample.score, sample.score_source = score_from_obj(obj)
306
- if sample.score is not None:
307
- return
308
-
309
-
310
- def assign_group_advantages(samples: list[Sample], expected_group_size: int | None) -> dict[str, int]:
311
- groups: dict[tuple[int | None, str], list[Sample]] = defaultdict(list)
312
- for sample in samples:
313
- groups[(sample.step, sample.task_id)].append(sample)
314
- diagnostics = {"groups": len(groups), "complete_groups": 0, "incomplete_groups": 0, "missing_score_samples": 0}
315
-
316
- for members in groups.values():
317
- scores = [sample.score for sample in members]
318
- complete = all(score is not None for score in scores)
319
- if expected_group_size is not None and len(members) != expected_group_size:
320
- complete = False
321
- if not complete:
322
- diagnostics["incomplete_groups"] += 1
323
- diagnostics["missing_score_samples"] += sum(score is None for score in scores)
324
- for sample in members:
325
- sample.group_complete = False
326
- continue
327
-
328
- diagnostics["complete_groups"] += 1
329
- numeric_scores = [float(score) for score in scores if score is not None]
330
- # GRPO with a singleton group uses a zero baseline in the reference
331
- # implementation; otherwise it uses the group mean. Sign is unchanged
332
- # by positive std normalization.
333
- baseline = 0.0 if len(numeric_scores) == 1 else fmean(numeric_scores)
334
- for sample in members:
335
- assert sample.score is not None
336
- sample.group_complete = True
337
- sample.group_mean = baseline
338
- sample.group_advantage = sample.score - baseline
339
- sample.positive_by_group_score = sample.group_advantage > 0.0
340
-
341
- return diagnostics
342
-
343
-
344
- def scan(root: Path, history_name: str, expected_group_size: int | None) -> tuple[list[Sample], dict[str, int]]:
345
- histories = sorted(root.rglob(history_name))
346
- reward_index = build_reward_index(root)
347
- samples: list[Sample] = []
348
- malformed = 0
349
- for path in histories:
350
- payload = load_json(path)
351
- if payload is None:
352
- malformed += 1
353
- continue
354
- result_dir, task_id, rollout_n = result_dir_and_identity(path, payload)
355
- turn_counts, token_counts = candidate_counts(payload)
356
- sample = Sample(
357
- history_path=path,
358
- result_dir=result_dir,
359
- step=infer_step(path, payload),
360
- task_id=task_id,
361
- rollout_n=rollout_n,
362
- payload=payload,
363
- candidate_turns=turn_counts,
364
- candidate_tokens=token_counts,
365
- )
366
- load_sample_score(sample, reward_index)
367
- samples.append(sample)
368
- diagnostics = {"history_files": len(histories), "loaded": len(samples), "malformed": malformed, "reward_records": sum(map(len, reward_index.values()))}
369
- diagnostics.update(assign_group_advantages(samples, expected_group_size))
370
- return samples, diagnostics
371
-
372
-
373
- def aggregate_rows(samples: list[Sample]) -> list[dict[str, Any]]:
374
- grouped: dict[int | None, list[Sample]] = defaultdict(list)
375
- for sample in samples:
376
- grouped[sample.step].append(sample)
377
- rows: list[dict[str, Any]] = []
378
- for step in sorted(grouped, key=lambda value: (value is None, value if value is not None else 0)):
379
- members = grouped[step]
380
- row: dict[str, Any] = {"step": "unknown" if step is None else step, "samples": len(members)}
381
- for reason in REASONS:
382
- row[f"{reason}_candidate_turns"] = sum(sample.candidate_turns[reason] for sample in members)
383
- row[f"{reason}_candidate_tokens"] = sum(sample.candidate_tokens[reason] for sample in members)
384
- positive_members = [sample for sample in members if sample.positive_by_group_score is True]
385
- row[f"{reason}_positive_masked_turns"] = sum(sample.candidate_turns[reason] for sample in positive_members)
386
- row[f"{reason}_positive_masked_tokens"] = sum(sample.candidate_tokens[reason] for sample in positive_members)
387
- row["scored_samples"] = sum(sample.score is not None for sample in members)
388
- row["positive_group_score_samples"] = sum(sample.positive_by_group_score is True for sample in members)
389
- row["incomplete_group_samples"] = sum(not sample.group_complete for sample in members)
390
- for reason in REASONS:
391
- row[f"{reason}_candidate_turns_per_sample"] = row[f"{reason}_candidate_turns"] / len(members) if members else 0.0
392
- row[f"{reason}_positive_masked_turns_per_sample"] = row[f"{reason}_positive_masked_turns"] / len(members) if members else 0.0
393
- rows.append(row)
394
- return rows
395
-
396
-
397
- def write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
398
- fields = list(rows[0].keys()) if rows else ["step", "samples"]
399
- with path.open("w", encoding="utf-8", newline="") as handle:
400
- writer = csv.DictWriter(handle, fieldnames=fields)
401
- writer.writeheader()
402
- writer.writerows(rows)
403
-
404
-
405
- def write_sample_csv(path: Path, samples: list[Sample]) -> None:
406
- fields = ["step", "task_id", "rollout_n", "result_dir", "score", "score_source", "group_mean", "group_advantage", "positive_by_group_score", "group_complete"]
407
- for reason in REASONS:
408
- fields.extend((f"{reason}_candidate_turns", f"{reason}_candidate_tokens"))
409
- with path.open("w", encoding="utf-8", newline="") as handle:
410
- writer = csv.DictWriter(handle, fieldnames=fields)
411
- writer.writeheader()
412
- for sample in samples:
413
- row: dict[str, Any] = {
414
- "step": "unknown" if sample.step is None else sample.step,
415
- "task_id": sample.task_id,
416
- "rollout_n": sample.rollout_n,
417
- "result_dir": str(sample.result_dir),
418
- "score": sample.score,
419
- "score_source": sample.score_source,
420
- "group_mean": sample.group_mean,
421
- "group_advantage": sample.group_advantage,
422
- "positive_by_group_score": sample.positive_by_group_score,
423
- "group_complete": sample.group_complete,
424
- }
425
- for reason in REASONS:
426
- row[f"{reason}_candidate_turns"] = sample.candidate_turns[reason]
427
- row[f"{reason}_candidate_tokens"] = sample.candidate_tokens[reason]
428
- writer.writerow(row)
429
-
430
-
431
- def make_plot(output_dir: Path, rows: list[dict[str, Any]]) -> Path | None:
432
- known = [row for row in rows if row["step"] != "unknown"]
433
- if not known:
434
- return None
435
- try:
436
- import matplotlib.pyplot as plt
437
- except ImportError:
438
- print("WARNING: matplotlib is unavailable; CSV/JSON were written without plots.", file=sys.stderr)
439
- return None
440
- colors = {"looping_response": "#d62728", "budget_exhausted_last_turn": "#ff7f0e", "duplicate_tool_result_turn": "#2ca02c", "error_tool_result_turn": "#1f77b4"}
441
- labels = {"looping_response": "looping", "budget_exhausted_last_turn": "budget exhausted", "duplicate_tool_result_turn": "duplicate tool", "error_tool_result_turn": "error tool"}
442
- steps = [int(row["step"]) for row in known]
443
- fig, axes = plt.subplots(2, 2, figsize=(15, 9), sharex="col", constrained_layout=True)
444
- for reason in REASONS:
445
- color, label = colors[reason], labels[reason]
446
- axes[0, 0].plot(steps, [row[f"{reason}_candidate_turns"] for row in known], marker="o", color=color, label=label)
447
- axes[0, 1].plot(steps, [row[f"{reason}_positive_masked_turns"] for row in known], marker="o", color=color, label=label)
448
- axes[1, 0].plot(steps, [row[f"{reason}_candidate_tokens"] for row in known], marker="o", color=color, label=label)
449
- axes[1, 1].plot(steps, [row[f"{reason}_positive_masked_tokens"] for row in known], marker="o", color=color, label=label)
450
- axes[0, 0].set_title("candidate bad-turns")
451
- axes[0, 1].set_title("positive group-score candidate turns")
452
- axes[1, 0].set_title("candidate tokens")
453
- axes[1, 1].set_title("positive group-score candidate tokens")
454
- for row_axes in axes:
455
- for axis in row_axes:
456
- axis.grid(True, alpha=0.3)
457
- axis.legend()
458
- axes[1, 0].set_xlabel("training step")
459
- axes[1, 1].set_xlabel("training step")
460
- plot_path = output_dir / "nanoclaw_mask_candidates_and_positive_by_step.png"
461
- fig.savefig(plot_path, dpi=160)
462
- plt.close(fig)
463
- return plot_path
464
-
465
-
466
- def main() -> int:
467
- args = parse_args()
468
- root = args.workplace_root.expanduser().resolve()
469
- if not root.is_dir():
470
- print(f"ERROR: workplace root is not a directory: {root}", file=sys.stderr)
471
- return 2
472
- output_dir = (args.output_dir or root / "mask_analysis").expanduser().resolve()
473
- samples, diagnostics = scan(root, args.history_name, args.expected_group_size)
474
- rows = aggregate_rows(samples)
475
- output_dir.mkdir(parents=True, exist_ok=True)
476
- summary_csv = output_dir / "nanoclaw_mask_8_metrics_by_step.csv"
477
- sample_csv = output_dir / "nanoclaw_mask_group_scores_and_candidates.csv"
478
- summary_json = output_dir / "nanoclaw_mask_8_metrics_by_step.json"
479
- write_csv(summary_csv, rows)
480
- write_sample_csv(sample_csv, samples)
481
- plot_path = None if args.no_plot else make_plot(output_dir, rows)
482
- summary_json.write_text(
483
- json.dumps(
484
- {
485
- "workplace_root": str(root),
486
- "history_name": args.history_name,
487
- "expected_group_size": args.expected_group_size,
488
- "advantage_reconstruction": "score - group_mean; singleton baseline=0; exact KL-in-reward advantage requires saved reward/advantage tensors",
489
- "diagnostics": diagnostics,
490
- "rows": rows,
491
- },
492
- ensure_ascii=False,
493
- indent=2,
494
- )
495
- + "\n",
496
- encoding="utf-8",
497
- )
498
-
499
- print(f"workplace root: {root}")
500
- print(f"history files: {diagnostics['history_files']}, loaded: {diagnostics['loaded']}, malformed: {diagnostics['malformed']}")
501
- print(f"reward records: {diagnostics['reward_records']}, groups: {diagnostics['groups']}, complete groups: {diagnostics['complete_groups']}")
502
- print(f"incomplete groups: {diagnostics['incomplete_groups']}, missing-score samples: {diagnostics['missing_score_samples']}")
503
- print(f"summary CSV: {summary_csv}")
504
- print(f"group/sample CSV: {sample_csv}")
505
- print(f"summary JSON: {summary_json}")
506
- if plot_path:
507
- print(f"plot: {plot_path}")
508
- for row in rows:
509
- print(
510
- f"step={row['step']} samples={row['samples']} "
511
- + " ".join(
512
- f"{reason}={row[f'{reason}_candidate_turns']}/{row[f'{reason}_positive_masked_turns']} turns"
513
- for reason in REASONS
514
- )
515
- )
516
- return 0
517
-
518
-
519
- if __name__ == "__main__":
520
- raise SystemExit(main())