trainloop 0.11.0__tar.gz → 0.12.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: trainloop
3
- Version: 0.11.0
3
+ Version: 0.12.0
4
4
  Summary: Minimal PyTorch training loop with hooks and checkpointing.
5
5
  Author: Karim Knaebel
6
6
  Author-email: Karim Knaebel <contact@knaebel.dev>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "trainloop"
3
- version = "0.11.0"
3
+ version = "0.12.0"
4
4
  description = "Minimal PyTorch training loop with hooks and checkpointing."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "trainloop"
3
- version = "0.11.0"
3
+ version = "0.12.0"
4
4
  description = "Minimal PyTorch training loop with hooks and checkpointing."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -4,6 +4,7 @@ from .hooks import (
4
4
  CUDAMaxMemoryHook,
5
5
  EMAHook,
6
6
  ImageFileLoggerHook,
7
+ JSONLHook,
7
8
  ProgressHook,
8
9
  StatsHook,
9
10
  TensorBoardHook,
@@ -19,6 +20,7 @@ __all__ = [
19
20
  "CheckpointingHook",
20
21
  "EMAHook",
21
22
  "ImageFileLoggerHook",
23
+ "JSONLHook",
22
24
  "LossNoneWarning",
23
25
  "ProgressHook",
24
26
  "StatsHook",
@@ -1,3 +1,5 @@
1
+ import json
2
+ import math
1
3
  import os
2
4
  import shutil
3
5
  import signal
@@ -602,7 +604,8 @@ class EMAHook(BaseHook):
602
604
 
603
605
  def on_before_train(self, trainer: BaseTrainer):
604
606
  trainer.logger.info(f"=> Creating EMA model {self.name!r} ...")
605
- # Note that AveragedModel does not seem to support FSDP. It will crash here.
607
+ # NOTE: AveragedModel does not seem to support FSDP. It will crash here.
608
+ # NOTE: AveragedModel's deepcopy clears _compiled_call_impl; compiled trainer.model does not imply compiled ema_model.
606
609
  self.ema_model = AveragedModel(
607
610
  trainer.model,
608
611
  multi_avg_fn=get_ema_multi_avg_fn(self.decay),
@@ -859,6 +862,66 @@ class TensorBoardHook(BaseHook):
859
862
  return img.convert("RGB")
860
863
 
861
864
 
865
+ class JSONLHook(BaseHook):
866
+ """Log nested scalar records to a JSONL file (rank 0 only)."""
867
+
868
+ def __init__(self, filename: str = "metrics.jsonl"):
869
+ self.filename = filename
870
+ self.file = None
871
+
872
+ def on_before_train(self, trainer: BaseTrainer):
873
+ if _dist_rank() == 0:
874
+ path = trainer.workspace / self.filename
875
+ path.parent.mkdir(parents=True, exist_ok=True)
876
+ self.file = path.open("a", encoding="utf-8")
877
+
878
+ def on_after_train(self, trainer: BaseTrainer):
879
+ if self.file is None:
880
+ return
881
+
882
+ self.file.close()
883
+ self.file = None
884
+
885
+ def on_log_scalars(
886
+ self, trainer: BaseTrainer, records: dict, dry_run: bool = False
887
+ ):
888
+ if self.file is None:
889
+ return
890
+
891
+ data, non_finite = self._split_non_finite(records)
892
+ event = {
893
+ "step": trainer.step,
894
+ "wall_time": time.time(),
895
+ "data": data,
896
+ }
897
+ if non_finite:
898
+ event["non_finite"] = non_finite
899
+ if dry_run:
900
+ trainer.logger.debug(f"Dry run log. Would log: {event}")
901
+ return
902
+
903
+ self.file.write(
904
+ json.dumps(event, separators=(",", ":"), allow_nan=False) + "\n"
905
+ )
906
+ self.file.flush()
907
+
908
+ @classmethod
909
+ def _split_non_finite(cls, value):
910
+ if isinstance(value, dict):
911
+ data = {}
912
+ non_finite = {}
913
+ for k, v in value.items():
914
+ data[k], non_finite_value = cls._split_non_finite(v)
915
+ if non_finite_value:
916
+ non_finite[k] = non_finite_value
917
+ return data, non_finite
918
+ if isinstance(value, float) and not math.isfinite(value):
919
+ return None, (
920
+ "NaN" if math.isnan(value) else "Infinity" if value > 0 else "-Infinity"
921
+ )
922
+ return value, None
923
+
924
+
862
925
  class ImageFileLoggerHook(BaseHook):
863
926
  """Persist logged images to ``workspace/visualizations`` on rank 0.
864
927
 
@@ -359,7 +359,9 @@ class BaseTrainer:
359
359
  nested paths may otherwise map to the same backend metric name.
360
360
 
361
361
  Args:
362
- records: Nested dict of scalar metrics to log.
362
+ records: Nested dict with string keys and Python ``int`` or ``float``
363
+ metric values. Convert numeric NumPy scalars and scalar PyTorch
364
+ tensors with ``.item()`` before logging.
363
365
  dry_run: If True, hooks should avoid side effects and only report intent.
364
366
  """
365
367
  self.logger.debug("log_scalars()")
File without changes