|
| 1 | +"""Episode JSON Logger for saving detailed episode information.""" |
| 2 | + |
| 3 | +import hashlib |
| 4 | +import json |
| 5 | +from pathlib import Path |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from rllm.agents.agent import Episode |
| 9 | + |
| 10 | + |
| 11 | +class EpisodeLogger: |
| 12 | + """Logger to save episodes to individual JSON files with step and data hash.""" |
| 13 | + |
| 14 | + def __init__(self, base_dir: str, subdirectory: str = "episodes"): |
| 15 | + """Initialize the episode logger. |
| 16 | +
|
| 17 | + Args: |
| 18 | + base_dir: Base directory for episode logs. Can be configured via |
| 19 | + config.trainer.episode_log_dir |
| 20 | + (default: "logs/${trainer.project_name}/${trainer.experiment_name}") |
| 21 | + subdirectory: Subdirectory within base_dir for episodes (default: "episodes") |
| 22 | + Final path will be: {base_dir}/{subdirectory}/ |
| 23 | + """ |
| 24 | + self.log_dir = Path(base_dir) / subdirectory |
| 25 | + self.log_dir.mkdir(parents=True, exist_ok=True) |
| 26 | + |
| 27 | + @staticmethod |
| 28 | + def compute_task_hash(task: Any, length: int = 8) -> str: |
| 29 | + """Compute a hash from the task data. |
| 30 | +
|
| 31 | + Args: |
| 32 | + task: The task dictionary or data |
| 33 | + length: Length of the hash to use (default 8 chars) |
| 34 | +
|
| 35 | + Returns: |
| 36 | + Hash string |
| 37 | + """ |
| 38 | + # Convert task to a stable string representation |
| 39 | + task_str = json.dumps(task, sort_keys=True, default=str) |
| 40 | + # Compute SHA256 hash |
| 41 | + hash_obj = hashlib.sha256(task_str.encode("utf-8")) |
| 42 | + # Return first `length` characters of hex digest |
| 43 | + return hash_obj.hexdigest()[:length] |
| 44 | + |
| 45 | + def get_step_dir(self, step: int, mode: str = "train", epoch: int = 0) -> Path: |
| 46 | + """Get the directory path for a specific training or validation step. |
| 47 | +
|
| 48 | + Args: |
| 49 | + step: Current training/validation step |
| 50 | + mode: Mode identifier ('train' or 'val'), defaults to 'train' |
| 51 | + epoch: Current epoch number, defaults to 0 |
| 52 | +
|
| 53 | + Returns: |
| 54 | + Path object for the step directory |
| 55 | + """ |
| 56 | + step_dir = self.log_dir / f"{mode}_step_{step}_epoch_{epoch}" |
| 57 | + step_dir.mkdir(parents=True, exist_ok=True) |
| 58 | + return step_dir |
| 59 | + |
| 60 | + def get_episode_filename(self, episode: Episode, step: int) -> str: |
| 61 | + """Generate filename for an episode. |
| 62 | +
|
| 63 | + Format: episode_hash{task_hash}_id{episode_id}.json |
| 64 | +
|
| 65 | + Args: |
| 66 | + episode: The episode to save |
| 67 | + step: Current training step (not used in filename, but kept for compatibility) |
| 68 | +
|
| 69 | + Returns: |
| 70 | + Filename string |
| 71 | + """ |
| 72 | + task_hash = self.compute_task_hash(episode.task) |
| 73 | + # Clean episode_id to make it filesystem-safe |
| 74 | + episode_id_safe = str(episode.id).replace(":", "_").replace("/", "_") |
| 75 | + |
| 76 | + filename = f"episode_hash{task_hash}_id{episode_id_safe}.json" |
| 77 | + return filename |
| 78 | + |
| 79 | + def log_episode(self, episode: Episode, step: int, mode: str = "train", epoch: int = 0): |
| 80 | + """Log a single episode to its own JSON file in a step-specific directory. |
| 81 | +
|
| 82 | + Args: |
| 83 | + episode: The episode to log |
| 84 | + step: Current training/validation step |
| 85 | + mode: Mode identifier ('train' or 'val'), defaults to 'train' |
| 86 | + epoch: Current epoch number, defaults to 0 |
| 87 | + """ |
| 88 | + episode_data = {"training_step": step, "epoch": epoch, "episode_id": episode.id, "task": episode.task, "task_hash": self.compute_task_hash(episode.task), "is_correct": episode.is_correct, "termination_reason": episode.termination_reason.value if episode.termination_reason else None, "metrics": episode.metrics, "timing": episode.info.get("timing", {}), "trajectories": []} |
| 89 | + |
| 90 | + for traj in episode.trajectories: |
| 91 | + traj_data = { |
| 92 | + "name": traj.name, |
| 93 | + "uid": traj.uid, |
| 94 | + "reward": traj.reward, |
| 95 | + "num_steps": len(traj.steps), |
| 96 | + "timing": traj.info.get("timing", {}), |
| 97 | + "steps": [ |
| 98 | + { |
| 99 | + "observation": step.observation, |
| 100 | + "thought": step.thought, |
| 101 | + "action": step.action, |
| 102 | + "reward": step.reward, |
| 103 | + "done": step.done, |
| 104 | + "model_response": step.model_response, |
| 105 | + "chat_completions": step.chat_completions, |
| 106 | + "timing": step.info.get("timing", {}), # Add step-level timing |
| 107 | + } |
| 108 | + for step in traj.steps |
| 109 | + ], |
| 110 | + } |
| 111 | + episode_data["trajectories"].append(traj_data) |
| 112 | + |
| 113 | + # Write to individual file in step-specific directory |
| 114 | + step_dir = self.get_step_dir(step, mode, epoch) |
| 115 | + filename = self.get_episode_filename(episode, step) |
| 116 | + filepath = step_dir / filename |
| 117 | + |
| 118 | + try: |
| 119 | + with open(filepath, "w") as f: |
| 120 | + json_str = json.dumps(episode_data, indent=2, default=str) |
| 121 | + f.write(json_str + "\n") |
| 122 | + f.flush() # Ensure data is written to disk |
| 123 | + except Exception as e: |
| 124 | + print(f"Error writing episode to {filepath}: {e}") |
| 125 | + import traceback |
| 126 | + |
| 127 | + traceback.print_exc() |
| 128 | + raise |
| 129 | + |
| 130 | + def log_episodes(self, episodes: list[Episode], step: int, mode: str = "train", epoch: int = 0): |
| 131 | + """Log multiple episodes, each to its own file. |
| 132 | +
|
| 133 | + Args: |
| 134 | + episodes: List of episodes to log |
| 135 | + step: Current training/validation step |
| 136 | + mode: Mode identifier ('train' or 'val'), defaults to 'train' |
| 137 | + epoch: Current epoch number, defaults to 0 |
| 138 | + """ |
| 139 | + print(f"[EpisodeLogger] Logging {len(episodes)} episodes for step={step}, mode={mode}, epoch={epoch}") |
| 140 | + for i, episode in enumerate(episodes): |
| 141 | + try: |
| 142 | + self.log_episode(episode, step, mode, epoch) |
| 143 | + print(f"[EpisodeLogger] Successfully logged episode {i + 1}/{len(episodes)}: {episode.id}") |
| 144 | + except Exception as e: |
| 145 | + print(f"[EpisodeLogger] Failed to log episode {i + 1}/{len(episodes)}: {e}") |
| 146 | + raise |
| 147 | + |
| 148 | + def log_episodes_batch(self, episodes: list[Episode], step: int, mode: str = "train", epoch: int = 0, batch_summary: bool = True): |
| 149 | + """Log multiple episodes and optionally create a batch summary in step-specific directory. |
| 150 | +
|
| 151 | + Args: |
| 152 | + episodes: List of episodes to log |
| 153 | + step: Current training/validation step |
| 154 | + mode: Mode identifier ('train' or 'val'), defaults to 'train' |
| 155 | + epoch: Current epoch number, defaults to 0 |
| 156 | + batch_summary: Whether to create a summary file for the batch |
| 157 | + """ |
| 158 | + # Log individual episodes |
| 159 | + self.log_episodes(episodes, step, mode, epoch) |
| 160 | + |
| 161 | + # Optionally create batch summary in step-specific directory |
| 162 | + if batch_summary and episodes: |
| 163 | + summary_data = { |
| 164 | + "training_step": step, |
| 165 | + "epoch": epoch, |
| 166 | + "mode": mode, |
| 167 | + "num_episodes": len(episodes), |
| 168 | + "episode_files": [self.get_episode_filename(ep, step) for ep in episodes], |
| 169 | + "summary_stats": { |
| 170 | + "total_correct": sum(1 for ep in episodes if ep.is_correct), |
| 171 | + "total_incorrect": sum(1 for ep in episodes if not ep.is_correct), |
| 172 | + "accuracy": sum(1 for ep in episodes if ep.is_correct) / len(episodes) if episodes else 0, |
| 173 | + "avg_trajectories_per_episode": sum(len(ep.trajectories) for ep in episodes) / len(episodes) if episodes else 0, |
| 174 | + }, |
| 175 | + } |
| 176 | + |
| 177 | + step_dir = self.get_step_dir(step, mode, epoch) |
| 178 | + summary_file = step_dir / "batch_summary.json" |
| 179 | + with open(summary_file, "w") as f: |
| 180 | + json.dump(summary_data, f, indent=2) |
0 commit comments