cleanjepa 0.1.0__py3-none-any.whl

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.
cleanjepa/__init__.py ADDED
@@ -0,0 +1,133 @@
1
+ """CleanJepa: minimal, composable PyTorch implementations of JEPA and latent world models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ # Acceleration
6
+ from cleanjepa.accel import (
7
+ enable_determinism,
8
+ enable_fast_math,
9
+ gpu_normalize_pixels,
10
+ make_adamw,
11
+ maybe_compile,
12
+ pick_device,
13
+ synchronize,
14
+ )
15
+
16
+ # Checkpoints
17
+ from cleanjepa.checkpoint import (
18
+ CHECKPOINT_FORMAT,
19
+ build_world_model,
20
+ export_world_model,
21
+ load_world_model,
22
+ )
23
+
24
+ # Data
25
+ from cleanjepa.data import HDF5TrajectoryDataset, ToyTrajectoryDataset, split_episodes
26
+
27
+ # Distributed training
28
+ from cleanjepa.distributed import all_gather_with_grad, cleanup_distributed, init_distributed
29
+
30
+ # Evaluation
31
+ from cleanjepa.evaluation import (
32
+ effective_rank,
33
+ latent_diagnostics,
34
+ logistic_probe,
35
+ ridge_probe,
36
+ roc_auc,
37
+ rollout_mse,
38
+ surprise_scores,
39
+ )
40
+
41
+ # Models
42
+ from cleanjepa.models import (
43
+ ACPredictor,
44
+ ActionEmbedder,
45
+ ARPredictor,
46
+ FrozenDINOv2Encoder,
47
+ JEPAWorldModel,
48
+ MLPProjector,
49
+ TokenPredictor,
50
+ VideoViTEncoder,
51
+ ViTEncoder,
52
+ VJEPA2ACWorldModel,
53
+ )
54
+
55
+ # Planners
56
+ from cleanjepa.planners import CEMSolver, GradientPlanner, MPPISolver, build_planner
57
+
58
+ # Provenance
59
+ from cleanjepa.provenance import file_fingerprint, run_metadata
60
+
61
+ # Regularizers
62
+ from cleanjepa.regularizers import EMAEncoder, RDMReg, SIGReg, VICReg
63
+
64
+ # Result files
65
+ from cleanjepa.results import load_results, make_result, summarize, write_result
66
+
67
+ # Utilities
68
+ from cleanjepa.utils import eval_mode
69
+
70
+ __version__ = "0.1.0"
71
+
72
+ __all__ = [
73
+ # Acceleration
74
+ "enable_determinism",
75
+ "enable_fast_math",
76
+ "gpu_normalize_pixels",
77
+ "make_adamw",
78
+ "maybe_compile",
79
+ "pick_device",
80
+ "synchronize",
81
+ # Checkpoints
82
+ "CHECKPOINT_FORMAT",
83
+ "build_world_model",
84
+ "export_world_model",
85
+ "load_world_model",
86
+ # Data
87
+ "HDF5TrajectoryDataset",
88
+ "ToyTrajectoryDataset",
89
+ "split_episodes",
90
+ # Distributed training
91
+ "all_gather_with_grad",
92
+ "cleanup_distributed",
93
+ "init_distributed",
94
+ # Evaluation
95
+ "effective_rank",
96
+ "latent_diagnostics",
97
+ "logistic_probe",
98
+ "ridge_probe",
99
+ "roc_auc",
100
+ "rollout_mse",
101
+ "surprise_scores",
102
+ # Models
103
+ "ACPredictor",
104
+ "ActionEmbedder",
105
+ "ARPredictor",
106
+ "FrozenDINOv2Encoder",
107
+ "JEPAWorldModel",
108
+ "MLPProjector",
109
+ "TokenPredictor",
110
+ "VideoViTEncoder",
111
+ "ViTEncoder",
112
+ "VJEPA2ACWorldModel",
113
+ # Planners
114
+ "CEMSolver",
115
+ "GradientPlanner",
116
+ "MPPISolver",
117
+ "build_planner",
118
+ # Provenance
119
+ "file_fingerprint",
120
+ "run_metadata",
121
+ # Regularizers
122
+ "EMAEncoder",
123
+ "RDMReg",
124
+ "SIGReg",
125
+ "VICReg",
126
+ # Result files
127
+ "load_results",
128
+ "make_result",
129
+ "summarize",
130
+ "write_result",
131
+ # Utilities
132
+ "eval_mode",
133
+ ]
cleanjepa/accel.py ADDED
@@ -0,0 +1,153 @@
1
+ """Thin, zero-dependency PyTorch acceleration primitives for CleanJepa.
2
+
3
+ Provides decoupled, opt-in building blocks (TF32/cuDNN fast math, fused AdamW,
4
+ selective torch.compile, and GPU batch pixel preprocessing) without hiding the
5
+ explicit PyTorch training loop. Multi-GPU helpers live in `cleanjepa.distributed`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from collections.abc import Iterable
12
+ from contextlib import AbstractContextManager, nullcontext
13
+
14
+ import torch
15
+ import torch.nn.functional as F
16
+ from torch import nn
17
+
18
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
19
+ IMAGENET_STD = (0.229, 0.224, 0.225)
20
+
21
+
22
+ def pick_device(name: str = "auto") -> torch.device:
23
+ """Resolve a `--device` choice to a torch.device.
24
+
25
+ Args:
26
+ name: "auto" (CUDA if available, then Apple-silicon MPS, then CPU) or any device string
27
+ torch accepts, such as "cpu", "mps", or "cuda:1".
28
+
29
+ Returns:
30
+ The device. An explicit "mps" or "cuda" that this machine lacks raises instead of quietly
31
+ running elsewhere, so a reported latency always names the device that produced it.
32
+
33
+ Raises:
34
+ RuntimeError: The requested backend is not available.
35
+ """
36
+ if name == "auto":
37
+ if torch.cuda.is_available():
38
+ return torch.device("cuda")
39
+ if torch.backends.mps.is_available():
40
+ return torch.device("mps")
41
+ return torch.device("cpu")
42
+ device = torch.device(name)
43
+ if device.type == "cuda" and not torch.cuda.is_available():
44
+ raise RuntimeError(f"--device {name} requested, but CUDA is not available.")
45
+ if device.type == "mps" and not torch.backends.mps.is_available():
46
+ raise RuntimeError(f"--device {name} requested, but MPS is not available.")
47
+ return device
48
+
49
+
50
+ def synchronize(device: torch.device) -> None:
51
+ """Wait for queued kernels on `device` (CUDA or MPS) to finish; a no-op on CPU.
52
+
53
+ GPU kernels run asynchronously, so wall-clock timing without this measures only the launch.
54
+ """
55
+ if device.type == "cuda":
56
+ torch.cuda.synchronize(device)
57
+ elif device.type == "mps":
58
+ torch.mps.synchronize()
59
+
60
+
61
+ def enable_fast_math() -> None:
62
+ """Enable TF32 matmul/cuDNN and cuDNN autotuner on CUDA (no-op on CPU)."""
63
+ if not torch.cuda.is_available():
64
+ return
65
+ torch.set_float32_matmul_precision("high")
66
+ torch.backends.cuda.matmul.allow_tf32 = True
67
+ torch.backends.cudnn.allow_tf32 = True
68
+ torch.backends.cudnn.benchmark = True
69
+
70
+
71
+ def enable_determinism() -> None:
72
+ """Make repeated runs bit-identical where PyTorch can, at some speed cost.
73
+
74
+ Disables TF32 and the cuDNN autotuner, and asks PyTorch for deterministic kernels. Kernels that
75
+ have no deterministic version warn instead of failing. Call this before any CUDA work: cuBLAS
76
+ reads CUBLAS_WORKSPACE_CONFIG when it is first used.
77
+ """
78
+ os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
79
+ torch.backends.cuda.matmul.allow_tf32 = False
80
+ torch.backends.cudnn.allow_tf32 = False
81
+ torch.backends.cudnn.benchmark = False
82
+ torch.backends.cudnn.deterministic = True
83
+ torch.use_deterministic_algorithms(True, warn_only=True)
84
+
85
+
86
+ def disable_autocast(device: torch.device) -> AbstractContextManager:
87
+ """Return a context that disables autocast on `device`.
88
+
89
+ Casting inputs with `.float()` alone is not enough for FP32 statistics: autocast casts
90
+ matmul/einsum operands back to half precision.
91
+ """
92
+ try:
93
+ return torch.autocast(device_type=device.type, enabled=False)
94
+ except RuntimeError:
95
+ # Older PyTorch rejects backends without autocast (e.g. MPS), so there is nothing to disable.
96
+ return nullcontext()
97
+
98
+
99
+ def make_adamw(
100
+ params: Iterable[torch.nn.Parameter],
101
+ lr: float,
102
+ weight_decay: float,
103
+ device: torch.device,
104
+ ) -> torch.optim.AdamW:
105
+ """Create AdamW with fused CUDA kernels when supported (eliminates per-tensor launch overhead)."""
106
+ if device.type == "cuda":
107
+ try:
108
+ return torch.optim.AdamW(params, lr=lr, weight_decay=weight_decay, fused=True)
109
+ except (TypeError, RuntimeError):
110
+ pass
111
+ return torch.optim.AdamW(params, lr=lr, weight_decay=weight_decay)
112
+
113
+
114
+ def maybe_compile(module: nn.Module, mode: str = "none") -> nn.Module:
115
+ """Optionally wrap a module with `torch.compile` when mode != 'none'.
116
+
117
+ Args:
118
+ module: PyTorch module to compile.
119
+ mode: "none" (no-op), "default", or "reduce-overhead".
120
+ """
121
+ if mode == "none" or not hasattr(torch, "compile"):
122
+ return module
123
+ return torch.compile(module, mode=mode)
124
+
125
+
126
+ def gpu_normalize_pixels(
127
+ pixels: torch.Tensor,
128
+ img_size: int | None = None,
129
+ mean: tuple[float, float, float] = IMAGENET_MEAN,
130
+ std: tuple[float, float, float] = IMAGENET_STD,
131
+ ) -> torch.Tensor:
132
+ """Vectorized GPU preprocessing for image/video batches.
133
+
134
+ Converts uint8 [0, 255] (or float [0, 1]) tensors of shape (B, ..., C, H, W)
135
+ to ImageNet-normalized float32, optionally resizing (H, W) -> (img_size, img_size).
136
+ """
137
+ x = pixels.float()
138
+ if pixels.dtype == torch.uint8:
139
+ x = x.mul_(1.0 / 255.0)
140
+
141
+ lead = x.shape[:-3]
142
+ C, H, W = x.shape[-3:]
143
+ if img_size is not None and (H != img_size or W != img_size):
144
+ x = F.interpolate(
145
+ x.reshape(-1, C, H, W),
146
+ size=(img_size, img_size),
147
+ mode="bilinear",
148
+ align_corners=False,
149
+ ).reshape(*lead, C, img_size, img_size)
150
+
151
+ m = torch.tensor(mean, device=x.device, dtype=x.dtype).view(*([1] * len(lead)), 3, 1, 1)
152
+ s = torch.tensor(std, device=x.device, dtype=x.dtype).view(*([1] * len(lead)), 3, 1, 1)
153
+ return (x - m) / s
@@ -0,0 +1,240 @@
1
+ """Rebuild JEPA world models (LeWM, DINO-WM, LpWM, token world models) from training checkpoints.
2
+
3
+ A `recipes/train_wm.py` checkpoint is a dict saved with `torch.save`:
4
+
5
+ {"format": "cleanjepa.wm/v1", "model": state_dict, "args": {flag: value},
6
+ "action_stats": {"mean": (A_raw,), "std": (A_raw,)} or None, "data_fingerprint": ...,
7
+ "provenance": ..., "args_resolved": True, "pixel_norm": "imagenet", "epoch": ...,
8
+ "global_step": ..., optimizer state}
9
+
10
+ Checkpoints written before the format version existed have no "format" key and load as v1. A
11
+ checkpoint from a newer, unknown format is refused instead of being misread.
12
+
13
+ Settings that change computation without changing parameter shapes cannot be recovered from the
14
+ weights, so a missing setting falls back to the behavior of the code that wrote the checkpoint:
15
+ SiLU projector activation, joint (not factorized) predictor attention, and a projector. Synthetic
16
+ runs saved before `args_resolved` existed stored the unresolved image-size defaults (224, 14) but
17
+ trained at (56, 7).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ from collections.abc import Mapping
24
+ from pathlib import Path
25
+
26
+ import torch
27
+
28
+ from cleanjepa.models import FrozenDINOv2Encoder, JEPAWorldModel, ViTEncoder
29
+
30
+ CHECKPOINT_FORMAT = "cleanjepa.wm/v1"
31
+ _KNOWN_FORMATS = {CHECKPOINT_FORMAT}
32
+
33
+
34
+ def check_format(payload: dict) -> None:
35
+ """Raise ValueError if `payload` declares a checkpoint format this version cannot read.
36
+
37
+ A payload without a "format" key predates versioning and is read as `cleanjepa.wm/v1`.
38
+ """
39
+ fmt = payload.get("format", CHECKPOINT_FORMAT)
40
+ if fmt not in _KNOWN_FORMATS:
41
+ raise ValueError(
42
+ f"Unsupported checkpoint format {fmt!r}; this version of CleanJepa reads {sorted(_KNOWN_FORMATS)}. "
43
+ "Upgrade CleanJepa to load it."
44
+ )
45
+
46
+
47
+ def build_world_model(cfg: dict, action_dim: int, device: torch.device | str = "cpu") -> JEPAWorldModel:
48
+ """Build an untrained world model with the architecture that a train_wm.py config describes.
49
+
50
+ Args:
51
+ cfg: Training arguments (`payload["args"]`), with resolved `img_size` and `patch_size`.
52
+ action_dim: Model action dimension A (raw action dim times frameskip).
53
+ device: Device for the parameters.
54
+
55
+ Returns:
56
+ JEPAWorldModel in train mode.
57
+ """
58
+ img_size, patch_size = cfg.get("img_size", 224), cfg.get("patch_size", 14)
59
+ if cfg.get("encoder", "vit") == "dinov2":
60
+ encoder = FrozenDINOv2Encoder(model_name=cfg.get("dinov2_model", "dinov2_vits14"), img_size=img_size)
61
+ else:
62
+ encoder = ViTEncoder(
63
+ img_size=img_size,
64
+ patch_size=patch_size,
65
+ embed_dim=cfg["embed_dim"],
66
+ depth=cfg["enc_depth"],
67
+ heads=cfg["enc_heads"],
68
+ )
69
+ return JEPAWorldModel(
70
+ encoder=encoder,
71
+ action_dim=action_dim,
72
+ embed_dim=cfg["embed_dim"],
73
+ history_size=cfg["history_size"],
74
+ representation=cfg["rep"],
75
+ pool=cfg.get("pool", 2),
76
+ head_mode=cfg["head"],
77
+ relu_out=(cfg.get("reg") == "rdmreg"),
78
+ predictor_depth=cfg["pred_depth"],
79
+ predictor_heads=cfg["pred_heads"],
80
+ # Joint and factorized predictors share identical state_dict keys and shapes, so a mismatch
81
+ # here would load without error but run the wrong attention topology.
82
+ factorized_predictor=cfg.get("factorized", False),
83
+ use_projector=not cfg.get("no_projector", False),
84
+ # Checkpoints from before this flag used SiLU; activations have no parameters to detect it.
85
+ projector_act=cfg.get("projector_act", "silu"),
86
+ ).to(device)
87
+
88
+
89
+ def resolve_config(payload: dict) -> dict:
90
+ """Training arguments of a checkpoint, with the image sizes the run actually used."""
91
+ cfg = dict(payload["args"])
92
+ img_size, patch_size = cfg.get("img_size", 224), cfg.get("patch_size", 14)
93
+ if cfg.get("synthetic") and not payload.get("args_resolved", False):
94
+ # Older synthetic runs replaced these two default values without recording it.
95
+ img_size = 56 if img_size == 224 else img_size
96
+ patch_size = 7 if patch_size == 14 else patch_size
97
+ cfg["img_size"], cfg["patch_size"] = img_size, patch_size
98
+ return cfg
99
+
100
+
101
+ def load_world_model(
102
+ path: str | Path, device: torch.device | str = "cpu"
103
+ ) -> tuple[JEPAWorldModel, dict, dict[str, torch.Tensor] | None]:
104
+ """Rebuild a trained model from a `recipes/train_wm.py` checkpoint.
105
+
106
+ Args:
107
+ path: Checkpoint file.
108
+ device: Device for the model and the loaded tensors.
109
+
110
+ Returns:
111
+ (model in eval mode, training args with resolved image sizes, action_stats). `action_stats`
112
+ holds the `mean` and `std` (A_raw,) used to normalize training actions, or None for synthetic
113
+ runs and older checkpoints.
114
+ """
115
+ payload = torch.load(path, map_location=device)
116
+ check_format(payload)
117
+ cfg = resolve_config(payload)
118
+ # The action encoder's first layer maps (A,) actions, so its input width is the action dim.
119
+ action_dim = int(payload["model"]["action_encoder.net.0.weight"].shape[1])
120
+ model = build_world_model(cfg, action_dim, device)
121
+ model.load_state_dict(payload["model"])
122
+ model.eval()
123
+ return model, cfg, payload.get("action_stats")
124
+
125
+
126
+ def save_world_model(
127
+ path: str | Path,
128
+ model: torch.nn.Module,
129
+ args: Mapping[str, object],
130
+ action_stats: Mapping[str, torch.Tensor] | None = None,
131
+ *,
132
+ optimizer: torch.optim.Optimizer | None = None,
133
+ epoch: int = 0,
134
+ global_step: int = 0,
135
+ provenance: dict[str, object] | None = None,
136
+ data_fingerprint: dict[str, object] | None = None,
137
+ pixel_norm: str = "imagenet",
138
+ extra: Mapping[str, object] | None = None,
139
+ ) -> None:
140
+ """Write a `cleanjepa.wm/v1` checkpoint that `load_world_model` can rebuild.
141
+
142
+ `img_size`/`patch_size` are copied from the model's encoder (both `ViTEncoder` and
143
+ `FrozenDINOv2Encoder` expose them), so the saved config records the sizes the run actually
144
+ trained at even when `args` still holds unresolved defaults; `args_resolved` is set so
145
+ `resolve_config` keeps them. The write is atomic (sibling temp file plus `os.replace`), so an
146
+ interrupted save cannot truncate a previous `epoch_*.pt` resume point. Parameter names of
147
+ `torch.compile`d submodules lose their `_orig_mod.` prefix, so the checkpoint loads into an
148
+ uncompiled model. `extra` adds recipe state to the payload (e.g. `scheduler`, `scaler`,
149
+ `steps_per_epoch`) and may not replace the keys above.
150
+
151
+ Raises:
152
+ ValueError: `args` lacks a key `build_world_model` indexes, or the state_dict has no
153
+ `action_encoder.net.0.weight` (where `load_world_model` reads the action dim from).
154
+ """
155
+ cfg = dict(args)
156
+ encoder = getattr(model, "encoder", None)
157
+ if hasattr(encoder, "img_size"):
158
+ cfg["img_size"] = encoder.img_size
159
+ if hasattr(encoder, "patch_size"):
160
+ cfg["patch_size"] = encoder.patch_size
161
+ required = ("embed_dim", "history_size", "rep", "head", "pred_depth", "pred_heads")
162
+ if cfg.get("encoder", "vit") != "dinov2":
163
+ required += ("enc_depth", "enc_heads")
164
+ missing = [key for key in required if key not in cfg]
165
+ if missing:
166
+ raise ValueError(f"args is missing the keys build_world_model indexes: {missing}.")
167
+ # torch.compile wraps a submodule as `<name>._orig_mod`; load_world_model builds plain modules.
168
+ state = {k.replace("._orig_mod.", ".").removeprefix("_orig_mod."): v for k, v in model.state_dict().items()}
169
+ if "action_encoder.net.0.weight" not in state:
170
+ raise ValueError(
171
+ "model state_dict has no 'action_encoder.net.0.weight'; load_world_model reads the "
172
+ "action dimension from that key."
173
+ )
174
+ payload = {
175
+ "format": CHECKPOINT_FORMAT,
176
+ "model": state,
177
+ "args": cfg,
178
+ "action_stats": action_stats,
179
+ "data_fingerprint": data_fingerprint,
180
+ "provenance": provenance,
181
+ "args_resolved": True,
182
+ "pixel_norm": pixel_norm,
183
+ "epoch": epoch,
184
+ "global_step": global_step,
185
+ }
186
+ if optimizer is not None:
187
+ payload["optimizer"] = optimizer.state_dict()
188
+ clash = sorted(set(extra or {}) & set(payload))
189
+ if clash:
190
+ raise ValueError(f"extra may not replace checkpoint keys {clash}.")
191
+ payload.update(extra or {})
192
+ _atomic_save(payload, Path(path))
193
+
194
+
195
+ # Everything load_world_model and the result provenance need; optimizer, scheduler, and scaler
196
+ # state exist only to resume training.
197
+ _INFERENCE_KEYS = (
198
+ "format", "model", "args", "action_stats", "data_fingerprint", "provenance", "args_resolved",
199
+ "pixel_norm", "epoch", "global_step",
200
+ ) # fmt: skip
201
+
202
+
203
+ def export_world_model(src: str | Path, dst: str | Path) -> None:
204
+ """Write an inference-only copy of a `cleanjepa.wm/v1` checkpoint.
205
+
206
+ Keeps the weights, training args, action statistics, provenance, and dataset fingerprint, and
207
+ drops the optimizer, scheduler, and scaler state, which is most of a training checkpoint's size.
208
+ The copy loads with `load_world_model` on any device and cannot be used to resume training.
209
+ Tensors are moved to CPU and `_orig_mod.` prefixes from `torch.compile` are stripped, as in
210
+ `save_world_model`.
211
+
212
+ Args:
213
+ src: Training checkpoint.
214
+ dst: Output path; written atomically.
215
+
216
+ Raises:
217
+ ValueError: `src` is in an unknown checkpoint format.
218
+ """
219
+ payload = torch.load(src, map_location="cpu")
220
+ check_format(payload)
221
+ out = {k: payload[k] for k in _INFERENCE_KEYS if k in payload}
222
+ out["format"] = CHECKPOINT_FORMAT
223
+ out["model"] = {k.replace("._orig_mod.", ".").removeprefix("_orig_mod."): v for k, v in payload["model"].items()}
224
+ # Older checkpoints stored the unresolved synthetic image sizes; record the resolved ones.
225
+ out["args"], out["args_resolved"] = resolve_config(payload), True
226
+ _atomic_save(out, Path(dst))
227
+
228
+
229
+ def _atomic_save(payload: dict, path: Path) -> None:
230
+ """torch.save to a sibling temp file, then rename, so a crash never leaves a truncated file."""
231
+ path.parent.mkdir(parents=True, exist_ok=True)
232
+ # The temp name ends in ".tmp", so it never matches the `epoch_*.pt` glob prepare_save_dir uses.
233
+ tmp = path.with_name(path.name + ".tmp")
234
+ try:
235
+ with tmp.open("wb") as f:
236
+ torch.save(payload, f)
237
+ os.replace(tmp, path)
238
+ except BaseException:
239
+ tmp.unlink(missing_ok=True)
240
+ raise
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+
3
+ from cleanjepa.data.toy import (
4
+ ToyTrajectoryDataset,
5
+ generate_episodes,
6
+ oracle_action,
7
+ render,
8
+ step,
9
+ )
10
+ from cleanjepa.data.trajectory import (
11
+ HDF5TrajectoryDataset,
12
+ split_episodes,
13
+ )
14
+
15
+ __all__ = [
16
+ "HDF5TrajectoryDataset",
17
+ "ToyTrajectoryDataset",
18
+ "generate_episodes",
19
+ "oracle_action",
20
+ "render",
21
+ "split_episodes",
22
+ "step",
23
+ ]