src/test/scala/chipsldpc/RelayBpExperiment.scala
Source from the repository checkout used to build these docs. Line numbers link to individual source lines.
1package chipsldpc
2
3import chisel3._
4import chisel3.simulator.scalatest.ChiselSim
5import chisel3.util.{Cat, Enum, log2Ceil}
6import java.nio.file.{Files, Path, Paths}
7import org.scalatest.freespec.AnyFreeSpec
8
9private[chipsldpc] final case class RelayBpExperimentProfile(
10 initialIterations: Int = 80,
11 relayIterations: Int = 60,
12 relayLegs: Int = 600,
13 solutionTarget: Int = 5,
14 seedOffset: Int = 0,
15) {
16 require(initialIterations > 0 && relayIterations > 0)
17 require(relayLegs >= 0)
18 require(solutionTarget > 0)
19 require(seedOffset >= 0 && seedOffset < (1 << LfsrRelayCoefficients.StateBits) - 1)
20 require(
21 BigInt(initialIterations) + BigInt(relayLegs) * relayIterations <=
22 RelayBpConfig.MaximumIterations,
23 )
24
25 def decoderConfig(problem: DecoderProblem): RelayBpConfig = RelayBpConfig(
26 problem.nodes, initialIterations, relayIterations, relayLegs + 1,
27 solutionTarget, seedOffset,
28 )
29}
30
31/** BB benchmark ABI around Relay-BP, with a replaceable downstream processor. */
32private final class RelayBpArtifact(problem: DecoderProblem, config: RelayBpConfig) extends Module {
33 override def desiredName: String = "RelayBpArtifact"
34 private val graph = problem.graph
35 private val q = config.q
36 private val indexBits = math.max(1, log2Ceil(problem.n))
37 private val streamConfig = SparseBitmaskStreamerConfig(problem.n)
38
39 val inputValid = IO(Input(Bool()))
40 val inputReady = IO(Output(Bool()))
41 val legLimit = IO(Input(UInt(config.legBits.W)))
42 val syndrome = IO(Input(UInt(graph.checkCount.W)))
43 val prior = IO(Input(UInt((problem.n * q.magnitudeBits).W)))
44 val scopeValid = IO(Input(Bool()))
45 val scope = IO(Input(UInt(problem.n.W)))
46 val correctionValid = IO(Output(Bool()))
47 val correctionReady = IO(Input(Bool()))
48 val correctionIndex = IO(Output(UInt(indexBits.W)))
49 val correctionValue = IO(Output(Bool()))
50 val correctionLast = IO(Output(Bool()))
51 val resultValid = IO(Output(Bool()))
52 val resultReady = IO(Input(Bool()))
53 val status = IO(Output(UInt(2.W)))
54 val completedIterations = IO(Output(UInt(config.iterationBits.W)))
55 val cycles = IO(Output(UInt(32.W)))
56 val bpCycles = IO(Output(UInt((config.iterationBits + 1).W)))
57 val osdCycles = IO(Output(UInt(32.W)))
58 val selected = IO(Output(UInt(1.W)))
59 val activeRows = IO(Output(UInt(1.W)))
60 val solverCycles = IO(Output(UInt(32.W)))
61 val softOutput = IO(Output(UInt((problem.n * q.accumulatorBits).W)))
62 val legsExecuted = IO(Output(UInt(config.legBits.W)))
63 val solutionsFound = IO(Output(UInt(config.solutionBits.W)))
64 val legTraceValid = IO(Output(Bool()))
65 val legTraceIndex = IO(Output(UInt(config.legBits.W)))
66 val legTraceIterations = IO(Output(UInt(config.localIterationBits.W)))
67 val legTraceConverged = IO(Output(Bool()))
68
69 private val sIdle :: sBp :: sOutput :: Nil = Enum(3)
70 private val state = RegInit(sIdle)
71 private val cycleCount = RegInit(0.U(32.W))
72 private val bp = Module(new RelayBpDecoder(config, runtimeLegLimit = true))
73 private val outcome = Reg(chiselTypeOf(bp.io.out.bits))
74 private val streamer = Module(new SparseBitmaskStreamer(streamConfig))
75
76 bp.io.in.valid := state === sIdle && inputValid
77 bp.legLimit.get := legLimit
78 bp.io.in.bits.syndrome.zipWithIndex.foreach { case (bit, i) => bit := syndrome(i) }
79 bp.io.in.bits.prior.zipWithIndex.foreach { case (value, i) =>
80 value := prior((i + 1) * q.magnitudeBits - 1, i * q.magnitudeBits)
81 }
82 bp.io.out.ready := state === sBp && streamer.io.in.ready
83 streamer.io.in.valid := state === sBp && bp.io.out.valid
84 streamer.io.in.bits := bp.io.out.bits.correction.asUInt
85 streamer.io.out.ready := state === sOutput && correctionReady
86 streamer.io.done.ready := state === sOutput && resultReady
87
88 inputReady := state === sIdle && bp.io.in.ready
89 correctionValid := state === sOutput && streamer.io.out.valid
90 correctionIndex := streamer.io.out.bits.index
91 correctionValue := true.B
92 correctionLast := streamer.io.out.bits.last
93 resultValid := state === sOutput && streamer.io.done.valid
94 status := Mux(outcome.success, 0.U, 2.U)
95 completedIterations := outcome.totalIterations
96 cycles := cycleCount
97 bpCycles := outcome.totalIterations << 1
98 osdCycles := 0.U
99 selected := 0.U
100 activeRows := 0.U
101 solverCycles := 0.U
102 softOutput := Cat(outcome.marginal.reverse.map(_.asUInt))
103 legsExecuted := outcome.legsExecuted
104 solutionsFound := outcome.solutionsFound
105 legTraceValid := bp.io.legTrace.valid
106 legTraceIndex := bp.io.legTrace.bits.index
107 legTraceIterations := bp.io.legTrace.bits.iterations
108 legTraceConverged := bp.io.legTrace.bits.converged
109
110 when(inputValid && inputReady) {
111 cycleCount := 0.U
112 state := sBp
113 }.elsewhen(state =/= sIdle && !resultValid) {
114 cycleCount := cycleCount + 1.U
115 }
116
117 when(state === sBp && bp.io.out.fire) {
118 outcome := bp.io.out.bits
119 state := sOutput
120 }.elsewhen(state === sOutput && streamer.io.done.fire) {
121 state := sIdle
122 }
123}
124
125object RelayBpExperiment {
126 private val sparseStreamAbi = 2
127 private val legTraceAbi = 1
128 val defaultProfile = RelayBpExperimentProfile()
129 private def bit(value: Boolean): Int = if (value) 1 else 0
130
131 private[chipsldpc] def parseProfile(values: Seq[String]): RelayBpExperimentProfile = {
132 if (values.isEmpty) defaultProfile
133 else {
134 require(values.size == 5, "expected T0 Tr R S seedOffset")
135 val parsed = values.map(_.toInt)
136 RelayBpExperimentProfile(parsed(0), parsed(1), parsed(2), parsed(3), parsed(4))
137 }
138 }
139
140 private[chipsldpc] def artifactConfig(
141 problem: DecoderProblem,
142 config: RelayBpConfig,
143 ): Seq[Int] = Seq(
144 problem.graph.checkCount, problem.n, config.q.magnitudeBits,
145 config.q.accumulatorBits, 0, 0,
146 sparseStreamAbi, SparseBitmaskStreamerConfig(problem.n).bankWidth,
147 config.initialIterations, config.relayIterations, config.maximumLegs,
148 config.solutionTarget, config.seedOffset, legTraceAbi,
149 )
150
151 private[chipsldpc] def golden(problem: DecoderProblem, config: RelayBpConfig): String = {
152 val beta = Reference.lfsrBeta(problem.n, config.maximumLegs, config.seedOffset)
153 val outcome = Reference.runRelay(config, problem.prior, problem.syndrome, beta)
154 val streamConfig = SparseBitmaskStreamerConfig(problem.n)
155 val correctionIndices = outcome.correction.zipWithIndex.collect { case (true, index) => index }
156 val occupiedBanks = correctionIndices.map(_ / streamConfig.bankWidth).distinct.size
157 val correction = correctionIndices.flatMap(index => Seq(index, 1))
158 val legTrace = outcome.legOutcomes.zipWithIndex.flatMap { case (leg, index) =>
159 Seq(index, leg.iterations, 2 * leg.iterations, bit(leg.converged))
160 }
161 Seq(
162 artifactConfig(problem, config), problem.syndrome.map(bit), problem.prior,
163 Seq(
164 if (outcome.success) 0 else 2,
165 outcome.iterations,
166 2 * outcome.iterations + 1 + occupiedBanks + correctionIndices.size,
167 2 * outcome.iterations,
168 0, 0, 0, 0, 0,
169 outcome.legs,
170 outcome.solutions,
171 ),
172 Seq(outcome.legOutcomes.size) ++ legTrace,
173 outcome.state.marginal,
174 Seq(correctionIndices.size) ++ correction,
175 ).map(_.mkString(" ")).mkString("", "\n", "\n")
176 }
177
178 private[chipsldpc] def writeGolden(
179 problem: DecoderProblem,
180 config: RelayBpConfig,
181 output: Path,
182 ): Unit = {
183 Files.createDirectories(output.getParent)
184 Files.writeString(output, golden(problem, config))
185 }
186
187 private def writeConfig(problem: DecoderProblem, config: RelayBpConfig, output: Path): Unit = {
188 val streamConfig = SparseBitmaskStreamerConfig(problem.n)
189 val figure7 = config.initialIterations == 80 && config.relayIterations == 60 &&
190 config.maximumLegs == 601 && config.solutionTarget == 5
191 Files.writeString(output.resolve("artifact/config.txt"),
192 artifactConfig(problem, config).mkString(" ") + "\n")
193 Files.writeString(output.resolve("artifact/config.json"), ujson.Obj(
194 "schema" -> "chipsldpc.bb144-relay-bp.v2",
195 "decoder" -> "relay_bp_s",
196 "profile" -> (if (figure7) "fpga-paper-figure-7-parameters-relay-5-int4.2.8" else "custom"),
197 "paper" -> "arXiv:2510.21600v1 Figure 7",
198 "initial_iterations" -> config.initialIterations,
199 "relay_iterations" -> config.relayIterations,
200 "paper_R_relay_legs_after_initial" -> (config.maximumLegs - 1),
201 "paper_R_interpretation" -> "Algorithm_1_and_trmue_num_sets",
202 "maximum_legs_total" -> config.maximumLegs,
203 "maximum_total_iterations" -> config.maximumIterations,
204 "solution_target" -> config.solutionTarget,
205 "seed_offset" -> config.seedOffset,
206 "coefficient_source" -> "per-variable_16-bit_galois_lfsr_x16+x14+x13+x11+1",
207 "coefficient_frame_policy" -> "reseed_each_frame",
208 "initial_beta" -> LfsrRelayCoefficients.InitialBeta,
209 "initial_gamma" -> 0.125,
210 "relay_beta_min" -> 3,
211 "relay_beta_max" -> 10,
212 "requested_relay_gamma_min" -> -0.24,
213 "requested_relay_gamma_max" -> 0.66,
214 "effective_quantized_relay_gamma_min" -> -0.25,
215 "effective_quantized_relay_gamma_max" -> 0.625,
216 "integer_format" -> "int4.2.8",
217 "prior_scale" -> RelayDefaults.priorScale,
218 "beta_scale" -> RelayDefaults.memoryScale,
219 "beta_fractional_bits" -> config.format.fractionalBits,
220 "candidate_selection" -> "minimum_prior_score_first_tie_wins",
221 "soft_output" -> "final_leg_marginal",
222 "correction_output" -> "best_converged_solution_else_final_leg_estimate",
223 "status" -> "0_if_any_relay_solution_else_2",
224 "correction_stream_abi" -> sparseStreamAbi,
225 "correction_stream" -> "ascending_sparse_ones",
226 "correction_bank_width" -> streamConfig.bankWidth,
227 "empty_correction" -> "zero stream entries; resultValid completes the frame",
228 "leg_trace_abi" -> legTraceAbi,
229 "leg_trace" -> "one nonblocking terminal-VNU event per executed leg",
230 "leg_trace_cycles" -> "measured between consecutive event clock boundaries",
231 "cycle_formula" -> "2*completed_iterations+1+occupied_banks+correction_weight",
232 "leg_control_cycles" -> 0,
233 "paper_decoder_clock_period_ns" -> 12,
234 "paper_bp_iteration_ns" -> 24,
235 "message_bits" -> config.q.magnitudeBits,
236 "soft_bits" -> config.q.accumulatorBits,
237 "m" -> problem.graph.checkCount,
238 "n" -> problem.n,
239 ).render(indent = 2) + "\n")
240 }
241
242 def main(args: Array[String]): Unit = {
243 require(args.length == 2 || args.length == 7,
244 "usage: RelayBpExperiment <problem.json> <output-directory> [T0 Tr R S seedOffset]")
245 val problem = DecoderProblem.read(Paths.get(args(0)))
246 val profile = parseProfile(args.drop(2).toSeq)
247 val config = profile.decoderConfig(problem)
248 val output = Paths.get(args(1))
249 Files.createDirectories(output.resolve("verification"))
250 Files.createDirectories(output.resolve("artifact"))
251 writeGolden(problem, config, output.resolve("verification/golden.txt"))
252 writeConfig(problem, config, output)
253 Generate.emitSystemVerilogFiles(
254 () => new RelayBpArtifact(problem, config), output.resolve("artifact/rtl"),
255 )
256 println(output.toAbsolutePath)
257 }
258}
259
260object RelayBpSweepGolden {
261 def main(args: Array[String]): Unit = {
262 require(args.length >= 7 && (args.length - 5) % 2 == 0,
263 "usage: RelayBpSweepGolden T0 Tr R S seedOffset (<problem.json> <golden.txt>)+")
264 val profile = RelayBpExperiment.parseProfile(args.take(5).toSeq)
265 args.drop(5).grouped(2).foreach { pair =>
266 val problem = DecoderProblem.read(Paths.get(pair(0)))
267 RelayBpExperiment.writeGolden(
268 problem, profile.decoderConfig(problem), Paths.get(pair(1)),
269 )
270 }
271 }
272}
273
274final class RelayBpArtifactSpec extends AnyFreeSpec with ChiselSim {
275 private val problem = DecoderProblem.parse(
276 """{"schema":1,"n":3,"row_ones":[[0,1,2]],"prior":[1,1,1],"syndrome":[1],"iterations":1}""",
277 )
278 private val profile = RelayBpExperimentProfile(
279 initialIterations = 1, relayIterations = 1, relayLegs = 2,
280 solutionTarget = 1, seedOffset = 17,
281 )
282 private val config = profile.decoderConfig(problem)
283
284 "the default experiment profile is Figure 7 Relay-5" in {
285 assert(RelayBpExperiment.defaultProfile == RelayBpExperimentProfile(
286 initialIterations = 80, relayIterations = 60, relayLegs = 600,
287 solutionTarget = 5, seedOffset = 0,
288 ))
289 assert(RelayBpExperiment.defaultProfile.decoderConfig(problem).maximumLegs == 601)
290 }
291
292 private def pack(values: Seq[Int], width: Int): BigInt =
293 values.zipWithIndex.foldLeft(BigInt(0)) { case (word, (value, index)) =>
294 word | BigInt(value) << (index * width)
295 }
296
297 private def signedField(value: BigInt, index: Int): Int = {
298 val width = config.q.accumulatorBits
299 val field = (value >> (index * width)) & ((BigInt(1) << width) - 1)
300 if (field.testBit(width - 1)) (field - (BigInt(1) << width)).toInt else field.toInt
301 }
302
303 "matches the independent Relay model and sparse-stream timing" in {
304 val beta = Reference.lfsrBeta(problem.n, config.maximumLegs, config.seedOffset)
305 val expected = Reference.runRelay(config, problem.prior, problem.syndrome, beta)
306 val indices = expected.correction.zipWithIndex.collect { case (true, index) => index }
307 val occupiedBanks = indices.map(_ / SparseBitmaskStreamerConfig(problem.n).bankWidth).distinct.size
308 val expectedCycles = 2 * expected.iterations + 1 + occupiedBanks + indices.size
309
310 simulate(new RelayBpArtifact(problem, config)) { dut =>
311 dut.inputValid.poke(false.B)
312 dut.legLimit.poke(config.maximumLegs.U)
313 dut.scopeValid.poke(false.B)
314 dut.scope.poke(0.U)
315 dut.correctionReady.poke(true.B)
316 dut.resultReady.poke(true.B)
317 dut.reset.poke(true.B)
318 dut.clock.step()
319 dut.reset.poke(false.B)
320
321 for (_ <- 0 until 2) {
322 dut.syndrome.poke(pack(problem.syndrome.map(if (_) 1 else 0), 1).U)
323 dut.prior.poke(pack(problem.prior, config.q.magnitudeBits).U)
324 dut.inputValid.poke(true.B)
325 dut.inputReady.expect(true.B)
326 dut.clock.step()
327 dut.inputValid.poke(false.B)
328
329 val observed = Vector.newBuilder[Int]
330 val observedLegs = Vector.newBuilder[(Int, Int, Int, Boolean)]
331 var elapsed = 0
332 var previousBoundary = 0
333 while (!dut.resultValid.peek().litToBoolean && elapsed <= expectedCycles) {
334 if (dut.legTraceValid.peek().litToBoolean) {
335 val boundary = elapsed + 1
336 observedLegs += ((
337 dut.legTraceIndex.peek().litValue.toInt,
338 dut.legTraceIterations.peek().litValue.toInt,
339 boundary - previousBoundary,
340 dut.legTraceConverged.peek().litToBoolean,
341 ))
342 previousBoundary = boundary
343 }
344 if (dut.correctionValid.peek().litToBoolean) {
345 dut.correctionValue.expect(true.B)
346 observed += dut.correctionIndex.peek().litValue.toInt
347 }
348 dut.clock.step()
349 elapsed += 1
350 }
351 assert(elapsed == expectedCycles)
352 assert(observed.result() == indices)
353 assert(observedLegs.result() == expected.legOutcomes.zipWithIndex.map {
354 case (leg, index) => (index, leg.iterations, 2 * leg.iterations, leg.converged)
355 })
356 dut.status.expect((if (expected.success) 0 else 2).U)
357 dut.completedIterations.expect(expected.iterations.U)
358 dut.bpCycles.expect((2 * expected.iterations).U)
359 dut.cycles.expect(expectedCycles.U)
360 dut.legsExecuted.expect(expected.legs.U)
361 dut.solutionsFound.expect(expected.solutions.U)
362 val soft = dut.softOutput.peek().litValue
363 expected.state.marginal.indices.foreach { index =>
364 assert(signedField(soft, index) == expected.state.marginal(index))
365 }
366 dut.clock.step()
367 dut.inputReady.expect(true.B)
368 }
369 }
370 }
371}