Download evaluation/metrics.py from Ian26/MarsLM: direct link, hf CLI and curl.
- Browser
- Download file 1.15 kB
-
https://huggingface.co/Ian26/MarsLM/resolve/main/evaluation/metrics.py
- Command line
-
hf download hf://Ian26/MarsLM/evaluation/metrics.py
-
curl -L -o metrics.py https://huggingface.co/Ian26/MarsLM/resolve/main/evaluation/metrics.py
1.15 kB
| 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() | |