"""Recompute every number on /crypto/lwr. Usage: python3 lwr-samples.py Source: https://www.lattices.io/examples/lwr-samples.py Exact rational arithmetic, no dependencies. It regenerates the two worked tables on the page and asserts each value, so the page cannot drift from the arithmetic. It also shows why ML-KEM's q = 3329 cannot use the clean p | q rounding that LWR relies on. """ from fractions import Fraction Q = 8 P = 2 SCALE = Fraction(P, Q) SECRET = (3, 5) def round_half_up(x: Fraction) -> int: """Round to the nearest integer; exact halves round up.""" return (2 * x.numerator + x.denominator) // (2 * x.denominator) def lwr_sample(a, secret=SECRET, q=Q, p=P): """Return (inner product, scaled value, rounded value, b, rounding error).""" scale = Fraction(p, q) inner = sum(ai * si for ai, si in zip(a, secret, strict=True)) scaled = scale * inner rounded = round_half_up(scaled) return inner, scaled, rounded, rounded % p, scaled - rounded def table_one(): print(f"LWR samples with n=2, q={Q}, p={P}, p/q={SCALE}, s={SECRET}\n") print(f" {'a':>8} {'':>7} {'(p/q)':>12} {'round':>6} {'b':>3} {'error':>8}") vectors = [(1, 2), (2, 1), (3, 3), (1, 0), (0, 1)] expected = [ ((1, 2), 13, Fraction(13, 4), 3, 1, Fraction(1, 4)), ((2, 1), 11, Fraction(11, 4), 3, 1, Fraction(-1, 4)), ((3, 3), 24, Fraction(6), 6, 0, Fraction(0)), ((1, 0), 3, Fraction(3, 4), 1, 1, Fraction(-1, 4)), ((0, 1), 5, Fraction(5, 4), 1, 1, Fraction(1, 4)), ] for a, (ea, ei, es, er, eb, ee) in zip(vectors, expected, strict=True): inner, scaled, rounded, b, error = lwr_sample(a) assert (a, inner, scaled, rounded, b, error) == (ea, ei, es, er, eb, ee), a print(f" {str(a):>8} {inner:>7} {float(scaled):>12.2f} {rounded:>6} {b:>3} {float(error):>+8.2f}") # The rounding error never exceeds half a step in the scaled domain. assert all(abs(lwr_sample(a)[4]) <= Fraction(1, 2) for a in vectors) print("\n every |error| <= 1/2 in the scaled domain: ok") # Exactly on an integer whenever is a multiple of 4. assert lwr_sample((3, 3))[4] == 0 and 24 % 4 == 0 print(" = 24 is a multiple of 4, so its error is exactly 0: ok") def table_two(): print(f"\nSame a = (1, 2), three secrets -> the output bit collides, the errors differ\n") print(f" {'s':>8} {'':>7} {'(p/q)':>12} {'b':>3} {'error':>8}") secrets = [(3, 5), (1, 1), (7, 2)] expected = [((3, 5), 13, 1, Fraction(1, 4)), ((1, 1), 3, 1, Fraction(-1, 4)), ((7, 2), 11, 1, Fraction(-1, 4))] bits = [] for s, (es, ei, eb, ee) in zip(secrets, expected, strict=True): inner, scaled, _, b, error = lwr_sample((1, 2), secret=s) assert (s, inner, b, error) == (es, ei, eb, ee), s bits.append(b) print(f" {str(s):>8} {inner:>7} {float(scaled):>12.2f} {b:>3} {float(error):>+8.2f}") assert len(set(bits)) == 1, "all three secrets give b = 1" assert len({lwr_sample((1, 2), secret=s)[4] for s in secrets}) == 2 print("\n all three produce b = 1, but only two distinct errors: the bit alone") print(" does not determine the remainder, and the remainder depends on the secret.") def modulus_contrast(): """Why LWR wants p | q, and why ML-KEM's prime modulus cannot have it.""" print("\nModulus choices and the p | q condition\n") for q, p, label in [ (8, 2, "the worked example above"), (2 ** 13, 2 ** 10, "SABER: q = 2^13, p = 2^10"), (3329, 256, "ML-KEM compression to d = 8 bits"), (3329, 2 ** 11, "ML-KEM compression to d = 11 bits"), ]: divides = q % p == 0 saving = 100 * (1 - Fraction(p.bit_length() - 1, q.bit_length() - 1)) if q != 8 else None note = "clean rounding" if divides else "NOT clean: rounding needs an explicit error bound" print(f" q = {q:<5} p = {p:<5} p|q = {str(divides):<5} {label}") print(f" {'':>22}{note}") if divides: assert q % p == 0 # The 23% per-coefficient saving quoted on the page. saved = 1 - Fraction(10, 13) print(f"\n SABER ratio: log2(p)/log2(q) = 10/13, so each coefficient saves " f"{float(saved) * 100:.1f}% before further compression") assert abs(float(saved) * 100 - 23.1) < 0.2 # ML-KEM: q = 3329 is prime, so no power of two divides it. q = 3329 assert all(q % (2 ** d) != 0 for d in range(1, 12)), "3329 is odd" print(f" q = {q} is odd, so no power-of-two p divides it; ML-KEM samples LWE noise") print(" and then rounds to save bytes. That is compression, not LWR.") if __name__ == "__main__": table_one() table_two() modulus_contrast() print("\nAll checks passed.")