geminiDeveloper commited on
Commit
9c49b58
·
verified ·
1 Parent(s): cbfbc9b

Upload analyze_nanoclaw_mask_trajectories.py

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