Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 34 additions & 140 deletions docs/iterations/current.md
Original file line number Diff line number Diff line change
@@ -1,97 +1,47 @@
# Current Iteration — M73
# Current Iteration — M81

## Milestone

**M73** — Multi-Model Comparison in Single Batch Run
**M81** — Automatic Threshold Tuning

## What Was Done

Added `multi_model.py` module enabling `batch-compare` to accept multiple `--model` flags
and run the same dataset against each model, producing a `MultiModelBatchReport` with:
Added `xpyd-acc auto-threshold --reports r1.json r2.json ...` command that analyzes
historical batch reports and recommends optimal `--fail-threshold` and `--numeric-tolerance`
values based on percentile-based statistical analysis.

- Per-model `BatchReport` (reuses existing `run_batch()`)
- Cross-model analysis: systematic divergences (all models), model-specific, all-match
- JSON and Markdown export with per-model breakdowns
- Terminal formatting with per-model pass/fail indicators

### Files Changed

- **`src/xpyd_acc/multi_model.py`** (new): `MultiModelBatchReport`, `CrossModelSummary`,
`compute_cross_model_summary()`, `format_multi_model_report()`, `run_multi_model()`
- **`src/xpyd_acc/cli.py`**: `--model` changed to `action="append"` for repeatable flag;
multi-model branch added in `_run_batch_compare()` with JSON/Markdown export and exit code
- **`tests/test_multi_model.py`** (new): 15 tests covering dataclasses, cross-model summary,
report serialization, formatting, and async `run_multi_model()` with mocked `run_batch`

### Tests

15 tests all passing:
- `CrossModelSummary` serialization
- `compute_cross_model_summary` for all-match, systematic, model-specific, empty, single-model
- `MultiModelBatchReport` JSON round-trip, Markdown generation
- `format_multi_model_report` terminal output
- `run_multi_model` with callback, backward compat, parameter forwarding, mixed results

## Iteration History

| # | Date | Task | Result | Reviewer Comments |
|---|------|------|--------|-------------------|
| 1 | 2026-04-06 | M73: Multi-Model Comparison | ⏳ pending review | — |
| 2 | 2026-04-06 | M73: CLI Modularization — split cli.py into cli/ package | ⏳ pending review | — |

---

## Iteration 3: M74 — Divergence Root Cause Heuristics

**Date:** 2026-04-06
**Issue:** #161
**Branch:** `feat/m74-root-cause-heuristics`

### What was done

Added `xpyd-acc root-cause --report <path>` CLI subcommand that analyzes batch report divergence patterns and suggests probable root cause (prefill, KV transfer, decode, truncation, mixed, or inconclusive).

### Files changed

- **`src/xpyd_acc/root_cause.py`** (new): `analyze_root_cause()`, `RootCauseAnalysis`, `Evidence` dataclasses, `_classify_sample()` heuristic rules, `format_root_cause()` terminal display, `analyze_from_file()` convenience function
- **`src/xpyd_acc/cli/analysis.py`**: Added `handle_root_cause()` CLI handler
- **`src/xpyd_acc/cli/parsers.py`**: Registered `root-cause` subcommand with `--report` and `--json` flags
- **`src/xpyd_acc/cli/__init__.py`**: Wired `root-cause` to handler
- **`tests/test_root_cause.py`** (new): 21 tests covering heuristic classification, analysis, serialization, formatting, file I/O, CLI integration
- **`ROADMAP.md`**: Marked M73 ✅, added M74-M76

### Tests

21 tests all passing. Full suite: 1085 passed.

---

## Iteration: M75 — Side-by-Side Token Diff Viewer
### Implementation

**Date:** 2026-04-06
**Issue:** #163
**Branch:** feat/m75-token-diff
- `auto_threshold.py` module:
- `ThresholdRecommendation` dataclass with `to_dict()` serialization
- `analyze_thresholds()` — percentile-based recommendation engine
- `load_reports()` — fault-tolerant multi-report loader
- `format_recommendations()` — terminal display
- `_percentile()` — interpolating percentile computation
- Fail threshold: p95 of observed divergence rates × 1.1 + headroom
- Numeric tolerance: p95 of logprob gaps at divergence points
- Confidence scoring: high (≥500 samples, ≥3 reports), medium, low
- `--percentile <float>` flag to control recommendation aggressiveness
- `--json <path>` export

### What was done
### Files Changed

- Created `src/xpyd_acc/token_diff.py` module with:
- `TokenDiffLine` and `TokenDiff` dataclasses with JSON serialization
- `build_token_diff()` — builds aligned diff with context window
- `format_token_diff()` — rich terminal output with ANSI colors or plain text
- `build_from_report()`, `build_all_divergent()`, `diff_from_file()` helpers
- Color-coded output: green (match), red (mismatch), yellow (logprob warning), cyan (one-sided)
- Logprob annotations at divergence point
- Added CLI subcommand `xpyd-acc token-diff`:
- `--report`, `--sample`, `--all-divergent`, `--context`, `--format`, `--json`
- Created `tests/test_token_diff.py` with 25 tests covering:
- Dataclass serialization, diff building, empty/asymmetric outputs
- Context window, logprob annotations, logprob warning status
- Report lookup, divergent filtering, file I/O
- CLI help, sample mode, JSON export, error handling
- `src/xpyd_acc/auto_threshold.py` (new)
- `src/xpyd_acc/cli/report.py` — added `_run_auto_threshold()` handler
- `src/xpyd_acc/cli/parsers.py` — registered `auto-threshold` subcommand
- `src/xpyd_acc/cli/__init__.py` — wired handler to early dispatch
- `tests/test_auto_threshold.py` (new, 18 tests)
- `docs/iterations/current.md` — updated

