"""Token-weighted NLL, exact token accuracy, and uncurated paired development continuations.""" import math import time import numpy as np import torch from tokenizers import Tokenizer from .models import logits_of, token_nll from .records import CONTEXT @torch.no_grad() def score(model, path, device, batch_size, limit_windows=None, unigram=None, progress=None, top1_sink=None): """Score each packed target once, including a final short window, with a fixed context grid.""" tokens = np.memmap(path, mode="r", dtype=" limit_windows: indices = np.linspace(0, full-1, limit_windows, dtype=np.int64) tail = 0 total_loss, correct, count = 0.0, 0, 0 started = last_log = time.perf_counter() def report(): progress({"targets_scored":count,"targets_to_score":len(indices)*CONTEXT+tail, "nll_so_far":total_loss/count,"accuracy_so_far":correct/count, "score_seconds":time.perf_counter()-started}) if model is not None: model.eval() def batch_score(ids): target = ids[:, 1:] if unigram is not None: mode = unigram.argmax() if top1_sink is not None: top1_sink(np.full(target.size,mode,dtype=np.int64)) return (-np.log(unigram[target])).sum(dtype=np.float64).item(), int((target == mode).sum()) seq = torch.from_numpy(ids.astype(np.int64)).to(device) logits = logits_of(model, seq[:, :-1]) losses = token_nll(logits, seq[:, 1:]) predictions = logits.argmax(-1) if top1_sink is not None: top1_sink(predictions.detach().cpu().numpy().reshape(-1)) return losses.sum(dtype=torch.float64).item(), (predictions == seq[:, 1:]).sum().item() for start in range(0, len(indices), batch_size): offsets = indices[start:start+batch_size, None] * CONTEXT + np.arange(CONTEXT+1) loss, hits = batch_score(tokens[offsets]) total_loss, correct, count = total_loss+loss, correct+hits, count+offsets.shape[0]*CONTEXT if progress and time.perf_counter()-last_log>=60: report() last_log = time.perf_counter() if tail: loss, hits = batch_score(np.asarray(tokens[full*CONTEXT:])[None, :]) total_loss, correct, count = total_loss+loss, correct+hits, count+tail nll = total_loss/count if progress: report() return {"nll": nll, "accuracy": correct/count, "tokens": count, "perplexity": math.exp(nll)} def unigram_distribution(train, size): """Laplace smoothing puts mass on the same output vocabulary as the neural decoder.""" tokens = np.memmap(train, mode="r", dtype="