Quality API¶
KLD (Kullback-Leibler Divergence) quality metric for attention distributions.
Measures the KL divergence between compressed and reference attention distributions. Lower KLD indicates better preservation of attention patterns.
Score mapping: KLD_score = 100 * exp(-mean_kld)
so 0 nats → 100, 0.7 nats → 50, 1.7 nats → ~18.
KLDResult
dataclass
¶
KLDResult(score: float, mean_kld: float, ppl: Optional[float] = None, rms_dp_pct: Optional[float] = None, same_topp_pct: Optional[float] = None, is_self_reference: bool = False)
Result of KLD quality evaluation.
KLDTracker ¶
Online KLD tracker for streaming evaluation.
Source code in turboquant/quality/kld.py
update ¶
Add a batch of attention score pairs.
Source code in turboquant/quality/kld.py
result ¶
Compute final KLD result.
Source code in turboquant/quality/kld.py
kld_to_score ¶
score_to_kld ¶
compute_attention_kld ¶
compute_attention_kld(candidate_scores: Tensor, reference_scores: Tensor, reduction: str = 'mean') -> float
Compute KL divergence between attention score distributions.
Args: candidate_scores: Attention logits from compressed cache [, seq_len]. reference_scores: Attention logits from reference cache [, seq_len]. reduction: "mean", "sum", or "none".
Returns: KLD in nats. Lower is better.
Source code in turboquant/quality/kld.py
compute_trajectory_kld ¶
Compute per-step KLD across a token trajectory.
For each token position, measures KLD between the candidate and reference next-token distributions.
Args: candidate_logits: [seq_len, vocab_size] or [batch, seq_len, vocab_size] reference_logits: Same shape as candidate.
Returns: KLDResult with mean KLD and derived score.
Source code in turboquant/quality/kld.py
compute_self_reference_kld ¶
Compute KLD with self as reference (should be ~0).
Useful for validating that the metric pipeline works correctly.
Source code in turboquant/quality/kld.py
compute_rms_delta_probability ¶
Compute RMS of probability deltas (percentage).
Measures the root-mean-square difference in probabilities between candidate and reference distributions.
Returns: RMS delta probability as a percentage (0-100).
Source code in turboquant/quality/kld.py
Token-trajectory and perturbation metrics for generation checks.
sequence_match ¶
Compare two token-id sequences in model-token units.
Source code in turboquant/quality/trajectory.py
trajectory_metrics ¶
trajectory_metrics(references: Sequence[Sequence[int]], candidates: Sequence[Sequence[int]], *, expected_tokens: int | None = None) -> TrajectoryMetrics
Compute prefix trajectory agreement over paired token-id sequences.
Source code in turboquant/quality/trajectory.py
levenshtein ¶
Levenshtein distance over token ids.
Source code in turboquant/quality/trajectory.py
normalized_drift ¶
Token edit distance divided by anchor length, clipped to [0, 1].
Source code in turboquant/quality/trajectory.py
eligible_words ¶
Return non-stopword word spans from a prompt.
Source code in turboquant/quality/trajectory.py
perturb_prompt ¶
Apply one deterministic local prompt perturbation.
Source code in turboquant/quality/trajectory.py
perturbation_metrics ¶
perturbation_metrics(*, prompt_ids: Sequence[str], prompts: Sequence[str], reference_anchor: Sequence[Sequence[int]], candidate_anchor: Sequence[Sequence[int]], reference_perturbed: dict[tuple[str, str], Sequence[int]], candidate_perturbed: dict[tuple[str, str], Sequence[int]], perturbations: Sequence[str] = ('typo', 'case', 'punct', 'paraphrase'), alpha: float = 5.0, seed: int = 42) -> PerturbationMetrics
Score excess token drift under small prompt changes.
Source code in turboquant/quality/trajectory.py
harmonic_mean ¶
Harmonic mean clipped to [0, 100].
Source code in turboquant/quality/trajectory.py
score_band ¶
Map a 0-100 score to a coarse report band.
Hardware replay system for TurboQuant diagnostic profiles.
Parses diagnostic output from turbo-hardware-diag.sh, builds structured hardware profiles, and enables comparison/replay across different hardware configurations.
Usage: # Parse a diagnostic output file profile = HardwareProfile.from_diag_file("turbo-diag-20260326.txt")
# Compare two profiles
report = compare_profiles(baseline, target)
# Predict performance for a hardware config
predicted = predict_decode_from_baseline(profile, target_gpu_family_id=1007)
GPUInfo
dataclass
¶
GPUInfo(name: str = 'unknown', family: str = 'unknown', family_id: int = 0, has_tensor: bool = False, has_unified_memory: bool = False, has_bfloat: bool = False, recommended_max_working_set_mb: float = 0.0, metal_version: str = 'unknown', cuda_compute_cap: str = '', cuda_vram_mb: float = 0.0)
GPU hardware capabilities.
SystemInfo
dataclass
¶
SystemInfo(platform: str = 'unknown', os_version: str = 'unknown', arch: str = 'unknown', cpu_brand: str = 'unknown', cpu_cores_physical: int = 0, cpu_cores_logical: int = 0, ram_total_gb: int = 0, apple_silicon: bool = False, chip_model: str = '', l1_dcache: int = 0, l2_cache: int = 0, gpu: GPUInfo = GPUInfo())
System hardware specs (no PII).
BenchResult
dataclass
¶
BenchResult(label: str, cache_type_k: str, cache_type_v: str, context_depth: int = 0, mode: str = '', tok_per_sec: float = 0.0, stddev: float = 0.0, wall_ms: int = 0, env: str = '')
Single benchmark measurement.
LoadSnapshot
dataclass
¶
LoadSnapshot(label: str, timestamp: str = '', load_avg: str = '', free_ram_mb: float = 0.0, swap_used: str = '', process_count: int = 0, thermal: str = '', gpu_util: str = '')
System load at a point in time.
ModelInfo
dataclass
¶
ModelInfo(filename: str = '', filesize_bytes: int = 0, architecture: str = '', name: str = '', file_type: str = '', model_type: str = '', params: str = '', n_layer: int = 0, n_head: int = 0, n_head_kv: int = 0, n_expert: int = 0, n_expert_used: int = 0, n_ctx_train: int = 0, n_embd: int = 0)
Model metadata.
PPLResult
dataclass
¶
Perplexity measurement.
HardwareProfile
dataclass
¶
HardwareProfile(diag_version: int = 0, timestamp: str = '', system: SystemInfo = SystemInfo(), model: ModelInfo = ModelInfo(), benchmarks: list[BenchResult] = list(), ppl_results: list[PPLResult] = list(), load_snapshots: list[LoadSnapshot] = list(), build_commit: str = '')
Complete hardware profile from a diagnostic run.
to_json ¶
save ¶
from_json
classmethod
¶
Load profile from JSON file.
Source code in turboquant/quality/hw_replay.py
from_diag_file
classmethod
¶
Parse a turbo-hardware-diag.sh output file into a profile.
get_decode_curve ¶
Extract decode speed vs context depth curve.
Source code in turboquant/quality/hw_replay.py
get_prefill_curve ¶
Extract prefill speed vs context depth curve.
Source code in turboquant/quality/hw_replay.py
get_ratio_curve ¶
get_ratio_curve(cache_type: str = 'turbo3', baseline: str = 'q8_0', mode: str = 'decode', env: str = '') -> dict[int, float]
Compute turbo3/q8_0 ratio at each context depth.
Source code in turboquant/quality/hw_replay.py
find_decode_inflection ¶
Find context depth where decode ratio drops most steeply.
Returns the depth where the gradient (ratio change per depth doubling) is most negative, indicating constant cache thrashing onset. Returns None if insufficient data.
Source code in turboquant/quality/hw_replay.py
flag_unreliable_measurements ¶
Flag measurements at 1K context (Metal async dispatch artifact).
Source code in turboquant/quality/hw_replay.py
ComparisonReport
dataclass
¶
ComparisonReport(baseline_name: str, target_name: str, hardware_diff: dict = dict(), decode_ratio_curve: dict = dict(), prefill_ratio_curve: dict = dict(), ppl_comparison: dict = dict(), anomalies: list[str] = list())
Result of comparing two hardware profiles.
to_markdown ¶
Render comparison as markdown table.
Source code in turboquant/quality/hw_replay.py
parse_diag_output ¶
Parse raw turbo-hardware-diag.sh output into a HardwareProfile.
Source code in turboquant/quality/hw_replay.py
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | |
compare_profiles ¶
Compare two hardware profiles and identify differences.
Source code in turboquant/quality/hw_replay.py
predict_decode_from_baseline ¶
predict_decode_from_baseline(baseline: HardwareProfile, target_gpu_family_id: int, target_has_tensor: bool) -> dict[int, float]
Predict target decode ratios from baseline profile using a simple model.
The model: constant cache throughput scales with GPU generation. M1 (family 1007): ~3x worse constant cache than M5 (family 1010) for divergent access patterns. Missing Tensor API adds additional penalty.