Download train_hyperbolic.py from lzhts1/ProWorld: direct link, hf CLI and curl.
- Browser
- Download file 60 kB
-
https://huggingface.co/datasets/lzhts1/ProWorld/resolve/main/train_hyperbolic.py
- Command line
-
hf download hf://datasets/lzhts1/ProWorld/train_hyperbolic.py
-
curl -L -o train_hyperbolic.py https://huggingface.co/datasets/lzhts1/ProWorld/resolve/main/train_hyperbolic.py
60 kB
| """ | |
| torchrun --standalone --nproc_per_node=16 train_hyperbolic.py --config-name=lewm_hyperbolic trainer.accelerator=npu trainer.devices=16 trainer.precision=bf16 wandb.enabled=False num_workers=4 loader.batch_size=32 subdir=ogbench/hyperbolic_exp_test | |
| """ | |
| import hashlib | |
| import faulthandler | |
| import math | |
| import os | |
| from functools import partial | |
| from pathlib import Path, PurePosixPath | |
| from types import MethodType | |
| import h5py | |
| import hydra | |
| import lightning as pl | |
| import numpy as np | |
| import stable_pretraining as spt | |
| import stable_worldmodel as swm | |
| import torch | |
| import torch.nn.functional as F | |
| from einops import rearrange | |
| from lightning.pytorch.callbacks import Callback | |
| from lightning.pytorch.loggers import WandbLogger | |
| from lightning.pytorch.strategies import SingleDeviceStrategy | |
| from omegaconf import OmegaConf, open_dict | |
| from torch import nn | |
| try: | |
| from torch.distributed.elastic.multiprocessing.errors import record | |
| except Exception: | |
| def record(fn): | |
| return fn | |
| try: | |
| import fcntl | |
| except ImportError: | |
| fcntl = None | |
| from module import ARPredictor, Embedder, MLP, SIGReg | |
| from npu_accelerator import NPUAccelerator | |
| from npu_ddp_strategy import NPUDDPStrategy | |
| try: | |
| from train_pahm import ( | |
| SafeSequenceDataset, | |
| dataset_has_preprocessed_pixels, | |
| is_rank_zero_process, | |
| maybe_resolve_sharded_dataset, | |
| print_dataset_diagnostics, | |
| resolve_npu_devices, | |
| validate_hdf5_episode_metadata, | |
| ) | |
| except ImportError: | |
| from train import ( | |
| SafeSequenceDataset, | |
| dataset_has_preprocessed_pixels, | |
| is_rank_zero_process, | |
| maybe_resolve_sharded_dataset, | |
| print_dataset_diagnostics, | |
| resolve_npu_devices, | |
| validate_hdf5_episode_metadata, | |
| ) | |
| from utils import ( | |
| LossHistoryCallback, | |
| ModelObjectCallBack, | |
| get_column_normalizer, | |
| get_img_preprocessor, | |
| maybe_enable_npu, | |
| resolve_runtime_device, | |
| ) | |
| def detach_clone(v): | |
| return v.detach().clone() if torch.is_tensor(v) else v | |
| def _non_finite_tensor_names(values: dict[str, torch.Tensor]) -> list[str]: | |
| bad_names = [] | |
| for name, value in values.items(): | |
| if torch.is_tensor(value) and not bool(torch.isfinite(value).all()): | |
| bad_names.append(name) | |
| return bad_names | |
| class NonFiniteGradientCallback(Callback): | |
| """Stop immediately when a non-finite gradient would corrupt a checkpoint.""" | |
| def on_after_backward(self, trainer, pl_module): | |
| parameters = [ | |
| parameter | |
| for parameter in pl_module.model.parameters() | |
| if parameter.grad is not None | |
| ] | |
| if not parameters: | |
| return | |
| try: | |
| torch.nn.utils.clip_grad_norm_( | |
| parameters, | |
| max_norm=float("inf"), | |
| error_if_nonfinite=True, | |
| ) | |
| except RuntimeError as exc: | |
| bad_names = [ | |
| f"model.{name}" | |
| for name, parameter in pl_module.model.named_parameters() | |
| if parameter.grad is not None and not bool(torch.isfinite(parameter.grad).all()) | |
| ] | |
| bad_preview = ", ".join(bad_names[:8]) or "<global gradient norm>" | |
| raise FloatingPointError( | |
| "Detected non-finite gradients before optimizer.step " | |
| f"at global_step={trainer.global_step}. " | |
| f"First affected parameters: {bad_preview}." | |
| ) from exc | |
| def _dataset_name_to_h5_path(dataset_name: str) -> Path: | |
| normalized = str(dataset_name).replace("\\", "/") | |
| cache_dir = Path(swm.data.utils.get_cache_dir()) | |
| return cache_dir / f"{normalized}.h5" | |
| def _build_preprocessed_dataset_candidates(dataset_name: str, img_size: int) -> list[str]: | |
| normalized = str(dataset_name).replace("\\", "/") | |
| pure_name = PurePosixPath(normalized) | |
| parent = "" if str(pure_name.parent) == "." else pure_name.parent.as_posix() | |
| stem = pure_name.name | |
| prep_suffix = f"_prep{img_size}" | |
| candidates = [] | |
| seen = set() | |
| def add(candidate: str) -> None: | |
| if candidate and candidate not in seen: | |
| seen.add(candidate) | |
| candidates.append(candidate) | |
| if parent: | |
| add(f"{parent}{prep_suffix}/{stem}{prep_suffix}") | |
| add(f"{parent}{prep_suffix}/{stem}") | |
| add(f"{normalized}{prep_suffix}") | |
| return candidates | |
| def maybe_resolve_full_dataset(cfg) -> None: | |
| base_name = str(cfg.data.dataset.name).replace("\\", "/") | |
| resolved_name = None | |
| resolved_reason = None | |
| for preprocessed_name in _build_preprocessed_dataset_candidates(base_name, cfg.img_size): | |
| if _dataset_name_to_h5_path(preprocessed_name).exists(): | |
| resolved_name = preprocessed_name | |
| resolved_reason = "preprocessed" | |
| break | |
| if resolved_name is None and _dataset_name_to_h5_path(base_name).exists(): | |
| resolved_name = base_name | |
| resolved_reason = "raw" | |
| if resolved_name is not None and resolved_name != base_name: | |
| with open_dict(cfg): | |
| cfg.data.dataset.name = resolved_name | |
| rank = int(os.environ.get("RANK", "0")) | |
| world_size = int(os.environ.get("WORLD_SIZE", "1")) | |
| effective_name = str(cfg.data.dataset.name).replace("\\", "/") | |
| print( | |
| f"[dataset-diag] using full dataset '{effective_name}' " | |
| f"(reason={resolved_reason or 'unverified'}, world_size={world_size}, rank={rank})", | |
| flush=True, | |
| ) | |
| def _unique_preserve_order(values) -> list: | |
| result = [] | |
| seen = set() | |
| for value in values or []: | |
| if value not in seen: | |
| seen.add(value) | |
| result.append(value) | |
| return result | |
| def resolve_dataset_cache_keys(cfg) -> list[str]: | |
| dataset_kwargs = OmegaConf.to_container(cfg.data.dataset, resolve=True) | |
| if bool(cfg.data_loading.get("cache_all_keys_in_memory", False)): | |
| return _unique_preserve_order(dataset_kwargs.get("keys_to_load") or []) | |
| return _unique_preserve_order(dataset_kwargs.get("keys_to_cache") or []) | |
| def build_hdf5_dataset_kwargs(cfg, cache_keys: list[str], use_shared_cache: bool) -> dict: | |
| dataset_kwargs = OmegaConf.to_container(cfg.data.dataset, resolve=True) | |
| dataset_kwargs["keys_to_cache"] = [] if use_shared_cache else cache_keys | |
| return dataset_kwargs | |
| def resolve_shared_cache_dir(cfg) -> Path: | |
| configured = str(cfg.data_loading.get("shared_cache_dir", "")).strip() | |
| if configured: | |
| return Path(configured) | |
| default_dir = Path("/dev/shm/lewm_shared_hdf5") | |
| if default_dir.exists(): | |
| return default_dir | |
| return Path(swm.data.utils.get_cache_dir(), "shared_hdf5") | |
| def _dataset_cache_fingerprint(h5_path: str | Path) -> str: | |
| resolved = Path(h5_path).resolve() | |
| stat = resolved.stat() | |
| payload = f"{resolved}|{stat.st_size}|{stat.st_mtime_ns}" | |
| return hashlib.sha1(payload.encode("utf-8")).hexdigest()[:16] | |
| def _sanitize_cache_key(key: str) -> str: | |
| return str(key).replace("/", "__") | |
| def _cache_file_path(cache_dir: Path, key: str) -> Path: | |
| return cache_dir / f"{_sanitize_cache_key(key)}.npy" | |
| def _rows_per_chunk(dataset_obj: h5py.Dataset, chunk_bytes: int) -> int: | |
| if len(dataset_obj.shape) == 0: | |
| return 1 | |
| if dataset_obj.shape[0] == 0: | |
| return 1 | |
| trailing = int(np.prod(dataset_obj.shape[1:], dtype=np.int64)) if len(dataset_obj.shape) > 1 else 1 | |
| bytes_per_row = max(1, trailing * dataset_obj.dtype.itemsize) | |
| return max(1, min(int(dataset_obj.shape[0]), max(1, int(chunk_bytes) // bytes_per_row))) | |
| def _is_valid_shared_cache_file(cache_path: Path, source_dataset: h5py.Dataset) -> bool: | |
| if not cache_path.exists(): | |
| return False | |
| try: | |
| cached = np.load(cache_path, mmap_mode="r") | |
| except Exception: | |
| return False | |
| try: | |
| return cached.shape == source_dataset.shape and cached.dtype == source_dataset.dtype | |
| finally: | |
| del cached | |
| def _write_hdf5_dataset_to_npy( | |
| source_dataset: h5py.Dataset, | |
| cache_path: Path, | |
| chunk_bytes: int, | |
| ) -> None: | |
| tmp_path = cache_path.with_suffix(f"{cache_path.suffix}.tmp.{os.getpid()}") | |
| if tmp_path.exists(): | |
| tmp_path.unlink() | |
| mmap = np.lib.format.open_memmap( | |
| tmp_path, | |
| mode="w+", | |
| dtype=source_dataset.dtype, | |
| shape=source_dataset.shape, | |
| ) | |
| progress_bar = None | |
| try: | |
| if len(source_dataset.shape) == 0: | |
| mmap[()] = source_dataset[()] | |
| else: | |
| rows_per_chunk = _rows_per_chunk(source_dataset, chunk_bytes) | |
| total_rows = int(source_dataset.shape[0]) | |
| rank = get_rank() if 'get_rank' in globals() else int(os.environ.get('RANK', os.environ.get('RANK_ID', '0'))) | |
| try: | |
| from tqdm.auto import tqdm | |
| progress_bar = tqdm( | |
| total=total_rows, | |
| desc=f"cache:{cache_path.stem}:rank{rank}", | |
| unit="rows", | |
| leave=True, | |
| ) | |
| except Exception: | |
| progress_bar = None | |
| for start in range(0, total_rows, rows_per_chunk): | |
| end = min(total_rows, start + rows_per_chunk) | |
| mmap[start:end] = source_dataset[start:end] | |
| if progress_bar is not None: | |
| progress_bar.update(end - start) | |
| mmap.flush() | |
| finally: | |
| if progress_bar is not None: | |
| progress_bar.close() | |
| del mmap | |
| os.replace(tmp_path, cache_path) | |
| def _lock_handle(lock_path: Path): | |
| lock_path.parent.mkdir(parents=True, exist_ok=True) | |
| handle = lock_path.open("a+b") | |
| if fcntl is not None: | |
| fcntl.flock(handle.fileno(), fcntl.LOCK_EX) | |
| return handle | |
| def _unlock_handle(handle) -> None: | |
| try: | |
| if fcntl is not None: | |
| fcntl.flock(handle.fileno(), fcntl.LOCK_UN) | |
| finally: | |
| handle.close() | |
| def ensure_shared_cache_files( | |
| h5_path: str | Path, | |
| cache_keys: list[str], | |
| shared_cache_root: Path, | |
| chunk_bytes: int, | |
| ) -> tuple[Path, dict[str, Path]]: | |
| h5_path = Path(h5_path) | |
| fingerprint = _dataset_cache_fingerprint(h5_path) | |
| dataset_cache_dir = shared_cache_root / fingerprint | |
| file_paths = {key: _cache_file_path(dataset_cache_dir, key) for key in cache_keys} | |
| lock_path = shared_cache_root / f"{fingerprint}.lock" | |
| rank = get_rank() if 'get_rank' in globals() else int(os.environ.get('RANK', os.environ.get('RANK_ID', '0'))) | |
| print( | |
| f"[dataset-diag] rank={rank} waiting for shared cache lock '{lock_path.name}'", | |
| flush=True, | |
| ) | |
| lock = _lock_handle(lock_path) | |
| try: | |
| print( | |
| f"[dataset-diag] rank={rank} acquired shared cache lock '{lock_path.name}'", | |
| flush=True, | |
| ) | |
| dataset_cache_dir.mkdir(parents=True, exist_ok=True) | |
| with h5py.File(h5_path, "r") as h5_file: | |
| for key in cache_keys: | |
| if key not in h5_file: | |
| raise KeyError(f"Requested shared cache key '{key}' not found in '{h5_path}'.") | |
| cache_path = file_paths[key] | |
| if _is_valid_shared_cache_file(cache_path, h5_file[key]): | |
| continue | |
| print( | |
| f"[dataset-diag] building shared cache key='{key}' path='{cache_path}'", | |
| flush=True, | |
| ) | |
| _write_hdf5_dataset_to_npy(h5_file[key], cache_path, chunk_bytes) | |
| finally: | |
| _unlock_handle(lock) | |
| return dataset_cache_dir, file_paths | |
| def _shared_cache_load_slice(self, ep_idx: int, start: int, end: int) -> dict: | |
| self._open() | |
| g_start, g_end = ( | |
| self.offsets[ep_idx] + start, | |
| self.offsets[ep_idx] + end, | |
| ) | |
| steps = {} | |
| for col in self._keys: | |
| if col in self._cache: | |
| data = np.array(self._cache[col][g_start:g_end], copy=True) | |
| else: | |
| data = self.h5_file[col][g_start:g_end] | |
| if col != "action": | |
| data = data[:: self.frameskip] | |
| if data.dtype == np.object_ or data.dtype.kind in ("S", "U"): | |
| val = data[0] if len(data) > 0 else b"" | |
| steps[col] = val.decode() if isinstance(val, bytes) else val | |
| else: | |
| steps[col] = torch.from_numpy(data) | |
| if data.ndim == 4 and data.shape[-1] in (1, 3): | |
| steps[col] = steps[col].permute(0, 3, 1, 2) | |
| return self.transform(steps) if self.transform else steps | |
| def attach_shared_cache_to_dataset(dataset, cache_keys: list[str], cfg) -> None: | |
| if not cache_keys: | |
| return | |
| shared_cache_root = resolve_shared_cache_dir(cfg) | |
| chunk_bytes = int(cfg.data_loading.get("shared_cache_chunk_bytes", 512 * 1024 * 1024)) | |
| dataset_cache_dir, file_paths = ensure_shared_cache_files( | |
| h5_path=getattr(dataset, "h5_path"), | |
| cache_keys=cache_keys, | |
| shared_cache_root=shared_cache_root, | |
| chunk_bytes=chunk_bytes, | |
| ) | |
| shared_arrays = {key: np.load(path, mmap_mode="r") for key, path in file_paths.items()} | |
| dataset._cache.update(shared_arrays) | |
| dataset._shared_cache_dir = dataset_cache_dir | |
| dataset._shared_cache_paths = file_paths | |
| dataset._load_slice = MethodType(_shared_cache_load_slice, dataset) | |
| print( | |
| f"[dataset-diag] attached shared cache dir='{dataset_cache_dir}' keys={cache_keys}", | |
| flush=True, | |
| ) | |
| class LorentzManifold(nn.Module): | |
| def __init__( | |
| self, | |
| *, | |
| curvature_init: float = 1.0, | |
| learn_curvature: bool = False, | |
| max_tangent_norm: float = 5.0, | |
| eps: float = 1e-5, | |
| fp32_distance: bool = True, | |
| ): | |
| super().__init__() | |
| curvature_init = max(float(curvature_init), float(eps)) | |
| raw_curvature = torch.log(torch.expm1(torch.tensor(curvature_init))) | |
| if learn_curvature: | |
| self.raw_curvature = nn.Parameter(raw_curvature) | |
| else: | |
| self.register_buffer("raw_curvature", raw_curvature) | |
| self.max_tangent_norm = float(max_tangent_norm) | |
| self.eps = float(eps) | |
| self.fp32_distance = bool(fp32_distance) | |
| def curvature(self) -> torch.Tensor: | |
| return F.softplus(self.raw_curvature) + self.eps | |
| def _work_dtype(self, x: torch.Tensor) -> torch.dtype: | |
| if self.fp32_distance and x.dtype in (torch.float16, torch.bfloat16): | |
| return torch.float32 | |
| return x.dtype | |
| def _curvature_like(self, x: torch.Tensor) -> torch.Tensor: | |
| return self.curvature.to(device=x.device, dtype=self._work_dtype(x)) | |
| def _radius_like(self, x: torch.Tensor) -> torch.Tensor: | |
| return self._curvature_like(x).rsqrt() | |
| def clamp_tangent(self, u: torch.Tensor) -> torch.Tensor: | |
| if self.max_tangent_norm <= 0: | |
| return u | |
| norm = torch.linalg.vector_norm(u, dim=-1, keepdim=True) | |
| scale = self.max_tangent_norm / norm.clamp_min(self.eps) | |
| return torch.where(norm > self.max_tangent_norm, u * scale, u) | |
| def project(self, x: torch.Tensor) -> torch.Tensor: | |
| x = x.to(dtype=self._work_dtype(x)) | |
| spatial = x[..., 1:] | |
| radius = self._radius_like(x) | |
| time = torch.sqrt( | |
| radius.square() + spatial.square().sum(dim=-1, keepdim=True) | |
| ).clamp_min(self.eps) | |
| return torch.cat([time, spatial], dim=-1) | |
| def expmap0(self, u: torch.Tensor) -> torch.Tensor: | |
| u = self.clamp_tangent(u).to(dtype=self._work_dtype(u)) | |
| c = self._curvature_like(u) | |
| sqrt_c = torch.sqrt(c) | |
| radius = c.rsqrt() | |
| norm = torch.linalg.vector_norm(u, dim=-1, keepdim=True) | |
| scaled_norm = sqrt_c * norm | |
| safe_norm = norm.clamp_min(self.eps) | |
| factor = torch.ones_like(norm) | |
| valid = norm > self.eps | |
| factor = torch.where( | |
| valid, | |
| torch.sinh(scaled_norm) / (sqrt_c * safe_norm), | |
| factor, | |
| ) | |
| time = torch.cosh(scaled_norm) * radius | |
| spatial = factor * u | |
| return self.project(torch.cat([time, spatial], dim=-1)) | |
| def minkowski_dot(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: | |
| x = x.to(dtype=self._work_dtype(x)) | |
| y = y.to(dtype=self._work_dtype(y)) | |
| return (x[..., 1:] * y[..., 1:]).sum(dim=-1) - x[..., 0] * y[..., 0] | |
| def pairwise_minkowski_dot(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: | |
| x = x.to(dtype=self._work_dtype(x)) | |
| y = y.to(dtype=self._work_dtype(y)) | |
| spatial = x[..., 1:] @ y[..., 1:].transpose(-1, -2) | |
| temporal = x[..., :1] @ y[..., :1].transpose(-1, -2) | |
| return spatial - temporal | |
| def dist(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: | |
| x = self.project(x) | |
| y = self.project(y) | |
| c = self._curvature_like(x) | |
| arg = (-c * self.minkowski_dot(x, y)).clamp_min(1.0 + self.eps) | |
| return torch.acosh(arg) / torch.sqrt(c) | |
| def pairwise_dist(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: | |
| x = self.project(x) | |
| y = self.project(y) | |
| c = self._curvature_like(x) | |
| arg = (-c * self.pairwise_minkowski_dot(x, y)).clamp_min(1.0 + self.eps) | |
| return torch.acosh(arg) / torch.sqrt(c) | |
| def to_poincare(self, x: torch.Tensor) -> torch.Tensor: | |
| x = self.project(x) | |
| radius = self._radius_like(x) | |
| return x[..., 1:] / (x[..., :1] + radius).clamp_min(self.eps) | |
| class LorentzContrastiveLoss(nn.Module): | |
| def __init__(self, temperature: float = 0.2, label_smoothing: float = 0.0): | |
| super().__init__() | |
| self.temperature = float(temperature) | |
| self.label_smoothing = float(label_smoothing) | |
| def forward( | |
| self, | |
| pred_points: torch.Tensor, | |
| target_points: torch.Tensor, | |
| manifold: LorentzManifold, | |
| ) -> dict[str, torch.Tensor]: | |
| pred_flat = pred_points.reshape(-1, pred_points.size(-1)) | |
| target_flat = target_points.reshape(-1, target_points.size(-1)) | |
| dist_matrix = manifold.pairwise_dist(pred_flat, target_flat) | |
| logits = -dist_matrix / max(self.temperature, 1e-6) | |
| labels = torch.arange(logits.size(0), device=logits.device) | |
| loss = 0.5 * ( | |
| F.cross_entropy(logits, labels, label_smoothing=self.label_smoothing) | |
| + F.cross_entropy(logits.t(), labels, label_smoothing=self.label_smoothing) | |
| ) | |
| pos_dist = dist_matrix.diag().mean() | |
| if dist_matrix.size(0) > 1: | |
| neg_mask = ~torch.eye(dist_matrix.size(0), dtype=torch.bool, device=dist_matrix.device) | |
| neg_dist = dist_matrix[neg_mask].mean() | |
| else: | |
| neg_dist = torch.zeros_like(pos_dist) | |
| return { | |
| "contrastive_loss": loss, | |
| "contrastive_pos_dist": pos_dist, | |
| "contrastive_neg_dist": neg_dist, | |
| } | |
| class AdaptiveEntailmentConeLoss(nn.Module): | |
| """Cone-style surrogate defined in Poincare coordinates.""" | |
| def __init__( | |
| self, | |
| *, | |
| min_aperture: float = 0.10, | |
| max_aperture: float = 1.10, | |
| radius_margin: float = 0.02, | |
| angle_weight: float = 1.0, | |
| radius_weight: float = 1.0, | |
| eps: float = 1e-6, | |
| ): | |
| super().__init__() | |
| self.min_aperture = float(min_aperture) | |
| self.max_aperture = float(max_aperture) | |
| self.radius_margin = float(radius_margin) | |
| self.angle_weight = float(angle_weight) | |
| self.radius_weight = float(radius_weight) | |
| self.eps = float(eps) | |
| def penalty( | |
| self, | |
| parent_points: torch.Tensor, | |
| child_points: torch.Tensor, | |
| manifold: LorentzManifold, | |
| ) -> dict[str, torch.Tensor]: | |
| parent_ball = manifold.to_poincare(parent_points).float() | |
| child_ball = manifold.to_poincare(child_points).float() | |
| parent_radius = torch.linalg.vector_norm(parent_ball, dim=-1) | |
| child_radius = torch.linalg.vector_norm(child_ball, dim=-1) | |
| valid = (parent_radius > self.eps) & (child_radius > self.eps) | |
| parent_dir = parent_ball / parent_radius.unsqueeze(-1).clamp_min(self.eps) | |
| child_dir = child_ball / child_radius.unsqueeze(-1).clamp_min(self.eps) | |
| cosine = (parent_dir * child_dir).sum(dim=-1).clamp(-0.9995, 0.9995) | |
| angle = torch.zeros_like(parent_radius) | |
| angle = torch.where(valid, torch.acos(cosine), angle) | |
| openness = (1.0 - parent_radius).clamp(0.0, 1.0) | |
| aperture = self.min_aperture + (self.max_aperture - self.min_aperture) * openness | |
| angle_violation = F.relu(angle - aperture) | |
| angle_violation = torch.where(valid, angle_violation, torch.zeros_like(angle_violation)) | |
| radius_violation = F.relu(parent_radius + self.radius_margin - child_radius) | |
| loss = self.angle_weight * angle_violation + self.radius_weight * radius_violation | |
| return { | |
| "loss": loss, | |
| "angle_violation": angle_violation, | |
| "radius_violation": radius_violation, | |
| "aperture": aperture, | |
| "parent_radius": parent_radius, | |
| "child_radius": child_radius, | |
| } | |
| def forward( | |
| self, | |
| parent_points: torch.Tensor, | |
| child_points: torch.Tensor, | |
| manifold: LorentzManifold, | |
| ) -> dict[str, torch.Tensor]: | |
| stats = self.penalty(parent_points, child_points, manifold) | |
| return { | |
| "cone_loss": stats["loss"].mean(), | |
| "cone_angle_loss": stats["angle_violation"].mean(), | |
| "cone_radius_loss": stats["radius_violation"].mean(), | |
| "cone_aperture": stats["aperture"].mean(), | |
| "parent_radius": stats["parent_radius"].mean(), | |
| "child_radius": stats["child_radius"].mean(), | |
| } | |
| class HyperbolicJEPA(nn.Module): | |
| def __init__( | |
| self, | |
| *, | |
| encoder: nn.Module, | |
| predictor: nn.Module, | |
| action_encoder: nn.Module, | |
| projector: nn.Module, | |
| pred_proj: nn.Module, | |
| hyper_projector: nn.Module, | |
| manifold: LorentzManifold, | |
| cone_loss: AdaptiveEntailmentConeLoss, | |
| contrastive_loss: LorentzContrastiveLoss, | |
| tangent_stabilization: dict | None = None, | |
| ): | |
| super().__init__() | |
| self.encoder = encoder | |
| self.predictor = predictor | |
| self.action_encoder = action_encoder | |
| self.projector = projector | |
| self.pred_proj = pred_proj | |
| self.hyper_projector = hyper_projector | |
| self.manifold = manifold | |
| self.cone_loss = cone_loss | |
| self.contrastive_loss = contrastive_loss | |
| self.tangent_stabilization = tangent_stabilization or {} | |
| self.planning_config = {} | |
| self.trm_metric = None | |
| def set_planning_config(self, config: dict | None = None): | |
| self.planning_config = config or {} | |
| def set_trajectory_reachability_metric(self, metric: nn.Module | None): | |
| self.trm_metric = metric | |
| if self.trm_metric is not None: | |
| self.trm_metric.eval() | |
| self.trm_metric.requires_grad_(False) | |
| def _stabilize_tangent( | |
| self, | |
| tangent: torch.Tensor, | |
| ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: | |
| cfg = self.tangent_stabilization | |
| enabled = bool(cfg.get("enabled", False)) | |
| tangent_fp32 = tangent.float() | |
| raw_norm = tangent_fp32.norm(dim=-1) | |
| if not enabled: | |
| max_norm = float(self.manifold.max_tangent_norm) | |
| if max_norm > 0: | |
| saturated = raw_norm >= max_norm | |
| else: | |
| saturated = torch.zeros_like(raw_norm, dtype=torch.bool) | |
| return tangent_fp32, { | |
| "raw_tangent_norm": raw_norm, | |
| "scaled_tangent_norm": raw_norm, | |
| "bounded_tangent_norm": raw_norm, | |
| "tangent_saturation_fraction": saturated.float(), | |
| } | |
| scaled = tangent_fp32 | |
| if bool(cfg.get("scale_by_sqrt_dim", True)): | |
| scaled = scaled / math.sqrt(float(tangent.size(-1))) | |
| scaled_norm = scaled.norm(dim=-1, keepdim=True) | |
| max_norm = float(cfg.get("max_norm", self.manifold.max_tangent_norm)) | |
| if max_norm <= 0: | |
| bounded = scaled | |
| else: | |
| bounded_norm = max_norm * torch.tanh(scaled_norm / max_norm) | |
| bounded = scaled * bounded_norm / scaled_norm.clamp_min(self.manifold.eps) | |
| bounded_norm = bounded.norm(dim=-1) | |
| saturation_threshold = float(cfg.get("saturation_threshold", 0.95)) | |
| if max_norm > 0: | |
| saturated = bounded_norm >= saturation_threshold * max_norm | |
| else: | |
| saturated = torch.zeros_like(bounded_norm, dtype=torch.bool) | |
| return bounded, { | |
| "raw_tangent_norm": raw_norm, | |
| "scaled_tangent_norm": scaled_norm.squeeze(-1), | |
| "bounded_tangent_norm": bounded_norm, | |
| "tangent_saturation_fraction": saturated.float(), | |
| } | |
| def to_hyperbolic( | |
| self, | |
| emb: torch.Tensor, | |
| *, | |
| return_stats: bool = False, | |
| ) -> tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, dict[str, torch.Tensor]]: | |
| shape_prefix = emb.shape[:-1] | |
| flat = emb.reshape(-1, emb.size(-1)) | |
| raw_tangent = self.hyper_projector(flat) | |
| tangent, stats = self._stabilize_tangent(raw_tangent) | |
| tangent = tangent.reshape(*shape_prefix, tangent.size(-1)) | |
| points = self.manifold.expmap0(tangent) | |
| if return_stats: | |
| stats = { | |
| key: value.reshape(*shape_prefix) | |
| for key, value in stats.items() | |
| } | |
| return tangent, points, stats | |
| return tangent, points | |
| def encode(self, info: dict) -> dict: | |
| pixels = info["pixels"].float() | |
| bsz = pixels.size(0) | |
| pixels = rearrange(pixels, "b t ... -> (b t) ...") | |
| output = self.encoder(pixels, interpolate_pos_encoding=True) | |
| pixels_emb = output.last_hidden_state[:, 0] | |
| emb = self.projector(pixels_emb) | |
| emb = rearrange(emb, "(b t) d -> b t d", b=bsz) | |
| hyp_tangent, hyp_emb, tangent_stats = self.to_hyperbolic(emb, return_stats=True) | |
| info["emb"] = emb | |
| info["hyp_tangent"] = hyp_tangent | |
| info["hyp_emb"] = hyp_emb | |
| info.update(tangent_stats) | |
| if "action" in info: | |
| info["act_emb"] = self.action_encoder(info["action"]) | |
| return info | |
| def predict(self, emb: torch.Tensor, act_emb: torch.Tensor) -> torch.Tensor: | |
| preds = self.predictor(emb, act_emb) | |
| preds = self.pred_proj(rearrange(preds, "b t d -> (b t) d")) | |
| return rearrange(preds, "(b t) d -> b t d", b=emb.size(0)) | |
| def rollout_from_encoded( | |
| self, | |
| emb: torch.Tensor, | |
| act_emb: torch.Tensor, | |
| *, | |
| history_size: int, | |
| rollout_steps: int, | |
| ) -> tuple[torch.Tensor, torch.Tensor]: | |
| max_rollout_steps = emb.size(1) - history_size | |
| rollout_steps = min(int(rollout_steps), int(max_rollout_steps)) | |
| if rollout_steps <= 0: | |
| raise ValueError( | |
| f"Expected rollout_steps > 0 with history_size={history_size}, got " | |
| f"rollout_steps={rollout_steps}, sequence_len={emb.size(1)}." | |
| ) | |
| pred_context = emb[:, :history_size].clone() | |
| act_context = act_emb[:, :history_size].clone() | |
| preds = [] | |
| for step_idx in range(rollout_steps): | |
| pred_step = self.predict( | |
| pred_context[:, -history_size:], | |
| act_context[:, -history_size:], | |
| )[:, -1:] | |
| preds.append(pred_step) | |
| pred_context = torch.cat([pred_context, pred_step], dim=1) | |
| if step_idx + 1 < rollout_steps: | |
| next_act = act_emb[:, history_size + step_idx : history_size + step_idx + 1] | |
| act_context = torch.cat([act_context, next_act], dim=1) | |
| pred_rollout = torch.cat(preds, dim=1) | |
| _, pred_rollout_hyp = self.to_hyperbolic(pred_rollout) | |
| return pred_rollout, pred_rollout_hyp | |
| def rollout(self, info: dict, action_sequence: torch.Tensor, history_size: int = 3) -> dict: | |
| assert "pixels" in info, "pixels not in info_dict" | |
| hist = info["pixels"].size(2) | |
| batch_size, num_samples, horizon = action_sequence.shape[:3] | |
| act_0, act_future = torch.split(action_sequence, [hist, horizon - hist], dim=2) | |
| info["action"] = act_0 | |
| n_steps = horizon - hist | |
| init = {k: v[:, 0] for k, v in info.items() if torch.is_tensor(v)} | |
| init = self.encode(init) | |
| emb = info["emb"] = init["emb"].unsqueeze(1).expand(batch_size, num_samples, -1, -1) | |
| init = {k: detach_clone(v) for k, v in init.items()} | |
| emb = rearrange(emb, "b s ... -> (b s) ...").clone() | |
| act = rearrange(act_0, "b s ... -> (b s) ...") | |
| act_future = rearrange(act_future, "b s ... -> (b s) ...") | |
| for step_idx in range(n_steps): | |
| act_emb = self.action_encoder(act) | |
| emb_trunc = emb[:, -history_size:] | |
| act_trunc = act_emb[:, -history_size:] | |
| pred_emb = self.predict(emb_trunc, act_trunc)[:, -1:] | |
| emb = torch.cat([emb, pred_emb], dim=1) | |
| next_act = act_future[:, step_idx : step_idx + 1] | |
| act = torch.cat([act, next_act], dim=1) | |
| act_emb = self.action_encoder(act) | |
| emb_trunc = emb[:, -history_size:] | |
| act_trunc = act_emb[:, -history_size:] | |
| pred_emb = self.predict(emb_trunc, act_trunc)[:, -1:] | |
| emb = torch.cat([emb, pred_emb], dim=1) | |
| pred_rollout = rearrange(emb, "(b s) ... -> b s ...", b=batch_size, s=num_samples) | |
| _, pred_hyp = self.to_hyperbolic(pred_rollout) | |
| info["predicted_emb"] = pred_rollout | |
| info["predicted_hyp_emb"] = pred_hyp | |
| return info | |
| def _planning_hyperbolic_config(self) -> dict[str, float | bool]: | |
| defaults = { | |
| "enabled": True, | |
| "terminal_weight": 1.0, | |
| "best_weight": 0.35, | |
| "mean_weight": 0.15, | |
| "progress_weight": 0.10, | |
| "progress_margin": 0.0, | |
| "cone_weight": 0.08, | |
| } | |
| if not isinstance(self.planning_config, dict): | |
| return defaults | |
| hyper_cfg = self.planning_config.get("hyperbolic", {}) | |
| source = hyper_cfg if isinstance(hyper_cfg, dict) and hyper_cfg else self.planning_config | |
| if not isinstance(source, dict): | |
| return defaults | |
| merged = defaults.copy() | |
| for key in defaults: | |
| if key in source: | |
| merged[key] = source[key] | |
| return merged | |
| def _planning_trm_config(self) -> dict[str, float | bool | str | None]: | |
| defaults = { | |
| "enabled": False, | |
| "checkpoint": None, | |
| "weight": 0.5, | |
| "mode": "hybrid", | |
| "normalize_candidates": True, | |
| } | |
| if not isinstance(self.planning_config, dict): | |
| return defaults | |
| source = self.planning_config.get("trm", {}) | |
| if not isinstance(source, dict): | |
| return defaults | |
| merged = defaults.copy() | |
| for key in defaults: | |
| if key in source: | |
| merged[key] = source[key] | |
| return merged | |
| def _standardize_candidate_cost(cost: torch.Tensor) -> torch.Tensor: | |
| mean = cost.mean(dim=-1, keepdim=True) | |
| std = cost.std(dim=-1, keepdim=True, unbiased=False).clamp_min(1e-6) | |
| return (cost - mean) / std | |
| def _trajectory_reachability_cost(self, info_dict: dict) -> torch.Tensor: | |
| if self.trm_metric is None: | |
| raise RuntimeError( | |
| "planning.trm.enabled=True requires a loaded trajectory reachability metric." | |
| ) | |
| input_space = str(getattr(self.trm_metric, "input_space", "tangent")) | |
| if input_space == "euclidean": | |
| predicted = info_dict["predicted_emb"][..., -1, :] | |
| goal = info_dict["goal_emb"][..., -1, :] | |
| elif input_space == "tangent": | |
| predicted, _ = self.to_hyperbolic(info_dict["predicted_emb"][..., -1:, :]) | |
| predicted = predicted[..., -1, :] | |
| goal = info_dict["goal_hyp_tangent"][..., -1, :] | |
| elif input_space == "lorentz": | |
| predicted = info_dict["predicted_hyp_emb"][..., -1, :] | |
| goal = info_dict["goal_hyp_emb"][..., -1, :] | |
| else: | |
| raise ValueError(f"Unsupported TRM input space: {input_space!r}") | |
| while goal.ndim < predicted.ndim: | |
| goal = goal.unsqueeze(1) | |
| goal = goal.expand_as(predicted) | |
| return self.trm_metric(predicted, goal) | |
| def _blend_trajectory_reachability_cost( | |
| self, | |
| base_cost: torch.Tensor, | |
| info_dict: dict, | |
| ) -> torch.Tensor: | |
| trm_cfg = self._planning_trm_config() | |
| if not bool(trm_cfg.get("enabled", False)): | |
| return base_cost | |
| trm_cost = self._trajectory_reachability_cost(info_dict) | |
| trm_weight = float(trm_cfg.get("weight", 0.5)) | |
| mode = str(trm_cfg.get("mode", "hybrid")).lower() | |
| normalize = bool(trm_cfg.get("normalize_candidates", True)) | |
| if mode == "replace": | |
| cost = trm_cost | |
| elif mode == "add": | |
| cost = base_cost + trm_weight * trm_cost | |
| elif mode == "hybrid": | |
| base_cost = self._standardize_candidate_cost(base_cost) if normalize else base_cost | |
| metric_cost = ( | |
| self._standardize_candidate_cost(trm_cost) | |
| if normalize | |
| else trm_cost | |
| ) | |
| cost = base_cost + trm_weight * metric_cost | |
| else: | |
| raise ValueError( | |
| f"Unsupported planning.trm.mode={mode!r}; expected hybrid, replace, or add." | |
| ) | |
| info_dict["planning_trm_cost"] = trm_cost.mean().detach() | |
| return cost | |
| def criterion(self, info_dict: dict) -> torch.Tensor: | |
| pred_hyp = info_dict["predicted_hyp_emb"] | |
| goal_hyp = info_dict["goal_hyp_emb"][..., -1:, :] | |
| while goal_hyp.ndim < pred_hyp.ndim: | |
| goal_hyp = goal_hyp.unsqueeze(1) | |
| goal_hyp = goal_hyp.expand_as(pred_hyp) | |
| step_cost = self.manifold.dist(pred_hyp, goal_hyp).pow(2) | |
| terminal_cost = step_cost[..., -1] | |
| planning_cfg = self._planning_hyperbolic_config() | |
| if not bool(planning_cfg.get("enabled", True)): | |
| return self._blend_trajectory_reachability_cost(terminal_cost, info_dict) | |
| history_size = 1 | |
| if "pixels" in info_dict and torch.is_tensor(info_dict["pixels"]): | |
| history_size = int(info_dict["pixels"].size(2)) | |
| rollout_cost = step_cost[..., history_size:] | |
| if rollout_cost.size(-1) == 0: | |
| rollout_cost = step_cost[..., -1:] | |
| best_cost = rollout_cost.min(dim=-1).values | |
| mean_cost = rollout_cost.mean(dim=-1) | |
| if rollout_cost.size(-1) > 1: | |
| progress_delta = rollout_cost[..., 1:] - rollout_cost[..., :-1] | |
| progress_cost = F.relu( | |
| progress_delta + float(planning_cfg.get("progress_margin", 0.0)) | |
| ).mean(dim=-1) | |
| else: | |
| progress_cost = torch.zeros_like(terminal_cost) | |
| cone_penalty = self.cone_loss.penalty(pred_hyp, goal_hyp, self.manifold)["loss"] | |
| rollout_cone = cone_penalty[..., history_size:] | |
| if rollout_cone.size(-1) == 0: | |
| rollout_cone = cone_penalty[..., -1:] | |
| cone_cost = rollout_cone.mean(dim=-1) | |
| cost = ( | |
| float(planning_cfg.get("terminal_weight", 1.0)) * terminal_cost | |
| + float(planning_cfg.get("best_weight", 0.35)) * best_cost | |
| + float(planning_cfg.get("mean_weight", 0.15)) * mean_cost | |
| + float(planning_cfg.get("progress_weight", 0.10)) * progress_cost | |
| + float(planning_cfg.get("cone_weight", 0.08)) * cone_cost | |
| ) | |
| cost = self._blend_trajectory_reachability_cost(cost, info_dict) | |
| info_dict.update( | |
| { | |
| "planning_terminal_cost": terminal_cost.mean().detach(), | |
| "planning_best_cost": best_cost.mean().detach(), | |
| "planning_mean_cost": mean_cost.mean().detach(), | |
| "planning_progress_cost": progress_cost.mean().detach(), | |
| "planning_cone_cost": cone_cost.mean().detach(), | |
| } | |
| ) | |
| return cost | |
| def get_cost(self, info_dict: dict, action_candidates: torch.Tensor) -> torch.Tensor: | |
| assert "goal" in info_dict, "goal not in info_dict" | |
| device = next(self.parameters()).device | |
| for key in list(info_dict.keys()): | |
| if torch.is_tensor(info_dict[key]): | |
| info_dict[key] = info_dict[key].to(device) | |
| goal = {k: v[:, 0] for k, v in info_dict.items() if torch.is_tensor(v)} | |
| goal["pixels"] = goal["goal"] | |
| for key in list(goal.keys()): | |
| if key.startswith("goal_"): | |
| goal[key[len("goal_") :]] = goal.pop(key) | |
| goal.pop("action", None) | |
| goal = self.encode(goal) | |
| info_dict["goal_emb"] = goal["emb"] | |
| info_dict["goal_hyp_tangent"] = goal["hyp_tangent"] | |
| info_dict["goal_hyp_emb"] = goal["hyp_emb"] | |
| info_dict = self.rollout(info_dict, action_candidates) | |
| return self.criterion(info_dict) | |
| def ensure_hyperbolic_defaults(cfg): | |
| with open_dict(cfg): | |
| if str(cfg.get("output_model_name", "")) == "lewm": | |
| cfg.output_model_name = "lewm_hyperbolic" | |
| if "data_loading" not in cfg or cfg.data_loading is None: | |
| cfg.data_loading = OmegaConf.create({}) | |
| if "use_sharded_dataset" not in cfg.data_loading: | |
| cfg.data_loading.use_sharded_dataset = True | |
| if "cache_all_keys_in_memory" not in cfg.data_loading: | |
| cfg.data_loading.cache_all_keys_in_memory = False | |
| if "share_cache_across_ranks" not in cfg.data_loading: | |
| cfg.data_loading.share_cache_across_ranks = False | |
| if "shared_cache_dir" not in cfg.data_loading: | |
| cfg.data_loading.shared_cache_dir = "" | |
| if "shared_cache_chunk_bytes" not in cfg.data_loading: | |
| cfg.data_loading.shared_cache_chunk_bytes = 512 * 1024 * 1024 | |
| if "hyperbolic" not in cfg or cfg.hyperbolic is None: | |
| cfg.hyperbolic = OmegaConf.create({}) | |
| hyp = cfg.hyperbolic | |
| if "learn_curvature" not in hyp: | |
| hyp.learn_curvature = False | |
| if "curvature_init" not in hyp: | |
| hyp.curvature_init = 1.0 | |
| if "max_tangent_norm" not in hyp: | |
| hyp.max_tangent_norm = 5.0 | |
| if "eps" not in hyp: | |
| hyp.eps = 1e-5 | |
| if "fp32_distance" not in hyp: | |
| hyp.fp32_distance = True | |
| if "cone_offset" not in hyp: | |
| hyp.cone_offset = int(cfg.wm.num_preds) | |
| if "loss_weights" not in hyp or hyp.loss_weights is None: | |
| hyp.loss_weights = OmegaConf.create({}) | |
| if "pred" not in hyp.loss_weights: | |
| hyp.loss_weights.pred = 1.0 | |
| if "contrastive" not in hyp.loss_weights: | |
| hyp.loss_weights.contrastive = 0.05 | |
| if "cone" not in hyp.loss_weights: | |
| hyp.loss_weights.cone = 0.05 | |
| if "tangent" not in hyp.loss_weights: | |
| hyp.loss_weights.tangent = 0.0 | |
| if "rollout" not in hyp.loss_weights: | |
| hyp.loss_weights.rollout = 0.25 | |
| if "rollout_hyp" not in hyp.loss_weights: | |
| hyp.loss_weights.rollout_hyp = 0.0 | |
| if "radius" not in hyp.loss_weights: | |
| hyp.loss_weights.radius = 0.0 | |
| if "rollout" not in hyp or hyp.rollout is None: | |
| hyp.rollout = OmegaConf.create({}) | |
| if "enabled" not in hyp.rollout: | |
| hyp.rollout.enabled = True | |
| if "steps" not in hyp.rollout: | |
| hyp.rollout.steps = int(cfg.wm.history_size) | |
| if "warmup_steps" not in hyp.rollout: | |
| hyp.rollout.warmup_steps = 0 | |
| if "stabilization" not in hyp or hyp.stabilization is None: | |
| hyp.stabilization = OmegaConf.create({}) | |
| if "enabled" not in hyp.stabilization: | |
| hyp.stabilization.enabled = False | |
| if "scale_by_sqrt_dim" not in hyp.stabilization: | |
| hyp.stabilization.scale_by_sqrt_dim = True | |
| if "max_norm" not in hyp.stabilization: | |
| hyp.stabilization.max_norm = float(hyp.max_tangent_norm) | |
| if "target_norm" not in hyp.stabilization: | |
| hyp.stabilization.target_norm = 2.0 | |
| if "saturation_threshold" not in hyp.stabilization: | |
| hyp.stabilization.saturation_threshold = 0.95 | |
| if "finite_guard" not in hyp or hyp.finite_guard is None: | |
| hyp.finite_guard = OmegaConf.create({}) | |
| if "enabled" not in hyp.finite_guard: | |
| hyp.finite_guard.enabled = False | |
| if "check_gradients" not in hyp.finite_guard: | |
| hyp.finite_guard.check_gradients = False | |
| if "contrastive" not in hyp or hyp.contrastive is None: | |
| hyp.contrastive = OmegaConf.create({}) | |
| if "temperature" not in hyp.contrastive: | |
| hyp.contrastive.temperature = 0.2 | |
| if "label_smoothing" not in hyp.contrastive: | |
| hyp.contrastive.label_smoothing = 0.0 | |
| if "cone" not in hyp or hyp.cone is None: | |
| hyp.cone = OmegaConf.create({}) | |
| if "min_aperture" not in hyp.cone: | |
| hyp.cone.min_aperture = 0.10 | |
| if "max_aperture" not in hyp.cone: | |
| hyp.cone.max_aperture = 1.10 | |
| if "radius_margin" not in hyp.cone: | |
| hyp.cone.radius_margin = 0.02 | |
| if "angle_weight" not in hyp.cone: | |
| hyp.cone.angle_weight = 1.0 | |
| if "radius_weight" not in hyp.cone: | |
| hyp.cone.radius_weight = 1.0 | |
| required_future_steps = int(cfg.wm.num_preds) | |
| if bool(hyp.rollout.enabled): | |
| required_future_steps = max(required_future_steps, int(hyp.rollout.steps)) | |
| required_num_steps = int(cfg.wm.history_size) + required_future_steps | |
| if int(cfg.data.dataset.num_steps) < required_num_steps: | |
| cfg.data.dataset.num_steps = required_num_steps | |
| def build_hyperbolic_world_model(cfg, action_dim: int) -> HyperbolicJEPA: | |
| hidden_dim = None | |
| encoder = spt.backbone.utils.vit_hf( | |
| cfg.encoder_scale, | |
| patch_size=cfg.patch_size, | |
| image_size=cfg.img_size, | |
| pretrained=False, | |
| use_mask_token=False, | |
| ) | |
| hidden_dim = encoder.config.hidden_size | |
| embed_dim = int(cfg.wm.get("embed_dim", hidden_dim)) | |
| effective_act_dim = int(cfg.data.dataset.frameskip) * int(action_dim) | |
| with open_dict(cfg): | |
| if "manifold_dim" not in cfg.hyperbolic: | |
| cfg.hyperbolic.manifold_dim = embed_dim + 1 | |
| if "head_hidden_dim" not in cfg.hyperbolic: | |
| cfg.hyperbolic.head_hidden_dim = 2 * embed_dim | |
| if int(cfg.hyperbolic.manifold_dim) < 2: | |
| raise ValueError("hyperbolic.manifold_dim must be at least 2.") | |
| cfg.wm.action_dim = int(action_dim) | |
| predictor = ARPredictor( | |
| num_frames=cfg.wm.history_size, | |
| input_dim=embed_dim, | |
| hidden_dim=hidden_dim, | |
| output_dim=hidden_dim, | |
| **cfg.predictor, | |
| ) | |
| action_encoder = Embedder(input_dim=effective_act_dim, emb_dim=embed_dim) | |
| projector = MLP( | |
| input_dim=hidden_dim, | |
| output_dim=embed_dim, | |
| hidden_dim=2048, | |
| norm_fn=torch.nn.BatchNorm1d, | |
| ) | |
| predictor_proj = MLP( | |
| input_dim=hidden_dim, | |
| output_dim=embed_dim, | |
| hidden_dim=2048, | |
| norm_fn=torch.nn.BatchNorm1d, | |
| ) | |
| manifold = LorentzManifold( | |
| curvature_init=float(cfg.hyperbolic.curvature_init), | |
| learn_curvature=bool(cfg.hyperbolic.learn_curvature), | |
| max_tangent_norm=float(cfg.hyperbolic.max_tangent_norm), | |
| eps=float(cfg.hyperbolic.eps), | |
| fp32_distance=bool(cfg.hyperbolic.fp32_distance), | |
| ) | |
| hyper_projector = MLP( | |
| input_dim=embed_dim, | |
| output_dim=int(cfg.hyperbolic.manifold_dim) - 1, | |
| hidden_dim=int(cfg.hyperbolic.head_hidden_dim), | |
| norm_fn=torch.nn.LayerNorm, | |
| ) | |
| cone_loss = AdaptiveEntailmentConeLoss( | |
| **OmegaConf.to_container(cfg.hyperbolic.cone, resolve=True), | |
| ) | |
| contrastive_loss = LorentzContrastiveLoss( | |
| **OmegaConf.to_container(cfg.hyperbolic.contrastive, resolve=True), | |
| ) | |
| return HyperbolicJEPA( | |
| encoder=encoder, | |
| predictor=predictor, | |
| action_encoder=action_encoder, | |
| projector=projector, | |
| pred_proj=predictor_proj, | |
| hyper_projector=hyper_projector, | |
| manifold=manifold, | |
| cone_loss=cone_loss, | |
| contrastive_loss=contrastive_loss, | |
| tangent_stabilization=OmegaConf.to_container( | |
| cfg.hyperbolic.stabilization, | |
| resolve=True, | |
| ), | |
| ) | |
| def resolve_accelerator(cfg) -> str: | |
| requested = str(cfg.trainer.get("accelerator", "auto")).lower() | |
| if requested == "auto": | |
| resolved = resolve_runtime_device("auto") | |
| with open_dict(cfg): | |
| cfg.trainer.accelerator = resolved | |
| print(f"[runtime] auto-selected accelerator={resolved}", flush=True) | |
| return resolved | |
| if requested == "gpu" and not torch.cuda.is_available(): | |
| resolved = resolve_runtime_device("auto") | |
| with open_dict(cfg): | |
| cfg.trainer.accelerator = resolved | |
| print( | |
| f"[runtime] accelerator=gpu requested but no CUDA backend is available; " | |
| f"falling back to accelerator={resolved}", | |
| flush=True, | |
| ) | |
| return resolved | |
| return requested | |
| def hyperbolic_forward(self, batch, stage, cfg): | |
| ctx_len = int(cfg.wm.history_size) | |
| n_preds = int(cfg.wm.num_preds) | |
| sigreg_weight = float(cfg.loss.sigreg.weight) | |
| loss_weights = cfg.hyperbolic.loss_weights | |
| rollout_cfg = cfg.hyperbolic.rollout | |
| batch["action"] = torch.nan_to_num( | |
| batch["action"], | |
| nan=0.0, | |
| posinf=0.0, | |
| neginf=0.0, | |
| ) | |
| output = self.model.encode(batch) | |
| emb = output["emb"] | |
| hyp_emb = output["hyp_emb"] | |
| act_emb = output["act_emb"] | |
| ctx_emb = emb[:, :ctx_len] | |
| ctx_act = act_emb[:, :ctx_len] | |
| tgt_emb = emb[:, n_preds:] | |
| tgt_hyp = hyp_emb[:, n_preds:] | |
| pred_emb = self.model.predict(ctx_emb, ctx_act) | |
| aligned_steps = min(pred_emb.size(1), tgt_emb.size(1)) | |
| if aligned_steps <= 0: | |
| raise ValueError( | |
| f"Expected at least one aligned prediction step, got pred={pred_emb.size(1)} target={tgt_emb.size(1)}." | |
| ) | |
| pred_emb = pred_emb[:, :aligned_steps] | |
| tgt_emb = tgt_emb[:, :aligned_steps] | |
| tgt_hyp = tgt_hyp[:, :aligned_steps] | |
| _, pred_hyp = self.model.to_hyperbolic(pred_emb) | |
| cone_offset = int(cfg.hyperbolic.cone_offset) | |
| cone_offset = max(1, min(cone_offset, hyp_emb.size(1) - 1)) | |
| parent_hyp = hyp_emb[:, :-cone_offset] | |
| child_hyp = hyp_emb[:, cone_offset:] | |
| cone_out = self.model.cone_loss(parent_hyp, child_hyp, self.model.manifold) | |
| contrastive_out = self.model.contrastive_loss(pred_hyp, tgt_hyp, self.model.manifold) | |
| output["pred_loss"] = self.model.manifold.dist(pred_hyp, tgt_hyp).pow(2).mean() | |
| output["tangent_loss"] = (pred_emb - tgt_emb).pow(2).mean() | |
| target_tangent_norm = float(cfg.hyperbolic.stabilization.target_norm) | |
| output["tangent_radius_loss"] = F.relu( | |
| output["scaled_tangent_norm"] - target_tangent_norm | |
| ).pow(2).mean() | |
| rollout_steps = 0 | |
| if bool(rollout_cfg.enabled): | |
| rollout_steps = min(int(rollout_cfg.steps), emb.size(1) - ctx_len) | |
| if rollout_steps > 0: | |
| rollout_pred_emb, rollout_pred_hyp = self.model.rollout_from_encoded( | |
| emb, | |
| act_emb, | |
| history_size=ctx_len, | |
| rollout_steps=rollout_steps, | |
| ) | |
| rollout_tgt_emb = emb[:, ctx_len : ctx_len + rollout_steps] | |
| rollout_tgt_hyp = hyp_emb[:, ctx_len : ctx_len + rollout_steps] | |
| output["rollout_loss"] = (rollout_pred_emb - rollout_tgt_emb).pow(2).mean() | |
| output["rollout_hyp_loss"] = ( | |
| self.model.manifold.dist(rollout_pred_hyp, rollout_tgt_hyp).pow(2).mean() | |
| ) | |
| else: | |
| output["rollout_loss"] = torch.zeros_like(output["tangent_loss"]) | |
| output["rollout_hyp_loss"] = torch.zeros_like(output["pred_loss"]) | |
| output["sigreg_loss"] = self.sigreg(emb.transpose(0, 1)) | |
| output.update(cone_out) | |
| output.update(contrastive_out) | |
| rollout_warmup_steps = int(rollout_cfg.warmup_steps) | |
| rollout_weight_scale = 1.0 | |
| if rollout_warmup_steps > 0: | |
| rollout_weight_scale = min( | |
| 1.0, | |
| float(int(getattr(self, "global_step", 0)) + 1) / float(rollout_warmup_steps), | |
| ) | |
| output["rollout_weight_scale"] = output["pred_loss"].new_tensor(rollout_weight_scale) | |
| output["loss"] = ( | |
| float(loss_weights.pred) * output["pred_loss"] | |
| + sigreg_weight * output["sigreg_loss"] | |
| + float(loss_weights.contrastive) * output["contrastive_loss"] | |
| + float(loss_weights.cone) * output["cone_loss"] | |
| + float(loss_weights.tangent) * output["tangent_loss"] | |
| + rollout_weight_scale * float(loss_weights.rollout) * output["rollout_loss"] | |
| + rollout_weight_scale * float(loss_weights.rollout_hyp) * output["rollout_hyp_loss"] | |
| + float(loss_weights.radius) * output["tangent_radius_loss"] | |
| ) | |
| if bool(cfg.hyperbolic.finite_guard.enabled): | |
| guarded_values = { | |
| key: value | |
| for key, value in output.items() | |
| if key.endswith("loss") | |
| or key | |
| in { | |
| "raw_tangent_norm", | |
| "scaled_tangent_norm", | |
| "bounded_tangent_norm", | |
| "tangent_saturation_fraction", | |
| } | |
| } | |
| bad_names = _non_finite_tensor_names(guarded_values) | |
| if bad_names: | |
| raise FloatingPointError( | |
| "Detected non-finite forward tensors before optimizer.step " | |
| f"at stage={stage} global_step={int(getattr(self, 'global_step', 0))}. " | |
| f"Affected tensors: {', '.join(bad_names)}." | |
| ) | |
| losses_dict = {f"{stage}/{k}": v.detach() for k, v in output.items() if "loss" in k} | |
| self.log_dict(losses_dict, on_step=True, on_epoch=True, sync_dist=True) | |
| metric_keys = { | |
| "contrastive_pos_dist", | |
| "contrastive_neg_dist", | |
| "cone_aperture", | |
| "parent_radius", | |
| "child_radius", | |
| "raw_tangent_norm_mean", | |
| "scaled_tangent_norm_mean", | |
| "bounded_tangent_norm_mean", | |
| "tangent_saturation_fraction_mean", | |
| "rollout_weight_scale", | |
| } | |
| output["raw_tangent_norm_mean"] = output["raw_tangent_norm"].mean() | |
| output["scaled_tangent_norm_mean"] = output["scaled_tangent_norm"].mean() | |
| output["bounded_tangent_norm_mean"] = output["bounded_tangent_norm"].mean() | |
| output["tangent_saturation_fraction_mean"] = output["tangent_saturation_fraction"].mean() | |
| metrics = {f"{stage}/{k}": v.detach() for k, v in output.items() if k in metric_keys} | |
| metrics[f"{stage}/curvature"] = self.model.manifold.curvature.detach() | |
| self.log_dict(metrics, on_step=True, on_epoch=True, sync_dist=True) | |
| return output | |
| def run_hyperbolic_training(cfg): | |
| ensure_hyperbolic_defaults(cfg) | |
| print( | |
| "[train] rollout loss config: " | |
| f"enabled={bool(cfg.hyperbolic.rollout.enabled)} " | |
| f"steps={int(cfg.hyperbolic.rollout.steps)} " | |
| f"warmup_steps={int(cfg.hyperbolic.rollout.warmup_steps)} " | |
| f"euclidean_weight={float(cfg.hyperbolic.loss_weights.rollout)} " | |
| f"hyperbolic_weight={float(cfg.hyperbolic.loss_weights.rollout_hyp)} " | |
| f"dataset.num_steps={int(cfg.data.dataset.num_steps)}", | |
| flush=True, | |
| ) | |
| print( | |
| "[train] tangent stabilization: " | |
| f"enabled={bool(cfg.hyperbolic.stabilization.enabled)} " | |
| f"scale_by_sqrt_dim={bool(cfg.hyperbolic.stabilization.scale_by_sqrt_dim)} " | |
| f"max_norm={float(cfg.hyperbolic.stabilization.max_norm)} " | |
| f"target_norm={float(cfg.hyperbolic.stabilization.target_norm)} " | |
| f"radius_weight={float(cfg.hyperbolic.loss_weights.radius)}", | |
| flush=True, | |
| ) | |
| accelerator_name = resolve_accelerator(cfg) | |
| maybe_enable_npu(accelerator_name) | |
| if str(accelerator_name).lower() == "npu": | |
| with open_dict(cfg): | |
| if cfg.trainer.get("devices", "auto") == "auto": | |
| cfg.trainer.devices = torch.npu.device_count() | |
| if cfg.loader.get("pin_memory", False): | |
| cfg.loader.pin_memory = False | |
| if bool(cfg.data_loading.get("use_sharded_dataset", True)): | |
| maybe_resolve_sharded_dataset(cfg) | |
| else: | |
| maybe_resolve_full_dataset(cfg) | |
| cache_keys = resolve_dataset_cache_keys(cfg) | |
| use_shared_cache = bool(cfg.data_loading.get("share_cache_across_ranks", False)) and len(cache_keys) > 0 | |
| dataset_kwargs = build_hdf5_dataset_kwargs(cfg, cache_keys=cache_keys, use_shared_cache=use_shared_cache) | |
| print( | |
| "[dataset-diag] loader_mode=" | |
| f"{'sharded' if bool(cfg.data_loading.get('use_sharded_dataset', True)) else 'full-dataset'} " | |
| f"cache_all_keys_in_memory={bool(cfg.data_loading.get('cache_all_keys_in_memory', False))} " | |
| f"share_cache_across_ranks={use_shared_cache} " | |
| f"keys_to_cache={cache_keys}", | |
| flush=True, | |
| ) | |
| dataset = swm.data.HDF5Dataset(**dataset_kwargs, transform=None) | |
| if use_shared_cache: | |
| attach_shared_cache_to_dataset(dataset, cache_keys=cache_keys, cfg=cfg) | |
| validate_hdf5_episode_metadata(dataset) | |
| skip_resize = dataset_has_preprocessed_pixels(dataset, cfg.img_size) | |
| print_dataset_diagnostics(dataset, skip_resize) | |
| transforms = [ | |
| get_img_preprocessor( | |
| source="pixels", | |
| target="pixels", | |
| img_size=cfg.img_size, | |
| resize=not skip_resize, | |
| ) | |
| ] | |
| with open_dict(cfg): | |
| for col in cfg.data.dataset.keys_to_load: | |
| if col.startswith("pixels"): | |
| continue | |
| transforms.append(get_column_normalizer(dataset, col, col)) | |
| setattr(cfg.wm, f"{col}_dim", dataset.get_dim(col)) | |
| dataset.transform = spt.data.transforms.Compose(*transforms) | |
| generator = torch.Generator().manual_seed(cfg.seed) | |
| train_set, val_set = spt.data.random_split( | |
| dataset, lengths=[cfg.train_split, 1 - cfg.train_split], generator=generator | |
| ) | |
| sequence_keys = tuple(cfg.data.dataset.keys_to_load) | |
| dataset_label = str(getattr(dataset, "h5_path", cfg.data.dataset.name)) | |
| train_set = SafeSequenceDataset( | |
| train_set, | |
| cfg.data.dataset.num_steps, | |
| sequence_keys, | |
| dataset_label=f"train:{dataset_label}", | |
| ) | |
| val_set = SafeSequenceDataset( | |
| val_set, | |
| cfg.data.dataset.num_steps, | |
| sequence_keys, | |
| dataset_label=f"val:{dataset_label}", | |
| ) | |
| loader_kwargs = OmegaConf.to_container(cfg.loader, resolve=True) | |
| if int(loader_kwargs.get("num_workers", 0)) == 0: | |
| loader_kwargs.pop("prefetch_factor", None) | |
| loader_kwargs["persistent_workers"] = False | |
| train_loader = torch.utils.data.DataLoader( | |
| train_set, | |
| **loader_kwargs, | |
| shuffle=True, | |
| drop_last=True, | |
| generator=generator, | |
| ) | |
| val_loader = torch.utils.data.DataLoader( | |
| val_set, | |
| **loader_kwargs, | |
| shuffle=False, | |
| drop_last=False, | |
| ) | |
| world_model = build_hyperbolic_world_model(cfg, action_dim=int(cfg.wm.action_dim)) | |
| optimizers = { | |
| "model_opt": { | |
| "modules": "model", | |
| "optimizer": dict(cfg.optimizer), | |
| "scheduler": {"type": "LinearWarmupCosineAnnealingLR"}, | |
| "interval": "epoch", | |
| }, | |
| } | |
| data_module = spt.data.DataModule(train=train_loader, val=val_loader) | |
| module = spt.Module( | |
| model=world_model, | |
| sigreg=SIGReg(**cfg.loss.sigreg.kwargs), | |
| forward=partial(hyperbolic_forward, cfg=cfg), | |
| optim=optimizers, | |
| ) | |
| run_id = cfg.get("subdir") or "" | |
| run_dir = Path(swm.data.utils.get_cache_dir(), run_id) | |
| logger = None | |
| if cfg.wandb.enabled and is_rank_zero_process(): | |
| logger = WandbLogger(**cfg.wandb.config) | |
| logger.log_hyperparams(OmegaConf.to_container(cfg)) | |
| run_dir.mkdir(parents=True, exist_ok=True) | |
| if is_rank_zero_process(): | |
| with open(run_dir / "config.yaml", "w") as handle: | |
| OmegaConf.save(cfg, handle) | |
| callbacks = [] | |
| if bool(cfg.get("dump_object", True)): | |
| callbacks.append( | |
| ModelObjectCallBack( | |
| dirpath=run_dir, | |
| filename=cfg.output_model_name, | |
| epoch_interval=1, | |
| ) | |
| ) | |
| callbacks.append( | |
| LossHistoryCallback( | |
| dirpath=run_dir, | |
| filename=f"{cfg.output_model_name}_losses.txt", | |
| ) | |
| ) | |
| if bool(cfg.hyperbolic.finite_guard.check_gradients): | |
| callbacks.append(NonFiniteGradientCallback()) | |
| trainer_kwargs = OmegaConf.to_container(cfg.trainer, resolve=True) | |
| num_sanity_val_steps = int(trainer_kwargs.pop("num_sanity_val_steps", 1)) | |
| enable_checkpointing = bool(trainer_kwargs.pop("enable_checkpointing", True)) | |
| if str(accelerator_name).lower() == "npu": | |
| npu_accelerator = NPUAccelerator() | |
| parsed_devices, parallel_devices = resolve_npu_devices(trainer_kwargs.get("devices", 1)) | |
| is_single_device = len(parsed_devices) == 1 | |
| trainer_kwargs.pop("accelerator", None) | |
| trainer_kwargs.pop("devices", None) | |
| if is_single_device: | |
| trainer_kwargs["strategy"] = SingleDeviceStrategy( | |
| device=parallel_devices[0], | |
| accelerator=npu_accelerator, | |
| ) | |
| else: | |
| trainer_kwargs["strategy"] = NPUDDPStrategy( | |
| accelerator=npu_accelerator, | |
| parallel_devices=parallel_devices, | |
| process_group_backend="hccl", | |
| start_method="popen", | |
| ) | |
| trainer = pl.Trainer( | |
| **trainer_kwargs, | |
| callbacks=callbacks, | |
| num_sanity_val_steps=num_sanity_val_steps, | |
| logger=logger, | |
| enable_checkpointing=enable_checkpointing, | |
| ) | |
| manager = spt.Manager( | |
| trainer=trainer, | |
| module=module, | |
| data=data_module, | |
| ckpt_path=run_dir / f"{cfg.output_model_name}_weights.ckpt", | |
| ) | |
| manager() | |
| def run(cfg): | |
| run_hyperbolic_training(cfg) | |
| def _main(): | |
| faulthandler.enable(all_threads=True) | |
| run() | |
| if __name__ == "__main__": | |
| _main() | |