torch_world.utils
INFO
Esta página ainda não foi traduzida. Leia em inglês
function fit
fit(
model: nn.Module,
loader: Iterable,
epochs: int,
lr: float = 0.0005,
weight_decay: float = 0.001,
inputs: Callable | None = None,
clip: float | None = None,
step: Callable[[], None] | None = None,
monitor: Monitor | None = None,
) -> dict[str, list[float]]Train model with AdamW for epochs over loader; returns every logged loss, one value per step.
inputs(batch) gives the model's positional arguments, (batch["pixels"], batch["actions"]) by default. Every output named loss or *_loss is logged, and monitor, for example a TensorBoardMonitor or RerunMonitor, receives each of them as a scalar, one call per optimizer step. clip clips the gradient norm, and step() runs after every optimizer step, for example an EMA target update. At the end, BatchNorm statistics are recomputed on 50 batches and the model is put in eval mode, ready to plan with.
Source code in torch_world/utils/training.py
def fit(
model: nn.Module,
loader: Iterable,
epochs: int,
lr: float = 5e-4,
weight_decay: float = 1e-3,
inputs: Callable | None = None,
clip: float | None = None,
step: Callable[[], None] | None = None,
monitor: Monitor | None = None,
) -> dict[str, list[float]]:
"""Train ``model`` with AdamW for ``epochs`` over ``loader``; returns every logged loss, one value per step.
``inputs(batch)`` gives the model's positional arguments, ``(batch["pixels"], batch["actions"])`` by default. Every
output named ``loss`` or ``*_loss`` is logged, and ``monitor``, for example a ``TensorBoardMonitor`` or
``RerunMonitor``, receives each of them as a scalar, one call per optimizer step. ``clip`` clips the gradient
norm, and ``step()`` runs after every optimizer step, for example an EMA target update. At the end, BatchNorm
statistics are recomputed on 50 batches and the model is put in eval mode, ready to plan with.
"""
inputs = inputs or (lambda batch: (batch["pixels"], batch["actions"]))
params = [p for p in model.parameters() if p.requires_grad]
opt = torch.optim.AdamW(params, lr=lr, weight_decay=weight_decay)
log: dict[str, list[float]] = {}
steps = 0
model.train()
for _ in range(epochs):
for batch in loader:
out = model(*inputs(batch))
opt.zero_grad()
out["loss"].backward()
if clip is not None:
nn.utils.clip_grad_norm_(params, clip)
opt.step()
if step is not None:
step()
for k, v in out.items():
if k == "loss" or k.endswith("_loss"):
value = v.item()
log.setdefault(k.removesuffix("_loss"), []).append(value)
if monitor is not None:
monitor.scalar(steps, k.removesuffix("_loss"), value)
steps += 1
if any(isinstance(m, nn.modules.batchnorm._BatchNorm) for m in model.modules()):
recompute_batchnorm(model, itertools.islice(loader, 50), lambda batch: model(*inputs(batch)))
model.eval()
return logclass Monitor
Monitor()A training monitor: scalar for a curve, video for a clip (B, T, 3, H, W) in [0, 1].
Source code in torch_world/utils/monitor.py
class Monitor(Protocol):
"""A training monitor: ``scalar`` for a curve, ``video`` for a clip ``(B, T, 3, H, W)`` in ``[0, 1]``."""
def scalar(self, step: int, name: str, value: float) -> None: ...
def video(self, step: int, name: str, tensor: Tensor, fps: int = 12) -> None: ...
def close(self) -> None: ...class NullMonitor
NullMonitor()The default monitor: every method is a no-op, so monitoring stays opt-in.
Source code in torch_world/utils/monitor.py
class NullMonitor:
"""The default monitor: every method is a no-op, so monitoring stays opt-in."""
def scalar(self, step: int, name: str, value: float) -> None:
pass
def video(self, step: int, name: str, tensor: Tensor, fps: int = 12) -> None:
pass
def close(self) -> None:
passclass TensorBoardMonitor
TensorBoardMonitor(dir: str | Path, **kwargs)Curves to TensorBoard event files under dir; watch them with tensorboard --logdir dir.
Videos need moviepy; without it, every frame becomes an image summary name/frame_000, ... instead.
Source code in torch_world/utils/monitor.py
class TensorBoardMonitor:
"""Curves to TensorBoard event files under ``dir``; watch them with ``tensorboard --logdir dir``.
Videos need ``moviepy``; without it, every frame becomes an image summary ``name/frame_000``, ... instead.
"""
def __init__(self, dir: str | Path, **kwargs):
try:
from torch.utils.tensorboard import SummaryWriter
except ImportError as e:
raise ImportError(
"TensorBoardMonitor needs the tensorboard extra: pip install 'torch-world[tensorboard]'"
) from e
self._writer = SummaryWriter(str(dir), **kwargs)
self._moviepy = importlib.util.find_spec("moviepy") is not None
self._warned = False
def scalar(self, step: int, name: str, value: float) -> None:
self._writer.add_scalar(name, value, step)
def video(self, step: int, name: str, tensor: Tensor, fps: int = 12) -> None:
x = tensor.clamp(0, 1)
if self._moviepy:
self._writer.add_video(name, x, step, fps=fps)
return
if not self._warned:
print("TensorBoardMonitor: moviepy is not installed; logging videos as one image per frame", flush=True)
self._warned = True
for t, frame in enumerate(x[0]): # the first clip of the batch, one image summary per frame
u8 = (frame * 255).clamp(0, 255).to(torch.uint8)
self._writer.add_images(f"{name}/frame_{t:03d}", u8[None], step)
def close(self) -> None:
self._writer.close()class RerunMonitor
RerunMonitor(destination: str | Path = "spawn")Curves and videos to a Rerun viewer; needs the rerun extra: pip install 'torch-world[rerun]'.
destination is "spawn" for a viewer on this machine, "rerun+http://host:9876/proxy" to stream to a remote one (run rerun on your laptop, train on the GPU box), or a .rrd path to record to file and open later with rerun file.rrd. Scalars land on the step timeline and each video call appends its frames to the frame timeline, so one entity plays everything logged under that name, in order.
Source code in torch_world/utils/monitor.py
class RerunMonitor:
"""Curves and videos to a Rerun viewer; needs the rerun extra: ``pip install 'torch-world[rerun]'``.
``destination`` is ``"spawn"`` for a viewer on this machine, ``"rerun+http://host:9876/proxy"`` to stream to a
remote one (run ``rerun`` on your laptop, train on the GPU box), or a ``.rrd`` path to record to file and open
later with ``rerun file.rrd``. Scalars land on the ``step`` timeline and each ``video`` call appends its frames
to the ``frame`` timeline, so one entity plays everything logged under that name, in order.
"""
def __init__(self, destination: str | Path = "spawn"):
try:
import rerun as rr
except ImportError as e:
raise ImportError("RerunMonitor needs the rerun extra: pip install 'torch-world[rerun]'") from e
self._rr = rr
where = str(destination)
rr.init("torch-world")
if where == "spawn":
rr.spawn()
elif where.startswith(("rerun://", "rerun+http://", "rerun+https://")):
rr.connect_grpc(where)
else:
Path(where).parent.mkdir(parents=True, exist_ok=True)
rr.save(where)
self._frame = 0
def scalar(self, step: int, name: str, value: float) -> None:
self._rr.set_time("step", sequence=step)
self._rr.log(name, self._rr.Scalars([float(value)]))
def video(self, step: int, name: str, tensor: Tensor, fps: int = 12) -> None:
for b, clip in enumerate(tensor.detach().cpu().clamp(0, 1)):
for t, frame in enumerate(clip):
self._rr.set_time("step", sequence=step)
self._rr.set_time("frame", duration=(self._frame + t) / fps)
u8 = (frame * 255).round().clamp(0, 255).to(torch.uint8)
self._rr.log(f"{name}/{b}", self._rr.Tensor(u8, dim_names=["channel", "height", "width"]))
self._frame += tensor.size(1)
def close(self) -> None:
self._rr.disconnect()function open_monitor
open_monitor(
backend: str, dir: str | Path = "runs", rerun: str | Path = "spawn"
) -> MonitorA monitor by backend name: "none", "tensorboard" (event files under dir) or "rerun".
This is what the dreamzero train command's --monitor flag uses.
Source code in torch_world/utils/monitor.py
def open_monitor(backend: str, dir: str | Path = "runs", rerun: str | Path = "spawn") -> Monitor:
"""A monitor by backend name: ``"none"``, ``"tensorboard"`` (event files under ``dir``) or ``"rerun"``.
This is what the ``dreamzero`` train command's ``--monitor`` flag uses.
"""
if backend == "none":
return NullMonitor()
if backend == "tensorboard":
return TensorBoardMonitor(dir)
if backend == "rerun":
return RerunMonitor(rerun)
raise ValueError(f"Unknown monitor backend {backend!r}; use 'none', 'tensorboard' or 'rerun'")function ema_update
ema_update(target: nn.Module, online: nn.Module, momentum: float)target <- momentum * target + (1 - momentum) * online, parameter-wise.
Source code in torch_world/utils/ema.py
@torch.no_grad()
def ema_update(target: nn.Module, online: nn.Module, momentum: float):
"""``target <- momentum * target + (1 - momentum) * online``, parameter-wise."""
for t, o in zip(target.parameters(), online.parameters()):
t.lerp_(o.detach(), 1.0 - momentum)function linear_schedule
linear_schedule(start: float, end: float, step: int, total: int) -> floatSource code in torch_world/utils/ema.py
def linear_schedule(start: float, end: float, step: int, total: int) -> float:
return start + (end - start) * min(step, total) / totalfunction recompute_batchnorm
recompute_batchnorm(model: nn.Module, inputs: Iterable, forward: Callable)Re-estimate BatchNorm running statistics as exact averages of forward(x) over inputs.
Running averages lag behind features that move during training; call this before evaluating in eval mode.
Source code in torch_world/utils/batchnorm.py
@torch.no_grad()
def recompute_batchnorm(model: nn.Module, inputs: Iterable, forward: Callable):
"""Re-estimate BatchNorm running statistics as exact averages of ``forward(x)`` over ``inputs``.
Running averages lag behind features that move during training; call this before evaluating in eval mode.
"""
norms = [m for m in model.modules() if isinstance(m, nn.modules.batchnorm._BatchNorm)]
momenta = [m.momentum for m in norms]
for m in norms:
m.reset_running_stats()
m.momentum = None
training = model.training
model.train()
for x in inputs:
forward(x)
for m, momentum in zip(norms, momenta):
m.momentum = momentum
model.train(training)