Debian Codegraph @

src/UnsaturatedSolinasHeuristics.v

raw
1 From Coq Require Import List.
2 From Coq Require Import Lia.
3 From Coq Require Import ZArith.
4 From Coq Require Import QArith_base Qround.
5 From Coq Require Import Qabs.
6 Require Import Crypto.Arithmetic.Core.
7 Require Import Crypto.Arithmetic.ModOps.
8 Require Import Crypto.Arithmetic.Partition.
9 Require Import Crypto.Util.ListUtil.
10 Require Import Crypto.Util.ZRange.
11 Require Import Crypto.Util.Option.
12 Require Import Crypto.Util.NatUtil.
13 Require Import Crypto.Util.ZUtil.Modulo.
14 Require Import Crypto.Util.ZUtil.Tactics.LtbToLt.
15 Require Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.
16 Require Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.
17 Require Import Crypto.Util.ListUtil.FoldBool.
18 Require Crypto.TAPSort.
19 Import ListNotations.
20 Local Open Scope Z_scope. Local Open Scope list_scope. Local Open Scope bool_scope.
21
22 Import Associational Positional.
23
24 Section encode_distributed.
25 Context weight
26 (n : nat)
27 (s : Z)
28 (c : list (Z * Z))
29 {wprops : @weight_properties weight}.
30
31 Local Notation eval := (eval weight) (only parsing).
32
33 (** Sometimes we want to ensure that each limb of our encoded
34 number [x] is larger than the corresponding limb of a given
35 bound [minvalues]. We can ensure this by encoding [x -
36 minvalues] in a way that ensures each limb is non-negative,
37 and then adding back [minvalues]. We extend [minvalues] with
38 zeros for convenience, so we don't need a proof that [length
39 minvalues = n] for the proofs about [encode_distributed]. *)
40 Definition encode_distributed (minvalues : list Z) (x : Z) : list Z
41 := let minvalues := List.firstn n (minvalues ++ List.repeat 0 n) in
42 (add weight n)
43 (Partition.partition weight n ((x - Positional.eval weight n minvalues) mod (s - Associational.eval c)))
44 minvalues.
45
46 Lemma eval_encode_distributed minvalues x
47 : 0 < s - Associational.eval c <= weight n
48 -> eval n (encode_distributed minvalues x) mod (s - Associational.eval c)
49 = x mod (s - Associational.eval c).
50 Proof using wprops.
51 intros; cbv [encode_distributed]; rewrite eval_add, Partition.eval_partition by (auto; distr_length).
52 assert (forall x, x mod (s - Associational.eval c) < s - Associational.eval c) by auto with zarith.
53 rewrite (Z.mod_small (_ mod (s - _)) (weight _)) by now eauto using Z.lt_le_trans with zarith.
54 pull_Zmod; now autorewrite with zsimplify_fast.
55 Qed.
56 Hint Rewrite eval_encode_distributed : push_eval.
57 Lemma length_encode_distributed minvalues x
58 : length (encode_distributed minvalues x) = n.
59 Proof using Type. cbv [encode_distributed]; repeat distr_length. Qed.
60 Hint Rewrite length_encode_distributed : distr_length.
61 Lemma nth_default_encode_distributed_bounded_eq'
62 (** We add an extra hypothesis that is too bulky to prove *)
63 (Hadd : forall x y, length x = n -> length y = n -> add weight n x y = List.map2 Z.add x y)
64 minvalues x i d
65 : nth_default d (encode_distributed minvalues x) i
66 = if Decidable.dec (i < n)%nat
67 then (((x - Positional.eval weight n (firstn n (minvalues ++ repeat 0 n)))
68 mod (s - Associational.eval c)) mod weight (S i))
69 / weight i
70 + nth_default 0 minvalues i
71 else d.
72 Proof using wprops.
73 cbv [encode_distributed].
74 rewrite Hadd by repeat distr_length.
75 rewrite nth_default_map2 with (d1:=0) (d2:=0);
76 autorewrite with push_nth_default distr_length.
77 autorewrite with natsimplify.
78 break_innermost_match; try lia.
79 now rewrite nth_default_out_of_bounds by lia.
80 Qed.
81 Lemma nth_default_encode_distributed_bounded'
82 (** We add an extra hypothesis that is too bulky to prove *)
83 (Hadd : forall x y, length x = n -> length y = n -> add weight n x y = List.map2 Z.add x y)
84 minvalues x i d' d
85 (Hmin : (i < length minvalues)%nat)
86 (Hn : (i < n)%nat)
87 : nth_default d' minvalues i <= nth_default d (encode_distributed minvalues x) i.
88 Proof using wprops.
89 rewrite (nth_default_in_bounds 0 d) by repeat distr_length.
90 rewrite (nth_default_in_bounds 0 d') by lia.
91 rewrite nth_default_encode_distributed_bounded_eq' by auto.
92 break_innermost_match; try lia.
93 match goal with |- ?x <= ?y + ?x => cut (0 <= y); [ lia | ] end.
94 auto with zarith.
95 Qed.
96 (** We would like to prove this general lemma, but since we're using
97 [Positional.add] rather than [List.map2 Z.add], it's kind-of
98 annoying to prove, so we skip it. *)
99 Lemma nth_default_encode_distributed_bounded
100 minvalues x i d' d
101 (Hmin : (i < length minvalues)%nat)
102 (Hn : (i < n)%nat)
103 : nth_default d' minvalues i <= nth_default d (encode_distributed minvalues x) i.
104 Proof using wprops.
105 apply nth_default_encode_distributed_bounded'; auto.
106 Abort.
107 End encode_distributed.
108 #[global]
109 Hint Rewrite @eval_encode_distributed using solve [auto; lia] : push_eval.
110 #[global]
111 Hint Rewrite @length_encode_distributed : distr_length.
112
113 Notation limbwidth n s c := (inject_Z (Z.log2_up (s - Associational.eval c)) / inject_Z (Z.of_nat n))%Q.
114
115 Local Coercion Z.of_nat : nat >-> Z.
116 Local Coercion QArith_base.inject_Z : Z >-> Q.
117 Local Coercion Z.pos : positive >-> Z.
118
119 (** The fraction by which to multiply upper bounds *)
120 Class tight_upperbound_fraction_opt := tight_upperbound_fraction : Q.
121 #[global]
122 Typeclasses Opaque tight_upperbound_fraction_opt.
123
124 Local Notation is_tighter_than0 x y
125 := ((lower y <=? lower x) && (upper x <=? upper y)).
126 Local Notation is_tighter_than0oo r1 r2
127 := (match r1, r2 with _, None => true | None, Some _ => false | Some r1', Some r2' => is_tighter_than0 r1' r2' end).
128 Local Notation is_tighter_than ls1 ls2
129 := (fold_andb_map (fun x y => is_tighter_than0oo x y) ls1 ls2).
130
131 Section __.
132 Context {tight_upperbound_fraction : tight_upperbound_fraction_opt}
133 (n : nat)
134 (s : Z)
135 (c : list (Z * Z))
136 (machine_wordsize : Z).
137 Let limbwidth := (limbwidth n s c).
138 Local Notation weight := (weight (Qnum limbwidth) (Qden limbwidth)).
139 Context (Hn_nz : n <> 0%nat)
140 (Hs_n : Z.of_nat n <= Z.log2_up (s - Associational.eval c))
141 (Hs_nz : s <> 0)
142 (Hs_c_nz : s - Associational.eval c <> 0)
143 (Hs_c_bounded : 0 < s - Associational.eval c <= weight n).
144
145 Lemma limbwidth_good : 0 < Qden limbwidth <= Qnum limbwidth.
146 Proof using Hn_nz Hs_n.
147 clear -Hn_nz Hs_n.
148 cbv [limbwidth Qnum Qden Qdiv inject_Z Qmult Qinv].
149 destruct n; cbn [Z.of_nat]; lia.
150 Qed.
151 Let wprops := wprops _ _ limbwidth_good.
152 Local Hint Resolve wprops : core.
153 (** Translating from https://github.com/mit-plv/fiat-crypto/blob/c60b1d2556a72c37f4bc7444204e9ddc0791ce4f/src/Specific/solinas64_2e448m2e224m1_8limbs/CurveParameters.v#L11-L35
154 <<
155 if len(p) > 2:
156 # do interleaved carry chains, starting at where the taps are
157 starts = [(int(t[1] / (num_bits(p) / sz)) - 1) % sz for t in p[1:]]
158 chain2 = []
159 for n in range(1,sz):
160 for j in starts:
161 chain2.append((j + n) % sz)
162 chain2 = remove_duplicates(chain2)
163 chain3 = list(map(lambda x:(x+1)%sz,starts))
164 carry_chains = [starts,chain2,chain3]
165 else:
166 carry_chains = "default"
167 >> *)
168 (* p is [(value, weight)]; c is [(weight, value)] *)
169 Let p := [(s / 2^Z.log2 s, Z.log2 s)] ++ TAPSort.sort (List.map (fun '(w, v) => (-v, Z.log2 w)) c).
170 Definition carry_chains : list nat
171 := if (2 <? List.length p)%nat
172 then (* do interleaved carry chains, starting at where the taps are *)
173 let starts := List.map (fun '((v, w) : Z * Z) => (Qfloor (w / limbwidth) - 1) mod n) (tl p) in
174 let chain2 := flat_map
175 (fun n' : nat
176 => List.map (fun j => (j + n') mod n) starts)
177 (List.seq 1 (pred n)) in
178 let chain2 := remove_duplicates Z.eqb chain2 in
179 let chain3 := List.map (fun x => (x + 1) mod n) starts in
180 List.map Z.to_nat (starts ++ chain2 ++ chain3)
181 else (List.seq 0 n ++ [0; 1])%list%nat.
182
183 Definition default_tight_upperbound_fraction : Q := 1%Q.
184 Definition coef := 2. (* for balance in sub *)
185 Definition prime_upperbound_list : list Z
186 := Partition.partition weight n (2 ^ Z.log2_up (s - Associational.eval c) - 1).
187 (** We take the absolute value mostly to make proofs easy *)
188 Definition tight_upperbounds : list Z
189 := List.map
190 (fun v : Z => Qceiling (Qabs (tight_upperbound_fraction * (v+1))))
191 prime_upperbound_list.
192
193 (** We compute loose bounds based on how much headspace we have in
194 each limb, and treat separately the maximum number of additions
195 and subtractions that we guarantee *)
196 (** Allow enough space to do two additions in a row w/o carrying *)
197 Definition headspace_add_count : nat := 2.
198 (** Allow enough space to do one subtraction w/o carrying *)
199 Definition headspace_sub_count : nat := 1.
200
201 (** readjust such that forall i, minvalues[i] <= B[i]
202 Algorithm:
203 B = encode (s - c)
204 B = map(Z.mul coef, B)
205 for i from 0 .. nlimbs-2:
206 if B[i] < tight_upperbounds[i]:
207 // need to find the lowest number we can add, confined to highest bits only
208 d = tight_upperbounds[i] - B[i]
209 x = d / fw[i]
210 if d mod fw[i] != 0:
211 x += 1 // round up
212 B[i] += x * fw[i]
213 B[i+1] -= x
214 *)
215 Definition distribute_balance_step (minvalues : list Z) (i : nat) (B : list Z) :=
216 let Bi := nth_default 0 B i in
217 let Mi := nth_default 0 minvalues i in
218 if (Bi <? Mi)
219 then
220 let fw := weight (S i) / weight i in
221 let x := ((Mi - Bi) / fw) + Z.b2z (negb ((Mi - Bi) mod fw =? 0)) in
222 let zero := [(weight i, x * fw); (weight (S i), -x)] in
223 let Ba := to_associational weight n B ++ zero in
224 let B := from_associational weight n Ba in
225 B
226 else B.
227
228 Definition distribute_balance minvalues B :=
229 fold_right (distribute_balance_step minvalues) B (rev (seq 0 (n-1))).
230
231 Definition balance : list Z
232 := let B := encode weight n s c (s - Associational.eval c) in
233 let B := scmul weight n coef B in
234 distribute_balance tight_upperbounds B.
235
236 Definition loose_upperbounds : list Z
237 := List.map
238 (fun '(v, bal) => v + Z.max (headspace_add_count * v)
239 (headspace_sub_count * bal))
240 (List.combine tight_upperbounds balance).
241
242 Definition tight_bounds : list (option zrange)
243 := List.map (fun u => Some r[0~>u]%zrange) tight_upperbounds.
244 Definition loose_bounds : list (option zrange)
245 := List.map (fun u => Some r[0~>u]%zrange) loose_upperbounds.
246
247 Lemma length_distribute_balance_step minvalues i B
248 : List.length B = n ->
249 List.length (distribute_balance_step minvalues i B) = n.
250 Proof using Type.
251 clear; cbv [distribute_balance_step]; break_innermost_match; now autorewrite with distr_length.
252 Qed.
253 Hint Rewrite length_distribute_balance_step : distr_length.
254
255 Lemma length_distribute_balance minvalues B
256 : List.length B = n ->
257 List.length (distribute_balance minvalues B) = n.
258 Proof using Type.
259 clear -limbwidth p; cbv [distribute_balance]; intros.
260 apply fold_right_invariant; intros; auto; now autorewrite with distr_length.
261 Qed.
262 Hint Rewrite length_distribute_balance : distr_length.
263
264 Lemma length_balance : List.length balance = n.
265 Proof using Type. cbv [balance]; now repeat autorewrite with distr_length. Qed.
266 Hint Rewrite length_balance : distr_length.
267
268 Lemma length_prime_upperbound_list : List.length prime_upperbound_list = n.
269 Proof using Type. cbv [prime_upperbound_list]; now autorewrite with distr_length. Qed.
270 Hint Rewrite length_prime_upperbound_list : distr_length.
271
272 Lemma length_tight_upperbounds : List.length tight_upperbounds = n.
273 Proof using Type. cbv [tight_upperbounds]; now autorewrite with distr_length. Qed.
274 Hint Rewrite length_tight_upperbounds : distr_length.
275
276 Lemma length_loose_upperbounds : List.length loose_upperbounds = n.
277 Proof using Type. cbv [loose_upperbounds]; now autorewrite with distr_length natsimplify. Qed.
278 Hint Rewrite length_loose_upperbounds : distr_length.
279
280 Lemma length_tight_bounds : List.length tight_bounds = n.
281 Proof using Type. cbv [tight_bounds]; now autorewrite with distr_length. Qed.
282 Hint Rewrite length_tight_bounds : distr_length.
283 Lemma length_loose_bounds : List.length loose_bounds = n.
284 Proof using Type. generalize length_loose_upperbounds; clear; cbv [loose_bounds]; autorewrite with distr_length natsimplify; lia. Qed.
285 Hint Rewrite length_loose_bounds : distr_length.
286
287 Lemma tight_bounds_tighter : is_tighter_than tight_bounds loose_bounds = true.
288 Proof using Type.
289 cbv [tight_bounds loose_bounds tight_upperbounds loose_upperbounds].
290 rewrite !combine_map_l, !fold_andb_map_map, !fold_andb_map_map1, fold_andb_map_iff.
291 cbn [lower upper].
292 autorewrite with distr_length natsimplify.
293 split; [ reflexivity | ].
294 intro; rewrite In_nth_error_iff; intros [n' H].
295 rewrite !nth_error_combine in H.
296 break_innermost_match_hyps; inversion_option; subst; cbn [fst snd].
297 rewrite !Bool.andb_true_iff; split; [ reflexivity | Z.ltb_to_lt ].
298 let x := lazymatch goal with |- ?x <= _ => x end in
299 rewrite <- (Z.add_0_r x) at 1; apply Zplus_le_compat_l.
300 etransitivity; [ | apply Z.le_max_l ].
301 cbv [Qceiling Qmult Qfloor Qnum Qden Qopp inject_Z Qabs]; case tight_upperbound_fraction; intros; clear.
302 Z.div_mod_to_quot_rem; nia.
303 Qed.
304
305 Lemma eval_distribute_balance_step minvalues i x :
306 eval weight n (distribute_balance_step minvalues i x)
307 = eval weight n x.
308 Proof using Hs_nz Hs_c_nz Hs_n Hn_nz.
309 clear -Hs_nz Hs_c_nz Hs_n Hn_nz wprops.
310 cbv [distribute_balance_step].
311 break_innermost_match; [ | lia ].
312 rewrite eval_from_associational by auto with zarith.
313 autorewrite with push_eval. cbn [fst snd].
314 rewrite eval_to_associational by auto.
315 ring_simplify.
316 do 2 match goal with
317 | |- context [?a * ?b * (?c / ?a)] =>
318 replace (a * b * (c / a)) with (a * (c / a) * b) by lia;
319 rewrite (Z.mul_div_eq_full c a) by auto with zarith
320 end.
321 rewrite weight_multiples by auto. lia.
322 Qed.
323
324 Lemma eval_distribute_balance minvalues x :
325 eval weight n (distribute_balance minvalues x)
326 = eval weight n x.
327 Proof using Hs_nz Hs_c_nz Hs_n Hn_nz.
328 clear -p Hs_nz Hs_c_nz Hs_n Hn_nz wprops.
329 cbv [distribute_balance].
330 apply fold_right_invariant; [ reflexivity | ].
331 intros; rewrite eval_distribute_balance_step; auto.
332 Qed.
333
334 Lemma eval_balance : eval weight n balance mod (s - Associational.eval c) = 0.
335 Proof using Hs_nz Hs_c_nz Hs_n Hn_nz.
336 clear -p Hs_nz Hs_c_nz Hs_n Hn_nz wprops.
337 cbv [balance]. rewrite eval_distribute_balance.
338 repeat first [ rewrite Z_mod_same_full
339 | rewrite eval_scmul by auto
340 | rewrite eval_encode by auto with zarith
341 | reflexivity
342 | progress (pull_Zmod; autorewrite with zsimplify_fast; push_Zmod) ].
343 Qed.
344
345 (*
346 Lemma nth_default_balance_bounded' i d' d
347 (** We add an extra hypothesis that is too bulky to prove *)
348 (Hadd : forall x y, length x = n -> length y = n -> Positional.add weight n x y = List.map2 Z.add x y)
349 : (i < n)%nat ->
350 coef * nth_default d' tight_upperbounds i <= nth_default d balance i.
351 Proof using wprops.
352 generalize length_tight_upperbounds.
353 clear -wprops Hadd.
354 intros; etransitivity; [ | eapply nth_default_encode_distributed_bounded'; auto ]; auto.
355 { rewrite map_nth_default_always; reflexivity. }
356 { distr_length. }
357 Qed.
358 (** We would like to prove this general lemma, but since we're using
359 [Positional.add] rather than [List.map2 Z.add], it's kind-of
360 annoying to prove, so we skip it. *)
361 Lemma nth_default_balance_bounded i d' d
362 : (i < n)%nat ->
363 coef * nth_default d' tight_upperbounds i <= nth_default d balance i.
364 Proof using wprops.
365 apply nth_default_balance_bounded'; auto.
366 Abort.
367 *)
368
369 (** check if the suggested number of limbs will overflow
370 double-width registers when adding partial products after a
371 multiplication and then doing solinas reduction *)
372 Definition overflow_free : bool
373 := let v := squaremod weight s c n loose_upperbounds in
374 forallb (fun k => Z.log2 k <? 2 * machine_wordsize) v.
375
376 Definition is_goldilocks : bool
377 := match c with
378 | (w, v) :: _
379 => (s =? 2^Z.log2 s)
380 && (w =? 2^Z.log2 w)
381 && (Z.log2 s =? 2 * Z.log2 w)
382 | nil => false
383 end.
384 End __.
385 #[global]
386 Hint Rewrite @length_distribute_balance @length_distribute_balance_step @length_balance @length_prime_upperbound_list @length_tight_upperbounds @length_loose_upperbounds @length_tight_bounds @length_loose_bounds : distr_length.
387
388 Inductive MaybeLimbCount := NumLimbs (n : nat) | Auto (idx : nat).
389
390 Section ___.
391 Context {tight_upperbound_fraction : tight_upperbound_fraction_opt}
392 (s : Z)
393 (c : list (Z * Z))
394 (machine_wordsize : Z).
395 (** given a parsed prime, pick out all plausible numbers of (unsaturated) limbs *)
396 (** an unsaturated implementation will necessarily need at least as many limbs
397 as a saturated one, so search starting there *)
398 Let num_bits_p := Z.log2_up s.
399 Let nlimbs_saturated := Z.to_nat (Qceiling (num_bits_p / machine_wordsize)).
400 Let min_limbs := nlimbs_saturated.
401 (* don't search past 2x as many limbs as saturated representation; that's just wasteful *)
402 Let result := filter (fun n => overflow_free n s c machine_wordsize) (seq min_limbs min_limbs).
403 Definition get_possible_limbs : list nat
404 := result.
405
406 Definition get_num_limbs (n : MaybeLimbCount) : option nat
407 := match n with
408 | NumLimbs n => Some n
409 | Auto idx => nth_error get_possible_limbs idx
410 end.
411 End ___.