Celestis-RL / src /celestis_rl /scoring.py
PureOne's picture
Release Celestis-RL v2.0.0: audited research reference
f95cbd4 verified
Raw History Blame Contribute Delete
3.25 kB
"""Chunked forward normalization with an exactly cancelled normalizer backward."""
from dataclasses import dataclass
import torch
from torch import Tensor
@dataclass
class SelectedScores:
logits: Tensor
log_probs: Tensor # detached: coefficient computation only
log_normalizer: Tensor # detached
def selected_linear_scores(hidden: Tensor, weight: Tensor, ids: Tensor, *,
bias: Tensor | None = None, chunk_size: int = 4096,
temperature: float = 1.0) -> SelectedScores:
"""Score [N,K] IDs from h[N,D], W[V,D] without a dense backward graph.
Exact softmax normalization still costs O(NVD) forward work, with a
[N,chunk_size] workspace. Gathered head activations cost O(NKD).
This is a portable reference, not a fused CUDA kernel. It assumes a linear
output head; apply all other logit transforms consistently outside it.
"""
import math
if hidden.ndim != 2 or weight.ndim != 2 or hidden.shape[1] != weight.shape[1]:
raise ValueError("hidden [N,D] and output weight [V,D] required")
if ids.ndim != 2 or ids.shape[0] != hidden.shape[0] or ids.dtype != torch.long:
raise ValueError("ids [N,K] must be int64")
if hidden.device != weight.device or ids.device != hidden.device:
raise ValueError("all tensors must share a device")
if not hidden.is_floating_point() or not weight.is_floating_point():
raise ValueError("floating point model tensors required")
if ids.numel() == 0 or ((ids < 0) | (ids >= weight.shape[0])).any():
raise ValueError("selected IDs must be nonempty and in range")
if isinstance(chunk_size, bool) or not isinstance(chunk_size, int) or chunk_size < 1:
raise ValueError("chunk_size must be a positive integer")
if not math.isfinite(temperature) or temperature <= 0:
raise ValueError("temperature must be positive and finite")
if bias is not None and (bias.shape != (weight.shape[0],) or bias.device != weight.device):
raise ValueError("bias shape/device mismatch")
dtype = torch.float64 if hidden.dtype == torch.float64 or weight.dtype == torch.float64 else torch.float32
h = hidden.to(dtype)
# Avoid a full FP32 copy of a reduced-precision output head.
selected_weight = weight[ids].to(dtype)
selected = (h[:, None, :] * selected_weight).sum(-1)
if bias is not None:
selected = selected + bias[ids].to(dtype)
selected = selected / temperature
with torch.no_grad():
normalizer = torch.full((len(h),), -torch.inf, dtype=dtype, device=h.device)
for start in range(0, len(weight), chunk_size):
stop = min(start+chunk_size, len(weight))
scores = h.detach() @ weight[start:stop].to(dtype).T
if bias is not None:
scores += bias[start:stop].to(dtype)
scores /= temperature
normalizer = torch.logaddexp(normalizer, torch.logsumexp(scores, -1))
if not torch.isfinite(normalizer).all() or not torch.isfinite(selected).all():
raise FloatingPointError("nonfinite output-head scores")
log_probs = selected.detach() - normalizer[:, None]
return SelectedScores(selected, log_probs, normalizer)