Download src/discerna/model/decision_model.py from CrazyH0rse/Discerna-v1-475M: direct link, hf CLI and curl.
- Browser
- Download file 7.97 kB
-
https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/model/decision_model.py
- Command line
-
hf download hf://CrazyH0rse/Discerna-v1-475M/src/discerna/model/decision_model.py
-
curl -L -o decision_model.py https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/model/decision_model.py
7.97 kB
| """The decision model: codec + trunk + head + vision encoder + calibrator, assembled from parts. | |
| Adapted from LiquidAI/d1-omni-600M `modeling_d1.py` (LFM Open License v1.0, see LICENSE). | |
| Modified: assembled from separate parts; batching bounded by tokens and attention size. | |
| Rows (one question over one state, with its media prefix) are sorted by length and packed | |
| into batches under a token budget. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| import torch | |
| import torch.nn as nn | |
| from discerna.contract import DecisionRequest, Question | |
| from discerna.model.calibration import BucketTemperature | |
| from discerna.model.codec import Encoded, MarkerCodec | |
| class Row: | |
| prefix: torch.Tensor | None # (1, P, D) media embeddings, shared by the request's questions | |
| encoded: Encoded | |
| question: Question | |
| def length(self) -> int: | |
| return (0 if self.prefix is None else self.prefix.shape[1]) + len(self.encoded.ids) | |
| class DecisionModel(nn.Module): | |
| def __init__(self, trunk: nn.Module, head: nn.Module, codec: MarkerCodec, vision: nn.Module | None = None, | |
| calibrator: BucketTemperature | None = None, max_length: int = 16384, | |
| image_text_length: int = 896, max_tokens: int = 65536, spec: dict | None = None): | |
| super().__init__() | |
| self.encoder, self.head, self.vision = trunk, head, vision | |
| self.codec, self.calibrator = codec, calibrator or BucketTemperature() | |
| self.max_length, self.image_text_length, self.max_tokens = max_length, image_text_length, max_tokens | |
| self.spec = spec or {} # how to rebuild this architecture (see discerna.model.weights); saved with checkpoints | |
| # Pad each batch's length (and marker count) up to a multiple of this, so a backend that compiles a | |
| # kernel per tensor shape (Apple MPS) sees few shapes. Padding is masked; None keeps exact shapes. | |
| self.pad_to_multiple: int | None = None | |
| # Batches also stay under this many attention-score elements (heads x rows x length^2). The kernel | |
| # expands the (rows, 1, L, L) mask per head: four 9k-token rows asked for 10.2 GiB and ran a 24 GB | |
| # GPU out of memory. A row alone may exceed it. Runtime only, never saved with the model. | |
| self.max_attention_elements = 2**30 | |
| def device(self) -> torch.device: | |
| return self.encoder.embed_tokens.weight.device | |
| def text_limit(self, prefix: int, media: bool, max_length: int | None = None) -> int: | |
| """Most text tokens a row may hold next to `prefix` media positions. `max_length` caps whole rows | |
| below the model's own limit (training uses it to bound memory); it is never saved with the model.""" | |
| limit = self.max_length if max_length is None else min(max_length, self.max_length) | |
| text = min(self.image_text_length if media else limit, limit - prefix) | |
| if text < 64: | |
| raise ValueError(f"the media take {prefix} of the {limit} positions; send fewer images") | |
| return text | |
| def rows(self, request: DecisionRequest, max_length: int | None = None) -> list[Row]: | |
| """Encode the request's media once and each of its questions against the state.""" | |
| prefix, media = None, None | |
| if request.images: | |
| if self.vision is None: | |
| raise ValueError("this model has no vision encoder") | |
| prefix, media = self.vision(list(request.images)), "image" | |
| max_len = self.text_limit(0 if prefix is None else prefix.shape[1], media is not None, max_length) | |
| return [Row(prefix, self.codec.encode(request.state, q, max_len, media), q) | |
| for q in request.questions.values()] | |
| def logits(self, rows: list[Row]) -> list[torch.Tensor]: | |
| """One padded forward pass over `rows`: each row's (K,) float32 option logits, in model slot order.""" | |
| device, dtype = self.device, self.encoder.embed_tokens.weight.dtype | |
| seqs, lengths, offsets = [], [], [] | |
| for row in rows: | |
| text = self.encoder.embed_tokens(torch.tensor(row.encoded.ids, device=device)) | |
| seqs.append(text if row.prefix is None else torch.cat([row.prefix[0].to(dtype), text])) | |
| offsets.append(0 if row.prefix is None else row.prefix.shape[1]) | |
| lengths.append(len(row.encoded.ids)) | |
| h = self._pad_length(torch.nn.utils.rnn.pad_sequence(seqs, batch_first=True)) | |
| self._set_row_gate(torch.tensor([float(r.prefix is not None) for r in rows], device=device, dtype=h.dtype)) | |
| total = torch.tensor([len(s) for s in seqs], device=device) | |
| pad = torch.arange(h.shape[1], device=device)[None] < total[:, None] | |
| h = self.encoder(h, pad, torch.tensor(offsets, device=device)) | |
| text = self._pad_length(torch.nn.utils.rnn.pad_sequence( | |
| [h[i, o:o + n] for i, (o, n) in enumerate(zip(offsets, lengths, strict=True))], batch_first=True)) | |
| k = self._round_up(max(len(r.encoded.markers) for r in rows)) | |
| text_pad = torch.arange(text.shape[1], device=device)[None] < torch.tensor(lengths, device=device)[:, None] | |
| marker_pos = torch.zeros(len(rows), k, dtype=torch.long, device=device) | |
| marker_mask = torch.zeros(len(rows), k, dtype=torch.bool, device=device) | |
| for i, r in enumerate(rows): | |
| marker_pos[i, :len(r.encoded.markers)] = torch.tensor(r.encoded.markers, device=device) | |
| marker_mask[i, :len(r.encoded.markers)] = True | |
| qtype = torch.tensor([r.encoded.qtype for r in rows], device=device) | |
| z = self.head(text, text_pad, marker_pos, marker_mask, qtype) | |
| return [z[i, :len(r.encoded.markers)] for i, r in enumerate(rows)] | |
| def _round_up(self, n: int) -> int: | |
| m = self.pad_to_multiple | |
| return n if not m else -(-n // m) * m | |
| def _pad_length(self, h: torch.Tensor) -> torch.Tensor: | |
| extra = self._round_up(h.shape[1]) - h.shape[1] | |
| return torch.nn.functional.pad(h, (0, 0, 0, extra)) if extra else h | |
| def _set_row_gate(self, gate: torch.Tensor) -> None: | |
| """Tell row-gated adapters which batch rows carry media (released models have none: a no-op).""" | |
| for module in self.encoder.modules(): | |
| if hasattr(module, "set_row_gate"): | |
| module.set_row_gate(gate) | |
| def distribution(self, row: Row, logits: torch.Tensor) -> list[float]: | |
| """Slot logits -> calibrated probabilities in canonical option order.""" | |
| z = logits / self.calibrator.temperature(row.question, has_media=row.prefix is not None) | |
| p = z.softmax(-1).tolist() | |
| out = [0.0] * len(p) | |
| for slot, canonical in enumerate(row.encoded.canonical): | |
| out[canonical] = p[slot] | |
| return out | |
| def probabilities(self, requests: list[DecisionRequest]) -> list[tuple[list[list[float]], int]]: | |
| """Per request: each question's canonical distribution, and the positions the trunk read.""" | |
| per_request = [self.rows(r) for r in requests] | |
| flat = [row for rows in per_request for row in rows] | |
| results: list[list[float] | None] = [None] * len(flat) | |
| order = sorted(range(len(flat)), key=lambda i: flat[i].length, reverse=True) | |
| while order: | |
| longest, size = flat[order[0]].length, 1 | |
| heads = self.encoder.config.num_attention_heads | |
| while (size < len(order) and (size + 1) * longest <= self.max_tokens | |
| and (size + 1) * heads * longest**2 <= self.max_attention_elements): | |
| size += 1 | |
| batch, order = order[:size], order[size:] | |
| for i, z in zip(batch, self.logits([flat[i] for i in batch]), strict=True): | |
| results[i] = self.distribution(flat[i], z) | |
| out, i = [], 0 | |
| for rows in per_request: | |
| out.append((results[i:i + len(rows)], sum(r.length for r in rows))) | |
| i += len(rows) | |
| return out | |