### Tests

25 tests all passing.
18 tests covering:
- Percentile computation (basic, p95, empty, single)
- Threshold analysis (empty reports, single report, multiple/high-confidence, no logprob gaps, custom percentile)
- ThresholdRecommendation serialization and JSON round-trip
- Format output with data and without data
- Report loading (valid, missing, mixed)
- CLI integration (basic and custom percentile)

## Iteration History

Expand All @@ -102,62 +52,6 @@ Added `xpyd-acc root-cause --report <path>` CLI subcommand that analyzes batch r
| M76 | 2026-04-06 | Report Dashboard Server | ✅ merged | Both approved |
| M77 | 2026-04-06 | Prometheus Metrics Export | ✅ merged | Both approved |
| M78 | 2026-04-06 | Grafana Dashboard Template Export | ✅ merged | Both approved |

## Iteration M79: Parallel Multi-Dataset Batch Run

### What
Added `multi_dataset.py` module for running multiple evaluation datasets concurrently.

### Implementation
- `MultiDatasetReport` dataclass with per-dataset `BatchReport` and aggregate stats
- `run_multi_dataset()` async function runs datasets in parallel via `asyncio.gather()`
- `format_multi_dataset_report()` for terminal display with per-dataset pass/fail indicators
- JSON and Markdown export with per-dataset breakdowns
- Callback support via `on_dataset_complete` parameter

### Files Changed
- `src/xpyd_acc/multi_dataset.py` (new)
- `tests/test_multi_dataset.py` (new, 18 tests)

### Tests
18 tests covering:
- Dataclass construction, aggregation, edge cases (empty, all match, all diverge)
- JSON serialization and round-trip
- Markdown export with truncation
- Async execution with mocked run_batch
- Callback invocation
- Kwargs forwarding
- Empty dataset map handling

---

## M80: Multi-Dataset CLI Integration

**Date:** 2026-04-06
**Issue:** #173
**Status:** In progress

### Problem
M79 added `multi_dataset.py` with `run_multi_dataset()` but no CLI integration — users cannot invoke multi-dataset runs from the command line.

### Solution
- Made `--dataset` flag repeatable (argparse `action="append"`)
- When >1 dataset given, `_run_batch_compare` delegates to `_run_multi_dataset()`
- Added `_run_multi_dataset()` in `batch.py`: loads datasets, runs concurrent comparison, prints results
- Per-dataset `--fail-threshold` checking
- JSON/Markdown export support

### Files Changed
- `src/xpyd_acc/cli/parsers.py` (--dataset becomes repeatable)
- `src/xpyd_acc/cli/batch.py` (multi-dataset routing + handler)
- `tests/test_multi_dataset_cli.py` (new, 10 tests)
- `ROADMAP.md` (M79 ✅, M80 added)

### Tests
10 tests covering:
- Dataclass aggregation
- JSON/Markdown export
- Terminal formatting
- CLI flag repeatability
- Multi-dataset delegation
- Single-dataset backward compatibility
| M79 | 2026-04-06 | Parallel Multi-Dataset Batch Run | ✅ merged | Both approved |
| M80 | 2026-04-06 | Multi-Dataset CLI Integration | ✅ merged | Both approved |
| M81 | 2026-04-06 | Automatic Threshold Tuning | ⏳ pending review | — |
183 changes: 183 additions & 0 deletions src/xpyd_acc/auto_threshold.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
"""Automatic threshold tuning from historical batch reports."""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any

from xpyd_acc.batch_compare import BatchReport, load_report
from xpyd_acc.log import get_logger

logger = get_logger("auto_threshold")


@dataclass
class ThresholdRecommendation:
"""Recommended threshold values based on historical report analysis."""

fail_threshold: float | None
numeric_tolerance: float | None
confidence: str # "high", "medium", "low"
sample_size: int
reasoning: list[str]
divergence_rates: list[float] = field(default_factory=list)
logprob_gaps: list[float] = field(default_factory=list)
percentile_used: float = 0.95

def to_dict(self) -> dict[str, Any]:
return {
"fail_threshold": self.fail_threshold,
"numeric_tolerance": self.numeric_tolerance,
"confidence": self.confidence,
"sample_size": self.sample_size,
"reasoning": self.reasoning,
"divergence_rates": self.divergence_rates,
"logprob_gaps": self.logprob_gaps,
"percentile_used": self.percentile_used,
}


