File size: 1,146 Bytes
8f20aff | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import math
from time import perf_counter
from typing import List, Tuple
import torch
def compute_perplexity(loss: float) -> float:
return math.exp(loss)
def compute_tokens_per_second(num_tokens: int, elapsed_seconds: float) -> float:
return num_tokens / max(elapsed_seconds, 1e-9)
def compute_loss(logits: torch.Tensor, labels: torch.Tensor) -> Tuple[float, int]:
shift_logits = logits[:, :-1, :].contiguous()
shift_labels = labels[:, 1:].contiguous()
loss = torch.nn.functional.cross_entropy(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1), reduction="mean")
return loss.item(), shift_labels.numel()
def measure_inference_speed(model: torch.nn.Module, input_ids: torch.Tensor, warmup_runs: int = 5) -> Tuple[float, float]:
device = next(model.parameters()).device
input_ids = input_ids.to(device)
with torch.no_grad():
for _ in range(warmup_runs):
model(input_ids)
start = perf_counter()
logits, _ = model(input_ids)
end = perf_counter()
elapsed = end - start
return elapsed, input_ids.numel()
|