deepedu's picture
BunGPT-DeepEdu-Decision-4B-Open
127ebd5 verified
Raw History Blame Contribute Delete
1.44 kB
"""The score head and the readout from scores to probabilities."""
from __future__ import annotations
from pathlib import Path
import torch
from safetensors.torch import load_file
HEAD_FILE = "score_head.safetensors"
class MLPHead(torch.nn.Module):
"""Linear(hidden, 1024) -> SiLU -> Linear(1024, 1), fp32: one raw score z per readout vector."""
def __init__(self, hidden: int, width: int = 1024):
super().__init__()
self.fc, self.out = torch.nn.Linear(hidden, width), torch.nn.Linear(width, 1)
def forward(self, vectors: torch.Tensor) -> torch.Tensor:
return self.out(torch.nn.functional.silu(self.fc(vectors.float())))
def load_head(source: Path, hidden: int) -> MLPHead:
path = source / HEAD_FILE
if not path.exists():
raise ValueError(f"{source} has no {HEAD_FILE}")
head = MLPHead(hidden)
head.load_state_dict(load_file(str(path)))
return head
def probabilities(z: torch.Tensor, temperature: float = 1.0, readout: str = "softmax") -> torch.Tensor:
"""Option probabilities from one question's scores ``z`` [n_options].
``softmax``: softmax(z/T). ``rcr``: sigmoid(z/T) divided by its sum over the options."""
z = z.float() / temperature
if readout == "softmax":
return torch.softmax(z, dim=-1)
if readout != "rcr":
raise ValueError(f"unknown readout {readout!r}")
s = torch.sigmoid(z)
return s / s.sum(-1, keepdim=True)