Download src/discerna/model/head.py from CrazyH0rse/Discerna-v1-475M: direct link, hf CLI and curl.
- Browser
- Download file 1.54 kB
-
https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/model/head.py
- Command line
-
hf download hf://CrazyH0rse/Discerna-v1-475M/src/discerna/model/head.py
-
curl -L -o head.py https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/model/head.py
1.54 kB
| """Decision heads: trunk hidden states -> one logit per option slot. | |
| Adapted from LiquidAI/d1-omni-600M `encoder.py` (LFM Open License v1.0, see LICENSE). | |
| `MarkerHead` adds a question-type embedding, runs pre-norm transformer layers over the text | |
| positions, and scores the hidden state at each option marker with one shared MLP. | |
| """ | |
| from __future__ import annotations | |
| import torch | |
| import torch.nn as nn | |
| class MarkerHead(nn.Module): | |
| def __init__(self, hidden_size: int, layers: int = 2, num_types: int = 3): | |
| super().__init__() | |
| d = hidden_size | |
| self.type_emb = nn.Embedding(num_types, d) | |
| layer = nn.TransformerEncoderLayer(d, d // 64, 4 * d, 0.0, batch_first=True, norm_first=True) | |
| self.head = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False) | |
| self.scorer = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, d), nn.GELU(), nn.Linear(d, 1)) | |
| def forward(self, h: torch.Tensor, pad: torch.Tensor, marker_pos: torch.Tensor, marker_mask: torch.Tensor, | |
| qtype: torch.Tensor) -> torch.Tensor: | |
| """`h` (B, L, D) text hidden states, `pad` (B, L), `marker_pos`/`marker_mask` (B, K), `qtype` (B,). | |
| Returns (B, K) float32 logits, -1e4 on empty slots.""" | |
| h = h + self.type_emb(qtype)[:, None, :] | |
| for layer in self.head.layers: | |
| h = layer(h, src_key_padding_mask=~pad) | |
| g = torch.gather(h, 1, marker_pos[:, :, None].expand(-1, -1, h.size(-1))) | |
| return self.scorer(g).squeeze(-1).float().masked_fill(~marker_mask, -1e4) | |