File size: 1,443 Bytes
127ebd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""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)