def _percentile(data: list[float], p: float) -> float:
"""Compute the p-th percentile of a sorted list (0 < p < 1)."""
if not data:
return 0.0
sorted_data = sorted(data)
k = (len(sorted_data) - 1) * p
floor_k = int(k)
ceil_k = min(floor_k + 1, len(sorted_data) - 1)
frac = k - floor_k
return sorted_data[floor_k] + frac * (sorted_data[ceil_k] - sorted_data[floor_k])


def analyze_thresholds(
reports: list[BatchReport],
percentile_level: float = 0.95,
) -> ThresholdRecommendation:
"""Analyze batch reports and recommend threshold values.

Args:
reports: List of BatchReport objects to analyze.
percentile_level: Percentile to use for recommendations (0-1).

Returns:
ThresholdRecommendation with suggested values.
"""
if not reports:
return ThresholdRecommendation(
fail_threshold=None,
numeric_tolerance=None,
confidence="low",
sample_size=0,
reasoning=["No reports provided — cannot compute thresholds."],
percentile_used=percentile_level,
)

divergence_rates: list[float] = []
logprob_gaps: list[float] = []
total_samples = 0

for report in reports:
divergence_rates.append(report.divergence_rate)
total_samples += report.total_samples
for result in report.results:
if result.logprob_gap is not None and not result.exact_match:
logprob_gaps.append(result.logprob_gap)

reasoning: list[str] = []

# Fail threshold recommendation
fail_threshold: float | None = None
if divergence_rates:
p_val = _percentile(divergence_rates, percentile_level)
# Round up slightly to give headroom
fail_threshold = round(min(p_val * 1.1 + 0.005, 1.0), 3)
reasoning.append(
f"Observed divergence rates: min={min(divergence_rates):.3f}, "
f"max={max(divergence_rates):.3f}, "
f"p{int(percentile_level * 100)}={p_val:.3f} "
f"→ recommended fail_threshold={fail_threshold:.3f}"
)

# Numeric tolerance recommendation
numeric_tolerance: float | None = None
if logprob_gaps:
p_val = _percentile(logprob_gaps, percentile_level)
numeric_tolerance = round(p_val, 4)
reasoning.append(
f"Observed logprob gaps at divergence: min={min(logprob_gaps):.4f}, "
f"max={max(logprob_gaps):.4f}, "
f"p{int(percentile_level * 100)}={p_val:.4f} "
f"→ recommended numeric_tolerance={numeric_tolerance:.4f}"
)
else:
reasoning.append("No logprob gap data available — cannot recommend numeric_tolerance.")

# Confidence assessment
if total_samples >= 500 and len(reports) >= 3:
confidence = "high"
elif total_samples >= 100 or len(reports) >= 2:
confidence = "medium"
else:
confidence = "low"

reasoning.append(
f"Analyzed {len(reports)} report(s) with {total_samples} total samples "
f"→ confidence: {confidence}"
)

return ThresholdRecommendation(
fail_threshold=fail_threshold,
numeric_tolerance=numeric_tolerance,
confidence=confidence,
sample_size=total_samples,
reasoning=reasoning,
divergence_rates=divergence_rates,
logprob_gaps=logprob_gaps,
percentile_used=percentile_level,
)


def load_reports(paths: list[str]) -> list[BatchReport]:
"""Load multiple batch reports from file paths."""
reports: list[BatchReport] = []
for p in paths:
try:
reports.append(load_report(p))
except Exception as exc:
logger.warning("Failed to load report %s: %s", p, exc)
return reports


def format_recommendations(rec: ThresholdRecommendation) -> str:
"""Format recommendations as a human-readable string."""
lines: list[str] = []
lines.append("═══ Threshold Recommendations ═══")
lines.append("")

if rec.fail_threshold is not None:
lines.append(f" fail_threshold: {rec.fail_threshold:.3f}")
else:
lines.append(" fail_threshold: (no data)")

if rec.numeric_tolerance is not None:
lines.append(f" numeric_tolerance: {rec.numeric_tolerance:.4f}")
else:
lines.append(" numeric_tolerance: (no data)")

lines.append(f" confidence: {rec.confidence}")
lines.append(f" sample_size: {rec.sample_size}")
lines.append(f" percentile: p{int(rec.percentile_used * 100)}")
lines.append("")

if rec.divergence_rates:
lines.append(f" Divergence rates: {', '.join(f'{r:.3f}' for r in rec.divergence_rates)}")
if rec.logprob_gaps:
n = len(rec.logprob_gaps)
lines.append(f" Logprob gap samples: {n}")

lines.append("")
lines.append("Reasoning:")
for r in rec.reasoning:
lines.append(f" • {r}")

return "\n".join(lines)
2 changes: 2 additions & 0 deletions src/xpyd_acc/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
_run_ab_test,
_run_aggregate,
_run_annotate,
_run_auto_threshold,
_run_cluster,
_run_diff,
_run_explain,
Expand Down Expand Up @@ -129,6 +130,7 @@ def main(argv: list[str] | None = None) -> None:
"config": lambda: _run_config(args),
"profiles": lambda: _run_profiles(config),
"completion": lambda: _run_completion(args, parser),
"auto-threshold": lambda: _run_auto_threshold(args),
}

if args.command in _early:
Expand Down
Loading
Loading