"""The pooled readout: label log-probabilities from the pooling runner's final hidden state (two-way attention). Two-way (bidirectional) reading runs vLLM's POOLING runner, whose embeddings endpoint returns the final hidden state at the last prompt position (after the final norm, before lm_head; `--pooler-config '{"task": "embed", "seq_pooling_type": "LAST", "use_activation": false}'`) and nothing else: no logits, no log-probabilities. The shim does the lm_head's last step itself, for the label tokens only: logit[id] = h . lm_head[id] (softcapped when the model has a final logit softcap) log P(label) = logsumexp(logit over the label's ids) - logsumexp(logit over every asked label's ids) That is the softmax restricted to the asked labels' tokens, which is what the one-way path reads from vLLM's `logprob_token_ids` too (the full-vocabulary normaliser cancels). The lm_head rows come from the LABEL-ROW FILE shipped beside serve_config.json (`label_rows.lightning`: the safetensors FORMAT under a name vLLM's weight loader does not glob, since `*.safetensors` beside model.safetensors would be read as a weight shard): the fp32 tensor `W` [n_tokens, hidden] and `token_ids` int64 [n_tokens] (the flattened label groups in the contract's label order), and in the metadata the hidden size, the softcap, the label order, the groups, the rows' sha256 and the weights' sha256. This module reads and writes that format itself (8-byte little-endian header length, JSON header, raw bytes) so the shim needs neither torch nor safetensors; numpy is used when present. """ import base64 import json import math import struct try: import numpy as np except ImportError: # optional: the pure-Python path is used without it np = None FORMAT = "lightning-label-rows-1" FLOOR = 1e-12 # --------------------------------------------------------------------------------------------------- label rows class LabelRows: """The exported lm_head rows: `ids` (token ids, the row order), `rows` (n x hidden, fp32), `groups` [(label, [ids]), ...] in the trained label order, `softcap` (0 = none), `hidden`, and the file's metadata.""" def __init__(self, ids, rows, groups, softcap, metadata): self.ids = [int(i) for i in ids] self.rows = rows self.groups = [(str(label), [int(i) for i in g]) for label, g in groups] self.softcap = float(softcap or 0.0) self.metadata = dict(metadata) self.hidden = int(metadata["hidden"]) self.index = {i: k for k, i in enumerate(self.ids)} self.labels = [label for label, _ in self.groups] if len(self.index) != len(self.ids): raise ValueError("label rows: a token id appears twice") missing = [i for _, g in self.groups for i in g if i not in self.index] if missing: raise ValueError(f"label rows: no row for token ids {missing[:5]} of the label groups") seen = [i for _, g in self.groups for i in g] if len(set(seen)) != len(seen): raise ValueError("label rows: a token id belongs to two labels") if len(set(self.labels)) != len(self.labels): raise ValueError("label rows: the labels are not distinct") def group_for(self, label): return next(g for l, g in self.groups if l == label) def _header(ids, hidden, groups, softcap, meta): m = { "format": FORMAT, "hidden": str(int(hidden)), "softcap": "none" if not softcap else repr(float(softcap)), "label_order": json.dumps([str(l) for l, _ in groups], ensure_ascii=False), "groups": json.dumps([[str(l), [int(i) for i in g]] for l, g in groups], ensure_ascii=False), } for k, v in (meta or {}).items(): if v is not None: m[str(k)] = v if isinstance(v, str) else json.dumps(v) return m def rows_sha256(rows): """sha256 of the fp32 rows as written (little-endian, row by row): the file's `lm_head_sha256`.""" import hashlib h = hashlib.sha256() for r in rows: h.update(struct.pack(f"<{len(r)}f", *[float(x) for x in r])) return h.hexdigest() def write_label_rows(path, rows, ids, groups, softcap, hidden=None, meta=None): """Write the label-row file: tensors `W` fp32 [n, hidden] (rows in the order of `ids`) and `token_ids` int64 [n]; metadata as _header plus `lm_head_sha256` of the rows (and whatever `meta` adds).""" rows = [[float(x) for x in r] for r in rows] if len(rows) != len(ids): raise ValueError(f"label rows: {len(rows)} rows for {len(ids)} token ids") hidden = int(hidden if hidden is not None else (len(rows[0]) if rows else 0)) if any(len(r) != hidden for r in rows): raise ValueError("label rows: the rows do not all have the hidden size") LabelRows(ids, rows, groups, softcap, {"hidden": hidden}) # the same checks the reader makes n_w = len(rows) * hidden * 4 n_i = len(ids) * 8 header = { "__metadata__": {**_header(ids, hidden, groups, softcap, meta), "lm_head_sha256": rows_sha256(rows)}, "W": {"dtype": "F32", "shape": [len(rows), hidden], "data_offsets": [0, n_w]}, "token_ids": {"dtype": "I64", "shape": [len(ids)], "data_offsets": [n_w, n_w + n_i]}, } hb = json.dumps(header, ensure_ascii=False, separators=(",", ":")).encode("utf-8") hb += b" " * (-len(hb) % 8) # safetensors pads the header to 8 bytes with open(path, "wb") as f: f.write(struct.pack("