Giuliocc's picture
Publish source-aware model SDK, forty-deliverable evidence and annotated-review tooling
1f5647a verified
Raw History Blame Contribute Delete
3.81 kB
"""One-thread compact contextual two-task classifiers and checked batches."""
from __future__ import annotations
import math
from pathlib import Path
import random
import numpy as np
import torch
from safetensors.torch import load_file, save_file
from transformers import AutoModel
BASE_ID = "sentence-transformers/all-MiniLM-L6-v2"
BASE_REVISION = "1110a243fdf4706b3f48f1d95db1a4f5529b4d41"
BASE_PATH = Path("/home/agent/.cache/huggingface/hub/models--sentence-transformers--all-MiniLM-L6-v2/snapshots") / BASE_REVISION
SEED = 1729
INPUT_NAMES = ("input_ids", "attention_mask", "token_type_ids", "target_mask", "context_mask")
def deterministic():
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.set_num_threads(1)
try:
torch.set_num_interop_threads(1)
except RuntimeError:
pass
def batches(packed, batch_size=16, order=None):
order = list(range(len(packed))) if order is None else list(order)
for start in range(0, len(order), batch_size):
indices = [i for i in order[start:start + batch_size] if packed[i]["status"] == "ok"]
if not indices:
continue
length = max(len(packed[i]["input_ids"]) for i in indices)
tensors = {name: torch.tensor([packed[i][name] + [0] * (length - len(packed[i][name])) for i in indices], dtype=torch.long)
for name in INPUT_NAMES}
yield indices, tensors
class ContextEncoder(torch.nn.Module):
def __init__(self):
super().__init__()
self.encoder = AutoModel.from_pretrained(BASE_PATH, local_files_only=True, attn_implementation="eager")
self.head = torch.nn.Linear(768, 2)
torch.nn.init.normal_(self.head.weight, std=.02)
torch.nn.init.zeros_(self.head.bias)
def features(self, input_ids, attention_mask, token_type_ids, target_mask, context_mask):
hidden = self.encoder(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids).last_hidden_state
def pool(mask):
mask = mask.unsqueeze(-1).to(hidden.dtype)
mean = (hidden * mask).sum(1) / mask.sum(1).clamp(min=1)
return torch.nn.functional.normalize(mean, dim=1)
return torch.cat((pool(target_mask), pool(context_mask)), dim=1)
def forward(self, input_ids, attention_mask, token_type_ids, target_mask, context_mask):
return self.head(self.features(input_ids, attention_mask, token_type_ids, target_mask, context_mask))
def save(self, folder):
folder = Path(folder)
folder.mkdir(parents=True, exist_ok=True)
save_file({name: value.detach().contiguous() for name, value in self.state_dict().items()}, str(folder / "model.safetensors"))
@classmethod
def load(cls, folder):
model = cls()
model.load_state_dict(load_file(str(Path(folder) / "model.safetensors")))
return model.eval()
def native_logits(model, packed, batch_size=16):
model.eval()
result = np.zeros((len(packed), 2), dtype=np.float32)
with torch.inference_mode():
for indices, values in batches(packed, batch_size=batch_size):
result[indices] = model(**values).numpy()
return result
def encoder_features(model, packed, batch_size=16):
model.eval()
result = np.zeros((len(packed), 768), dtype=np.float32)
with torch.inference_mode():
for indices, values in batches(packed, batch_size=batch_size):
result[indices] = model.features(**values).numpy()
return result
def install_logistic(model, fits):
model.head.weight.data.copy_(torch.tensor(np.vstack([fit.coef_[0] for fit in fits]), dtype=torch.float32))
model.head.bias.data.copy_(torch.tensor([fit.intercept_[0] for fit in fits], dtype=torch.float32))
return model.eval()