Analysis¶
Tools for parsing, summarizing, and visualizing training logs produced by Forgather's JSON logger. For CLI usage, plots, and the full forgather logs command reference, see Log Analysis.
Quick Example¶
from forgather.ml.analysis import TrainingLog, compute_summary_statistics
log = TrainingLog.from_file("output_models/my_model/runs/run_id/trainer_logs.json")
summary = compute_summary_statistics(log)
print(f"Best loss: {summary['best_loss']} at step {summary['best_loss_step']}")
forgather.ml.analysis.TrainingLog
dataclass
¶
Container for a parsed Forgather training log.
Holds all JSON records emitted by Forgather's JSON logger
(trainer_logs.json) together with metadata inferred from the
file-system path. Typically created via :meth:from_file or
:meth:from_run_dir rather than constructed directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_path
|
Path
|
Absolute path to the |
required |
records
|
list of dict
|
Raw JSON records as loaded from the log file. Each record is a
dictionary that may contain keys such as |
required |
run_name
|
str
|
Human-readable name of the training run, usually the timestamped
directory name under |
None
|
model_name
|
str
|
Name of the model, usually the directory immediately above |
None
|
label
|
str
|
Explicit display label used when plotting. When set, this takes priority over model_name and run_name. |
None
|
Examples:
>>> from forgather.ml.analysis import TrainingLog
>>> log = TrainingLog.from_file("output_models/my_model/runs/run_001/trainer_logs.json")
>>> train_records = log.get_training_records()
>>> losses = log.get_metric_values("loss", train_records)
Source code in src/forgather/ml/analysis/log_parser.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | |
__post_init__()
¶
Extract run name and model name from path if not provided.
Source code in src/forgather/ml/analysis/log_parser.py
get_label(index=0)
¶
Return a human-readable label for this log.
Selection priority: explicit :attr:label > :attr:model_name >
:attr:run_name > 'Run N' (where N is index + 1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Zero-based position of this log in a collection, used as a fallback label suffix. Default is 0. |
0
|
Returns:
| Type | Description |
|---|---|
str
|
Display label suitable for plot legends and summary output. |
Source code in src/forgather/ml/analysis/log_parser.py
from_file(log_path)
classmethod
¶
Load a training log from a trainer_logs.json file.
Handles truncated files (e.g. from a crash or a still-running job) by attempting to recover all complete JSON records before the truncation point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_path
|
str or Path
|
Path to a |
required |
Returns:
| Type | Description |
|---|---|
TrainingLog
|
Populated instance with all recoverable records. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If log_path does not exist on disk. |
ValueError
|
If the file is not a valid JSON array and recovery fails. |
Examples:
>>> log = TrainingLog.from_file("output_models/my_model/runs/run_001/trainer_logs.json")
>>> print(f"Loaded {len(log.records)} records")
Source code in src/forgather/ml/analysis/log_parser.py
from_run_dir(run_dir)
classmethod
¶
Load a training log from a run directory.
Convenience wrapper around :meth:from_file that automatically appends
trainer_logs.json to the supplied directory path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
run_dir
|
str or Path
|
Path to a run directory (e.g.
|
required |
Returns:
| Type | Description |
|---|---|
TrainingLog
|
Populated instance with all recoverable records. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If the log file is not a valid JSON array and recovery fails. |
Source code in src/forgather/ml/analysis/log_parser.py
get_training_records()
¶
Return records that contain training-step metrics.
Training records are identified by the presence of a loss key and
the absence of an eval_loss key. They typically also carry
grad_norm, learning_rate, global_step, epoch, and
timestamp.
Returns:
| Type | Description |
|---|---|
list of dict
|
Subset of :attr: |
Source code in src/forgather/ml/analysis/log_parser.py
get_eval_records()
¶
Return records that contain evaluation metrics.
Evaluation records are identified by the presence of an eval_loss
key. They typically also carry global_step and epoch.
Returns:
| Type | Description |
|---|---|
list of dict
|
Subset of :attr: |
Source code in src/forgather/ml/analysis/log_parser.py
get_final_record()
¶
Return the final summary record emitted at the end of training.
The final record is identified by the presence of a train_runtime
key and may also contain train_samples,
train_samples_per_second, train_steps_per_second, and
effective_batch_size.
Returns:
| Type | Description |
|---|---|
dict or None
|
The last record containing |
Source code in src/forgather/ml/analysis/log_parser.py
get_metric_values(metric, records=None)
¶
Extract the values for a named metric from a set of records.
Records that do not contain metric are silently skipped, so the returned list may be shorter than records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
str
|
Key to extract (e.g. |
required |
records
|
list of dict
|
Records to search. When |
None
|
Returns:
| Type | Description |
|---|---|
list of float
|
Ordered values for metric drawn from the matching records. |
Source code in src/forgather/ml/analysis/log_parser.py
get_steps(records=None)
¶
Extract global_step values from records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
list of dict
|
Records to search. When |
None
|
Returns:
| Type | Description |
|---|---|
list of int
|
Ordered global step numbers. |
Source code in src/forgather/ml/analysis/log_parser.py
get_epochs(records=None)
¶
Extract epoch values from records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
list of dict
|
Records to search. When |
None
|
Returns:
| Type | Description |
|---|---|
list of float
|
Ordered fractional epoch numbers. |
Source code in src/forgather/ml/analysis/log_parser.py
get_timestamps(records=None)
¶
Extract timestamp values from records.
Timestamps are Unix epoch seconds recorded when each log entry was written. They can be used to build a wall-clock x-axis for plots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
list of dict
|
Records to search. When |
None
|
Returns:
| Type | Description |
|---|---|
list of float
|
Ordered Unix timestamps (seconds since epoch). |
Source code in src/forgather/ml/analysis/log_parser.py
find_best_step(metric, mode='min')
¶
Find the training step at which a metric reaches its best value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
str
|
Metric key to search for (e.g. |
required |
mode
|
(min, max)
|
Whether to look for the minimum ( |
'min'
|
Returns:
| Type | Description |
|---|---|
tuple of (int, float) or None
|
|
Source code in src/forgather/ml/analysis/log_parser.py
forgather.ml.analysis.compute_summary_statistics(log)
¶
Compute summary statistics from a training log.
Aggregates training-step records, evaluation records, and the final
summary record into a flat dictionary of key metrics. Keys are only
present when the underlying data exists; callers should use
summary.get(key) rather than direct indexing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log
|
TrainingLog
|
Parsed training log to summarise. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with a subset of the following keys, depending on what data is available in log:
|
Examples:
>>> from forgather.ml.analysis import TrainingLog, compute_summary_statistics
>>> log = TrainingLog.from_file("output_models/my_model/runs/run_001/trainer_logs.json")
>>> summary = compute_summary_statistics(log)
>>> print(f"Best loss: {summary['best_loss']:.4f} at step {summary['best_loss_step']}")
Source code in src/forgather/ml/analysis/metrics.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | |
forgather.ml.analysis.plot_training_metrics(logs, metrics=None, x_axis='step', smooth_window=None, log_scale=False, output_path=None, figsize=(12, 8), show=False, title=None, ignore_outliers=True, perplexity=False, x_min=None, x_max=None, y_min=None, y_max=None)
¶
Plot one or more training metrics from one or more training logs.
Creates a grid of subplots (up to two columns) with one panel per metric.
When multiple logs are supplied each run is drawn in a distinct colour with
a legend entry. For loss-like metrics (loss, eval_loss,
grad_norm) the y-axis is automatically clipped to the 5th–95th
percentile window to suppress early-training outliers; pass
ignore_outliers=False to disable this.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logs
|
list of TrainingLog
|
One or more parsed training logs to plot. |
required |
metrics
|
list of str
|
Metric keys to plot. Each element must be a key present in at least
some log records (e.g. |
None
|
x_axis
|
(step, epoch, time)
|
X-axis variable. |
'step'
|
smooth_window
|
int
|
When greater than 1, draws the raw series at low opacity and overlays
a centred moving-average with the given window size. Default is
|
None
|
log_scale
|
bool
|
Use a logarithmic y-axis. Outlier-aware auto-scaling is suppressed
on log axes. Default is |
False
|
output_path
|
str or Path
|
If provided, the figure is saved to this path at 300 dpi. Parent directories are created automatically. |
None
|
figsize
|
tuple of int
|
|
(12, 8)
|
show
|
bool
|
Call |
False
|
title
|
str
|
Figure-level suptitle. When |
None
|
ignore_outliers
|
bool
|
Apply percentile-based y-axis clipping for loss-like metrics.
Default is |
True
|
perplexity
|
bool
|
Convert loss values to perplexity ( |
False
|
x_min
|
float
|
Clip data and set the left x-axis limit to this value. |
None
|
x_max
|
float
|
Clip data and set the right x-axis limit to this value. |
None
|
y_min
|
float
|
Override the bottom y-axis limit. Takes priority over auto-scaling. |
None
|
y_max
|
float
|
Override the top y-axis limit. Takes priority over auto-scaling. |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
The rendered figure. The caller is responsible for closing it when
no longer needed ( |
Examples:
>>> from forgather.ml.analysis import TrainingLog
>>> from forgather.ml.analysis.plotting import plot_training_metrics
>>> log = TrainingLog.from_file("output_models/my_model/runs/run_001/trainer_logs.json")
>>> fig = plot_training_metrics([log], metrics=["loss", "eval_loss"], smooth_window=20)
>>> fig.savefig("training.png", dpi=150)
Source code in src/forgather/ml/analysis/plotting.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | |