Follow-up: lost 289th bit in the reduction mod 2^256-2^32-977 after nj_umul256wide - correct fix costs 1.2 % on sm_89, cheaper way?

Hi @njuffa,

this is a follow-up to my earlier thread Squeezing the last 17.5% out of a compute-bound 256-bit modular arithmetic kernel, which has been closed automatically. It is about the 512 → 256 reduction that follows your nj_umul256wide (post #29), modulo the secp256k1 field prime p = 2^256 - 2^32 - 977.

In #41 you asked how we know that (2^32 + 977) * h fits into nine 32-bit chunks t0..t8 rather than ten. In #42 I agreed that it does not fit, but I drew the wrong conclusion. I claimed the result was merely left in [p, 2p) and that a final conditional subtraction would fix it. That was wrong. The carry out of t8 is simply discarded, so the result is a wrong residue, off by exactly -2^288 (mod p), and not just a non-reduced one. The value I reported for (p-1)^2 in #42, 0xFFFF...FFFEFFFFFC2DFFFFFC30, is exactly (1 - 2^288) mod p, and it is below p. A final if (r >= p) r -= p would not have changed anything. Your bit-counting question was spot on, and I should have followed it through properly back then.

I have now characterized the bug, verified a fix on the RTX 4090, and measured its cost: about 1.2 % end-to-end throughput. My question is whether there is a cheaper way to do this reduction correctly on sm_89.

TL;DR

  • t = h * (2^32 + 977) needs 289 bits, but only nine 32-bit words t0..t8 (288 bits) are kept. addc.u32 t8, t8, h7; drops the carry whenever the top product word h7 is >= ~0xFFFFFC30. The result is then correct - 2^288 (mod p).
  • For a squaring of a uniformly random input this happens with probability ~488/2^32 = 1.14e-7. Measured on the RTX 4090: 7,776 wrong results in 6.87e10 random squarings.
  • In the kernel, one modsqr per launch advances each thread’s state. So on an RTX 4090 (4,194,304 threads) about 0.5 threads per launch end up working on a wrong point for the rest of the run. That is 104 threads after 200 launches in my test, and 0 with the fix.
  • Keeping bit 288 in an extra register and folding (t9:t8) costs +7..+13 SASS per modmul/modsqr (see tables). Is there a better formulation?

Setup

  • Same kernel as in the old thread: RTX 4090 (sm_89), also checked on a GTX 1660 Ti (sm_75). CUDA 12.8, MSVC 2022, Windows.
  • Each thread computes a batch of affine point additions P + iG and P - iG (i = 1..512) that share one modular inverse (Montgomery’s trick). Per resulting point: 3 modmul + 1 modsqr, plus 0.5 modmul for the prefix products and some per-point work that is not arithmetic. At the end of each launch, the per-thread state P is advanced by a fixed point J (one more modsqr).
  • The kernel is compute-bound and sits exactly at 128 registers/thread (256-thread blocks, 2 blocks/SM). Anything that needs more registers halves occupancy. All variants below still compile to 128 registers with 0 spill.
  • Operands are 4 x 64-bit limbs, little-endian. Inputs to modmul/modsqr are arbitrary values < 2^256 (not necessarily < p). The output only has to be < 2^256 and congruent mod p (not fully reduced); the rest of the code copes with that.

The reduction as it was (buggy)

This is the same code I posted in #39. _ModSqr is identical except that it calls nj_umul256wide(a4, a4, r512); its reduction block is character-for-character the same as below.

What goes wrong

The first fold computes t = h * 977 + (h << 32) into t0..t8. Since h < 2^256, h * (2^32 + 977) < 2^288 * (1 + 977/2^32), i.e. it can exceed 2^288. The last add of the chain

"addc.u32        t8, t8, h7;\n\t"

produces a carry out whenever hi(h7*977) + h7 + CF >= 2^32, i.e. for h7 >= ~0xFFFFFC30, and that carry is discarded. The result is then correct - 2^288 (mod p), with 2^288 mod p = 0x1000003D100000000.

  • Squares a*a, a uniform in [0, 2^256): needs a >= 2^256 * sqrt(1 - 976/2^32), probability ~488/2^32 = 1.14e-7.
  • Products a*b, a and b independent and uniform: ~0.5 * (977/2^32)^2 = 2.6e-14.
  • A second, much rarer case: the final carry out of word 7 in the second fold is also dropped. It needs the intermediate to be within ~2^65 of 2^256 (~2^-190 for random inputs; for squares only when a lies within ~2^33 below 2^256).

Examples (original vs. fixed, 256-bit values as big-endian hex):

input a a^2 mod p original result fixed result
p - 1 ...0001 FFFF...FFFEFFFFFC2DFFFFFC30 (wrong) FFFF...FFFFFFFEFFFFFC30 (= p + 1, ok)
FFFFFFFEFFFFFFFEC9208929BBA0FCD041682F0E1517DDF500000001CAB5E7C3 ...2EA975AD30F8199F0D95ED27 ...2EA975AC30F815CE0D95ED27 (wrong) ...2EA975AD30F8199F0D95ED27 (ok)
FFFFFFFFFFFFFC2F000000000000000000000000000000000123456789ABCDEF ...DE7A81859F3545C8625AEDA7 ...DE7A81849F3541F7625AEDA7 (wrong) ...DE7A81859F3545C8625AEDA7 (ok)

In all failing cases the difference is exactly -(2^288 mod p).

In the kernel this matters mostly through the modsqr in the per-thread state update: once a state is computed wrongly, all later launches of that thread work on a wrong point. On the RTX 4090, 104 of 4,194,304 thread states were wrong after 200 launches (0 with the fix); on the GTX 1660 Ti 26 of 524,288 after 400 launches. That matches the 1.14e-7 rate.

Our fix

  1. addc.cc.u32 t8, t8, h7; + addc.u32 t9, 0, 0; keeps bit 288.
  2. After adding t0..t7 to the low half: addc.cc.u32 t8, t8, 0; + addc.u32 t9, t9, 0;. Now H = t9:t8 <= 2^32 + 978.
  3. Second fold with H instead of t8: mad.lo.u32 t1, t9, 977, t1; (t9*977 into word 1) and add.u32 c, c, t9; (t9 into word 2).
  4. Third fold: the carry out of word 7 is captured and c*(2^32 + 977) is added once more. After an overflow the value is < 2^65, so this cannot overflow again and touches only words 0..2.

With this the result is < 2^256 and == a*b (mod p) for all a, b < 2^256. The “minimal” variant does only steps 1-3 and keeps the old behavior for the ~2^-190 case.

Cost on sm_89 (CUDA 12.8)

SASS instruction counts. A standalone kernel does one operation; the counts include 8 LDG / 4 STG and about 22 MOV.

kernel original fix (steps 1-4) minimal (steps 1-3)
nj_umul256wide only 126 126 126
_ModMult (mul + reduction) 173 186 (+13) 181 (+8)
_ModSqr 163 176 (+13) 170 (+7)
full kernel, main loop, per point 2817.5 2866.0 (+1.72 %) 2846.5 (+1.03 %)
registers / spill 128 / 0 128 / 0 128 / 0
throughput RTX 4090 (M points/s) 8,135 8,040 (-1.17 %) 8,084 (-0.63 %)

Throughput was measured in order A-F-M-K-K-M-F-A, 90 s per run with 60 s pauses; run-to-run spread is about ±0.1 %.

For comparison, the arithmetic part of the main loop (with the non-arithmetic per-point work stubbed out) is about 756 SASS per point. Its mix per point is IMAD.WIDE 296, IADD3.X ~200, and the rest IADD3/IMAD/SEL/MOV.

Verification

  • A Python emulator of the exact PTX (including CC.CF semantics) reproduces the GPU results bit-exactly for 135k inputs. The 512-bit product was always correct; only the reduction failed.

  • A GPU test bench compares against a deliberately simple loop-based reference (32-bit schoolbook, repeated folding, final reduction to [0, p)), plus an independent Python check of a sample. Inputs:

    • all 7^8 = 5,764,801 combinations of limb values {0, 1, 2, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFE, 0xFFFFFFFF}, as a^2 and a*b
    • 5.4e8 structured random inputs (each 32-bit limb 50 % “special”)
    • 5.4e8 uniform random inputs

    Fixed version: 0 mismatches everywhere (sm_75 and sm_89). The original has 1,647,086 wrong squares and 470,584 wrong products among the pattern inputs, and 67,107,372 wrong squares among 5.4e8 structured random ones.

Side note: squaring by reusing duplicate partial products did not help

I tried a squaring that is a copy of nj_umul256wide with b := a, where the 28 duplicated products a_i*a_j (i != j) are replaced by a mov from their already computed twin. The add chains are unchanged, so the result is bit-identical. On sm_89 this was slower:

  • per point: IMAD.WIDE 292 → 284, but IADD3.X 215 → 229
  • total SASS per point: +8.5; throughput: -0.2 %

Apparently ptxas fuses mul.wide.u32 with the following 64-bit add into an IMAD.WIDE(.X) with accumulator. Once the multiply is gone, the add shows up as separate IADD3/IADD3.X instructions.

Questions

  1. Is there a cheaper correct reduction modulo 2^256 - 2^32 - 977 on sm_89? For example, a formulation in which bit 288 cannot get lost in the first place, or one where the fold of the high half is merged into the multiply’s accumulation chains (a single fused “mulmod” asm block)?
  2. Given the contracts (inputs < 2^256, output < 2^256 and congruent, not fully reduced), is the three-fold structure above the right shape? Or is there a standard bound argument or trick that makes one of the steps unnecessary?
  3. Would a dedicated 256-bit squaring that keeps ptxas’ IMAD.WIDE accumulate fusion be expected to beat a*a on sm_89? If so, how would you structure it?
  4. Any general advice on how to evaluate such variants beyond SASS counts? In our experience SASS savings do not always translate into throughput on this kernel (~33 % occupancy, math-pipe bound).

Thanks a lot for any hints. Thanks also for the multiply routine itself, and for the question in #41 that pointed straight at this bug.

Very detailed analysis that makes for a fascinating read. Unfortunately, I don’t have any ideas for a cheaper fix.

As for accurately assessing the performance impact, in addition to a unit test, the preferred way in my book is to measure end-to-end in a real-life context where the function under test is actually being used. That is the approach I used when I worked on fixed-point and software floating-point math libraries for OpenGL-ES at NVIDIA, by rendering relevant test scenes. I even automated it so a regression test would run after every check-in. The reason measuring in context is important is because small changes in one direction in a unit test can actually turn into a change in the opposite direction due to interaction with other components.

However, small changes will often stay within a 2% noise level. I decided on that limit based on experience with repeated measurements; there is enough state involved that one never achieves absolute agreement between repeated runs.

What I am wondering about is your approach to correctness. Testing with random operands makes bugs like the one discussed here hard to find due to the very small chance of encountering it, as I am painfully aware from working on both integer and floating-point arithmetic, software and hardware. As a young engineer in Silicon Valley, I got a front-row seat to the impact of the Pentium division bug, and that really drove the point home.

Other than white-box testing based on knowledge of transition points in a design, I have had reasonable success finding issues in black-box testing by using the simple patterns described in

Norman L. Schryer, A Test of a Computer’s Floating-Point Arithmetic Unit. Technical report, AT&T Bell Laboratories, February 1981.

There used to be a Postscript (.ps) file of this technical report floating around the internet. If you cannot find it, I can describe the patterns, there are not that many. At one company I worked for we also used test generation technology from IBM’s Haifa Labs. The experience was positive, but it was a long time ago and I wouldn’t know anything about the cost or whether this is still a thing.

Of course, there are non-test approaches like review processes and (mechanically checked) mathematical proofs. One of my colleagues at AMD in the 1990s, David Russinoff, is an expert in the latter and wrote a book about this, which is now in its second edition. It is floating-point centric, though.

[Later:]

Looking at my paper copy of Schryer’s report, the patterns, other than all-0 and all-1, really boil down to (1 << i) ± (1 << k), but he assigns separate classes to cases where k=0 or where i=(n-1), where n is the bit-width of the operands. So those produce left-contiguous and right-contiguous masks

0...01...1
1...10...0

or a solitary left/right “roaming” 1 bit:

0...010...01
10...010...0

Looking at some of my code base, I seem to have added patterns with 1...10...01 and 10...01...1, as well as repeated blocks of 0s and 1s generated from (2n-1) / (2j+1), j=1,2,4,… I did not record the rationale for adding these. The first two were probably motivated by testing of floating-point arithmetic in conjunction with the masks 1...10...0 and 0...01...1, the third one by the testing of in-register SIMD operators.

It is good to hear that you were able to put the issue to rest, and I am impressed that you did all this work and produced a new write-up in the space of 1.5 hours.