#!/usr/bin/env python3 """ Local rollout visualizer. Usage: python scripts/visualize.py --rollout_path results/ [--host 127.0.0.1] [--port 8000] The script launches a small HTTP server that lets you inspect .pkl files (containing verl.DataProto dumps) inside the rollout path. Open the printed URL in a browser to explore directories, select a file, and view its meta information and non-tensor batches entry by entry. """ from __future__ import annotations import argparse import json import logging import threading from functools import lru_cache from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Any, Dict, List from urllib.parse import parse_qs, urlparse import webbrowser import numpy as np from verl import DataProto LOGGER = logging.getLogger(__name__) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Launch a local rollout visualizer") parser.add_argument("--rollout_path", required=True, help="Directory containing rollout .pkl files") parser.add_argument("--host", default="127.0.0.1", help="Host to bind (default: 127.0.0.1)") parser.add_argument("--port", type=int, default=8000, help="Port to bind (default: 8000)") parser.add_argument("--no-browser", action="store_true", help="Do not attempt to open a browser automatically") return parser.parse_args() def ensure_within(path: Path, root: Path) -> Path: resolved = path.resolve() try: resolved.relative_to(root) except ValueError as exc: raise ValueError(f"Path {path} escapes the rollout root {root}") from exc return resolved def numpy_summary(array: np.ndarray) -> Dict[str, Any]: array = np.asarray(array) summary: Dict[str, Any] = { "__type__": "ndarray", "dtype": str(array.dtype), "shape": list(array.shape), "size": int(array.size), } preview_limit = 32 flat = array.reshape(-1) preview = flat[:preview_limit].tolist() summary["preview"] = preview summary["preview_count"] = len(preview) if array.size <= preview_limit and array.size <= 10_000: summary["values"] = array.tolist() return summary def serialize_for_view(value: Any, depth: int = 0) -> Any: if depth > 6: return repr(value) if value is None or isinstance(value, (str, int, float, bool)): return value if isinstance(value, (np.integer, np.floating, np.bool_)): return value.item() if isinstance(value, dict): return {str(key): serialize_for_view(val, depth + 1) for key, val in value.items()} if isinstance(value, (list, tuple, set)): return [serialize_for_view(val, depth + 1) for val in value] if isinstance(value, np.ndarray): return numpy_summary(value) return repr(value) def build_tree(root: Path) -> Dict[str, Any]: root_node: Dict[str, Any] = {"name": root.name, "path": "", "type": "dir", "children": []} nodes: Dict[str, Dict[str, Any]] = {"": root_node} for file_path in sorted(root.rglob("*.pkl")): rel_path = file_path.relative_to(root) rel_path_posix = rel_path.as_posix() parts = rel_path.parts if not parts: continue cumulative = [] for part in parts[:-1]: cumulative.append(part) current_key = "/".join(cumulative) parent_key = "/".join(cumulative[:-1]) if len(cumulative) > 1 else "" if current_key not in nodes: node = {"name": part, "path": current_key, "type": "dir", "children": []} nodes[current_key] = node nodes[parent_key]["children"].append(node) file_parent_key = "/".join(parts[:-1]) if len(parts) > 1 else "" file_node = {"name": parts[-1], "path": rel_path_posix, "type": "file"} nodes[file_parent_key]["children"].append(file_node) def sort_children(node: Dict[str, Any]) -> None: children = node.get("children") if not children: return children.sort(key=lambda item: (item.get("type") != "dir", item.get("name", ""))) for child in children: if child.get("type") == "dir": sort_children(child) sort_children(root_node) return root_node def data_proto_to_payload(file_path: Path) -> Dict[str, Any]: data = DataProto.load_from_disk(str(file_path)) length = len(data) items: List[Dict[str, Any]] = [] for idx in range(length): try: item = data[idx] except Exception as exc: # pragma: no cover - defensive guard LOGGER.warning("Failed to read item %s from %s: %s", idx, file_path, exc) continue items.append( { "index": idx, "meta_info": serialize_for_view(item.meta_info), "non_tensor_batch": serialize_for_view(item.non_tensor_batch), } ) return { "path": str(file_path), "length": length, "meta_info": serialize_for_view(data.meta_info), "items": items, } class RolloutExplorer: def __init__(self, root: Path): self.root = root self._tree_cache: Dict[str, Any] | None = None self._lock = threading.Lock() def tree(self) -> Dict[str, Any]: with self._lock: if self._tree_cache is None: self._tree_cache = build_tree(self.root) return self._tree_cache @lru_cache(maxsize=32) def load_file(self, relative_path: str) -> Dict[str, Any]: normalized_path = Path(relative_path) target = ensure_within(self.root / normalized_path, self.root) if not target.exists() or not target.is_file(): raise FileNotFoundError(f"File {relative_path} not found under {self.root}") payload = data_proto_to_payload(target) payload["relative_path"] = target.relative_to(self.root).as_posix() return payload HTML_PAGE = """