Source file fixed_point_transform.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
type cast_mode = Ceil | Floor | Round
type options = {
precision : int;
max_relative_error : float;
cast_mode : cast_mode;
inverse_scaling : int;
resolution : int;
}
type fp_error = Bad_fpclass of Float.fpclass | Negative_or_zero_fp
type fixed_point_transform_error = Term_is_not_closed of Free_variable.t
exception Bad_floating_point_number of fp_error
exception Fixed_point_transform_error of fixed_point_transform_error
let default_options =
{
precision = 4;
max_relative_error = 0.1;
cast_mode = Round;
inverse_scaling = 3;
resolution = 5;
}
let pp_fixed_point_transform_error fmtr (err : fixed_point_transform_error) =
match err with
| Term_is_not_closed s ->
Format.fprintf
fmtr
"Fixed_point_transform: Term is not closed (free variable %a \
encountered)"
Free_variable.pp
s
let cast_mode_encoding =
let open Data_encoding in
union
[
case
~title:"Ceil"
(Tag 0)
(constant "Ceil")
(function Ceil -> Some () | _ -> None)
(fun () -> Ceil);
case
~title:"Floor"
(Tag 1)
(constant "Floor")
(function Floor -> Some () | _ -> None)
(fun () -> Floor);
case
~title:"Round"
(Tag 2)
(constant "Round")
(function Round -> Some () | _ -> None)
(fun () -> Round);
]
let options_encoding =
let open Data_encoding in
conv
(fun {precision; max_relative_error; cast_mode; inverse_scaling; resolution} ->
(precision, max_relative_error, cast_mode, inverse_scaling, resolution))
(fun (precision, max_relative_error, cast_mode, inverse_scaling, resolution) ->
{precision; max_relative_error; cast_mode; inverse_scaling; resolution})
(obj5
(dft "precision" int31 default_options.precision)
(dft "max_relative_error" float default_options.max_relative_error)
(dft "cast_mode" cast_mode_encoding default_options.cast_mode)
(dft "inverse_scaling" int31 default_options.inverse_scaling)
(dft "resolution" int31 default_options.resolution))
let () =
Printexc.register_printer (fun exn ->
match exn with
| Bad_floating_point_number error ->
let s =
match error with
| Bad_fpclass fpcl -> (
match fpcl with
| FP_subnormal -> "FP_subnormal"
| FP_infinite -> "FP_infinite"
| FP_nan -> "FP_nan"
| _ -> assert false)
| Negative_or_zero_fp -> "<= 0"
in
Some
(Printf.sprintf
"Fixed_point_transform: Bad floating point number: %s"
s)
| Fixed_point_transform_error err ->
let s = Format.asprintf "%a" pp_fixed_point_transform_error err in
Some s
| _ -> None)
let rec log10 x =
if x <= 0 then invalid_arg "log10"
else if x <= 10 then 1
else 1 + log10 (x / 10)
let rec pow x n =
if n < 0 then invalid_arg "pow"
else if n = 0 then 1
else if n = 1 then x
else x * pow x (n - 1)
let snap_to_grid ~inverse_scaling ~resolution x =
if x = 0 then 0
else
let not_significant = log10 x / inverse_scaling in
let grid = resolution * pow 10 not_significant in
(x + grid - 1) / grid * grid
let int_of_float mode x =
match mode with
| Ceil -> int_of_float (Float.ceil x)
| Floor -> int_of_float (Float.floor x)
| Round -> int_of_float (Float.round x)
let assert_fp_is_correct (x : float) =
let fpcl = Float.classify_float x in
match fpcl with
| FP_subnormal | FP_infinite | FP_nan ->
raise (Bad_floating_point_number (Bad_fpclass fpcl))
| FP_normal when x <= 0.0 ->
raise (Bad_floating_point_number Negative_or_zero_fp)
| _ -> fpcl
let cast_to_int max_relative_error mode f : int =
let i = int_of_float mode f in
let fi = float_of_int i in
let re = abs_float (f -. fi) /. abs_float f in
if re > max_relative_error then
Format.eprintf
"Warning: Fixed_point_transform: Imprecise integer cast of %f to %d: %f \
%% relative error@."
f
i
(re *. 100.) ;
i
module type Fixed_point_lang_sig = sig
type 'a repr
type size
val shift_right : size repr -> int -> size repr
val ( + ) : size repr -> size repr -> size repr
val ( * ) : size repr -> size repr -> size repr
val int : int -> size repr
end
module Fixed_point_arithmetic (Lang : Fixed_point_lang_sig) : sig
(** [approx_mult precision i f] generates fixed-precision multiplication
of [i * f] by positive constants. [precision] is a paramter to control
how many bit shifts are used.
*)
val approx_mult :
cast_mode -> int -> Lang.size Lang.repr -> float -> Lang.size Lang.repr
end = struct
let bit (x : float) (i : int) =
assert (not (i < 0 || i > 63)) ;
let bits = Int64.bits_of_float x in
Int64.(logand (shift_right bits i) one)
let all_bits (x : float) : int64 list =
List.init ~when_negative_length:() 64 (fun i -> bit x i)
|> WithExceptions.Result.get_ok ~loc:__LOC__
|> List.rev
let take n l =
let rec take n l acc =
if n <= 0 then (List.rev acc, l)
else
match l with
| [] -> Stdlib.failwith "take"
| hd :: tl -> take (n - 1) tl (hd :: acc)
in
take n l []
let split bits =
let sign, rest = take 1 bits in
let expo, rest = take 11 rest in
let mant, _ = take 52 rest in
(sign, expo, mant)
let exponent_bits_to_int (l : int64 list) =
let rec exponent_to_int (l : int64 list) (index : int) : int64 =
match l with
| [] -> -1023L
| bit :: tail ->
let tail = exponent_to_int tail (index + 1) in
Int64.(add (shift_left bit index) tail)
in
exponent_to_int (List.rev l) 0
let decompose (x : float) = split (all_bits x)
let increment_bits exp bits =
let rec f = function
| [] -> (true, [])
| 0L :: rest ->
let up, rest = f rest in
(false, (if up then 1L else 0L) :: rest)
| 1L :: rest ->
let up, rest = f rest in
if up then (true, 0L :: rest) else (false, 1L :: rest)
| _ -> assert false
in
let up, bits = f bits in
if up then (exp + 1, 1L :: bits) else (exp, bits)
let approx_mult mode (precision : int) (i : Lang.size Lang.repr) (x : float) :
Lang.size Lang.repr =
assert (precision > 0) ;
let fpcl = assert_fp_is_correct x in
match fpcl with
| FP_zero -> Lang.int 0
| _ ->
let _sign, exp, mant = decompose x in
let exp = Int64.to_int @@ exponent_bits_to_int exp in
let bits = 1L :: mant in
let bits, rest = take precision bits in
let exp, bits_rounded =
match mode with
| Ceil ->
if List.for_all (fun x -> x = 0L) rest then (exp, bits)
else increment_bits exp bits
| Floor -> (exp, bits)
| Round -> (
match rest with
| 1L :: _ -> increment_bits exp bits
| [] | 0L :: _ -> (exp, bits)
| _ -> assert false)
in
let _, integer, fracs =
List.fold_left
(fun (k, integer, fracs) bit ->
let integer, fracs =
if bit = 1L then
if exp - k < 0 then
(integer, Lang.shift_right i (k - exp) :: fracs)
else (integer + (1 lsl (exp - k)), fracs)
else (integer, fracs)
in
(k + 1, integer, fracs))
(0, 0, [])
bits_rounded
in
if integer = 0 then
match List.rev fracs with
| [] -> assert false
| f :: fracs -> List.fold_left (fun sum t -> Lang.(sum + t)) f fracs
else
List.fold_left
(fun t sum -> Lang.(sum + t))
(if integer = 1 then i else Lang.(i * int integer))
(List.rev fracs)
end
module Convert_mult (P : sig
val options : options
end)
(X : Costlang.S) : sig
include Costlang.S with type size = X.size
val prj : 'a repr -> 'a X.repr
end = struct
type size = X.size
type 'a repr = Term : 'a X.repr -> 'a repr | Float : float -> X.size repr
let {precision; max_relative_error; cast_mode; inverse_scaling; resolution} =
P.options
module FPA = Fixed_point_arithmetic (X)
let cast_and_snap f =
X.int
@@ snap_to_grid ~inverse_scaling ~resolution
@@ cast_to_int max_relative_error cast_mode f
let prj (type a) (term : a repr) : a X.repr =
match term with Term t -> t | Float f -> cast_and_snap f
let lift_unop op x =
match x with
| Term x -> Term (op x)
| Float x -> Term (op @@ cast_and_snap x)
let lift_binop op x y =
match (x, y) with
| Term x, Term y -> Term (op x y)
| Term x, Float y -> Term (op x (cast_and_snap y))
| Float x, Term y -> Term (op (cast_and_snap x) y)
| Float x, Float y -> Term (op (cast_and_snap x) (cast_and_snap y))
let gensym : unit -> string =
let x = ref 0 in
fun () ->
let v = !x in
incr x ;
"v" ^ string_of_int v
let false_ = Term X.false_
let true_ = Term X.true_
let float f = Float f
let int i = Term (X.int i)
let ( + ) = lift_binop X.( + )
let sat_sub = lift_binop X.sat_sub
let ( * ) x y =
match (x, y) with
| Term x, Term y -> Term X.(x * y)
| Term x, Float y | Float y, Term x ->
Term
(X.let_ ~name:(gensym ()) x (fun x ->
FPA.approx_mult Ceil precision x y))
| Float x, Float y -> Float (x *. y)
let ( / ) = lift_binop X.( / )
let max = lift_binop X.max
let min = lift_binop X.min
let shift_left x i = lift_unop (fun x -> X.shift_left x i) x
let shift_right x i = lift_unop (fun x -> X.shift_right x i) x
let log2 = lift_unop X.log2
let sqrt = lift_unop X.sqrt
let free ~name = raise (Fixed_point_transform_error (Term_is_not_closed name))
let lt = lift_binop X.lt
let eq = lift_binop X.eq
let lam (type a b) ~name (f : a repr -> b repr) : (a -> b) repr =
Term
(X.lam ~name (fun x ->
match f (Term x) with Term y -> y | Float f -> X.float f))
let app (type a b) (fn : (a -> b) repr) (arg : a repr) : b repr =
match (fn, arg) with
| Term fn, Term arg -> Term (X.app fn arg)
| Term fn, Float f -> Term (X.app fn (X.float f))
| Float _, _ -> assert false
let let_ (type a b) ~name (m : a repr) (fn : a repr -> b repr) : b repr =
match m with
| Term m ->
Term
(X.let_ ~name m (fun x ->
match fn (Term x) with Term y -> y | Float f -> X.float f))
| Float f ->
Term
(X.let_ ~name (X.float f) (fun x ->
match fn (Term x) with Term y -> y | Float f -> X.float f))
let if_ cond ift iff = Term (X.if_ (prj cond) (prj ift) (prj iff))
end
module Apply (P : sig
val options : options
end) : Costlang.Transform =
functor (X : Costlang.S) -> Convert_mult (P) (X)