src/test/scala/chipsldpc/AnimationTraceSpec.scala
Source from the repository checkout used to build these docs. Line numbers link to individual source lines.
1package chipsldpc
2
3import chipsldpc.graph.{TannerGraph, TannerNodeGraphs}
4import java.nio.file.{Files, Paths}
5import org.scalatest.freespec.AnyFreeSpec
6
7/** Replay the immutable animation numbers through the current integer reference.
8 * This is a software regression check, not a waveform or hardware timing test.
9 */
10final class AnimationTraceSpec extends AnyFreeSpec {
11 private val assets = {
12 val starts = Seq(Paths.get("").toAbsolutePath) ++
13 sys.env.get("MILL_WORKSPACE_ROOT").map(Paths.get(_)) ++
14 sys.env.get("PWD").map(Paths.get(_))
15 starts.iterator.flatMap(start =>
16 Iterator.iterate(start)(_.getParent).takeWhile(_ != null)
17 ).map(_.resolve("docs/source/_static/learning"))
18 .find(path => Files.isRegularFile(path.resolve("steane-trace.json")))
19 .getOrElse(throw new IllegalStateException("Cannot find the checked-in animation fixtures"))
20 }
21 private def read(name: String): ujson.Value = ujson.read(Files.readString(assets.resolve(name)))
22 private def ints(value: ujson.Value): Vector[Int] = value.arr.map(_.num.toInt).toVector
23 private def bits(values: Seq[Boolean]): Vector[Int] = values.map(b => if (b) 1 else 0).toVector
24
25 for (fixture <- Seq("steane", "uniform"); mode <- Seq("vanilla", "relay")) {
26 s"$fixture $mode animation matches the current integer reference" in {
27 val problem = read(s"$fixture-problem.json")
28 val trace = read(s"$fixture-trace.json")
29 assert(trace("schema").str == "chipsldpc.documentation-trace.v1")
30 val captured = trace("decoders").arr.find(_("name").str == mode).get
31 val relay = mode == "relay"
32 val n = problem("n").num.toInt
33 val rows = problem("row_ones").arr.map(ints).toVector
34 val priors = ints(problem("prior"))
35 val syndrome = ints(problem("syndrome")).map(_ != 0)
36 val nodes = TannerNodeGraphs.from(TannerGraph.fromRows(n, rows))
37 val q = if (relay) RelayDefaults.paperQ else RelayDefaults.q
38 val scale = RelayDefaults.scale
39 val r = problem("relay")
40 val relayConfig = RelayBpConfig(nodes,
41 initialIterations = r("initial_iterations").num.toInt,
42 relayIterations = r("relay_iterations").num.toInt,
43 maximumLegs = r("maximum_legs").num.toInt,
44 solutionTarget = r("solution_target").num.toInt,
45 seedOffset = r("seed_offset").num.toInt)
46 val vanillaConfig = VanillaBpConfig(nodes, problem("iterations").num.toInt)
47 val betas = Reference.lfsrBeta(n, relayConfig.maximumLegs, relayConfig.seedOffset)
48 assert(captured("quantization")("magnitude_bits").num.toInt == q.magnitudeBits)
49 assert(captured("quantization")("accumulator_bits").num.toInt == q.accumulatorBits)
50 assert(ints(trace("input")("prior")) == priors)
51 assert(ints(trace("input")("syndrome")) == bits(syndrome))
52 assert(trace("input")("row_ones").arr.map(ints).toVector == rows)
53 assert(trace("graph")("checks").num.toInt == nodes.graph.checkCount)
54 assert(trace("graph")("variables").num.toInt == n)
55 trace("graph")("edges").arr.zip(nodes.connections).foreach { case (edge, actual) =>
56 assert(ints(ujson.Arr(edge("id"), edge("check"), edge("variable"),
57 edge("check_port"), edge("variable_port"))) ==
58 Vector(actual.edgeId, actual.checkId, actual.variableId, actual.checkPort, actual.variablePort))
59 }
60 assert(trace("graph")("edges").arr.size == nodes.graph.edgeCount)
61
62 val initial = Reference.initialize(nodes, priors, q)
63 var state = initial
64 var leg = 0
65 var local = 0
66 var solutions = 0
67 var bestScore = Option.empty[Int]
68 var finished = false
69 val steps = captured("steps").arr
70 steps.zipWithIndex.foreach { case (step, index) =>
71 withClue(s"iteration ${index + 1}: ") {
72 assert(!finished, "trace continues after the decoder should stop")
73 local += 1
74 def vector(name: String, actual: Seq[Int]): Unit =
75 assert(ints(step(name)) == actual.toVector, name)
76 assert(step("leg").num.toInt == leg)
77 assert(step("local_iteration").num.toInt == local)
78 assert(step("total_iteration").num.toInt == index + 1)
79 // These fields describe the animation's nominal schedule only.
80 assert(step("cnu_cycle").num.toInt == 2 * index + 1)
81 assert(step("vnu_cycle").num.toInt == 2 * index + 2)
82 vector("previous_marginal", state.marginal)
83 vector("input_v2c", state.v2c.map(_.signed))
84 if (relay) vector("beta_int", betas(leg))
85 else assert(step("beta_int") == ujson.Null)
86 val bias = if (relay) priors.indices.map(i =>
87 Reference.relayBias(priors(i), state.marginal(i), betas(leg)(i), relayConfig.format, q)
88 ).toVector else priors
89 vector("bias", bias)
90 val control = local.min((1 << scale.controlBits) - 1)
91 val checks = nodes.checks.map { check =>
92 val input = check.edges.map(edge => state.v2c(edge.edgeId))
93 val raw = Reference.twoMin(input.map(_.magnitude))
94 assert(ints(step("raw_minima")(check.checkId)) == Vector(raw.first, raw.second))
95 val result = Reference.check(input, syndrome(check.checkId), control,
96 CheckConfig(check.degree, q, scale))
97 assert(ints(step("scaled_minima")(check.checkId)) ==
98 Vector(result.minima.first, result.minima.second))
99 result
100 }
101 val messages = nodes.connections.map { edge =>
102 val result = checks(edge.checkId)
103 val meta = result.edges(edge.checkPort)
104 Reference.CheckMessage(result.minima, meta.sign, meta.useSecond).signed
105 }
106 vector("c2v", messages)
107 vector("total", nodes.variables.map(node =>
108 bias(node.variableId) + node.edges.map(edge => messages(edge.edgeId)).sum))
109 val next = Reference.iterate(nodes, state, syndrome, bias, control, q, scale)
110 vector("computed_v2c", next.v2c.map(_.signed))
111 vector("marginal", next.marginal)
112 vector("decision", bits(next.decision))
113 val residual = Reference.residual(nodes, next, syndrome)
114 vector("residual", bits(residual))
115 val converged = !residual.contains(true)
116 assert(step("converged").bool == converged)
117 val score = priors.zip(next.decision).collect { case (prior, true) => prior }.sum
118 val wins = converged && bestScore.forall(score < _)
119 assert(step("candidate_score").num.toInt == score)
120 assert(step("candidate_wins").bool == wins)
121 if (converged) solutions += 1
122 if (wins) bestScore = Some(score)
123 val limit = if (!relay) vanillaConfig.iterations
124 else if (leg == 0) relayConfig.initialIterations else relayConfig.relayIterations
125 val legEnd = converged || local == limit
126 assert(step("leg_end").bool == legEnd)
127 finished = legEnd && (!relay || solutions >= relayConfig.solutionTarget || leg + 1 == relayConfig.maximumLegs)
128 val restart = legEnd && !finished
129 assert(step("restart_messages").bool == restart)
130 state = if (restart) next.copy(v2c = initial.v2c) else next
131 vector("committed_v2c", state.v2c.map(_.signed))
132 if (restart) { leg += 1; local = 0 }
133 }
134 }
135 assert(finished, "trace ends before the decoder stops")
136 val outcome = if (relay) Reference.runRelay(relayConfig, priors, syndrome, betas)
137 else Reference.runVanilla(vanillaConfig, priors, syndrome)
138 val result = captured("result")
139 assert(result("success").bool == outcome.success)
140 assert(ints(result("correction")) == bits(outcome.correction))
141 assert(ints(result("marginal")) == outcome.state.marginal)
142 assert(ints(result("residual")) == bits(outcome.residual))
143 assert(result("total_iterations").num.toInt == outcome.iterations)
144 assert(result("legs_executed").num.toInt == outcome.legs)
145 assert(result("solutions_found").num.toInt == outcome.solutions)
146 assert(outcome.iterations == steps.size)
147 val predicted = problem("logical_ones").arr.map { row =>
148 ints(row).count(i => outcome.correction(i)) % 2
149 }.toVector
150 assert(ints(result("predicted_observables")) == predicted)
151 val logicalMatch = predicted == ints(problem("actual_observables"))
152 assert(result("logical_match").bool == logicalMatch)
153 assert(result("logical_success").bool == (outcome.success && logicalMatch))
154 }
155 }
156}