# value_tokenizer.py from collections.abc import Mapping import torch def to_symlog(x: torch.Tensor) -> torch.Tensor: return torch.sign(x) * torch.log1p(torch.abs(x)) def to_symexp(x: torch.Tensor) -> torch.Tensor: return torch.sign(x) * torch.expm1(torch.abs(x)) def _cfg_get(config, key, default=None): """Read a field from a plain dict, an OmegaConf DictConfig or a PretrainedConfig. ``ValueTokenizerConfig`` is a ``PretrainedConfig``, which is neither subscriptable nor has ``.get``; the trainer passes a ``DictConfig`` and the tests pass plain dicts. """ if isinstance(config, Mapping): return config.get(key, default) return getattr(config, key, default) def _interp(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor: """Piecewise-linear interpolation (np.interp analogue), clamped at both ends.""" shape = x.shape xf = x.reshape(-1) idx = torch.searchsorted(xp, xf.contiguous(), right=False).clamp(1, xp.numel() - 1) x0 = xp[idx - 1] x1 = xp[idx] y0 = fp[idx - 1] y1 = fp[idx] t = ((xf - x0) / (x1 - x0).clamp_min(1e-12)).clamp(0.0, 1.0) affine = y0 + t * (y1 - y0) # `y0 + t*(y1-y0)` is monotone but not exact at t == 1: a subnormal knot # next to a large one rounds away. Bin identity is a frozen contract, so the # knot-aligned case must reproduce the knot bit-for-bit. return torch.where(t >= 1.0, y1, affine).reshape(shape) def make_quantile_transform(knots): """Build (forward, inverse) transforms from precomputed quantile knots. ``knots`` are strictly increasing values at equally spaced probability levels of the training-data value distribution (see tools/compute_value_quantiles.py). forward = piecewise-linear empirical CDF (value -> [0, 1]); bins uniform in this warped space are therefore equal-probability-mass (quantile) bins in value space. The knots must be computed once offline and FROZEN for the whole run, since bin identity is part of the checkpoint contract. """ knots_t = torch.tensor(list(knots), dtype=torch.float32) if knots_t.ndim != 1 or knots_t.numel() < 2: raise ValueError("quantile_knots must be a 1-D sequence with >= 2 values") if not torch.all(knots_t[1:] > knots_t[:-1]): raise ValueError("quantile_knots must be strictly increasing") levels_t = torch.linspace(0.0, 1.0, knots_t.numel(), dtype=torch.float32) def forward(x: torch.Tensor) -> torch.Tensor: return _interp( x, knots_t.to(device=x.device, dtype=x.dtype), levels_t.to(device=x.device, dtype=x.dtype), ) def inverse(u: torch.Tensor) -> torch.Tensor: return _interp( u, levels_t.to(device=u.device, dtype=u.dtype), knots_t.to(device=u.device, dtype=u.dtype), ) return forward, inverse def make_bin_values(config) -> torch.Tensor: """Build the value-space bin centers for a value-tokenizer config. Every ``support_transform`` yields a sorted 1-D tensor of ``bins`` representative values in ORIGINAL value space; ``ValueTokenizer`` then only discretizes against this list and stays agnostic of the transform: * ``linear`` — equally spaced in value space. * ``symlog`` — equally spaced in symlog space, mapped back by symexp. * ``quantile``— inverse empirical CDF at equally spaced probability levels, i.e. the value-space bin centers are the quantiles themselves (equal-mass bins). The support follows the knots; ``min_value`` / ``max_value`` are ignored. """ mode = _cfg_get(config, "support_transform", "linear") bins = int(_cfg_get(config, "bins", 256)) if mode == "linear": return torch.linspace( float(_cfg_get(config, "min_value")), float(_cfg_get(config, "max_value")), bins, dtype=torch.float32, ) if mode == "symlog": lo = to_symlog(torch.tensor(float(_cfg_get(config, "min_value")), dtype=torch.float32)) hi = to_symlog(torch.tensor(float(_cfg_get(config, "max_value")), dtype=torch.float32)) return to_symexp(torch.linspace(float(lo), float(hi), bins, dtype=torch.float32)) if mode == "quantile": knots = _cfg_get(config, "quantile_knots") if knots is None: raise ValueError( "support_transform='quantile' requires quantile_knots " "(precompute them with tools/compute_value_quantiles.py and point " "quantile_knots_path at the result; the trainer inlines it)" ) _forward, inverse = make_quantile_transform(knots) levels = torch.linspace(0.0, 1.0, bins, dtype=torch.float32) return inverse(levels) raise ValueError(f"unknown support_transform: {mode!r}") class ValueTokenizer: """ Tokenizer for continuous scalar values via discretization onto a fixed set of value-space bin centers. The bin centers (``bin_values``) are computed OUTSIDE by ``make_bin_values`` for the chosen support transform (linear / symlog / quantile). This class is transform-agnostic: it only maps a scalar to the nearest / two adjacent centers and back. Everything is interpreted in ORIGINAL value space, so the two-hot soft label and the expectation decode are exact inverses there (no nonlinear-warp Jensen gap). """ def __init__( self, bin_values, device=None, dtype=torch.float32, ) -> None: if dtype not in (torch.float32, torch.float64): # bfloat16 collapses adjacent quantile knots (a subnormal knot next # to 0 rounds to 0), silently destroying bin identity. raise ValueError( f"ValueTokenizer requires float32 or float64, got {dtype}." ) if not isinstance(bin_values, torch.Tensor): bin_values = torch.tensor(bin_values) bin_values = bin_values.to(dtype=dtype, device=device).reshape(-1) if bin_values.numel() < 1: raise ValueError("bin_values must have at least 1 entry") if bin_values.numel() > 1 and not torch.all(bin_values[1:] > bin_values[:-1]): gaps = bin_values[1:] - bin_values[:-1] raise ValueError( f"bin_values must be strictly increasing; got {bin_values.numel()} " f"centers with min adjacent gap {float(gaps.min()):.3e} at index " f"{int(gaps.argmin())} (dtype={dtype}). For " "support_transform='quantile' this usually means `bins` " "over-samples the quantile knots: reduce bins, or regenerate the " "knots with more separation." ) self.bin_values = bin_values self.n_bins = int(bin_values.numel()) self.min_val = float(bin_values[0]) self.max_val = float(bin_values[-1]) self.device = device self.dtype = dtype @classmethod def from_config(cls, config, **kwargs): """Build from a config (dict / DictConfig / ValueTokenizerConfig); None -> None.""" if config is None: return None return cls(bin_values=make_bin_values(config), **kwargs) def _to_tensor(self, x, device=None): if isinstance(x, torch.Tensor): return x.to(device=device if device is not None else x.device, dtype=self.dtype) return torch.tensor( x, dtype=self.dtype, device=device if device is not None else self.device, ) def encode_two_hot(self, value: torch.Tensor) -> torch.Tensor: """ Convert scalar values into a two-hot distribution over bins. The value is expressed as a convex combination of the two adjacent value-space bin centers that bracket it, so the expectation over bins reconstructs the value exactly in value space. Args: value: Tensor with shape (...,) Returns: Tensor with shape (..., n_bins) """ value = self._to_tensor(value) device = value.device bin_values = self.bin_values.to(device=device, dtype=self.dtype) value = torch.clamp(value, min=self.min_val, max=self.max_val) shape = value.shape v = value.reshape(-1) pos = torch.searchsorted(bin_values, v.contiguous(), right=False).clamp(1, self.n_bins - 1) lower_idx = pos - 1 upper_idx = pos lower = bin_values[lower_idx] upper = bin_values[upper_idx] weight_upper = ((v - lower) / (upper - lower).clamp_min(1e-12)).clamp(0.0, 1.0) weight_lower = 1.0 - weight_upper target_dist = torch.zeros(v.numel(), self.n_bins, dtype=self.dtype, device=device) target_dist.scatter_add_( dim=-1, index=lower_idx.unsqueeze(-1), src=weight_lower.unsqueeze(-1) ) target_dist.scatter_add_( dim=-1, index=upper_idx.unsqueeze(-1), src=weight_upper.unsqueeze(-1) ) target_dist = target_dist / target_dist.sum(dim=-1, keepdim=True).clamp_min(1e-12) return target_dist.reshape(*shape, self.n_bins) def encode_index(self, value: torch.Tensor) -> torch.Tensor: """Map scalar values to the nearest bin index. Args: value: Tensor with shape (...,) Returns: LongTensor with shape (...,) holding indices in [0, n_bins - 1]. """ value = self._to_tensor(value) device = value.device bin_values = self.bin_values.to(device=device, dtype=self.dtype) value = torch.clamp(value, min=self.min_val, max=self.max_val) shape = value.shape v = value.reshape(-1) pos = torch.searchsorted(bin_values, v.contiguous(), right=False).clamp(1, self.n_bins - 1) lower_idx = pos - 1 lower = bin_values[lower_idx] upper = bin_values[pos] idx = torch.where(v - lower <= upper - v, lower_idx, pos) return idx.reshape(shape).long().clamp(0, self.n_bins - 1) def decode_from_bins(self, bin_logits: torch.Tensor) -> torch.Tensor: """ Decode scalar predictions from bin logits. Args: bin_logits: Tensor with shape (..., n_bins) Returns: Tensor with shape (...,) """ bin_logits = bin_logits.float() if bin_logits.shape[-1] != self.n_bins: raise ValueError( f"Expected bin_logits last dim == n_bins ({self.n_bins}), got {bin_logits.shape[-1]}" ) probs = torch.softmax(bin_logits, dim=-1) bin_values = self.bin_values.to(device=bin_logits.device, dtype=bin_logits.dtype) return torch.sum(probs * bin_values, dim=-1) def decode_index(self, idx: torch.Tensor) -> torch.Tensor: """Decode discrete bin indices to scalar values (each bin's center). Inverse of ``encode_index``: reads the value-space center of a single hard bin per element — unlike ``decode_from_bins`` (a softmax expectation over bin *logits*). Args: idx: integer Tensor with shape (...,) holding indices in [0, n_bins - 1]. Returns: Tensor with shape (...,) of decoded scalars. """ if not isinstance(idx, torch.Tensor): idx = torch.tensor(idx) idx = idx.long().clamp(0, self.n_bins - 1) bin_values = self.bin_values.to(idx.device) return bin_values[idx]