Download grid.py from LiquidAI/d1-2B-ONNX: direct link, hf CLI and curl.
- Browser
- Download file 1.71 kB
-
https://huggingface.co/LiquidAI/d1-2B-ONNX/resolve/main/grid.py
- Command line
-
hf download hf://LiquidAI/d1-2B-ONNX/grid.py
-
curl -L -o grid.py https://huggingface.co/LiquidAI/d1-2B-ONNX/resolve/main/grid.py
1.71 kB
| """Ordered values read as a distribution over equally spaced bins.""" | |
| from __future__ import annotations | |
| import math | |
| from collections.abc import Callable | |
| from dataclasses import dataclass | |
| from functools import cached_property | |
| from typing import Sequence | |
| class Grid: | |
| low: float | |
| high: float | |
| size: int = 128 | |
| def __post_init__(self): | |
| if self.size < 2 or not self.low < self.high: | |
| raise ValueError("a grid needs two values or more, low to high") | |
| def step(self) -> float: | |
| return (self.high - self.low) / (self.size - 1) | |
| def values(self) -> tuple[float, ...]: | |
| return tuple(self.low + i * self.step for i in range(self.size - 1)) + (self.high,) | |
| def read(self, probabilities: Sequence[float], level: Callable[[float], float] | None = None) -> dict[str, float]: | |
| """The mean, median and central 80 percent interval, on this grid's values; `level`, the level a quantile is | |
| read at (a calibration's, increasing).""" | |
| total = math.fsum(probabilities) | |
| values = self.values | |
| out = {"mean": math.fsum(v * (p / total) for v, p in zip(values, probabilities))} | |
| at = [(key, level(q) if level else q) for key, q in (("p10", 0.1), ("median", 0.5), ("p90", 0.9))] | |
| mass = 0.0 | |
| for value, p in zip(values, probabilities): | |
| mass += p / total | |
| for key, quantile in at: | |
| if key not in out and mass >= quantile: | |
| out[key] = value | |
| for key, _ in at: # a level near 1 the summed mass falls short of by rounding: the last value | |
| out.setdefault(key, values[-1]) | |
| return out | |