geppo / geppo_runtime /core.py
grokked-it's picture
Add GEPPO mean-pooling pointer-head verification release
e6742a5 verified
Raw History Blame Contribute Delete
6.2 kB
"""Inference primitives retained from the evaluated GEPPO experiment."""
import math
import re
import numpy as np
import onnx
import torch
from onnx import numpy_helper
from torch import nn
FORMAT = "emma_canonical_context_isolated_candidate_branches_v1"
REVISION = "7be4190ef58ab7202188cc802688c2fc52e9bac8"
BASE_MODEL = "egomnia/emma-6"
class PointerHead(nn.Module):
def __init__(self, width: int = 2048, dimension: int = 64):
super().__init__()
self.query = nn.Linear(width, dimension)
self.key = nn.Linear(width, dimension)
self.factor = 1 / math.sqrt(dimension)
for name in ("query_mean", "key_mean"):
self.register_buffer(name, torch.zeros(width))
for name in ("query_scale", "key_scale"):
self.register_buffer(name, torch.ones(width))
def forward(self, query, options, mask):
q = self.query((query - self.query_mean) / self.query_scale)
k = self.key((options - self.key_mean) / self.key_scale)
logits = torch.einsum("bd,bkd->bk", q, k) * self.factor
return logits.masked_fill(~mask, -torch.inf)
def options_of(question: dict) -> dict[str, str]:
if question["type"] == "choice":
if any(not isinstance(value, str) or not value.strip() for value in question["criteria"].values()):
raise ValueError("Each choice option needs a textual description")
return {str(key): value for key, value in question["criteria"].items()}
if question["type"] == "score":
return {str(i): text for i, text in enumerate(question["criteria"])}
if question["type"] == "noul":
criteria = question.get("criteria") or {}
return {"no": criteria.get("false", "No, la risposta alla domanda è negativa."),
"yes": criteria.get("true", "Sì, la risposta alla domanda è positiva.")}
raise ValueError("Unsupported question type")
def format_answer(question: dict, option_ids: list[str], probabilities: np.ndarray) -> dict:
values = dict(zip(option_ids, map(float, probabilities), strict=True))
result = {"type": question["type"], "probabilities": values, "calibrated": False}
if question["type"] == "choice":
result["choice"] = option_ids[int(probabilities.argmax())]
elif question["type"] == "noul":
result["noul"] = values["yes"]
else:
result["score"] = sum(int(key) * value for key, value in values.items())
result["legend"] = options_of(question)
return result
def encode_branches(tokenizer, state: str, question: dict) -> dict:
options = options_of(question)
if not state.strip() or not question["instructions"].strip():
raise ValueError("State and instructions must not be empty")
if not 2 <= len(options) <= 255:
raise ValueError("Expected 2-255 candidate options")
if any(not isinstance(v, str) or not v.strip() for v in options.values()):
raise ValueError("Each candidate needs a non-empty description")
if len(set(options.values())) != len(options):
raise ValueError("Candidate descriptions must be distinct")
canonical = sorted(options, key=options.__getitem__)
context = "\n".join(f"- {options[key]}" for key in canonical)
prefix = [tokenizer.bos_id(), *tokenizer.encode(
f"Contesto:\n{state}\nDomanda:\n{question['instructions']}\n"
f"Opzioni possibili:\n{context}\nValutazione:\n")]
tokens, positions = prefix.copy(), list(range(len(prefix)))
ends, spans, separate = [], [], []
for key in canonical:
branch = tokenizer.encode(f"Candidata:\n{options[key]}\nDecisione:\n")
start = len(tokens)
tokens.extend(branch)
positions.extend(range(len(prefix), len(prefix)+len(branch)))
spans.append((start, len(tokens)))
ends.append(len(tokens)-1)
separate.append(prefix+branch)
if len(tokens) > 4096:
raise ValueError("Packed request exceeds Emma context; no truncation")
lookup = {key: i for i, key in enumerate(canonical)}
readout = [lookup[key] for key in options]
return {"tokens": tokens, "position_ids": positions, "prefix_length": len(prefix),
"spans": spans, "ends": ends, "readout": readout,
"option_ids": list(options), "separate": [separate[i] for i in readout]}
def branch_features(model, encoded: dict, device: str, pooling: str = "last"):
if pooling not in ("last","mean"):
raise ValueError("Unknown candidate pooling")
length, prefix = len(encoded["tokens"]), encoded["prefix_length"]
# A branch sees the causal prefix and itself; never another branch.
mask = torch.full((length, length), torch.finfo(torch.float32).min, device=device)
mask[:prefix, :prefix] = torch.triu(mask[:prefix, :prefix], diagonal=1)
for start, stop in encoded["spans"]:
mask[start:stop, :prefix] = 0
mask[start:stop, start:stop] = torch.triu(mask[start:stop, start:stop], diagonal=1)
hidden = model(input_ids=torch.tensor([encoded["tokens"]], device=device),
position_ids=torch.tensor([encoded["position_ids"]], device=device),
attention_mask=mask[None, None], use_cache=False).last_hidden_state[0]
keys = (hidden[encoded["ends"]] if pooling == "last" else
torch.stack([hidden[start:stop].mean(0) for start,stop in encoded["spans"]]))[encoded["readout"]]
return hidden[prefix-1], keys
def projection_weights(graph: onnx.ModelProto, tensors: dict) -> dict[str, torch.Tensor]:
initializers = {tensor.name: tensor for tensor in graph.graph.initializer}
weights = {}
for node in graph.graph.node:
match = re.fullmatch(r"/blocks\.(\d+)/(attn|mlp)/(\w+)/MatMul", node.name)
if match is None:
continue
layer, kind, name = match.groups()
if kind == "mlp":
name = {"w_gate": "gate_proj", "w_up": "up_proj", "w_down": "down_proj"}[name]
key = node.input[1]
weight = tensors[key] if key in tensors else torch.from_numpy(numpy_helper.to_array(initializers[key]).copy())
weights[f"layers.{layer}.{'self_attn' if kind == 'attn' else 'mlp'}.{name}.weight"] = weight.T
return weights