|
23 | 23 | from __future__ import annotations |
24 | 24 |
|
25 | 25 | import math |
| 26 | +from typing import Any |
26 | 27 |
|
27 | 28 | import torch |
28 | 29 | import torch.nn as nn |
29 | 30 |
|
| 31 | +from kempnerforge.config.registry import registry |
30 | 32 |
|
31 | | -class FrameTimeEmbedding(nn.Module): |
| 33 | + |
| 34 | +class TimeEmbedding(nn.Module): |
| 35 | + """Base for per-frame timestamp embeddings (the *additive* family). |
| 36 | +
|
| 37 | + Contract: ``forward(times: (B, F) seconds) -> (B, F, dim)`` — an additive |
| 38 | + embedding added to each frame's visual tokens, with **no change to sequence |
| 39 | + length** — plus ``reset_parameters()`` so meta-device builds can re-init |
| 40 | + after ``to_empty``. Register a new technique with |
| 41 | + ``@registry.register_time_embedding`` and select it via |
| 42 | + ``[time_embedding].type``; ``build_time_embedding`` dispatches through the |
| 43 | + registry. |
| 44 | +
|
| 45 | + Out of scope (a separate, future integration point): sequence-*modifying* |
| 46 | + time encodings — e.g. Molmo2-style textual time-tokens interleaved between |
| 47 | + frame groups — change the token sequence (count / ``output_slice`` / |
| 48 | + ``modality_ids`` / MoT split) and need tokenizer + interleaved-sequence |
| 49 | + support KF does not have yet. Those would hook the sequence-assembly layer |
| 50 | + (``ModalityStrategy.prepare``), not this additive registry; set |
| 51 | + ``[time_embedding].type = "none"`` to run them instead of an additive one. |
| 52 | + """ |
| 53 | + |
| 54 | + def forward(self, times: torch.Tensor) -> torch.Tensor: # pragma: no cover - interface |
| 55 | + raise NotImplementedError |
| 56 | + |
| 57 | + def reset_parameters(self) -> None: # pragma: no cover - interface |
| 58 | + raise NotImplementedError |
| 59 | + |
| 60 | + |
| 61 | +class FrameTimeEmbedding(TimeEmbedding): |
32 | 62 | """Sinusoidal embedding of a per-frame timestamp (seconds) -> model dim. |
33 | 63 |
|
34 | 64 | Args: |
@@ -93,3 +123,37 @@ def forward(self, times: torch.Tensor) -> torch.Tensor: |
93 | 123 | ang = times.to(torch.float32).unsqueeze(-1) * (2.0 * math.pi / periods) # (B, F, bands) |
94 | 124 | feats = torch.cat([torch.sin(ang), torch.cos(ang)], dim=-1) # (B, F, 2*bands) |
95 | 125 | return self.proj(feats.to(self.proj.weight.dtype)) |
| 126 | + |
| 127 | + |
| 128 | +@registry.register_time_embedding("sinusoidal") |
| 129 | +def _build_sinusoidal( |
| 130 | + dim: int, |
| 131 | + *, |
| 132 | + num_bands: int = 16, |
| 133 | + min_period: float = 0.5, |
| 134 | + max_period: float = 256.0, |
| 135 | + **_: Any, |
| 136 | +) -> FrameTimeEmbedding: |
| 137 | + """Registry builder for the sinusoidal time embedding.""" |
| 138 | + return FrameTimeEmbedding( |
| 139 | + dim, num_bands=num_bands, min_period=min_period, max_period=max_period |
| 140 | + ) |
| 141 | + |
| 142 | + |
| 143 | +def build_time_embedding(time_embedding_config: Any, dim: int) -> TimeEmbedding | None: |
| 144 | + """Build the per-frame time embedding from a ``TimeEmbeddingConfig``. |
| 145 | +
|
| 146 | + Returns ``None`` when disabled (``type == "none"``). A ``None`` config falls |
| 147 | + back to the default (sinusoidal) so video callers that pass nothing keep the |
| 148 | + default behavior. The config is duck-typed (``.enabled`` / ``.type`` / |
| 149 | + ``.extra_kwargs()``) to avoid a model->config import cycle, matching |
| 150 | + ``build_adapter``. |
| 151 | + """ |
| 152 | + if time_embedding_config is None: |
| 153 | + from kempnerforge.config.time_embedding import TimeEmbeddingConfig # noqa: PLC0415 |
| 154 | + |
| 155 | + time_embedding_config = TimeEmbeddingConfig() |
| 156 | + if not time_embedding_config.enabled: |
| 157 | + return None |
| 158 | + builder = registry.get_time_embedding(time_embedding_config.type) |
| 159 | + return builder(dim, **time_embedding_config.extra_kwargs()) |
0 commit comments