src/test/scala/chipsldpc/Reference.scala
Source from the repository checkout used to build these docs. Line numbers link to individual source lines.
1package chipsldpc
2
3import chipsldpc.graph.TannerNodeGraphs
4
5object Reference {
6 final case class SignMag(sign: Boolean, magnitude: Int) {
7 def signed: Int = if (sign && magnitude != 0) -magnitude else magnitude
8 }
9 final case class MinPair(first: Int, second: Int)
10 final case class EdgeMeta(sign: Boolean, useSecond: Boolean)
11 final case class CheckResult(minima: MinPair, edges: Seq[EdgeMeta])
12 final case class CheckMessage(minima: MinPair, sign: Boolean, useSecond: Boolean) {
13 def signed: Int = SignMag(sign, if (useSecond) minima.second else minima.first).signed
14 }
15 final case class VariableResult(marginal: Int, decision: Boolean, extrinsic: Seq[SignMag])
16 final case class DecoderState(v2c: Vector[SignMag], marginal: Vector[Int], decision: Vector[Boolean])
17 final case class LegOutcome(iterations: Int, converged: Boolean)
18 final case class DecoderOutcome(
19 success: Boolean,
20 correction: Vector[Boolean],
21 state: DecoderState,
22 residual: Vector[Boolean],
23 iterations: Int,
24 legs: Int,
25 solutions: Int,
26 legOutcomes: Vector[LegOutcome],
27 )
28
29 def twoMin(values: Seq[Int]): MinPair = {
30 val sorted = values.sorted
31 MinPair(sorted(0), sorted(1))
32 }
33
34 private def maximum(bits: Int): Int = (1 << bits) - 1
35
36 def scale(value: Int, control: Int, policy: CheckScale, bits: Int): Int = policy match {
37 case NoScale => value
38 case VallsScale(a, b) => ((value >> a) + (value >> b)).min(maximum(bits))
39 case RampScale(limit) => if (control <= limit) value - (value >> control) else value
40 }
41
42 def check(inputs: Seq[SignMag], syndrome: Boolean, control: Int, config: CheckConfig): CheckResult = {
43 val minima = twoMin(inputs.map(_.magnitude))
44 val scaled = MinPair(
45 scale(minima.first, control, config.scale, config.q.magnitudeBits),
46 scale(minima.second, control, config.scale, config.q.magnitudeBits),
47 )
48 val parity = inputs.foldLeft(syndrome)((p, x) => p ^ (x.sign && x.magnitude != 0))
49 val edges = inputs.map { input =>
50 val useSecond = input.magnitude == minima.first
51 EdgeMeta(parity ^ (input.sign && input.magnitude != 0), useSecond)
52 }
53 CheckResult(scaled, edges)
54 }
55
56 private def clip(value: Int, bits: Int): Int =
57 value.max(-(1 << (bits - 1))).min((1 << (bits - 1)) - 1)
58
59 private def signMag(value: Int, bits: Int): SignMag = {
60 val magnitude = value.abs.min(maximum(bits))
61 SignMag(value < 0 && magnitude != 0, magnitude)
62 }
63
64 def hardDecision(value: Int): Boolean = value < 0
65
66 def variable(inputs: Seq[CheckMessage], prior: Int, config: VariableConfig): VariableResult = {
67 val messages = inputs.map(_.signed)
68 val total = prior + messages.sum
69 VariableResult(
70 clip(total, config.q.accumulatorBits),
71 hardDecision(total),
72 messages.map(message => signMag(total - message, config.q.magnitudeBits)),
73 )
74 }
75
76 def relayProduct(value: Int, beta: Int, format: RelayFormat, q: Quantization): Int = {
77 val magnitude = math.abs(value)
78 val product = (0 until q.accumulatorBits)
79 .filter(bit => ((magnitude >> bit) & 1) != 0)
80 .map(bit => (beta << bit) >> format.fractionalBits)
81 .sum
82 if (value < 0) -product else product
83 }
84
85 def relayBias(prior: Int, previous: Int, beta: Int, format: RelayFormat, q: Quantization): Int =
86 clip(
87 relayProduct(prior, beta, format, q) + previous -
88 relayProduct(previous, beta, format, q),
89 q.accumulatorBits,
90 )
91
92 def initialize(nodes: TannerNodeGraphs, priors: Seq[Int], q: Quantization): DecoderState = {
93 require(priors.size == nodes.graph.variableCount)
94 require(priors.forall(p => p >= 0 && p <= maximum(q.magnitudeBits)))
95 DecoderState(
96 nodes.graph.edges.map(edge => SignMag(false, priors(edge.variable))),
97 priors.map(clip(_, q.accumulatorBits)).toVector,
98 Vector.fill(priors.size)(false),
99 )
100 }
101
102 def iterate(
103 nodes: TannerNodeGraphs,
104 state: DecoderState,
105 syndrome: Seq[Boolean],
106 biases: Seq[Int],
107 control: Int,
108 q: Quantization,
109 scalePolicy: CheckScale,
110 ): DecoderState = {
111 require(syndrome.size == nodes.graph.checkCount && state.v2c.size == nodes.graph.edgeCount)
112 val checks = nodes.checks.map { node =>
113 check(
114 node.edges.map(edge => state.v2c(edge.edgeId)),
115 syndrome(node.checkId),
116 control,
117 CheckConfig(node.degree, q, scalePolicy),
118 )
119 }
120 val variables = nodes.variables.map { node =>
121 val messages = node.edges.map { edge =>
122 val port = nodes.connections(edge.edgeId).checkPort
123 val result = checks(edge.checkId)
124 CheckMessage(result.minima, result.edges(port).sign, result.edges(port).useSecond)
125 }
126 variable(messages, biases(node.variableId), VariableConfig(node.degree, q))
127 }
128 val v2c = nodes.connections.map { edge =>
129 variables(edge.variableId).extrinsic(edge.variablePort)
130 }
131 DecoderState(v2c, variables.map(_.marginal), variables.map(_.decision))
132 }
133
134 def relayIterate(
135 nodes: TannerNodeGraphs,
136 state: DecoderState,
137 syndrome: Seq[Boolean],
138 priors: Seq[Int],
139 beta: Seq[Int],
140 control: Int,
141 q: Quantization,
142 scalePolicy: CheckScale,
143 format: RelayFormat,
144 ): DecoderState = {
145 val biases = priors.indices.map { i => relayBias(priors(i), state.marginal(i), beta(i), format, q) }
146 iterate(nodes, state, syndrome, biases, control, q, scalePolicy)
147 }
148
149 def residual(nodes: TannerNodeGraphs, state: DecoderState, syndrome: Seq[Boolean]): Vector[Boolean] =
150 nodes.graph.rowOnes.zip(syndrome).map { case (row, bit) =>
151 row.foldLeft(bit)((parity, variable) => parity ^ state.decision(variable))
152 }
153
154 def runVanilla(
155 config: VanillaBpConfig,
156 priors: Vector[Int],
157 syndrome: Vector[Boolean],
158 ): DecoderOutcome = {
159 var state = initialize(config.nodes, priors, config.q)
160 var iteration = 0
161 var converged = false
162 while (iteration < config.iterations && !converged) {
163 iteration += 1
164 state = iterate(
165 config.nodes, state, syndrome, priors,
166 iteration.min((1 << config.scale.controlBits) - 1), config.q, config.scale,
167 )
168 converged = !residual(config.nodes, state, syndrome).contains(true)
169 }
170 DecoderOutcome(
171 converged, state.decision, state, residual(config.nodes, state, syndrome),
172 iteration, legs = 1, solutions = if (converged) 1 else 0,
173 legOutcomes = Vector(LegOutcome(iteration, converged)),
174 )
175 }
176
177 def runRelay(
178 config: RelayBpConfig,
179 priors: Vector[Int],
180 syndrome: Vector[Boolean],
181 beta: Vector[Vector[Int]],
182 ): DecoderOutcome = {
183 require(beta.size == config.maximumLegs && beta.forall(_.size == priors.size))
184 val initialMessages = initialize(config.nodes, priors, config.q).v2c
185 var state = initialize(config.nodes, priors, config.q)
186 var best = Option.empty[(Int, Vector[Boolean])]
187 var solutions = 0
188 var total = 0
189 var leg = 0
190 var done = false
191 val legOutcomes = Vector.newBuilder[LegOutcome]
192
193 while (!done) {
194 val limit = if (leg == 0) config.initialIterations else config.relayIterations
195 var local = 0
196 var legDone = false
197 var legConverged = false
198 while (!legDone) {
199 local += 1
200 total += 1
201 state = relayIterate(
202 config.nodes, state, syndrome, priors, beta(leg),
203 local.min((1 << config.scale.controlBits) - 1),
204 config.q, config.scale, config.format,
205 )
206 legConverged = !residual(config.nodes, state, syndrome).contains(true)
207 if (legConverged) {
208 solutions += 1
209 val score = priors.zip(state.decision).collect { case (prior, true) => prior }.sum
210 if (best.forall(score < _._1)) best = Some(score -> state.decision)
211 }
212 legDone = legConverged || local == limit
213 }
214 legOutcomes += LegOutcome(local, legConverged)
215
216 done = solutions >= config.solutionTarget || leg + 1 == config.maximumLegs
217 if (!done) {
218 state = state.copy(v2c = initialMessages)
219 leg += 1
220 }
221 }
222
223 val finalResidual = residual(config.nodes, state, syndrome)
224 DecoderOutcome(
225 solutions > 0, best.map(_._2).getOrElse(state.decision), state,
226 if (solutions > 0) Vector.fill(finalResidual.size)(false) else finalResidual,
227 total, leg + 1, solutions,
228 legOutcomes.result(),
229 )
230 }
231
232 def lfsrBeta(variableCount: Int, legs: Int, seedOffset: Int): Vector[Vector[Int]] = {
233 def seed(lane: Int): Int =
234 1 + ((BigInt(seedOffset) + BigInt(lane) * 32768) % 65535).toInt
235 def step(state: Int): Int =
236 (state >>> 1) ^ (if ((state & 1) != 0) 0xb400 else 0)
237 var states = Vector.tabulate(variableCount)(seed)
238 Vector.tabulate(legs) { leg =>
239 if (leg == 0) Vector.fill(variableCount)(7)
240 else {
241 states = states.map(step)
242 states.map(value => 3 + (value & 7))
243 }
244 }
245 }
246}