"""Token-weighted NLL, exact token accuracy, and uncurated paired development continuations.""" import math 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): """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 if model is not None: model.eval() def batch_score(ids): target = ids[:, 1:] if unigram is not None: return (-np.log(unigram[target])).sum(dtype=np.float64).item(), int((target == unigram.argmax()).sum()) seq = torch.from_numpy(ids.astype(np.int64)).to(device) logits = logits_of(model, seq[:, :-1]) losses = token_nll(logits, seq[:, 1:]) return losses.sum(dtype=torch.float64).item(), (logits.argmax(-1) == 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 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 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="