benchmarks/bb144/report.py

Source from the repository checkout used to build these docs. Line numbers link to individual source lines.

  1#!/usr/bin/env python3
  2"""Reduce a BB144 RTL sweep into logical-error, cycle, and plot artifacts."""
  3
  4import argparse
  5import csv
  6import json
  7import math
  8import statistics
  9from collections import Counter
 10from pathlib import Path
 11
 12
 13STAGES = {
 14    "dispatch": "dispatch_cycles",
 15    "bp": "bp_cycles",
 16    "bp_output": "bp_output_cycles",
 17    "sort": "sort_cycles",
 18    "solver_rows": "solver_row_cycles",
 19    "solver_mesh": "solver_mesh_cycles",
 20    "osd_output": "osd_output_cycles",
 21    "osd_control": "osd_control_cycles",
 22}
 23
 24
 25def percentile(values, probability):
 26    ordered = sorted(values)
 27    return ordered[math.ceil(probability * len(ordered)) - 1]
 28
 29
 30def histogram_percentile(counts, probability):
 31    target = math.ceil(probability * sum(counts.values()))
 32    seen = 0
 33    for value, count in sorted(counts.items()):
 34        seen += count
 35        if seen >= target:
 36            return value
 37
 38
 39def histogram_median(counts):
 40    size = sum(counts.values())
 41    targets = {(size - 1) // 2, size // 2}
 42    values = []
 43    seen = 0
 44    for value, count in sorted(counts.items()):
 45        values.extend(value for target in targets if seen <= target < seen + count)
 46        seen += count
 47    return statistics.fmean(values)
 48
 49
 50def wilson(failures, shots):
 51    z = 1.959963984540054
 52    center = (failures / shots + z * z / (2 * shots)) / (1 + z * z / shots)
 53    radius = z * math.sqrt(
 54        failures * (shots - failures) / shots**3 + z * z / (4 * shots**2)
 55    ) / (1 + z * z / shots)
 56    return max(0.0, center - radius), min(1.0, center + radius)
 57
 58
 59def per_qec_cycle(probability, cycles):
 60    return 1.0 if probability == 1 else -math.expm1(math.log1p(-probability) / cycles)
 61
 62
 63def breakdown(rows):
 64    total = sum(int(row["total_cycles"]) for row in rows)
 65    return {
 66        name: {
 67            "cycles": sum(int(row[field]) for row in rows),
 68            "mean_cycles": sum(int(row[field]) for row in rows) / len(rows),
 69            "share": sum(int(row[field]) for row in rows) / total,
 70        }
 71        for name, field in STAGES.items()
 72    }
 73
 74
 75def leg_trace(row):
 76    if "leg_trace" not in row:
 77        return []
 78    try:
 79        trace = [tuple(map(int, item.split(":")))
 80                 for item in row["leg_trace"].split("|") if item]
 81    except ValueError as error:
 82        raise ValueError("malformed Relay leg_trace") from error
 83    if (len(trace) != int(row["legs_executed"])
 84            or any(len(item) != 4 for item in trace)
 85            or [item[0] for item in trace] != list(range(len(trace)))
 86            or any(iterations < 1 or cycles < 1 or converged not in (0, 1)
 87                   for _, iterations, cycles, converged in trace)
 88            or sum(item[1] for item in trace) != int(row["iterations"])
 89            or sum(item[2] for item in trace) != int(row["bp_cycles"])
 90            or sum(item[3] for item in trace) != int(row["solutions_found"])):
 91        raise ValueError("Relay leg_trace violates decoder totals")
 92    return trace
 93
 94
 95def observable_mismatch(row):
 96    return int(row["predicted_observables"], 0) != int(row["actual_observables"], 0)
 97
 98
 99def summarize(p, rows, qec_cycles):
100    failures = sum(int(row["logical_failure"]) for row in rows)
101    word = failures / len(rows)
102    word_low, word_high = wilson(failures, len(rows))
103    clocks = [int(row["total_cycles"]) for row in rows]
104    statuses = Counter(row["status"] for row in rows)
105    converged = [row for row in rows if row["status"] == "bp_converged"]
106    converged_failures = sum(observable_mismatch(row) for row in converged)
107    if converged:
108        converged_word = converged_failures / len(converged)
109        converged_low, converged_high = wilson(converged_failures, len(converged))
110        converged_rate = per_qec_cycle(converged_word, qec_cycles)
111        converged_rate_low = per_qec_cycle(converged_low, qec_cycles)
112        converged_rate_high = per_qec_cycle(converged_high, qec_cycles)
113    else:
114        converged_word = converged_low = converged_high = None
115        converged_rate = converged_rate_low = converged_rate_high = None
116    selected = Counter(int(row["selected"]) for row in rows if int(row["selected"]) > 0)
117    result = {
118        "p": p,
119        "shots": len(rows),
120        "failures": failures,
121        "word_failure_probability": word,
122        "word_failure_ci95_low": word_low,
123        "word_failure_ci95_high": word_high,
124        "logical_failure_rate_per_qec_cycle": per_qec_cycle(word, qec_cycles),
125        "logical_rate_ci95_low": per_qec_cycle(word_low, qec_cycles),
126        "logical_rate_ci95_high": per_qec_cycle(word_high, qec_cycles),
127        "bp_converged": statuses["bp_converged"],
128        "bp_nonconverged": statuses["bp_nonconverged"],
129        "bp_converged_logical_failures": converged_failures,
130        "bp_converged_word_failure_probability": converged_word,
131        "bp_converged_word_failure_ci95_low": converged_low,
132        "bp_converged_word_failure_ci95_high": converged_high,
133        "bp_converged_logical_failure_rate_per_qec_cycle": converged_rate,
134        "bp_converged_logical_rate_ci95_low": converged_rate_low,
135        "bp_converged_logical_rate_ci95_high": converged_rate_high,
136        "osd_solved": statuses["osd_solved"],
137        "osd_inconsistent": statuses["osd_inconsistent"],
138        "status_counts": dict(statuses),
139        "osd_prefix_counts": dict(selected),
140        "decoder_clock_cycles_total": sum(clocks),
141        "decoder_clock_cycles_mean": statistics.fmean(clocks),
142        "decoder_clock_cycles_median": statistics.median(clocks),
143        "decoder_clock_cycles_p95": percentile(clocks, 0.95),
144        "decoder_clock_cycles_max": max(clocks),
145        "timing": breakdown(rows),
146    }
147    if "legs_executed" in rows[0]:
148        legs = [int(row["legs_executed"]) for row in rows]
149        solutions = [int(row["solutions_found"]) for row in rows]
150        result.update({
151            "relay_legs_mean": statistics.fmean(legs),
152            "relay_legs_median": statistics.median(legs),
153            "relay_legs_p95": percentile(legs, 0.95),
154            "relay_legs_max": max(legs),
155            "relay_solutions_found_mean": statistics.fmean(solutions),
156            "relay_solutions_found_max": max(solutions),
157        })
158    if "leg_trace" in rows[0]:
159        cycles = Counter()
160        count = total = 0
161        initial_count = initial_total = subsequent_count = subsequent_total = 0
162        for row in rows:
163            for index, _, leg_cycles, _ in leg_trace(row):
164                cycles[leg_cycles] += 1
165                count += 1
166                total += leg_cycles
167                if index == 0:
168                    initial_count += 1
169                    initial_total += leg_cycles
170                else:
171                    subsequent_count += 1
172                    subsequent_total += leg_cycles
173        result.update({
174            "relay_leg_clock_cycles_total": total,
175            "relay_leg_clock_cycles_mean": total / count,
176            "relay_leg_clock_cycles_median": histogram_median(cycles),
177            "relay_leg_clock_cycles_p95": histogram_percentile(cycles, 0.95),
178            "relay_leg_clock_cycles_max": max(cycles),
179            "relay_initial_leg_clock_cycles_mean": initial_total / initial_count,
180            "relay_subsequent_leg_clock_cycles_mean": (
181                subsequent_total / subsequent_count if subsequent_count else None
182            ),
183        })
184    return result
185
186
187def plot_rate(
188        axis, records, *,
189        rate_key="logical_failure_rate_per_qec_cycle",
190        low_key="logical_rate_ci95_low",
191        high_key="logical_rate_ci95_high",
192        ylabel="logical failure rate / QEC cycle",
193        estimate_label="estimate with Wilson 95% CI"):
194    x = [row["p"] for row in records]
195    rates = [row[rate_key] for row in records]
196    low = [row[low_key] for row in records]
197    high = [row[high_key] for row in records]
198    measured = [i for i, value in enumerate(rates) if value is not None and value > 0]
199    if measured:
200        axis.errorbar(
201            [x[i] for i in measured], [rates[i] for i in measured],
202            yerr=([rates[i] - low[i] for i in measured],
203                  [high[i] - rates[i] for i in measured]),
204            fmt="o-", capsize=3, label=estimate_label,
205        )
206    zero = [i for i, value in enumerate(rates) if value == 0]
207    if zero:
208        axis.scatter(
209            [x[i] for i in zero], [high[i] for i in zero], marker="v",
210            label="95% upper bound (zero failures)",
211        )
212    axis.set(xscale="log", yscale="log",
213             ylabel=ylabel)
214    axis.grid(True, which="both", alpha=0.25)
215    if measured or zero:
216        axis.legend()
217    else:
218        axis.text(0.5, 0.5, "no converged samples", ha="center", va="center",
219                  transform=axis.transAxes)
220
221
222def write_plots(records, overall, output, label):
223    import matplotlib
224    matplotlib.use("Agg")
225    import matplotlib.pyplot as plt
226
227    title = f"{label}, {records[0]['shots']:,} shots/p"
228    figure, axis = plt.subplots(figsize=(6.4, 4.2))
229    plot_rate(axis, records)
230    axis.set(xlabel="physical error probability p", title=title)
231    figure.tight_layout()
232    figure.savefig(output / "logical_failure_rate.png", dpi=180)
233    plt.close(figure)
234
235    figure, axis = plt.subplots(figsize=(6.4, 4.2))
236    plot_rate(
237        axis, records,
238        rate_key="bp_converged_logical_failure_rate_per_qec_cycle",
239        low_key="bp_converged_logical_rate_ci95_low",
240        high_key="bp_converged_logical_rate_ci95_high",
241        ylabel="logical failure rate / QEC cycle\nconditioned on BP convergence",
242        estimate_label="conditional estimate with Wilson 95% CI",
243    )
244    axis.set(
245        xlabel="physical error probability p",
246        title=f"{label}, converged BP samples only\n"
247              f"{records[0]['shots']:,} generated shots/p; conditional denominator varies",
248    )
249    figure.tight_layout()
250    figure.savefig(output / "logical_failure_rate_converged_only.png", dpi=180)
251    plt.close(figure)
252
253    figure, axes = plt.subplots(2, 1, figsize=(6.6, 7.4), sharex=True)
254    plot_rate(axes[0], records)
255    x = [row["p"] for row in records]
256    axes[1].plot(x, [row["decoder_clock_cycles_mean"] for row in records],
257                 "o-", label="mean")
258    axes[1].plot(x, [row["decoder_clock_cycles_p95"] for row in records],
259                 "s--", label="p95")
260    axes[1].set(xscale="log", xlabel="physical error probability p",
261                ylabel="decoder clocks / shot")
262    axes[1].grid(True, which="both", alpha=0.25)
263    axes[1].legend()
264    figure.suptitle(
265        f"{title}\n{overall['decoder_clock_cycles_total']:,} aggregate decoder clocks; "
266        f"{overall['simulation_wall_seconds'] / 60:.1f} min RTL wall time"
267    )
268    figure.tight_layout()
269    figure.savefig(output / "logical_failure_and_cycles.png", dpi=180)
270    plt.close(figure)
271
272
273def write_relay_leg_outputs(rows, output, label):
274    if "leg_trace" not in rows[0]:
275        return None
276    fields = ("p", "shot", "leg", "iterations", "cycles", "converged")
277    grouped = {}
278    by_p_cycles = {}
279    total_legs = total_cycles = 0
280    with (output / "relay_leg_timing.csv").open("w", newline="") as stream:
281        writer = csv.writer(stream)
282        writer.writerow(fields)
283        for row in rows:
284            p, shot = float(row["p"]), int(row["shot"])
285            for index, iterations, cycles, converged in leg_trace(row):
286                writer.writerow((p, shot, index + 1, iterations, cycles, converged))
287                bucket = grouped.setdefault(
288                    (p, index + 1), [0, 0, Counter(), Counter()],
289                )
290                bucket[0] += 1
291                bucket[1] += converged
292                bucket[2][iterations] += 1
293                bucket[3][cycles] += 1
294                by_p_cycles.setdefault(p, Counter())[cycles] += 1
295                total_legs += 1
296                total_cycles += cycles
297
298    if not total_legs:
299        raise ValueError("Relay leg trace is empty")
300    summary = []
301    for (p, leg), (executions, converged, iterations, cycles) in sorted(grouped.items()):
302        summary.append({
303            "p": p, "leg": leg, "executions": executions,
304            "converged": converged,
305            "convergence_rate": converged / executions,
306            "mean_iterations": (
307                sum(value * count for value, count in iterations.items()) / executions
308            ),
309            "p95_iterations": histogram_percentile(iterations, 0.95),
310            "mean_cycles": sum(value * count for value, count in cycles.items()) / executions,
311            "p95_cycles": histogram_percentile(cycles, 0.95), "max_cycles": max(cycles),
312        })
313    with (output / "relay_leg_timing_summary.csv").open("w", newline="") as stream:
314        writer = csv.DictWriter(stream, fieldnames=summary[0])
315        writer.writeheader()
316        writer.writerows(summary)
317
318    import matplotlib
319    matplotlib.use("Agg")
320    import matplotlib.pyplot as plt
321
322    probabilities = sorted(by_p_cycles)
323    figure, axes = plt.subplots(2, 1, figsize=(7.2, 7.6))
324    axes[0].plot(probabilities, [sum(value * count for value, count in by_p_cycles[p].items()) /
325                                sum(by_p_cycles[p].values()) for p in probabilities],
326                 "o-", label="mean")
327    axes[0].plot(probabilities, [histogram_percentile(by_p_cycles[p], 0.95)
328                                 for p in probabilities],
329        "s--", label="p95")
330    axes[0].set(xscale="log", xlabel="physical error probability p",
331                ylabel="decoder clocks / executed leg")
332    axes[0].grid(True, which="both", alpha=0.25)
333    axes[0].legend()
334
335    for p in probabilities:
336        rows = [row for row in summary if row["p"] == p]
337        axes[1].plot([row["leg"] for row in rows],
338                     [row["mean_cycles"] for row in rows], label=f"p={p:g}")
339    axes[1].set(xlabel="Relay leg number (initial leg = 1)",
340                ylabel="mean decoder clocks")
341    axes[1].grid(True, alpha=0.25)
342    axes[1].legend(ncol=2)
343    figure.suptitle(f"{label}: measured per-leg decoder clocks")
344    figure.tight_layout()
345    figure.savefig(output / "relay_leg_timing.png", dpi=180)
346    plt.close(figure)
347    return {"count": total_legs, "cycles": total_cycles}
348
349
350def main():
351    parser = argparse.ArgumentParser(description=__doc__)
352    parser.add_argument("raw", type=Path)
353    parser.add_argument("sweep", type=Path)
354    parser.add_argument("run", type=Path)
355    parser.add_argument("output", type=Path)
356    parser.add_argument("--label", default="BB144 Z-check decoder")
357    parser.add_argument("--decoder-config", type=Path)
358    args = parser.parse_args()
359
360    with args.raw.open(newline="") as stream:
361        raw = list(csv.DictReader(stream))
362    sweep = json.loads(args.sweep.read_text())
363    run = json.loads(args.run.read_text())
364    if not raw:
365        raise ValueError("raw result CSV is empty")
366    args.output.mkdir(parents=True, exist_ok=True)
367    for row in raw:
368        if sum(int(row[field]) for field in STAGES.values()) != int(row["total_cycles"]):
369            raise ValueError("timing stages do not sum to total_cycles")
370    leg_stats = write_relay_leg_outputs(raw, args.output, args.label)
371
372    grouped = {}
373    for row in raw:
374        grouped.setdefault(float(row["p"]), []).append(row)
375    expected = sorted(map(float, sweep["sampling"]["p_values"]))
376    shots_per_p = int(sweep["sampling"]["shots_per_p"])
377    if sorted(grouped) != expected:
378        raise ValueError("raw and declared probability points differ")
379    for p, rows in grouped.items():
380        if len(rows) != shots_per_p or {int(row["shot"]) for row in rows} != set(range(shots_per_p)):
381            raise ValueError(f"p={p}: incomplete or duplicate shot records")
382
383    qec_cycles = int(sweep["code"]["cycles"])
384    records = [summarize(p, grouped[p], qec_cycles) for p in expected]
385    all_clocks = [int(row["total_cycles"]) for row in raw]
386    overall = {
387        "shots": len(raw),
388        "probability_points": len(records),
389        "qec_cycles_per_shot": qec_cycles,
390        "decoder_clock_cycles_total": sum(all_clocks),
391        "decoder_clock_cycles_mean": statistics.fmean(all_clocks),
392        "simulation_wall_seconds": float(run["wall_seconds"]),
393        "simulation_shots_per_second": float(run["shots_per_second"]),
394        "timing": breakdown(raw),
395    }
396    if leg_stats:
397        overall.update({
398            "relay_legs_traced": leg_stats["count"],
399            "relay_leg_clock_cycles_total": leg_stats["cycles"],
400            "relay_leg_clock_cycles_mean": leg_stats["cycles"] / leg_stats["count"],
401        })
402    report = {
403        "schema": "chipsldpc.bb144-decoder-sweep.v1",
404        "decoder": args.label,
405        "logical_failure": (
406            "unsuccessful decoder status or any mismatch among the 12 "
407            "Z-check-sector logical observables"
408        ),
409        "bp_converged_logical_failure": (
410            "any mismatch among the 12 logical observables, conditioned on "
411            "status=bp_converged; nonconverged shots are excluded from both "
412            "the numerator and denominator"
413        ),
414        "logical_rate": "1 - (1 - word_failure_probability)^(1 / qec_cycles_per_shot)",
415        "cycle_accounting": (
416            "sum of measured end-to-end architecture clocks across shots; parallel "
417            "Verilator wall time is reported separately"
418        ),
419        "overall": overall,
420        "records": records,
421    }
422    if args.decoder_config:
423        report["decoder_configuration"] = json.loads(args.decoder_config.read_text())
424    (args.output / "results.json").write_text(json.dumps(report, indent=2) + "\n")
425
426    flat = [
427        {key: value for key, value in record.items()
428         if key not in {"status_counts", "osd_prefix_counts", "timing"}}
429        for record in records
430    ]
431    with (args.output / "results.csv").open("w", newline="") as stream:
432        writer = csv.DictWriter(stream, fieldnames=flat[0])
433        writer.writeheader()
434        writer.writerows(flat)
435    with (args.output / "timing.csv").open("w", newline="") as stream:
436        writer = csv.writer(stream)
437        writer.writerow(("p", "stage", "cycles", "mean_cycles", "share"))
438        for p, timing in [("all", overall["timing"])] + [
439                (record["p"], record["timing"]) for record in records]:
440            for stage, values in timing.items():
441                writer.writerow((p, stage, values["cycles"],
442                                 values["mean_cycles"], values["share"]))
443
444    write_plots(records, overall, args.output, args.label)
445    print("p       shots failures P_word      p_L/QEC     total_clocks mean_clocks")
446    for row in records:
447        print(f"{row['p']:<7g} {row['shots']:>5} {row['failures']:>8} "
448              f"{row['word_failure_probability']:<11.6g} "
449              f"{row['logical_failure_rate_per_qec_cycle']:<11.6g} "
450              f"{row['decoder_clock_cycles_total']:>12} "
451              f"{row['decoder_clock_cycles_mean']:>11.2f}")
452    print(f"PASS: {len(raw)} shots, {overall['decoder_clock_cycles_total']} total decoder "
453          f"clocks; results: {args.output}")
454
455
456if __name__ == "__main__":
457    main()