| |
| """Offline NanoClaw mask-candidate and positive-advantage analysis. |
| |
| The script reads saved ``conversation_history.json`` files and the reward |
| records written under ``step_N/_reward_logs``. It does not load a model, start |
| Ray/vLLM, call a verifier, or modify the old rollout directories. |
| |
| For every step it reports eight primary quantities: |
| |
| 1. candidate turns for each of four bad-turn types; |
| 2. candidate turns whose group-score advantage is positive for each type. |
| |
| Token counterparts are emitted as additional columns and plotted as well. |
| The positive-advantage decision is reconstructed from the saved final reward |
| score within each prompt/task group. If the historical run used KL-in-reward, |
| the exact token-level KL contribution was not saved in conversation history; |
| the output therefore labels this reconstruction as ``positive_by_group_score`` |
| and reports missing/incomplete groups explicitly. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import concurrent.futures |
| import json |
| import re |
| import sys |
| from collections import defaultdict |
| from dataclasses import dataclass, field |
| from pathlib import Path |
| from statistics import fmean |
| from typing import Any |
|
|
| try: |
| import orjson |
| except ImportError: |
| orjson = None |
|
|
|
|
| REASONS = ( |
| "looping_response", |
| "budget_exhausted_last_turn", |
| "duplicate_tool_result_turn", |
| "error_tool_result_turn", |
| ) |
| TERMINATION_REASONS = {"max_assistant_response_tokens", "max_response_tokens"} |
| STEP_RE = re.compile(r"(?:^|/)step_(\d+)(?:/|$)") |
| RESULT_DIR_RE = re.compile(r"^(?P<task>.+)_sample_(?P<sample>\d+)(?:_[A-Za-z0-9]+)?$") |
|
|
|
|
| @dataclass |
| class Sample: |
| history_path: Path |
| result_dir: Path |
| step: int | None |
| task_id: str |
| rollout_n: int | None |
| payload: dict[str, Any] |
| candidate_turns: dict[str, int] = field(default_factory=dict) |
| candidate_tokens: dict[str, int] = field(default_factory=dict) |
| score: float | None = None |
| score_source: str | None = None |
| group_mean: float | None = None |
| group_advantage: float | None = None |
| positive_by_group_score: bool | None = None |
| group_complete: bool = False |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description="Analyze saved NanoClaw mask candidates by step.") |
| parser.add_argument("workplace_root", type=Path, help="nanoclaw_temp_workplace... root") |
| parser.add_argument("--output-dir", type=Path, default=None, help="Defaults to <root>/mask_analysis") |
| parser.add_argument( |
| "--history-name", |
| "--trajectory-name", |
| dest="history_name", |
| default="conversation_history.json", |
| help="Saved event file to scan (default: conversation_history.json; trajectory.json is also supported)", |
| ) |
| parser.add_argument( |
| "--expected-group-size", |
| type=int, |
| default=None, |
| help="Expected GRPO samples per prompt, e.g. 8. Incomplete groups are not used for positive classification.", |
| ) |
| parser.add_argument( |
| "--workers", |
| type=int, |
| default=8, |
| help="Parallel history readers (default: 8; use 2-4 on a slow shared filesystem).", |
| ) |
| parser.add_argument("--no-plot", action="store_true", help="Write CSV/JSON only.") |
| return parser.parse_args() |
|
|
|
|
| def load_json(path: Path) -> dict[str, Any] | None: |
| try: |
| raw = path.read_bytes() |
| value = orjson.loads(raw) if orjson is not None else json.loads(raw) |
| except (OSError, UnicodeDecodeError, json.JSONDecodeError): |
| return None |
| return value if isinstance(value, dict) else None |
|
|
|
|
| def number(value: Any) -> float | None: |
| if isinstance(value, bool): |
| return None |
| try: |
| result = float(value) |
| except (TypeError, ValueError): |
| return None |
| return result if result == result else None |
|
|
|
|
| def integer(*values: Any) -> int | None: |
| for value in values: |
| if isinstance(value, bool): |
| continue |
| try: |
| return int(value) |
| except (TypeError, ValueError): |
| continue |
| return None |
|
|
|
|
| def events_from_history(payload: dict[str, Any]) -> list[dict[str, Any]]: |
| events = payload.get("events") |
| if isinstance(events, list): |
| return [event for event in events if isinstance(event, dict)] |
| nested = payload.get("conversation_history") |
| if isinstance(nested, dict) and isinstance(nested.get("events"), list): |
| return [event for event in nested["events"] if isinstance(event, dict)] |
| return [] |
|
|
|
|
| def infer_step(path: Path, payload: dict[str, Any]) -> int | None: |
| match = STEP_RE.search(path.as_posix()) |
| if match: |
| return int(match.group(1)) |
| for container_key in ("rollout", "workspace"): |
| container = payload.get(container_key) |
| if isinstance(container, dict): |
| value = integer(container.get("step"), container.get("rollout_step")) |
| if value is not None: |
| return value |
| return integer(payload.get("rollout_step"), payload.get("step")) |
|
|
|
|
| def result_dir_and_identity(history_path: Path, payload: dict[str, Any]) -> tuple[Path, str, int | None]: |
| result_dir = history_path.parent |
| task_id = payload.get("task_id") |
| rollout_n = integer(payload.get("rollout_n"), payload.get("rollout_sample_index")) |
| match = RESULT_DIR_RE.match(result_dir.name) |
| if match: |
| task_id = task_id or match.group("task") |
| rollout_n = rollout_n if rollout_n is not None else int(match.group("sample")) |
| if not isinstance(task_id, str) or not task_id: |
| task_id = result_dir.name |
| return result_dir, task_id, rollout_n |
|
|
|
|
| def event_turn(event: dict[str, Any]) -> int | None: |
| return integer(event.get("assistant_turn"), event.get("turn")) |
|
|
|
|
| def assistant_events(events: list[dict[str, Any]]) -> dict[int, dict[str, Any]]: |
| result: dict[int, dict[str, Any]] = {} |
| for event in events: |
| if event.get("type") == "assistant": |
| turn = event_turn(event) |
| if turn is not None: |
| result[turn] = event |
| return result |
|
|
|
|
| def assistant_tokens(event: dict[str, Any] | None) -> int: |
| if not isinstance(event, dict): |
| return 0 |
| explicit = integer(event.get("token_count")) |
| if explicit is not None and explicit >= 0: |
| return explicit |
| start = integer(event.get("response_start")) |
| end = integer(event.get("response_end")) |
| return max(0, end - start) if start is not None and end is not None else 0 |
|
|
|
|
| def text_parts(value: Any) -> list[str]: |
| if isinstance(value, str): |
| return [value] |
| if isinstance(value, list): |
| result: list[str] = [] |
| for item in value: |
| result.extend(text_parts(item)) |
| return result |
| if isinstance(value, dict): |
| result: list[str] = [] |
| for key in ("text", "content"): |
| if key in value: |
| result.extend(text_parts(value[key])) |
| return result |
| return [] |
|
|
|
|
| def is_error_tool_result(event: dict[str, Any]) -> bool: |
| response = event.get("response") |
| content = response.get("content") if isinstance(response, dict) else response |
| if any(re.match(r"^\s*error(?:\b|\s*:)", text, re.IGNORECASE) for text in text_parts(content)): |
| return True |
| result = event.get("result") |
| if not isinstance(result, dict): |
| return False |
| error_value = result.get("error") |
| if error_value is not None and error_value is not False and error_value != "": |
| return True |
| status = result.get("status") |
| return isinstance(status, str) and status.strip().lower() in {"error", "failed", "failure"} |
|
|
|
|
| def canonical_key(value: Any) -> str: |
| try: |
| return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=repr) |
| except (TypeError, ValueError): |
| return repr(value) |
|
|
|
|
| def duplicate_turns(events: list[dict[str, Any]]) -> set[int]: |
| seen: set[str] = set() |
| result: set[int] = set() |
| for event in events: |
| if event.get("type") != "tool": |
| continue |
| key = canonical_key({key: event.get(key) for key in ("tool", "arguments", "response", "result")}) |
| turn = event_turn(event) |
| if key in seen and turn is not None: |
| result.add(turn) |
| seen.add(key) |
| return result |
|
|
|
|
| def candidate_counts(payload: dict[str, Any]) -> tuple[dict[str, int], dict[str, int]]: |
| events = events_from_history(payload) |
| assistants = assistant_events(events) |
| turns: dict[str, set[int]] = {reason: set() for reason in REASONS} |
|
|
| for turn, event in assistants.items(): |
| repeats = integer(event.get("looping_repeat_count"), event.get("repeat_count")) or 0 |
| if repeats > 0 or event.get("looping_response_mask_candidate") is True: |
| turns["looping_response"].add(turn) |
|
|
| termination = payload.get("termination_reason") |
| if not isinstance(termination, str) and isinstance(payload.get("summary"), dict): |
| termination = payload["summary"].get("termination_reason") |
| if termination in TERMINATION_REASONS and assistants: |
| turns["budget_exhausted_last_turn"].add(max(assistants)) |
|
|
| turns["duplicate_tool_result_turn"] = duplicate_turns(events) |
| for event in events: |
| if event.get("type") == "tool" and is_error_tool_result(event): |
| turn = event_turn(event) |
| if turn is not None: |
| turns["error_tool_result_turn"].add(turn) |
|
|
| token_counts = { |
| reason: sum(assistant_tokens(assistants.get(turn)) for turn in reason_turns) |
| for reason, reason_turns in turns.items() |
| } |
| return {reason: len(reason_turns) for reason, reason_turns in turns.items()}, token_counts |
|
|
|
|
| def score_from_obj(obj: dict[str, Any]) -> tuple[float | None, str | None]: |
| |
| |
| for key in ("score", "reward_score", "nanoclaw_score"): |
| value = number(obj.get(key)) |
| if value is not None: |
| return value, key |
| summary = obj.get("score_summary") |
| if isinstance(summary, dict): |
| for key in ("score", "score_ratio"): |
| value = number(summary.get(key)) |
| if value is not None: |
| return value, f"score_summary.{key}" |
| return None, None |
|
|
|
|
| def build_reward_index(root: Path) -> dict[str, list[tuple[float, str, Path]]]: |
| index: dict[str, list[tuple[float, str, Path]]] = defaultdict(list) |
| reward_paths: list[Path] = [] |
| for step_dir in root.glob("step_*"): |
| reward_dir = step_dir / "_reward_logs" |
| if reward_dir.is_dir(): |
| reward_paths.extend(reward_dir.glob("*.reward.json")) |
| for path in sorted(reward_paths): |
| obj = load_json(path) |
| if not obj: |
| continue |
| score, source = score_from_obj(obj) |
| result_dir = obj.get("result_dir") |
| if score is None or not isinstance(result_dir, str): |
| continue |
| index[Path(result_dir).name].append((score, f"reward_log.{source}", path)) |
| return index |
|
|
|
|
| def load_sample_score(sample: Sample, reward_index: dict[str, list[tuple[float, str, Path]]]) -> None: |
| result_name = sample.result_dir.name |
| candidates = reward_index.get(result_name, []) |
| if candidates: |
| sample.score, sample.score_source, _ = candidates[-1] |
| return |
|
|
| |
| for filename in ("score_summary.json", "verifier_result.json"): |
| obj = load_json(sample.result_dir / filename) |
| if obj: |
| sample.score, sample.score_source = score_from_obj(obj) |
| if sample.score is not None: |
| return |
| for container_key in ("score_summary", "verifier"): |
| obj = sample.payload.get(container_key) |
| if isinstance(obj, dict): |
| sample.score, sample.score_source = score_from_obj(obj) |
| if sample.score is not None: |
| return |
|
|
|
|
| def assign_group_advantages(samples: list[Sample], expected_group_size: int | None) -> dict[str, int]: |
| groups: dict[tuple[int | None, str], list[Sample]] = defaultdict(list) |
| for sample in samples: |
| groups[(sample.step, sample.task_id)].append(sample) |
| diagnostics = {"groups": len(groups), "complete_groups": 0, "incomplete_groups": 0, "missing_score_samples": 0} |
|
|
| for members in groups.values(): |
| scores = [sample.score for sample in members] |
| complete = all(score is not None for score in scores) |
| if expected_group_size is not None and len(members) != expected_group_size: |
| complete = False |
| if not complete: |
| diagnostics["incomplete_groups"] += 1 |
| diagnostics["missing_score_samples"] += sum(score is None for score in scores) |
| for sample in members: |
| sample.group_complete = False |
| continue |
|
|
| diagnostics["complete_groups"] += 1 |
| numeric_scores = [float(score) for score in scores if score is not None] |
| |
| |
| |
| baseline = 0.0 if len(numeric_scores) == 1 else fmean(numeric_scores) |
| for sample in members: |
| assert sample.score is not None |
| sample.group_complete = True |
| sample.group_mean = baseline |
| sample.group_advantage = sample.score - baseline |
| sample.positive_by_group_score = sample.group_advantage > 0.0 |
|
|
| return diagnostics |
|
|
|
|
| def find_history_paths(root: Path, history_name: str) -> list[Path]: |
| paths: list[Path] = [] |
| for step_dir in root.glob("step_*"): |
| if step_dir.is_dir(): |
| paths.extend(step_dir.glob(f"*/{history_name}")) |
| if paths: |
| return sorted(path for path in paths if path.is_file()) |
| |
| return sorted(path for path in root.rglob(history_name) if path.is_file()) |
|
|
|
|
| def parse_history_sample(path: Path) -> Sample | None: |
| payload = load_json(path) |
| if payload is None: |
| return None |
| result_dir, task_id, rollout_n = result_dir_and_identity(path, payload) |
| turn_counts, token_counts = candidate_counts(payload) |
| return Sample( |
| history_path=path, |
| result_dir=result_dir, |
| step=infer_step(path, payload), |
| task_id=task_id, |
| rollout_n=rollout_n, |
| payload=payload, |
| candidate_turns=turn_counts, |
| candidate_tokens=token_counts, |
| ) |
|
|
|
|
| def scan(root: Path, history_name: str, expected_group_size: int | None, workers: int) -> tuple[list[Sample], dict[str, int]]: |
| histories = find_history_paths(root, history_name) |
| reward_index = build_reward_index(root) |
| samples: list[Sample] = [] |
| malformed = 0 |
| worker_count = max(1, int(workers)) |
| if worker_count == 1 or len(histories) <= 1: |
| parsed_iter = (parse_history_sample(path) for path in histories) |
| executor_context = None |
| else: |
| executor_context = concurrent.futures.ThreadPoolExecutor(max_workers=worker_count) |
| parsed_iter = executor_context.map(parse_history_sample, histories) |
| try: |
| for file_index, sample in enumerate(parsed_iter, start=1): |
| if file_index % 500 == 0 or file_index == len(histories): |
| print(f"[scan] parsed {file_index}/{len(histories)} histories", file=sys.stderr, flush=True) |
| if sample is None: |
| malformed += 1 |
| continue |
| load_sample_score(sample, reward_index) |
| |
| |
| sample.payload = {} |
| samples.append(sample) |
| finally: |
| if executor_context is not None: |
| executor_context.shutdown(wait=True) |
| diagnostics = { |
| "history_files": len(histories), |
| "loaded": len(samples), |
| "malformed": malformed, |
| "reward_records": sum(map(len, reward_index.values())), |
| "workers": worker_count, |
| "orjson": int(orjson is not None), |
| } |
| diagnostics.update(assign_group_advantages(samples, expected_group_size)) |
| return samples, diagnostics |
|
|
|
|
| def aggregate_rows(samples: list[Sample]) -> list[dict[str, Any]]: |
| grouped: dict[int | None, list[Sample]] = defaultdict(list) |
| for sample in samples: |
| grouped[sample.step].append(sample) |
| rows: list[dict[str, Any]] = [] |
| for step in sorted(grouped, key=lambda value: (value is None, value if value is not None else 0)): |
| members = grouped[step] |
| row: dict[str, Any] = {"step": "unknown" if step is None else step, "samples": len(members)} |
| for reason in REASONS: |
| row[f"{reason}_candidate_turns"] = sum(sample.candidate_turns[reason] for sample in members) |
| row[f"{reason}_candidate_tokens"] = sum(sample.candidate_tokens[reason] for sample in members) |
| positive_members = [sample for sample in members if sample.positive_by_group_score is True] |
| row[f"{reason}_positive_masked_turns"] = sum(sample.candidate_turns[reason] for sample in positive_members) |
| row[f"{reason}_positive_masked_tokens"] = sum(sample.candidate_tokens[reason] for sample in positive_members) |
| row["scored_samples"] = sum(sample.score is not None for sample in members) |
| row["positive_group_score_samples"] = sum(sample.positive_by_group_score is True for sample in members) |
| row["incomplete_group_samples"] = sum(not sample.group_complete for sample in members) |
| for reason in REASONS: |
| row[f"{reason}_candidate_turns_per_sample"] = row[f"{reason}_candidate_turns"] / len(members) if members else 0.0 |
| row[f"{reason}_positive_masked_turns_per_sample"] = row[f"{reason}_positive_masked_turns"] / len(members) if members else 0.0 |
| rows.append(row) |
| return rows |
|
|
|
|
| def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: |
| fields = list(rows[0].keys()) if rows else ["step", "samples"] |
| with path.open("w", encoding="utf-8", newline="") as handle: |
| writer = csv.DictWriter(handle, fieldnames=fields) |
| writer.writeheader() |
| writer.writerows(rows) |
|
|
|
|
| def write_sample_csv(path: Path, samples: list[Sample]) -> None: |
| fields = ["step", "task_id", "rollout_n", "result_dir", "score", "score_source", "group_mean", "group_advantage", "positive_by_group_score", "group_complete"] |
| for reason in REASONS: |
| fields.extend((f"{reason}_candidate_turns", f"{reason}_candidate_tokens")) |
| with path.open("w", encoding="utf-8", newline="") as handle: |
| writer = csv.DictWriter(handle, fieldnames=fields) |
| writer.writeheader() |
| for sample in samples: |
| row: dict[str, Any] = { |
| "step": "unknown" if sample.step is None else sample.step, |
| "task_id": sample.task_id, |
| "rollout_n": sample.rollout_n, |
| "result_dir": str(sample.result_dir), |
| "score": sample.score, |
| "score_source": sample.score_source, |
| "group_mean": sample.group_mean, |
| "group_advantage": sample.group_advantage, |
| "positive_by_group_score": sample.positive_by_group_score, |
| "group_complete": sample.group_complete, |
| } |
| for reason in REASONS: |
| row[f"{reason}_candidate_turns"] = sample.candidate_turns[reason] |
| row[f"{reason}_candidate_tokens"] = sample.candidate_tokens[reason] |
| writer.writerow(row) |
|
|
|
|
| def make_plot(output_dir: Path, rows: list[dict[str, Any]]) -> Path | None: |
| known = [row for row in rows if row["step"] != "unknown"] |
| if not known: |
| return None |
| try: |
| import matplotlib.pyplot as plt |
| except ImportError: |
| print("WARNING: matplotlib is unavailable; CSV/JSON were written without plots.", file=sys.stderr) |
| return None |
| colors = {"looping_response": "#d62728", "budget_exhausted_last_turn": "#ff7f0e", "duplicate_tool_result_turn": "#2ca02c", "error_tool_result_turn": "#1f77b4"} |
| labels = {"looping_response": "looping", "budget_exhausted_last_turn": "budget exhausted", "duplicate_tool_result_turn": "duplicate tool", "error_tool_result_turn": "error tool"} |
| steps = [int(row["step"]) for row in known] |
| fig, axes = plt.subplots(2, 2, figsize=(15, 9), sharex="col", constrained_layout=True) |
| for reason in REASONS: |
| color, label = colors[reason], labels[reason] |
| axes[0, 0].plot(steps, [row[f"{reason}_candidate_turns"] for row in known], marker="o", color=color, label=label) |
| axes[0, 1].plot(steps, [row[f"{reason}_positive_masked_turns"] for row in known], marker="o", color=color, label=label) |
| axes[1, 0].plot(steps, [row[f"{reason}_candidate_tokens"] for row in known], marker="o", color=color, label=label) |
| axes[1, 1].plot(steps, [row[f"{reason}_positive_masked_tokens"] for row in known], marker="o", color=color, label=label) |
| axes[0, 0].set_title("candidate bad-turns") |
| axes[0, 1].set_title("positive group-score candidate turns") |
| axes[1, 0].set_title("candidate tokens") |
| axes[1, 1].set_title("positive group-score candidate tokens") |
| for row_axes in axes: |
| for axis in row_axes: |
| axis.grid(True, alpha=0.3) |
| axis.legend() |
| axes[1, 0].set_xlabel("training step") |
| axes[1, 1].set_xlabel("training step") |
| plot_path = output_dir / "nanoclaw_mask_candidates_and_positive_by_step.png" |
| fig.savefig(plot_path, dpi=160) |
| plt.close(fig) |
| return plot_path |
|
|
|
|
| def main() -> int: |
| args = parse_args() |
| root = args.workplace_root.expanduser().resolve() |
| if not root.is_dir(): |
| print(f"ERROR: workplace root is not a directory: {root}", file=sys.stderr) |
| return 2 |
| output_dir = (args.output_dir or root / "mask_analysis").expanduser().resolve() |
| samples, diagnostics = scan(root, args.history_name, args.expected_group_size, args.workers) |
| rows = aggregate_rows(samples) |
| output_dir.mkdir(parents=True, exist_ok=True) |
| summary_csv = output_dir / "nanoclaw_mask_8_metrics_by_step.csv" |
| sample_csv = output_dir / "nanoclaw_mask_group_scores_and_candidates.csv" |
| summary_json = output_dir / "nanoclaw_mask_8_metrics_by_step.json" |
| write_csv(summary_csv, rows) |
| write_sample_csv(sample_csv, samples) |
| plot_path = None if args.no_plot else make_plot(output_dir, rows) |
| summary_json.write_text( |
| json.dumps( |
| { |
| "workplace_root": str(root), |
| "history_name": args.history_name, |
| "expected_group_size": args.expected_group_size, |
| "advantage_reconstruction": "score - group_mean; singleton baseline=0; exact KL-in-reward advantage requires saved reward/advantage tensors", |
| "diagnostics": diagnostics, |
| "rows": rows, |
| }, |
| ensure_ascii=False, |
| indent=2, |
| ) |
| + "\n", |
| encoding="utf-8", |
| ) |
|
|
| print(f"workplace root: {root}") |
| print(f"history files: {diagnostics['history_files']}, loaded: {diagnostics['loaded']}, malformed: {diagnostics['malformed']}") |
| print(f"history workers: {diagnostics['workers']}, orjson: {diagnostics['orjson']}") |
| print(f"reward records: {diagnostics['reward_records']}, groups: {diagnostics['groups']}, complete groups: {diagnostics['complete_groups']}") |
| print(f"incomplete groups: {diagnostics['incomplete_groups']}, missing-score samples: {diagnostics['missing_score_samples']}") |
| print(f"summary CSV: {summary_csv}") |
| print(f"group/sample CSV: {sample_csv}") |
| print(f"summary JSON: {summary_json}") |
| if plot_path: |
| print(f"plot: {plot_path}") |
| for row in rows: |
| print( |
| f"step={row['step']} samples={row['samples']} " |
| + " ".join( |
| f"{reason}={row[f'{reason}_candidate_turns']}/{row[f'{reason}_positive_masked_turns']} turns" |
| for reason in REASONS |
| ) |
| ) |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|