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