benchmarks/bb144/sim_main.cpp

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

  1#ifdef RELAY_BP_ARTIFACT
  2#include "VRelayBpArtifact.h"
  3#elif defined(BP_ONLY_ARTIFACT)
  4#include "VBpOnlyArtifact.h"
  5#else
  6#include "VBpFilteredOsd0Artifact.h"
  7#endif
  8#include "verilated.h"
  9
 10#include <algorithm>
 11#include <cmath>
 12#include <cstdint>
 13#include <cstdlib>
 14#include <fstream>
 15#include <iomanip>
 16#include <iostream>
 17#include <numeric>
 18#include <string>
 19#include <type_traits>
 20#include <vector>
 21
 22#ifdef RELAY_BP_ARTIFACT
 23using Dut = VRelayBpArtifact;
 24#elif defined(BP_ONLY_ARTIFACT)
 25using Dut = VBpOnlyArtifact;
 26#else
 27using Dut = VBpFilteredOsd0Artifact;
 28#endif
 29
 30template <typename T> static void clearPort(T &port) {
 31  static_assert(std::is_integral_v<T>, "expected an integral Verilator port");
 32  port = 0;
 33}
 34
 35// Use the VlWide template parameter: older supported Verilator releases do not
 36// expose VlIsVlWide or VlWide::Words.
 37template <std::size_t Words> static void clearPort(VlWide<Words> &port) {
 38  for (std::size_t word = 0; word < Words; ++word) port.at(word) = 0;
 39}
 40
 41template <typename T> static void setBit(T &port, int bit, bool value) {
 42  static_assert(std::is_integral_v<T>, "expected an integral Verilator port");
 43  const auto mask = uint64_t{1} << bit;
 44  const auto word = static_cast<uint64_t>(port);
 45  port = static_cast<T>(value ? word | mask : word & ~mask);
 46}
 47
 48template <std::size_t Words> static void setBit(VlWide<Words> &port, int bit, bool value) {
 49  const auto mask = uint32_t{1} << (bit % 32);
 50  auto &word = port.at(bit / 32);
 51  word = value ? word | mask : word & ~mask;
 52}
 53
 54template <typename T> static bool getBit(const T &port, int bit) {
 55  static_assert(std::is_integral_v<T>, "expected an integral Verilator port");
 56  return (static_cast<uint64_t>(port) >> bit) & 1U;
 57}
 58
 59template <std::size_t Words> static bool getBit(const VlWide<Words> &port, int bit) {
 60  return (port.at(bit / 32) >> (bit % 32)) & 1U;
 61}
 62
 63template <typename T> static void setField(T &port, int offset, int width, int value) {
 64  for (int bit = 0; bit < width; ++bit) setBit(port, offset + bit, value >> bit & 1);
 65}
 66
 67template <typename T> static int signedField(const T &port, int offset, int width) {
 68  int value = 0;
 69  for (int bit = 0; bit < width; ++bit) value |= int(getBit(port, offset + bit)) << bit;
 70  return value & (1 << (width - 1)) ? value - (1 << width) : value;
 71}
 72
 73static void tick(Dut &dut) {
 74  dut.clock = 0;
 75  dut.eval();
 76  dut.clock = 1;
 77  dut.eval();
 78}
 79
 80static void reset(Dut &dut) {
 81  dut.inputValid = 0;
 82  dut.scopeValid = 0;
 83  dut.correctionReady = 1;
 84  dut.resultReady = 1;
 85#ifdef BP_ONLY_ARTIFACT
 86  dut.iterationLimit = 1;
 87#endif
 88#ifdef RELAY_BP_ARTIFACT
 89  dut.legLimit = 1;
 90#endif
 91  clearPort(dut.syndrome);
 92  clearPort(dut.prior);
 93  clearPort(dut.scope);
 94  dut.reset = 1;
 95  tick(dut);
 96  dut.reset = 0;
 97}
 98
 99[[noreturn]] static void fail(const std::string &message) {
100  std::cerr << "FAIL: " << message << '\n';
101  std::exit(1);
102}
103
104static std::vector<int> readValues(std::istream &input, int count, const char *name) {
105  std::vector<int> values(count);
106  for (auto &value : values)
107    if (!(input >> value)) fail(std::string("malformed ") + name);
108  return values;
109}
110
111struct LegTiming {
112  int index, iterations, cycles, converged;
113};
114
115static bool operator==(const LegTiming &a, const LegTiming &b) {
116  return a.index == b.index && a.iterations == b.iterations &&
117    a.cycles == b.cycles && a.converged == b.converged;
118}
119
120struct Frame {
121  int status, iterations, cycles, bpCycles, osdCycles, selected, activeRows, solverCycles;
122  int legsExecuted = 0, solutionsFound = 0;
123  std::vector<int> soft, correction;
124  std::vector<std::pair<int, int>> stream;
125  std::vector<LegTiming> legTimings;
126};
127
128static void checkSparseOnes(const Frame &frame) {
129  int previous = -1;
130  for (const auto &[index, value] : frame.stream) {
131    if (value != 1) fail("sparse correction contained a zero value");
132    if (index <= previous) fail("sparse correction indices were not strictly ascending");
133    previous = index;
134  }
135}
136
137static Frame decode(
138    Dut &dut, const std::vector<int> &syndrome, const std::vector<int> &prior,
139    int magnitudeBits, int accumulatorBits, int runtimeLimit, int64_t maxCycles) {
140  const int m = syndrome.size(), n = prior.size();
141  dut.inputValid = 0;
142  dut.scopeValid = 0;
143  dut.correctionReady = 1;
144  dut.resultReady = 1;
145  clearPort(dut.syndrome);
146  clearPort(dut.prior);
147  clearPort(dut.scope);
148#ifdef BP_ONLY_ARTIFACT
149  dut.iterationLimit = runtimeLimit;
150#endif
151#ifdef RELAY_BP_ARTIFACT
152  dut.legLimit = runtimeLimit;
153#endif
154  for (int row = 0; row < m; ++row) setBit(dut.syndrome, row, syndrome[row]);
155  for (int col = 0; col < n; ++col)
156    setField(dut.prior, col * magnitudeBits, magnitudeBits, prior[col]);
157  dut.inputValid = 1;
158  dut.eval();
159  if (!dut.inputReady) fail("input was not ready");
160  tick(dut);
161  dut.inputValid = 0;
162
163  Frame frame{};
164  frame.correction.assign(n, 0);
165  std::vector<int> seen(n, 0);
166  int64_t elapsed = 0;
167  int lastAt = -1;
168  int previousLegBoundary = 0;
169  while (!dut.resultValid && elapsed < maxCycles) {
170#ifdef RELAY_BP_ARTIFACT
171    if (dut.legTraceValid) {
172      const int boundary = static_cast<int>(elapsed) + 1;
173      frame.legTimings.push_back({
174        int(dut.legTraceIndex), int(dut.legTraceIterations),
175        boundary - previousLegBoundary, int(dut.legTraceConverged),
176      });
177      previousLegBoundary = boundary;
178    }
179#endif
180    if (dut.correctionValid && dut.correctionReady) {
181      const int index = dut.correctionIndex;
182      if (index < 0 || index >= n || seen[index]) fail("invalid correction index stream");
183      seen[index] = 1;
184      frame.correction[index] = dut.correctionValue;
185      frame.stream.emplace_back(index, int(dut.correctionValue));
186      if (dut.correctionLast) {
187        if (lastAt >= 0) fail("multiple correction.last assertions");
188        lastAt = frame.stream.size() - 1;
189      }
190    }
191    tick(dut);
192    ++elapsed;
193  }
194  if (!dut.resultValid) fail("decoder timeout");
195  if (!frame.stream.empty() && lastAt != int(frame.stream.size()) - 1)
196    fail("correction.last was not on the final item");
197  frame.status = dut.status;
198  frame.iterations = dut.completedIterations;
199  frame.cycles = dut.cycles;
200  frame.bpCycles = dut.bpCycles;
201  frame.osdCycles = dut.osdCycles;
202  frame.selected = dut.selected;
203  frame.activeRows = dut.activeRows;
204  frame.solverCycles = dut.solverCycles;
205#ifdef RELAY_BP_ARTIFACT
206  frame.legsExecuted = dut.legsExecuted;
207  frame.solutionsFound = dut.solutionsFound;
208#endif
209  frame.soft.resize(n);
210  for (int col = 0; col < n; ++col)
211    frame.soft[col] = signedField(dut.softOutput, col * accumulatorBits, accumulatorBits);
212  if (frame.cycles != elapsed) fail("reported and observed cycle counts differ");
213  tick(dut);
214  return frame;
215}
216
217static const char *statusName(int status, bool bpOnly) {
218  if (bpOnly && status == 2) return "bp_nonconverged";
219  static const char *names[] = {"bp_converged", "osd_solved", "osd_inconsistent", "osd_overflow"};
220  return status >= 0 && status < 4 ? names[status] : "invalid";
221}
222
223struct Timing {
224  int dispatch, bp, bpOutput, sort, solverRows, solverMesh, osdOutput, osdControl;
225};
226
227struct ArtifactConfig {
228  int m, n, magnitudeBits, accumulatorBits, threshold;
229  int sparseBankWidth = 0;
230  int initialIterations = 0, relayIterations = 0, maximumLegs = 0;
231  int solutionTarget = 0, seedOffset = 0, maximumIterations = 0;
232  std::vector<int> prefixes;
233};
234
235static ArtifactConfig readConfig(std::istream &input) {
236  ArtifactConfig config{};
237  int count;
238  if (!(input >> config.m >> config.n >> config.magnitudeBits >> config.accumulatorBits
239              >> config.threshold >> count) || count < 0)
240    fail("invalid artifact configuration");
241  config.prefixes = readValues(input, count, "artifact prefixes");
242#if defined(BP_ONLY_ARTIFACT) || defined(RELAY_BP_ARTIFACT)
243  int streamAbi;
244  if (!(input >> streamAbi >> config.sparseBankWidth) ||
245      streamAbi != 2 || config.sparseBankWidth <= 0)
246    fail("invalid sparse correction stream configuration");
247#endif
248#ifdef BP_ONLY_ARTIFACT
249  if (!(input >> config.maximumIterations) || config.maximumIterations <= 0)
250    fail("invalid BP iteration capacity");
251#endif
252#ifdef RELAY_BP_ARTIFACT
253  int legTraceAbi;
254  if (!(input >> config.initialIterations >> config.relayIterations >>
255      config.maximumLegs >> config.solutionTarget >> config.seedOffset >> legTraceAbi) ||
256      config.initialIterations <= 0 || config.relayIterations <= 0 ||
257      config.maximumLegs <= 0 || config.solutionTarget <= 0 || config.seedOffset < 0 ||
258      config.seedOffset >= 65535 || legTraceAbi != 1)
259    fail("invalid Relay-BP configuration");
260  const auto maximum = static_cast<int64_t>(config.initialIterations) +
261    static_cast<int64_t>(config.maximumLegs - 1) * config.relayIterations;
262  if (maximum > 1000000000) fail("Relay-BP iteration limit is too large");
263  config.maximumIterations = maximum;
264#endif
265  if (!config.prefixes.empty() && (config.prefixes.front() < 1 ||
266      config.prefixes.back() > config.n ||
267      !std::is_sorted(config.prefixes.begin(), config.prefixes.end()) ||
268      std::adjacent_find(config.prefixes.begin(), config.prefixes.end()) != config.prefixes.end()))
269    fail("invalid artifact prefixes");
270  return config;
271}
272
273static int decoderRuntimeLimit(const ArtifactConfig &config, int budget) {
274#ifdef BP_ONLY_ARTIFACT
275  if (budget < 1 || budget > config.maximumIterations) fail("BP budget exceeds artifact capacity");
276  return budget;
277#elif defined(RELAY_BP_ARTIFACT)
278  if (budget < config.initialIterations ||
279      (budget - config.initialIterations) % config.relayIterations)
280    fail("Relay budget must equal T0 + R*Tr");
281  const int legs = 1 + (budget - config.initialIterations) / config.relayIterations;
282  if (legs > config.maximumLegs) fail("Relay budget exceeds artifact capacity");
283  return legs;
284#else
285  (void)config; (void)budget;
286  return 0;
287#endif
288}
289
290#ifdef RELAY_BP_ARTIFACT
291static void checkRelayTiming(const Frame &frame, const ArtifactConfig &config) {
292  if (int(frame.legTimings.size()) != frame.legsExecuted ||
293      frame.legsExecuted < 1 || frame.legsExecuted > config.maximumLegs ||
294      frame.solutionsFound < 0 || frame.solutionsFound > config.solutionTarget)
295    fail("invalid Relay leg or solution count");
296  int iterations = 0, cycles = 0, solutions = 0;
297  for (std::size_t index = 0; index < frame.legTimings.size(); ++index) {
298    const auto &leg = frame.legTimings[index];
299    const int limit = index == 0 ? config.initialIterations : config.relayIterations;
300    if (leg.index != int(index) || leg.iterations < 1 || leg.iterations > limit ||
301        leg.cycles != 2 * leg.iterations)
302      fail("invalid Relay leg trace record");
303    iterations += leg.iterations;
304    cycles += leg.cycles;
305    solutions += leg.converged;
306  }
307  if (iterations != frame.iterations || cycles != frame.bpCycles ||
308      solutions != frame.solutionsFound)
309    fail("Relay leg trace totals differ from decoder totals");
310}
311#endif
312
313static void checkSparseTiming(const Frame &frame, int bankWidth) {
314  checkSparseOnes(frame);
315  int occupiedBanks = 0, previousBank = -1;
316  for (const auto &entry : frame.stream) {
317    const int bank = entry.first / bankWidth;
318    if (bank != previousBank) ++occupiedBanks;
319    previousBank = bank;
320  }
321  const int expected = 2 * frame.iterations + 1 + occupiedBanks +
322    int(frame.stream.size());
323  if (frame.bpCycles != 2 * frame.iterations || frame.cycles != expected)
324    fail("sparse correction timing contract violated");
325}
326
327static Timing breakdown(
328  const Frame &frame, int n, int eligible, const std::vector<int> &prefixes,
329  int sparseBankWidth) {
330  const bool bpOnly = sparseBankWidth > 0;
331  const bool bp = frame.status == 0;
332  const int bpOutput = bpOnly ? frame.cycles - frame.bpCycles - 1 :
333    bp ? frame.stream.size() : 0;
334  const int sort = bp || bpOnly ? 0 : n + eligible;
335  const int osdOutput = !bpOnly && frame.status == 1 ? frame.stream.size() : 0;
336  int solverMesh = 0;
337  if (frame.solverCycles)
338    for (int prefix : prefixes) {
339      solverMesh += 3 * prefix + 1;
340      if (frame.selected <= prefix) break;
341    }
342  const int solverRows = frame.solverCycles - solverMesh;
343  const int osdControl = bpOnly ? 0 : frame.osdCycles - sort - frame.solverCycles - osdOutput;
344  const int dispatch = frame.cycles - frame.bpCycles - frame.osdCycles - bpOutput;
345  if (dispatch < 0 || osdControl < 0 || solverMesh < 0) fail("invalid timing decomposition");
346  return {dispatch, frame.bpCycles, bpOutput, sort, solverRows, solverMesh, osdOutput, osdControl};
347}
348
349template <typename T> static void writeArray(std::ostream &out, const std::vector<T> &values) {
350  out << '[';
351  for (std::size_t i = 0; i < values.size(); ++i) {
352    if (i) out << ',';
353    out << values[i];
354  }
355  out << ']';
356}
357
358#ifdef RELAY_BP_ARTIFACT
359static void writeLegTraceJson(std::ostream &out, const std::vector<LegTiming> &trace) {
360  out << '[';
361  for (std::size_t i = 0; i < trace.size(); ++i) {
362    if (i) out << ',';
363    const auto &leg = trace[i];
364    out << "{\"index\":" << leg.index << ",\"iterations\":" << leg.iterations
365        << ",\"cycles\":" << leg.cycles << ",\"converged\":"
366        << (leg.converged ? "true" : "false") << '}';
367  }
368  out << ']';
369}
370
371static void writeLegTraceCsv(std::ostream &out, const std::vector<LegTiming> &trace) {
372  for (std::size_t i = 0; i < trace.size(); ++i) {
373    if (i) out << '|';
374    const auto &leg = trace[i];
375    out << leg.index << ':' << leg.iterations << ':' << leg.cycles << ':' << leg.converged;
376  }
377}
378#endif
379
380static int exactMain(const char *goldenPath, const char *resultPath) {
381  std::ifstream input(goldenPath);
382  const auto config = readConfig(input);
383  const auto syndrome = readValues(input, config.m, "golden syndrome");
384  const auto prior = readValues(input, config.n, "golden prior");
385  Frame expected{};
386  int eligible, correctionCount;
387  input >> expected.status >> expected.iterations >> expected.cycles >> expected.bpCycles
388        >> expected.osdCycles >> expected.selected >> expected.activeRows
389        >> expected.solverCycles >> eligible;
390#ifdef RELAY_BP_ARTIFACT
391  input >> expected.legsExecuted >> expected.solutionsFound;
392  int legCount;
393  input >> legCount;
394  if (legCount < 1) fail("invalid golden Relay leg trace length");
395  for (int i = 0; i < legCount; ++i) {
396    LegTiming leg{};
397    input >> leg.index >> leg.iterations >> leg.cycles >> leg.converged;
398    expected.legTimings.push_back(leg);
399  }
400#endif
401  expected.soft = readValues(input, config.n, "golden soft output");
402  input >> correctionCount;
403  for (int i = 0, index, value; i < correctionCount; ++i) {
404    input >> index >> value;
405    expected.stream.emplace_back(index, value);
406  }
407  std::string extra;
408  if (!input || input >> extra) fail("malformed or excess golden data");
409
410  Dut dut;
411  reset(dut);
412  const auto actual = decode(
413    dut, syndrome, prior, config.magnitudeBits, config.accumulatorBits,
414    decoderRuntimeLimit(config, config.maximumIterations),
415    4 * config.n + 2 * config.m + 3 * std::accumulate(
416      config.prefixes.begin(), config.prefixes.end(), 0) +
417      2 * expected.iterations + 128);
418  if (config.sparseBankWidth > 0) checkSparseTiming(actual, config.sparseBankWidth);
419#ifdef RELAY_BP_ARTIFACT
420  checkRelayTiming(actual, config);
421#endif
422#define CHECK(field) if (actual.field != expected.field) fail(#field " differs from software golden")
423  CHECK(status); CHECK(iterations); CHECK(cycles); CHECK(bpCycles); CHECK(osdCycles);
424  CHECK(selected); CHECK(activeRows); CHECK(solverCycles); CHECK(soft); CHECK(stream);
425#ifdef RELAY_BP_ARTIFACT
426  CHECK(legsExecuted); CHECK(solutionsFound); CHECK(legTimings);
427#endif
428#undef CHECK
429  const int observedEligible = std::count_if(actual.soft.begin(), actual.soft.end(),
430    [&config](int value) { return std::abs(value) < config.threshold; });
431  if (observedEligible != eligible) fail("eligible count differs from software golden");
432  const auto timing = breakdown(
433    actual, config.n, eligible, config.prefixes, config.sparseBankWidth);
434  std::vector<int> correctionOnes;
435  for (int col = 0; col < config.n; ++col)
436    if (actual.correction[col]) correctionOnes.push_back(col);
437
438  std::ofstream output(resultPath);
439  output << "{\n  \"status\":\"" << statusName(actual.status, config.sparseBankWidth > 0)
440         << "\",\n  \"iterations\":" << actual.iterations
441         << ",\n  \"eligible\":" << eligible << ",\n  \"selected\":" << actual.selected
442         << ",\n  \"active_rows\":" << actual.activeRows;
443#ifdef RELAY_BP_ARTIFACT
444  output << ",\n  \"legs_executed\":" << actual.legsExecuted
445         << ",\n  \"solutions_found\":" << actual.solutionsFound
446         << ",\n  \"leg_timing\":";
447  writeLegTraceJson(output, actual.legTimings);
448#endif
449  output << ",\n  \"timing_cycles\":{"
450         << "\"total\":" << actual.cycles << ",\"dispatch\":" << timing.dispatch
451         << ",\"bp\":" << timing.bp << ",\"bp_output\":" << timing.bpOutput
452         << ",\"sort\":" << timing.sort << ",\"solver_rows\":" << timing.solverRows
453         << ",\"solver_mesh\":" << timing.solverMesh
454         << ",\"osd_output\":" << timing.osdOutput
455         << ",\"osd_control\":" << timing.osdControl << "},\n  \"soft_outputs\":";
456  writeArray(output, actual.soft);
457  output << ",\n  \"correction_ones\":";
458  writeArray(output, correctionOnes);
459  output << "\n}\n";
460  dut.final();
461  std::cout << "PASS: exact emitted RTL matched the independent golden; result: "
462            << resultPath << '\n';
463  return 0;
464}
465
466static std::string packObservableBits(const std::vector<int> &bits) {
467  static const char digits[] = "0123456789abcdef";
468  std::string value;
469  for (std::size_t end = (bits.size() + 3) / 4; end > 0; --end) {
470    unsigned nibble = 0;
471    for (std::size_t bit = 0; bit < 4; ++bit) {
472      const auto index = (end - 1) * 4 + bit;
473      if (index < bits.size() && bits[index]) nibble |= 1U << bit;
474    }
475    if (nibble || !value.empty()) value += digits[nibble];
476  }
477  return "0x" + (value.empty() ? std::string("0") : value);
478}
479
480static int benchmarkMain(
481    const char *inputPath, const char *csvPath, const char *configPath,
482    int requestedBudget = 0) {
483  std::ifstream input(inputPath);
484  std::ifstream artifactConfig(configPath);
485  const auto config = readConfig(artifactConfig);
486  int m, n, logicalCount, iterations, codeCycles, pCount, magnitudeBits, controlMax;
487  if (!(input >> m >> n >> logicalCount >> iterations >> codeCycles >> pCount
488              >> magnitudeBits >> controlMax) || logicalCount <= 0)
489    fail("invalid benchmark header");
490  if (m != config.m || n != config.n || magnitudeBits != config.magnitudeBits)
491    fail("benchmark and artifact dimensions differ");
492  const int budget = requestedBudget ? requestedBudget :
493    (config.maximumIterations ? config.maximumIterations : iterations);
494  const int runtimeLimit = decoderRuntimeLimit(config, budget);
495  std::vector<std::vector<int>> logicals(logicalCount);
496  for (auto &logical : logicals) {
497    int degree;
498    if (!(input >> degree) || degree < 0) fail("invalid logical row degree");
499    logical = readValues(input, degree, "logical row");
500    if (std::any_of(logical.begin(), logical.end(),
501        [n](int column) { return column < 0 || column >= n; }))
502      fail("logical row contains an out-of-range variable");
503  }
504  std::ofstream csv(csvPath);
505  if (!csv) fail("cannot create benchmark output");
506  csv << "p,shot,max_bp_iterations,status,converged,iterations,";
507#ifdef RELAY_BP_ARTIFACT
508  csv << "legs_executed,solutions_found,leg_trace,";
509#endif
510  csv << "total_cycles,dispatch_cycles,bp_cycles,"
511         "bp_output_cycles,sort_cycles,solver_row_cycles,solver_mesh_cycles,"
512         "osd_output_cycles,osd_control_cycles,eligible,selected,active_rows,"
513         "correction_weight,predicted_observables,actual_observables,logical_failure\n";
514  Dut dut;
515  reset(dut);
516  const bool bpOnly = config.sparseBankWidth > 0;
517  int totalShots = 0;
518  for (int point = 0; point < pCount; ++point) {
519    double p;
520    int shots;
521    input >> p >> shots;
522    const auto prior = readValues(input, n, "benchmark prior");
523    for (int shot = 0; shot < shots; ++shot) {
524      const auto syndrome = readValues(input, m, "benchmark syndrome");
525      const auto observedBits = readValues(input, logicalCount, "logical observables");
526      if (std::any_of(observedBits.begin(), observedBits.end(),
527          [](int bit) { return bit != 0 && bit != 1; }))
528        fail("logical observables must be binary");
529      const auto frame = decode(
530        dut, syndrome, prior, magnitudeBits, config.accumulatorBits,
531        runtimeLimit,
532        4 * n + 2 * m + 3 * std::accumulate(
533          config.prefixes.begin(), config.prefixes.end(), 0) +
534          2LL * budget + 128);
535      const int eligible = std::count_if(frame.soft.begin(), frame.soft.end(),
536        [&config](int value) { return std::abs(value) < config.threshold; });
537      if (frame.status == 0 && frame.selected != 0) fail("BP result selected OSD columns");
538      if (!bpOnly && frame.status != 0 && std::find(
539            config.prefixes.begin(), config.prefixes.end(), frame.selected) == config.prefixes.end())
540        fail("selected count is not a configured OSD prefix");
541      if (bpOnly && frame.status != 0 && frame.status != 2)
542        fail("invalid BP-only status");
543      if (frame.status == 3) fail("all-column ranking must not overflow");
544      if (bpOnly) {
545        checkSparseTiming(frame, config.sparseBankWidth);
546      } else {
547        const int expectedCount = frame.status == 0 ? n :
548          frame.status == 1 ? frame.selected : 0;
549        if (int(frame.stream.size()) != expectedCount)
550          fail("unexpected correction stream length");
551      }
552#ifdef RELAY_BP_ARTIFACT
553      checkRelayTiming(frame, config);
554#endif
555
556      std::vector<int> predicted(logicalCount, 0);
557      for (int logical = 0; logical < logicalCount; ++logical) {
558        bool parity = false;
559        for (int column : logicals[logical]) parity ^= frame.correction[column];
560        predicted[logical] = int(parity);
561      }
562      const bool success = frame.status == 0 || (!bpOnly && frame.status == 1);
563      const bool logicalFailure = !success || predicted != observedBits;
564      const auto timing = breakdown(
565        frame, n, eligible, config.prefixes, config.sparseBankWidth);
566      const int weight = std::count(frame.correction.begin(), frame.correction.end(), 1);
567      csv << std::setprecision(12) << p << ',' << shot << ',' << budget << ','
568          << statusName(frame.status, bpOnly)
569          << ',' << int(frame.status == 0) << ',' << frame.iterations << ',';
570#ifdef RELAY_BP_ARTIFACT
571      csv << frame.legsExecuted << ',' << frame.solutionsFound << ',';
572      writeLegTraceCsv(csv, frame.legTimings);
573      csv << ',';
574#endif
575      csv << frame.cycles
576          << ',' << timing.dispatch << ',' << timing.bp << ',' << timing.bpOutput
577          << ',' << timing.sort << ',' << timing.solverRows << ',' << timing.solverMesh
578          << ',' << timing.osdOutput << ',' << timing.osdControl << ',' << eligible
579          << ',' << frame.selected << ',' << frame.activeRows << ',' << weight << ','
580          << packObservableBits(predicted) << ',' << packObservableBits(observedBits) << ','
581          << int(logicalFailure) << '\n';
582
583      ++totalShots;
584    }
585  }
586  std::string extra;
587  if (input >> extra) fail("extra benchmark data");
588  dut.final();
589  std::cout << "PASS: simulated " << totalShots << " shots; raw results: "
590            << csvPath << '\n';
591  return 0;
592}
593
594int main(int argc, char **argv) {
595  Verilated::commandArgs(argc, argv);
596  if (argc == 5 && std::string(argv[1]) == "--benchmark")
597    return benchmarkMain(argv[2], argv[3], argv[4]);
598  if (argc == 7 && std::string(argv[1]) == "--budget" &&
599      std::string(argv[3]) == "--benchmark")
600    return benchmarkMain(argv[4], argv[5], argv[6], std::stoi(argv[2]));
601  if (argc != 3) {
602    std::cerr << "usage: <simulator> <golden.txt> <result.json>\n"
603                 "   or: <simulator> --benchmark <input> <shots.csv> "
604                 "<artifact-config>\n"
605                 "   or: <simulator> --budget <iterations> --benchmark <input> "
606                 "<shots.csv> <artifact-config>\n";
607    return 2;
608  }
609  return exactMain(argv[1], argv[2]);
610}