add WIP HDL version of goldschmidt division -- it's currently broken
[soc.git] / src / soc / fu / div / experiment / goldschmidt_div_sqrt.py
1 # SPDX-License-Identifier: LGPL-3-or-later
2 # Copyright 2022 Jacob Lifshay programmerjake@gmail.com
3
4 # Funded by NLnet Assure Programme 2021-02-052, https://nlnet.nl/assure part
5 # of Horizon 2020 EU Programme 957073.
6
7 from collections import defaultdict
8 from dataclasses import dataclass, field, fields, replace
9 import logging
10 import math
11 import enum
12 from fractions import Fraction
13 from types import FunctionType
14 from functools import lru_cache
15 from nmigen.hdl.ast import Signal, unsigned, Mux, signed
16 from nmigen.hdl.dsl import Module, Elaboratable
17 from nmigen.hdl.mem import Memory
18 from nmutil.clz import CLZ
19
20 try:
21 from functools import cached_property
22 except ImportError:
23 from cached_property import cached_property
24
25 # fix broken IDE type detection for cached_property
26 from typing import TYPE_CHECKING, Any
27 if TYPE_CHECKING:
28 from functools import cached_property
29
30
31 _NOT_FOUND = object()
32
33
34 def cache_on_self(func):
35 """like `functools.cached_property`, except for methods. unlike
36 `lru_cache` the cache is per-class instance rather than a global cache
37 per-method."""
38
39 assert isinstance(func, FunctionType), \
40 "non-plain methods are not supported"
41
42 cache_name = func.__name__ + "__cache"
43
44 def wrapper(self, *args, **kwargs):
45 # specifically access through `__dict__` to bypass frozen=True
46 cache = self.__dict__.get(cache_name, _NOT_FOUND)
47 if cache is _NOT_FOUND:
48 self.__dict__[cache_name] = cache = {}
49 key = (args, *kwargs.items())
50 retval = cache.get(key, _NOT_FOUND)
51 if retval is _NOT_FOUND:
52 retval = func(self, *args, **kwargs)
53 cache[key] = retval
54 return retval
55
56 wrapper.__doc__ = func.__doc__
57 return wrapper
58
59
60 @enum.unique
61 class RoundDir(enum.Enum):
62 DOWN = enum.auto()
63 UP = enum.auto()
64 NEAREST_TIES_UP = enum.auto()
65 ERROR_IF_INEXACT = enum.auto()
66
67
68 @dataclass(frozen=True)
69 class FixedPoint:
70 bits: int
71 frac_wid: int
72
73 def __post_init__(self):
74 # called by the autogenerated __init__
75 assert isinstance(self.bits, int)
76 assert isinstance(self.frac_wid, int) and self.frac_wid >= 0
77
78 @staticmethod
79 def cast(value):
80 """convert `value` to a fixed-point number with enough fractional
81 bits to preserve its value."""
82 if isinstance(value, FixedPoint):
83 return value
84 if isinstance(value, int):
85 return FixedPoint(value, 0)
86 if isinstance(value, str):
87 value = value.strip()
88 neg = value.startswith("-")
89 if neg or value.startswith("+"):
90 value = value[1:]
91 if value.startswith(("0x", "0X")) and "." in value:
92 value = value[2:]
93 got_dot = False
94 bits = 0
95 frac_wid = 0
96 for digit in value:
97 if digit == "_":
98 continue
99 if got_dot:
100 if digit == ".":
101 raise ValueError("too many `.` in string")
102 frac_wid += 4
103 if digit == ".":
104 got_dot = True
105 continue
106 if not digit.isalnum():
107 raise ValueError("invalid hexadecimal digit")
108 bits <<= 4
109 bits |= int("0x" + digit, base=16)
110 else:
111 bits = int(value, base=0)
112 frac_wid = 0
113 if neg:
114 bits = -bits
115 return FixedPoint(bits, frac_wid)
116
117 if isinstance(value, float):
118 n, d = value.as_integer_ratio()
119 log2_d = d.bit_length() - 1
120 assert d == 1 << log2_d, ("d isn't a power of 2 -- won't ever "
121 "fail with float being IEEE 754")
122 return FixedPoint(n, log2_d)
123 raise TypeError("can't convert type to FixedPoint")
124
125 @staticmethod
126 def with_frac_wid(value, frac_wid, round_dir=RoundDir.ERROR_IF_INEXACT):
127 """convert `value` to the nearest fixed-point number with `frac_wid`
128 fractional bits, rounding according to `round_dir`."""
129 assert isinstance(frac_wid, int) and frac_wid >= 0
130 assert isinstance(round_dir, RoundDir)
131 if isinstance(value, Fraction):
132 numerator = value.numerator
133 denominator = value.denominator
134 else:
135 value = FixedPoint.cast(value)
136 numerator = value.bits
137 denominator = 1 << value.frac_wid
138 if denominator < 0:
139 numerator = -numerator
140 denominator = -denominator
141 bits, remainder = divmod(numerator << frac_wid, denominator)
142 if round_dir == RoundDir.DOWN:
143 pass
144 elif round_dir == RoundDir.UP:
145 if remainder != 0:
146 bits += 1
147 elif round_dir == RoundDir.NEAREST_TIES_UP:
148 if remainder * 2 >= denominator:
149 bits += 1
150 elif round_dir == RoundDir.ERROR_IF_INEXACT:
151 if remainder != 0:
152 raise ValueError("inexact conversion")
153 else:
154 assert False, "unimplemented round_dir"
155 return FixedPoint(bits, frac_wid)
156
157 def to_frac_wid(self, frac_wid, round_dir=RoundDir.ERROR_IF_INEXACT):
158 """convert to the nearest fixed-point number with `frac_wid`
159 fractional bits, rounding according to `round_dir`."""
160 return FixedPoint.with_frac_wid(self, frac_wid, round_dir)
161
162 def __float__(self):
163 # use truediv to get correct result even when bits
164 # and frac_wid are huge
165 return float(self.bits / (1 << self.frac_wid))
166
167 def as_fraction(self):
168 return Fraction(self.bits, 1 << self.frac_wid)
169
170 def cmp(self, rhs):
171 """compare self with rhs, returning a positive integer if self is
172 greater than rhs, zero if self is equal to rhs, and a negative integer
173 if self is less than rhs."""
174 rhs = FixedPoint.cast(rhs)
175 common_frac_wid = max(self.frac_wid, rhs.frac_wid)
176 lhs = self.to_frac_wid(common_frac_wid)
177 rhs = rhs.to_frac_wid(common_frac_wid)
178 return lhs.bits - rhs.bits
179
180 def __eq__(self, rhs):
181 return self.cmp(rhs) == 0
182
183 def __ne__(self, rhs):
184 return self.cmp(rhs) != 0
185
186 def __gt__(self, rhs):
187 return self.cmp(rhs) > 0
188
189 def __lt__(self, rhs):
190 return self.cmp(rhs) < 0
191
192 def __ge__(self, rhs):
193 return self.cmp(rhs) >= 0
194
195 def __le__(self, rhs):
196 return self.cmp(rhs) <= 0
197
198 def fract(self):
199 """return the fractional part of `self`.
200 that is `self - math.floor(self)`.
201 """
202 fract_mask = (1 << self.frac_wid) - 1
203 return FixedPoint(self.bits & fract_mask, self.frac_wid)
204
205 def __str__(self):
206 if self < 0:
207 return "-" + str(-self)
208 digit_bits = 4
209 frac_digit_count = (self.frac_wid + digit_bits - 1) // digit_bits
210 fract = self.fract().to_frac_wid(frac_digit_count * digit_bits)
211 frac_str = hex(fract.bits)[2:].zfill(frac_digit_count)
212 return hex(math.floor(self)) + "." + frac_str
213
214 def __repr__(self):
215 return f"FixedPoint.with_frac_wid({str(self)!r}, {self.frac_wid})"
216
217 def __add__(self, rhs):
218 rhs = FixedPoint.cast(rhs)
219 common_frac_wid = max(self.frac_wid, rhs.frac_wid)
220 lhs = self.to_frac_wid(common_frac_wid)
221 rhs = rhs.to_frac_wid(common_frac_wid)
222 return FixedPoint(lhs.bits + rhs.bits, common_frac_wid)
223
224 def __radd__(self, lhs):
225 # symmetric
226 return self.__add__(lhs)
227
228 def __neg__(self):
229 return FixedPoint(-self.bits, self.frac_wid)
230
231 def __sub__(self, rhs):
232 rhs = FixedPoint.cast(rhs)
233 common_frac_wid = max(self.frac_wid, rhs.frac_wid)
234 lhs = self.to_frac_wid(common_frac_wid)
235 rhs = rhs.to_frac_wid(common_frac_wid)
236 return FixedPoint(lhs.bits - rhs.bits, common_frac_wid)
237
238 def __rsub__(self, lhs):
239 # a - b == -(b - a)
240 return -self.__sub__(lhs)
241
242 def __mul__(self, rhs):
243 rhs = FixedPoint.cast(rhs)
244 return FixedPoint(self.bits * rhs.bits, self.frac_wid + rhs.frac_wid)
245
246 def __rmul__(self, lhs):
247 # symmetric
248 return self.__mul__(lhs)
249
250 def __floor__(self):
251 return self.bits >> self.frac_wid
252
253 def div(self, rhs, frac_wid, round_dir=RoundDir.ERROR_IF_INEXACT):
254 assert isinstance(frac_wid, int) and frac_wid >= 0
255 assert isinstance(round_dir, RoundDir)
256 rhs = FixedPoint.cast(rhs)
257 return FixedPoint.with_frac_wid(self.as_fraction()
258 / rhs.as_fraction(),
259 frac_wid, round_dir)
260
261 def sqrt(self, round_dir=RoundDir.ERROR_IF_INEXACT):
262 assert isinstance(round_dir, RoundDir)
263 if self < 0:
264 raise ValueError("can't compute sqrt of negative number")
265 if self == 0:
266 return self
267 retval = FixedPoint(0, self.frac_wid)
268 int_part_wid = self.bits.bit_length() - self.frac_wid
269 first_bit_index = -(-int_part_wid // 2) # division rounds up
270 last_bit_index = -self.frac_wid
271 for bit_index in range(first_bit_index, last_bit_index - 1, -1):
272 trial = retval + FixedPoint(1 << (bit_index + self.frac_wid),
273 self.frac_wid)
274 if trial * trial <= self:
275 retval = trial
276 if round_dir == RoundDir.DOWN:
277 pass
278 elif round_dir == RoundDir.UP:
279 if retval * retval < self:
280 retval += FixedPoint(1, self.frac_wid)
281 elif round_dir == RoundDir.NEAREST_TIES_UP:
282 half_way = retval + FixedPoint(1, self.frac_wid + 1)
283 if half_way * half_way <= self:
284 retval += FixedPoint(1, self.frac_wid)
285 elif round_dir == RoundDir.ERROR_IF_INEXACT:
286 if retval * retval != self:
287 raise ValueError("inexact sqrt")
288 else:
289 assert False, "unimplemented round_dir"
290 return retval
291
292 def rsqrt(self, round_dir=RoundDir.ERROR_IF_INEXACT):
293 """compute the reciprocal-sqrt of `self`"""
294 assert isinstance(round_dir, RoundDir)
295 if self < 0:
296 raise ValueError("can't compute rsqrt of negative number")
297 if self == 0:
298 raise ZeroDivisionError("can't compute rsqrt of zero")
299 retval = FixedPoint(0, self.frac_wid)
300 first_bit_index = -(-self.frac_wid // 2) # division rounds up
301 last_bit_index = -self.frac_wid
302 for bit_index in range(first_bit_index, last_bit_index - 1, -1):
303 trial = retval + FixedPoint(1 << (bit_index + self.frac_wid),
304 self.frac_wid)
305 if trial * trial * self <= 1:
306 retval = trial
307 if round_dir == RoundDir.DOWN:
308 pass
309 elif round_dir == RoundDir.UP:
310 if retval * retval * self < 1:
311 retval += FixedPoint(1, self.frac_wid)
312 elif round_dir == RoundDir.NEAREST_TIES_UP:
313 half_way = retval + FixedPoint(1, self.frac_wid + 1)
314 if half_way * half_way * self <= 1:
315 retval += FixedPoint(1, self.frac_wid)
316 elif round_dir == RoundDir.ERROR_IF_INEXACT:
317 if retval * retval * self != 1:
318 raise ValueError("inexact rsqrt")
319 else:
320 assert False, "unimplemented round_dir"
321 return retval
322
323
324 class ParamsNotAccurateEnough(Exception):
325 """raised when the parameters aren't accurate enough to have goldschmidt
326 division work."""
327
328
329 def _assert_accuracy(condition, msg="not accurate enough"):
330 if condition:
331 return
332 raise ParamsNotAccurateEnough(msg)
333
334
335 @dataclass(frozen=True, unsafe_hash=True)
336 class GoldschmidtDivParamsBase:
337 """parameters for a Goldschmidt division algorithm, excluding derived
338 parameters.
339 """
340
341 io_width: int
342 """bit-width of the input divisor and the result.
343 the input numerator is `2 * io_width`-bits wide.
344 """
345
346 extra_precision: int
347 """number of bits of additional precision used inside the algorithm."""
348
349 table_addr_bits: int
350 """the number of address bits used in the lookup-table."""
351
352 table_data_bits: int
353 """the number of data bits used in the lookup-table."""
354
355 iter_count: int
356 """the total number of iterations of the division algorithm's loop"""
357
358
359 @dataclass(frozen=True, unsafe_hash=True)
360 class GoldschmidtDivParams(GoldschmidtDivParamsBase):
361 """parameters for a Goldschmidt division algorithm.
362 Use `GoldschmidtDivParams.get` to find a efficient set of parameters.
363 """
364
365 # tuple to be immutable, repr=False so repr() works for debugging even when
366 # __post_init__ hasn't finished running yet
367 table: "tuple[FixedPoint, ...]" = field(init=False, repr=False)
368 """the lookup-table"""
369
370 ops: "tuple[GoldschmidtDivOp, ...]" = field(init=False, repr=False)
371 """the operations needed to perform the goldschmidt division algorithm."""
372
373 def _shrink_bound(self, bound, round_dir):
374 """prevent fractions from having huge numerators/denominators by
375 rounding to a `FixedPoint` and converting back to a `Fraction`.
376
377 This is intended only for values used to compute bounds, and not for
378 values that end up in the hardware.
379 """
380 assert isinstance(bound, (Fraction, int))
381 assert round_dir is RoundDir.DOWN or round_dir is RoundDir.UP, \
382 "you shouldn't use that round_dir on bounds"
383 frac_wid = self.io_width * 4 + 100 # should be enough precision
384 fixed = FixedPoint.with_frac_wid(bound, frac_wid, round_dir)
385 return fixed.as_fraction()
386
387 def _shrink_min(self, min_bound):
388 """prevent fractions used as minimum bounds from having huge
389 numerators/denominators by rounding down to a `FixedPoint` and
390 converting back to a `Fraction`.
391
392 This is intended only for values used to compute bounds, and not for
393 values that end up in the hardware.
394 """
395 return self._shrink_bound(min_bound, RoundDir.DOWN)
396
397 def _shrink_max(self, max_bound):
398 """prevent fractions used as maximum bounds from having huge
399 numerators/denominators by rounding up to a `FixedPoint` and
400 converting back to a `Fraction`.
401
402 This is intended only for values used to compute bounds, and not for
403 values that end up in the hardware.
404 """
405 return self._shrink_bound(max_bound, RoundDir.UP)
406
407 @property
408 def table_addr_count(self):
409 """number of distinct addresses in the lookup-table."""
410 # used while computing self.table, so can't just do len(self.table)
411 return 1 << self.table_addr_bits
412
413 def table_input_exact_range(self, addr):
414 """return the range of inputs as `Fraction`s used for the table entry
415 with address `addr`."""
416 assert isinstance(addr, int)
417 assert 0 <= addr < self.table_addr_count
418 _assert_accuracy(self.io_width >= self.table_addr_bits)
419 addr_shift = self.io_width - self.table_addr_bits
420 min_numerator = (1 << self.io_width) + (addr << addr_shift)
421 denominator = 1 << self.io_width
422 values_per_table_entry = 1 << addr_shift
423 max_numerator = min_numerator + values_per_table_entry - 1
424 min_input = Fraction(min_numerator, denominator)
425 max_input = Fraction(max_numerator, denominator)
426 min_input = self._shrink_min(min_input)
427 max_input = self._shrink_max(max_input)
428 assert 1 <= min_input <= max_input < 2
429 return min_input, max_input
430
431 def table_value_exact_range(self, addr):
432 """return the range of values as `Fraction`s used for the table entry
433 with address `addr`."""
434 min_input, max_input = self.table_input_exact_range(addr)
435 # division swaps min/max
436 min_value = 1 / max_input
437 max_value = 1 / min_input
438 min_value = self._shrink_min(min_value)
439 max_value = self._shrink_max(max_value)
440 assert 0.5 < min_value <= max_value <= 1
441 return min_value, max_value
442
443 def table_exact_value(self, index):
444 min_value, max_value = self.table_value_exact_range(index)
445 # we round down
446 return min_value
447
448 def __post_init__(self):
449 # called by the autogenerated __init__
450 _assert_accuracy(self.io_width >= 1, "io_width out of range")
451 _assert_accuracy(self.extra_precision >= 0,
452 "extra_precision out of range")
453 _assert_accuracy(self.table_addr_bits >= 1,
454 "table_addr_bits out of range")
455 _assert_accuracy(self.table_data_bits >= 1,
456 "table_data_bits out of range")
457 _assert_accuracy(self.iter_count >= 1, "iter_count out of range")
458 table = []
459 for addr in range(1 << self.table_addr_bits):
460 table.append(FixedPoint.with_frac_wid(self.table_exact_value(addr),
461 self.table_data_bits,
462 RoundDir.DOWN))
463 # we have to use object.__setattr__ since frozen=True
464 object.__setattr__(self, "table", tuple(table))
465 object.__setattr__(self, "ops", tuple(self.__make_ops()))
466
467 @property
468 def expanded_width(self):
469 """the total number of bits of precision used inside the algorithm."""
470 return self.io_width + self.extra_precision
471
472 @property
473 def n_d_f_int_wid(self):
474 """the number of bits in the integer part of `state.n`, `state.d`, and
475 `state.f` during the main iteration loop.
476 """
477 return 2
478
479 @property
480 def n_d_f_total_wid(self):
481 """the total number of bits (both integer and fraction bits) in
482 `state.n`, `state.d`, and `state.f` during the main iteration loop.
483 """
484 return self.n_d_f_int_wid + self.expanded_width
485
486 @cache_on_self
487 def max_neps(self, i):
488 """maximum value of `neps[i]`.
489 `neps[i]` is defined to be `n[i] * N_prime[i - 1] * F_prime[i - 1]`.
490 """
491 assert isinstance(i, int) and 0 <= i < self.iter_count
492 return Fraction(1, 1 << self.expanded_width)
493
494 @cache_on_self
495 def max_deps(self, i):
496 """maximum value of `deps[i]`.
497 `deps[i]` is defined to be `d[i] * D_prime[i - 1] * F_prime[i - 1]`.
498 """
499 assert isinstance(i, int) and 0 <= i < self.iter_count
500 return Fraction(1, 1 << self.expanded_width)
501
502 @cache_on_self
503 def max_feps(self, i):
504 """maximum value of `feps[i]`.
505 `feps[i]` is defined to be `f[i] * (2 - D_prime[i - 1])`.
506 """
507 assert isinstance(i, int) and 0 <= i < self.iter_count
508 # zero, because the computation of `F_prime[i]` in
509 # `GoldschmidtDivOp.MulDByF.run(...)` is exact.
510 return Fraction(0)
511
512 @cached_property
513 def e0_range(self):
514 """minimum and maximum values of `e[0]`
515 (the relative error in `F_prime[-1]`)
516 """
517 min_e0 = Fraction(0)
518 max_e0 = Fraction(0)
519 for addr in range(self.table_addr_count):
520 # `F_prime[-1] = (1 - e[0]) / B`
521 # => `e[0] = 1 - B * F_prime[-1]`
522 min_b, max_b = self.table_input_exact_range(addr)
523 f_prime_m1 = self.table[addr].as_fraction()
524 assert min_b >= 0 and f_prime_m1 >= 0, \
525 "only positive quadrant of interval multiplication implemented"
526 min_product = min_b * f_prime_m1
527 max_product = max_b * f_prime_m1
528 # negation swaps min/max
529 cur_min_e0 = 1 - max_product
530 cur_max_e0 = 1 - min_product
531 min_e0 = min(min_e0, cur_min_e0)
532 max_e0 = max(max_e0, cur_max_e0)
533 min_e0 = self._shrink_min(min_e0)
534 max_e0 = self._shrink_max(max_e0)
535 return min_e0, max_e0
536
537 @cached_property
538 def min_e0(self):
539 """minimum value of `e[0]` (the relative error in `F_prime[-1]`)
540 """
541 min_e0, max_e0 = self.e0_range
542 return min_e0
543
544 @cached_property
545 def max_e0(self):
546 """maximum value of `e[0]` (the relative error in `F_prime[-1]`)
547 """
548 min_e0, max_e0 = self.e0_range
549 return max_e0
550
551 @cached_property
552 def max_abs_e0(self):
553 """maximum value of `abs(e[0])`."""
554 return max(abs(self.min_e0), abs(self.max_e0))
555
556 @cached_property
557 def min_abs_e0(self):
558 """minimum value of `abs(e[0])`."""
559 return Fraction(0)
560
561 @cache_on_self
562 def max_n(self, i):
563 """maximum value of `n[i]` (the relative error in `N_prime[i]`
564 relative to the previous iteration)
565 """
566 assert isinstance(i, int) and 0 <= i < self.iter_count
567 if i == 0:
568 # from Claim 10
569 # `n[0] = neps[0] / ((1 - e[0]) * (A / B))`
570 # `n[0] <= 2 * neps[0] / (1 - e[0])`
571
572 assert self.max_e0 < 1 and self.max_neps(0) >= 0, \
573 "only one quadrant of interval division implemented"
574 retval = 2 * self.max_neps(0) / (1 - self.max_e0)
575 elif i == 1:
576 # from Claim 10
577 # `n[1] <= neps[1] / ((1 - f[0]) * (1 - pi[0] - delta[0]))`
578 min_mpd = 1 - self.max_pi(0) - self.max_delta(0)
579 assert self.max_f(0) <= 1 and min_mpd >= 0, \
580 "only one quadrant of interval multiplication implemented"
581 prod = (1 - self.max_f(0)) * min_mpd
582 assert self.max_neps(1) >= 0 and prod > 0, \
583 "only one quadrant of interval division implemented"
584 retval = self.max_neps(1) / prod
585 else:
586 # from Claim 6
587 # `0 <= n[i] <= 2 * max_neps[i] / (1 - pi[i - 1] - delta[i - 1])`
588 min_mpd = 1 - self.max_pi(i - 1) - self.max_delta(i - 1)
589 assert self.max_neps(i) >= 0 and min_mpd > 0, \
590 "only one quadrant of interval division implemented"
591 retval = self.max_neps(i) / min_mpd
592
593 return self._shrink_max(retval)
594
595 @cache_on_self
596 def max_d(self, i):
597 """maximum value of `d[i]` (the relative error in `D_prime[i]`
598 relative to the previous iteration)
599 """
600 assert isinstance(i, int) and 0 <= i < self.iter_count
601 if i == 0:
602 # from Claim 10
603 # `d[0] = deps[0] / (1 - e[0])`
604
605 assert self.max_e0 < 1 and self.max_deps(0) >= 0, \
606 "only one quadrant of interval division implemented"
607 retval = self.max_deps(0) / (1 - self.max_e0)
608 elif i == 1:
609 # from Claim 10
610 # `d[1] <= deps[1] / ((1 - f[0]) * (1 - delta[0] ** 2))`
611 assert self.max_f(0) <= 1 and self.max_delta(0) <= 1, \
612 "only one quadrant of interval multiplication implemented"
613 divisor = (1 - self.max_f(0)) * (1 - self.max_delta(0) ** 2)
614 assert self.max_deps(1) >= 0 and divisor > 0, \
615 "only one quadrant of interval division implemented"
616 retval = self.max_deps(1) / divisor
617 else:
618 # from Claim 6
619 # `0 <= d[i] <= max_deps[i] / (1 - delta[i - 1])`
620 assert self.max_deps(i) >= 0 and self.max_delta(i - 1) < 1, \
621 "only one quadrant of interval division implemented"
622 retval = self.max_deps(i) / (1 - self.max_delta(i - 1))
623
624 return self._shrink_max(retval)
625
626 @cache_on_self
627 def max_f(self, i):
628 """maximum value of `f[i]` (the relative error in `F_prime[i]`
629 relative to the previous iteration)
630 """
631 assert isinstance(i, int) and 0 <= i < self.iter_count
632 if i == 0:
633 # from Claim 10
634 # `f[0] = feps[0] / (1 - delta[0])`
635
636 assert self.max_delta(0) < 1 and self.max_feps(0) >= 0, \
637 "only one quadrant of interval division implemented"
638 retval = self.max_feps(0) / (1 - self.max_delta(0))
639 elif i == 1:
640 # from Claim 10
641 # `f[1] = feps[1]`
642 retval = self.max_feps(1)
643 else:
644 # from Claim 6
645 # `f[i] <= max_feps[i]`
646 retval = self.max_feps(i)
647
648 return self._shrink_max(retval)
649
650 @cache_on_self
651 def max_delta(self, i):
652 """ maximum value of `delta[i]`.
653 `delta[i]` is defined in Definition 4 of paper.
654 """
655 assert isinstance(i, int) and 0 <= i < self.iter_count
656 if i == 0:
657 # `delta[0] = abs(e[0]) + 3 * d[0] / 2`
658 retval = self.max_abs_e0 + Fraction(3, 2) * self.max_d(0)
659 else:
660 # `delta[i] = delta[i - 1] ** 2 + f[i - 1]`
661 prev_max_delta = self.max_delta(i - 1)
662 assert prev_max_delta >= 0
663 retval = prev_max_delta ** 2 + self.max_f(i - 1)
664
665 # `delta[i]` has to be smaller than one otherwise errors would go off
666 # to infinity
667 _assert_accuracy(retval < 1)
668
669 return self._shrink_max(retval)
670
671 @cache_on_self
672 def max_pi(self, i):
673 """ maximum value of `pi[i]`.
674 `pi[i]` is defined right below Theorem 5 of paper.
675 """
676 assert isinstance(i, int) and 0 <= i < self.iter_count
677 # `pi[i] = 1 - (1 - n[i]) * prod`
678 # where `prod` is the product of,
679 # for `j` in `0 <= j < i`, `(1 - n[j]) / (1 + d[j])`
680 min_prod = Fraction(1)
681 for j in range(i):
682 max_n_j = self.max_n(j)
683 max_d_j = self.max_d(j)
684 assert max_n_j <= 1 and max_d_j > -1, \
685 "only one quadrant of interval division implemented"
686 min_prod *= (1 - max_n_j) / (1 + max_d_j)
687 max_n_i = self.max_n(i)
688 assert max_n_i <= 1 and min_prod >= 0, \
689 "only one quadrant of interval multiplication implemented"
690 retval = 1 - (1 - max_n_i) * min_prod
691 return self._shrink_max(retval)
692
693 @cached_property
694 def max_n_shift(self):
695 """ maximum value of `state.n_shift`.
696 """
697 # input numerator is `2*io_width`-bits
698 max_n = (1 << (self.io_width * 2)) - 1
699 max_n_shift = 0
700 # normalize so 1 <= n < 2
701 while max_n >= 2:
702 max_n >>= 1
703 max_n_shift += 1
704 return max_n_shift
705
706 @cached_property
707 def n_hat(self):
708 """ maximum value of, for all `i`, `max_n(i)` and `max_d(i)`
709 """
710 n_hat = Fraction(0)
711 for i in range(self.iter_count):
712 n_hat = max(n_hat, self.max_n(i), self.max_d(i))
713 return self._shrink_max(n_hat)
714
715 def __make_ops(self):
716 """ Goldschmidt division algorithm.
717
718 based on:
719 Even, G., Seidel, P. M., & Ferguson, W. E. (2003).
720 A Parametric Error Analysis of Goldschmidt's Division Algorithm.
721 https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.1238&rep=rep1&type=pdf
722
723 yields: GoldschmidtDivOp
724 the operations needed to perform the division.
725 """
726 # establish assumptions of the paper's error analysis (section 3.1):
727
728 # 1. normalize so A (numerator) and B (denominator) are in [1, 2)
729 yield GoldschmidtDivOp.Normalize
730
731 # 2. ensure all relative errors from directed rounding are <= 1 / 4.
732 # the assumption is met by multipliers with > 4-bits precision
733 _assert_accuracy(self.expanded_width > 4)
734
735 # 3. require `abs(e[0]) + 3 * d[0] / 2 + f[0] < 1 / 2`.
736 _assert_accuracy(self.max_abs_e0 + 3 * self.max_d(0) / 2
737 + self.max_f(0) < Fraction(1, 2))
738
739 # 4. the initial approximation F'[-1] of 1/B is in [1/2, 1].
740 # (B is the denominator)
741
742 for addr in range(self.table_addr_count):
743 f_prime_m1 = self.table[addr]
744 _assert_accuracy(0.5 <= f_prime_m1 <= 1)
745
746 yield GoldschmidtDivOp.FEqTableLookup
747
748 # we use Setting I (section 4.1 of the paper):
749 # Require `n[i] <= n_hat` and `d[i] <= n_hat` and `f[i] = 0`:
750 # the conditions on n_hat are satisfied by construction.
751 for i in range(self.iter_count):
752 _assert_accuracy(self.max_f(i) == 0)
753 yield GoldschmidtDivOp.MulNByF
754 if i != self.iter_count - 1:
755 yield GoldschmidtDivOp.MulDByF
756 yield GoldschmidtDivOp.FEq2MinusD
757
758 # relative approximation error `p(N_prime[i])`:
759 # `p(N_prime[i]) = (A / B - N_prime[i]) / (A / B)`
760 # `0 <= p(N_prime[i])`
761 # `p(N_prime[i]) <= (2 * i) * n_hat \`
762 # ` + (abs(e[0]) + 3 * n_hat / 2) ** (2 ** i)`
763 i = self.iter_count - 1 # last used `i`
764 # compute power manually to prevent huge intermediate values
765 power = self._shrink_max(self.max_abs_e0 + 3 * self.n_hat / 2)
766 for _ in range(i):
767 power = self._shrink_max(power * power)
768
769 max_rel_error = (2 * i) * self.n_hat + power
770
771 min_a_over_b = Fraction(1, 2)
772 max_a_over_b = Fraction(2)
773 max_allowed_abs_error = max_a_over_b / (1 << self.max_n_shift)
774 max_allowed_rel_error = max_allowed_abs_error / min_a_over_b
775
776 _assert_accuracy(max_rel_error < max_allowed_rel_error,
777 f"not accurate enough: max_rel_error={max_rel_error}"
778 f" max_allowed_rel_error={max_allowed_rel_error}")
779
780 yield GoldschmidtDivOp.CalcResult
781
782 @cache_on_self
783 def default_cost_fn(self):
784 """ calculate the estimated cost on an arbitrary scale of implementing
785 goldschmidt division with the specified parameters. larger cost
786 values mean worse parameters.
787
788 This is the default cost function for `GoldschmidtDivParams.get`.
789
790 returns: float
791 """
792 rom_cells = self.table_data_bits << self.table_addr_bits
793 cost = float(rom_cells)
794 for op in self.ops:
795 if op == GoldschmidtDivOp.MulNByF \
796 or op == GoldschmidtDivOp.MulDByF:
797 mul_cost = self.expanded_width ** 2
798 mul_cost *= self.expanded_width.bit_length()
799 cost += mul_cost
800 cost += 5e7 * self.iter_count
801 return cost
802
803 @staticmethod
804 @lru_cache(maxsize=1 << 16)
805 def __cached_new(base_params):
806 assert isinstance(base_params, GoldschmidtDivParamsBase)
807 # can't use dataclasses.asdict, since it's recursive and will also give
808 # child class fields too, which we don't want.
809 kwargs = {}
810 for field in fields(GoldschmidtDivParamsBase):
811 kwargs[field.name] = getattr(base_params, field.name)
812 try:
813 return GoldschmidtDivParams(**kwargs), None
814 except ParamsNotAccurateEnough as e:
815 return None, e
816
817 @staticmethod
818 def __raise(e): # type: (ParamsNotAccurateEnough) -> Any
819 raise e
820
821 @staticmethod
822 def cached_new(base_params, handle_error=__raise):
823 assert isinstance(base_params, GoldschmidtDivParamsBase)
824 params, error = GoldschmidtDivParams.__cached_new(base_params)
825 if error is None:
826 return params
827 else:
828 return handle_error(error)
829
830 @staticmethod
831 def get(io_width, cost_fn=default_cost_fn, max_table_addr_bits=12):
832 """ find efficient parameters for a goldschmidt division algorithm
833 with `params.io_width == io_width`.
834
835 arguments:
836 io_width: int
837 bit-width of the input divisor and the result.
838 the input numerator is `2 * io_width`-bits wide.
839 cost_fn: Callable[[GoldschmidtDivParams], float]
840 return the estimated cost on an arbitrary scale of implementing
841 goldschmidt division with the specified parameters. larger cost
842 values mean worse parameters.
843 max_table_addr_bits: int
844 maximum allowable value of `table_addr_bits`
845 """
846 assert isinstance(io_width, int) and io_width >= 1
847 assert callable(cost_fn)
848
849 last_error = None
850 last_error_params = None
851
852 def cached_new(base_params):
853 def handle_error(e):
854 nonlocal last_error, last_error_params
855 last_error = e
856 last_error_params = base_params
857 return None
858
859 retval = GoldschmidtDivParams.cached_new(base_params, handle_error)
860 if retval is None:
861 logging.debug(f"GoldschmidtDivParams.get: err: {base_params}")
862 else:
863 logging.debug(f"GoldschmidtDivParams.get: ok: {base_params}")
864 return retval
865
866 @lru_cache(maxsize=None)
867 def get_cost(base_params):
868 params = cached_new(base_params)
869 if params is None:
870 return math.inf
871 retval = cost_fn(params)
872 logging.debug(f"GoldschmidtDivParams.get: cost={retval}: {params}")
873 return retval
874
875 # start with parameters big enough to always work.
876 initial_extra_precision = io_width * 2 + 4
877 initial_params = GoldschmidtDivParamsBase(
878 io_width=io_width,
879 extra_precision=initial_extra_precision,
880 table_addr_bits=min(max_table_addr_bits, io_width),
881 table_data_bits=io_width + initial_extra_precision,
882 iter_count=1 + io_width.bit_length())
883
884 if cached_new(initial_params) is None:
885 raise ValueError(f"initial goldschmidt division algorithm "
886 f"parameters are invalid: {initial_params}"
887 ) from last_error
888
889 # find good initial `iter_count`
890 params = initial_params
891 for iter_count in range(1, initial_params.iter_count):
892 trial_params = replace(params, iter_count=iter_count)
893 if cached_new(trial_params) is not None:
894 params = trial_params
895 break
896
897 # now find `table_addr_bits`
898 cost = get_cost(params)
899 for table_addr_bits in range(1, max_table_addr_bits):
900 trial_params = replace(params, table_addr_bits=table_addr_bits)
901 trial_cost = get_cost(trial_params)
902 if trial_cost < cost:
903 params = trial_params
904 cost = trial_cost
905 break
906
907 # check one higher `iter_count` to see if it has lower cost
908 for table_addr_bits in range(1, max_table_addr_bits + 1):
909 trial_params = replace(params,
910 table_addr_bits=table_addr_bits,
911 iter_count=params.iter_count + 1)
912 trial_cost = get_cost(trial_params)
913 if trial_cost < cost:
914 params = trial_params
915 cost = trial_cost
916 break
917
918 # now shrink `table_data_bits`
919 while True:
920 trial_params = replace(params,
921 table_data_bits=params.table_data_bits - 1)
922 trial_cost = get_cost(trial_params)
923 if trial_cost < cost:
924 params = trial_params
925 cost = trial_cost
926 else:
927 break
928
929 # and shrink `extra_precision`
930 while True:
931 trial_params = replace(params,
932 extra_precision=params.extra_precision - 1)
933 trial_cost = get_cost(trial_params)
934 if trial_cost < cost:
935 params = trial_params
936 cost = trial_cost
937 else:
938 break
939
940 return cached_new(params)
941
942
943 def clz(v, wid):
944 assert isinstance(wid, int)
945 assert isinstance(v, int) and 0 <= v < (1 << wid)
946 return (1 << wid).bit_length() - v.bit_length()
947
948
949 @enum.unique
950 class GoldschmidtDivOp(enum.Enum):
951 Normalize = "n, d, n_shift = normalize(n, d)"
952 FEqTableLookup = "f = table_lookup(d)"
953 MulNByF = "n *= f"
954 MulDByF = "d *= f"
955 FEq2MinusD = "f = 2 - d"
956 CalcResult = "result = unnormalize_and_round(n)"
957
958 def run(self, params, state):
959 assert isinstance(params, GoldschmidtDivParams)
960 assert isinstance(state, GoldschmidtDivState)
961 expanded_width = params.expanded_width
962 table_addr_bits = params.table_addr_bits
963 if self == GoldschmidtDivOp.Normalize:
964 # normalize so 1 <= d < 2
965 # can easily be done with count-leading-zeros and left shift
966 while state.d < 1:
967 state.n = (state.n * 2).to_frac_wid(expanded_width)
968 state.d = (state.d * 2).to_frac_wid(expanded_width)
969
970 state.n_shift = 0
971 # normalize so 1 <= n < 2
972 while state.n >= 2:
973 state.n = (state.n * 0.5).to_frac_wid(expanded_width)
974 state.n_shift += 1
975 elif self == GoldschmidtDivOp.FEqTableLookup:
976 # compute initial f by table lookup
977 d_m_1 = state.d - 1
978 d_m_1 = d_m_1.to_frac_wid(table_addr_bits, RoundDir.DOWN)
979 assert 0 <= d_m_1.bits < (1 << params.table_addr_bits)
980 state.f = params.table[d_m_1.bits]
981 elif self == GoldschmidtDivOp.MulNByF:
982 assert state.f is not None
983 n = state.n * state.f
984 state.n = n.to_frac_wid(expanded_width, round_dir=RoundDir.DOWN)
985 elif self == GoldschmidtDivOp.MulDByF:
986 assert state.f is not None
987 d = state.d * state.f
988 state.d = d.to_frac_wid(expanded_width, round_dir=RoundDir.UP)
989 elif self == GoldschmidtDivOp.FEq2MinusD:
990 state.f = (2 - state.d).to_frac_wid(expanded_width)
991 elif self == GoldschmidtDivOp.CalcResult:
992 assert state.n_shift is not None
993 # scale to correct value
994 n = state.n * (1 << state.n_shift)
995
996 state.quotient = math.floor(n)
997 state.remainder = state.orig_n - state.quotient * state.orig_d
998 if state.remainder >= state.orig_d:
999 state.quotient += 1
1000 state.remainder -= state.orig_d
1001 else:
1002 assert False, f"unimplemented GoldschmidtDivOp: {self}"
1003
1004 def gen_hdl(self, params, state, sync_rom):
1005 # FIXME: finish getting hdl/simulation to work
1006 """generate the hdl for this operation.
1007
1008 arguments:
1009 params: GoldschmidtDivParams
1010 the goldschmidt division parameters.
1011 state: GoldschmidtDivHDLState
1012 the input/output state
1013 sync_rom: bool
1014 true if the rom should be read synchronously rather than
1015 combinatorially, incurring an extra clock cycle of latency.
1016 """
1017 assert isinstance(params, GoldschmidtDivParams)
1018 assert isinstance(state, GoldschmidtDivHDLState)
1019 m = state.m
1020 expanded_width = params.expanded_width
1021 table_addr_bits = params.table_addr_bits
1022 if self == GoldschmidtDivOp.Normalize:
1023 # normalize so 1 <= d < 2
1024 assert state.d.width == params.io_width
1025 assert state.n.width == 2 * params.io_width
1026 d_leading_zeros = CLZ(params.io_width)
1027 m.submodules.d_leading_zeros = d_leading_zeros
1028 m.d.comb += d_leading_zeros.sig_in.eq(state.d)
1029 d_shift_out = Signal.like(state.d)
1030 m.d.comb += d_shift_out.eq(state.d << d_leading_zeros.lz)
1031 state.d = Signal(params.n_d_f_total_wid)
1032 m.d.comb += state.d.eq(d_shift_out << (params.extra_precision
1033 + params.n_d_f_int_wid))
1034
1035 # normalize so 1 <= n < 2
1036 n_leading_zeros = CLZ(2 * params.io_width)
1037 m.submodules.n_leading_zeros = n_leading_zeros
1038 m.d.comb += n_leading_zeros.sig_in.eq(state.n)
1039 n_shift_s_v = (params.io_width + d_leading_zeros.lz
1040 - n_leading_zeros.lz)
1041 n_shift_s = Signal.like(n_shift_s_v)
1042 state.n_shift = Signal(d_leading_zeros.lz.width)
1043 m.d.comb += [
1044 n_shift_s.eq(n_shift_s_v),
1045 state.n_shift.eq(Mux(n_shift_s < 0, 0, n_shift_s)),
1046 ]
1047 n = Signal(params.n_d_f_total_wid)
1048 shifted_n = state.n << state.n_shift
1049 fixed_shift = params.expanded_width - state.n.width
1050 m.d.comb += n.eq(shifted_n << fixed_shift)
1051 state.n = n
1052 elif self == GoldschmidtDivOp.FEqTableLookup:
1053 assert state.d.width == params.n_d_f_total_wid, "invalid d width"
1054 # compute initial f by table lookup
1055
1056 # extra bit for table entries == 1.0
1057 table_width = 1 + params.table_data_bits
1058 table = Memory(width=table_width, depth=len(params.table),
1059 init=[i.bits for i in params.table])
1060 addr = state.d[:-params.n_d_f_int_wid][-table_addr_bits:]
1061 if sync_rom:
1062 table_read = table.read_port()
1063 m.d.comb += table_read.addr.eq(addr)
1064 state.insert_pipeline_register()
1065 else:
1066 table_read = table.read_port(domain="comb")
1067 m.d.comb += table_read.addr.eq(addr)
1068 m.submodules.table_read = table_read
1069 state.f = Signal(params.n_d_f_int_wid + params.expanded_width)
1070 data_shift = (table_width - params.table_data_bits
1071 + params.expanded_width)
1072 m.d.comb += state.f.eq(table_read.data << data_shift)
1073 elif self == GoldschmidtDivOp.MulNByF:
1074 assert state.n.width == params.n_d_f_total_wid, "invalid n width"
1075 assert state.f is not None
1076 assert state.f.width == params.n_d_f_total_wid, "invalid f width"
1077 n = Signal.like(state.n)
1078 m.d.comb += n.eq((state.n * state.f) >> params.expanded_width)
1079 state.n = n
1080 elif self == GoldschmidtDivOp.MulDByF:
1081 assert state.d.width == params.n_d_f_total_wid, "invalid d width"
1082 assert state.f is not None
1083 assert state.f.width == params.n_d_f_total_wid, "invalid f width"
1084 d = Signal.like(state.d)
1085 m.d.comb += d.eq((state.d * state.f) >> params.expanded_width)
1086 state.d = d
1087 elif self == GoldschmidtDivOp.FEq2MinusD:
1088 assert state.d.width == params.n_d_f_total_wid, "invalid d width"
1089 f = Signal.like(state.d)
1090 m.d.comb += f.eq((2 << params.expanded_width) - state.d)
1091 state.f = f
1092 elif self == GoldschmidtDivOp.CalcResult:
1093 assert state.n.width == params.n_d_f_total_wid, "invalid n width"
1094 assert state.n_shift is not None
1095 # scale to correct value
1096 n = state.n * (1 << state.n_shift)
1097 q_approx = Signal(params.io_width)
1098 # extra bit for if it's bigger than orig_d
1099 r_approx = Signal(params.io_width + 1)
1100 adjusted_r = Signal(signed(1 + params.io_width))
1101 m.d.comb += [
1102 q_approx.eq((state.n << state.n_shift)
1103 >> params.expanded_width),
1104 r_approx.eq(state.orig_n - q_approx * state.orig_d),
1105 adjusted_r.eq(r_approx - state.orig_d),
1106 ]
1107 state.quotient = Signal(params.io_width)
1108 state.remainder = Signal(params.io_width)
1109
1110 with m.If(adjusted_r >= 0):
1111 m.d.comb += [
1112 state.quotient.eq(q_approx + 1),
1113 state.remainder.eq(adjusted_r),
1114 ]
1115 with m.Else():
1116 m.d.comb += [
1117 state.quotient.eq(q_approx),
1118 state.remainder.eq(r_approx),
1119 ]
1120 else:
1121 assert False, f"unimplemented GoldschmidtDivOp: {self}"
1122
1123
1124 @dataclass
1125 class GoldschmidtDivState:
1126 orig_n: int
1127 """original numerator"""
1128
1129 orig_d: int
1130 """original denominator"""
1131
1132 n: FixedPoint
1133 """numerator -- N_prime[i] in the paper's algorithm 2"""
1134
1135 d: FixedPoint
1136 """denominator -- D_prime[i] in the paper's algorithm 2"""
1137
1138 f: "FixedPoint | None" = None
1139 """current factor -- F_prime[i] in the paper's algorithm 2"""
1140
1141 quotient: "int | None" = None
1142 """final quotient"""
1143
1144 remainder: "int | None" = None
1145 """final remainder"""
1146
1147 n_shift: "int | None" = None
1148 """amount the numerator needs to be left-shifted at the end of the
1149 algorithm.
1150 """
1151
1152
1153 def goldschmidt_div(n, d, params):
1154 """ Goldschmidt division algorithm.
1155
1156 based on:
1157 Even, G., Seidel, P. M., & Ferguson, W. E. (2003).
1158 A Parametric Error Analysis of Goldschmidt's Division Algorithm.
1159 https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.1238&rep=rep1&type=pdf
1160
1161 arguments:
1162 n: int
1163 numerator. a `2*width`-bit unsigned integer.
1164 must be less than `d << width`, otherwise the quotient wouldn't
1165 fit in `width` bits.
1166 d: int
1167 denominator. a `width`-bit unsigned integer. must not be zero.
1168 width: int
1169 the bit-width of the inputs/outputs. must be a positive integer.
1170
1171 returns: tuple[int, int]
1172 the quotient and remainder. a tuple of two `width`-bit unsigned
1173 integers.
1174 """
1175 assert isinstance(params, GoldschmidtDivParams)
1176 assert isinstance(d, int) and 0 < d < (1 << params.io_width)
1177 assert isinstance(n, int) and 0 <= n < (d << params.io_width)
1178
1179 # this whole algorithm is done with fixed-point arithmetic where values
1180 # have `width` fractional bits
1181
1182 state = GoldschmidtDivState(
1183 orig_n=n,
1184 orig_d=d,
1185 n=FixedPoint(n, params.io_width),
1186 d=FixedPoint(d, params.io_width),
1187 )
1188
1189 for op in params.ops:
1190 op.run(params, state)
1191
1192 assert state.quotient is not None
1193 assert state.remainder is not None
1194
1195 return state.quotient, state.remainder
1196
1197
1198 @dataclass(eq=False)
1199 class GoldschmidtDivHDLState:
1200 m: Module
1201 """The HDL Module"""
1202
1203 orig_n: Signal
1204 """original numerator"""
1205
1206 orig_d: Signal
1207 """original denominator"""
1208
1209 n: Signal
1210 """numerator -- N_prime[i] in the paper's algorithm 2"""
1211
1212 d: Signal
1213 """denominator -- D_prime[i] in the paper's algorithm 2"""
1214
1215 f: "Signal | None" = None
1216 """current factor -- F_prime[i] in the paper's algorithm 2"""
1217
1218 quotient: "Signal | None" = None
1219 """final quotient"""
1220
1221 remainder: "Signal | None" = None
1222 """final remainder"""
1223
1224 n_shift: "Signal | None" = None
1225 """amount the numerator needs to be left-shifted at the end of the
1226 algorithm.
1227 """
1228
1229 old_signals: "defaultdict[str, list[Signal]]" = field(repr=False,
1230 init=False)
1231
1232 __signal_name_prefix: "str" = field(default="state_", repr=False,
1233 init=False)
1234
1235 def __post_init__(self):
1236 # called by the autogenerated __init__
1237 self.old_signals = defaultdict(list)
1238
1239 def __setattr__(self, name, value):
1240 assert isinstance(name, str)
1241 if name.startswith("_"):
1242 return super().__setattr__(name, value)
1243 try:
1244 old_signals = self.old_signals[name]
1245 except AttributeError:
1246 # haven't yet finished __post_init__
1247 return super().__setattr__(name, value)
1248 assert name != "m" and name != "old_signals", f"can't write to {name}"
1249 assert isinstance(value, Signal)
1250 value.name = f"{self.__signal_name_prefix}{name}_{len(old_signals)}"
1251 old_signal = getattr(self, name, None)
1252 if old_signal is not None:
1253 assert isinstance(old_signal, Signal)
1254 old_signals.append(old_signal)
1255 return super().__setattr__(name, value)
1256
1257 def insert_pipeline_register(self):
1258 old_prefix = self.__signal_name_prefix
1259 try:
1260 for field in fields(GoldschmidtDivHDLState):
1261 if field.name.startswith("_") or field.name == "m":
1262 continue
1263 old_sig = getattr(self, field.name, None)
1264 if old_sig is None:
1265 continue
1266 assert isinstance(old_sig, Signal)
1267 new_sig = Signal.like(old_sig)
1268 setattr(self, field.name, new_sig)
1269 self.m.d.sync += new_sig.eq(old_sig)
1270 finally:
1271 self.__signal_name_prefix = old_prefix
1272
1273
1274 class GoldschmidtDivHDL(Elaboratable):
1275 # FIXME: finish getting hdl/simulation to work
1276 """ Goldschmidt division algorithm.
1277
1278 based on:
1279 Even, G., Seidel, P. M., & Ferguson, W. E. (2003).
1280 A Parametric Error Analysis of Goldschmidt's Division Algorithm.
1281 https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.1238&rep=rep1&type=pdf
1282
1283 attributes:
1284 params: GoldschmidtDivParams
1285 the goldschmidt division algorithm parameters.
1286 pipe_reg_indexes: list[int]
1287 the operation indexes where pipeline registers should be inserted.
1288 duplicate values mean multiple registers should be inserted for
1289 that operation index -- this is useful to allow yosys to spread a
1290 multiplication across those multiple pipeline stages.
1291 sync_rom: bool
1292 true if the rom should be read synchronously rather than
1293 combinatorially, incurring an extra clock cycle of latency.
1294 n: Signal(unsigned(2 * params.io_width))
1295 input numerator. a `2 * params.io_width`-bit unsigned integer.
1296 must be less than `d << params.io_width`, otherwise the quotient
1297 wouldn't fit in `params.io_width` bits.
1298 d: Signal(unsigned(params.io_width))
1299 input denominator. a `params.io_width`-bit unsigned integer.
1300 must not be zero.
1301 q: Signal(unsigned(params.io_width))
1302 output quotient. only valid when `n < (d << params.io_width)`.
1303 r: Signal(unsigned(params.io_width))
1304 output remainder. only valid when `n < (d << params.io_width)`.
1305 """
1306
1307 @property
1308 def total_pipeline_registers(self):
1309 """the total number of pipeline registers"""
1310 return len(self.pipe_reg_indexes) + self.sync_rom
1311
1312 def __init__(self, params, pipe_reg_indexes=(), sync_rom=False):
1313 assert isinstance(params, GoldschmidtDivParams)
1314 assert isinstance(sync_rom, bool)
1315 self.params = params
1316 self.pipe_reg_indexes = sorted(int(i) for i in pipe_reg_indexes)
1317 self.sync_rom = sync_rom
1318 self.n = Signal(unsigned(2 * params.io_width))
1319 self.d = Signal(unsigned(params.io_width))
1320 self.q = Signal(unsigned(params.io_width))
1321 self.r = Signal(unsigned(params.io_width))
1322
1323 def elaborate(self, platform):
1324 m = Module()
1325 state = GoldschmidtDivHDLState(
1326 m=m,
1327 orig_n=self.n,
1328 orig_d=self.d,
1329 n=self.n,
1330 d=self.d)
1331
1332 # copy and reverse
1333 pipe_reg_indexes = list(reversed(self.pipe_reg_indexes))
1334
1335 for op_index, op in enumerate(self.params.ops):
1336 while len(pipe_reg_indexes) > 0 \
1337 and pipe_reg_indexes[-1] <= op_index:
1338 pipe_reg_indexes.pop()
1339 state.insert_pipeline_register()
1340 op.gen_hdl(self.params, state, self.sync_rom)
1341
1342 while len(pipe_reg_indexes) > 0:
1343 pipe_reg_indexes.pop()
1344 state.insert_pipeline_register()
1345
1346 m.d.comb += self.q.eq(state.quotient)
1347 m.d.comb += self.r.eq(state.remainder)
1348 return m
1349
1350
1351 GOLDSCHMIDT_SQRT_RSQRT_TABLE_ADDR_INT_WID = 2
1352
1353
1354 @lru_cache()
1355 def goldschmidt_sqrt_rsqrt_table(table_addr_bits, table_data_bits):
1356 """Generate the look-up table needed for Goldschmidt's square-root and
1357 reciprocal-square-root algorithm.
1358
1359 arguments:
1360 table_addr_bits: int
1361 the number of address bits for the look-up table.
1362 table_data_bits: int
1363 the number of data bits for the look-up table.
1364 """
1365 assert isinstance(table_addr_bits, int) and \
1366 table_addr_bits >= GOLDSCHMIDT_SQRT_RSQRT_TABLE_ADDR_INT_WID
1367 assert isinstance(table_data_bits, int) and table_data_bits >= 1
1368 table = []
1369 table_len = 1 << table_addr_bits
1370 for addr in range(table_len):
1371 if addr == 0:
1372 value = FixedPoint(0, table_data_bits)
1373 elif (addr << 2) < table_len:
1374 value = None # table entries should be unused
1375 else:
1376 table_addr_frac_wid = table_addr_bits
1377 table_addr_frac_wid -= GOLDSCHMIDT_SQRT_RSQRT_TABLE_ADDR_INT_WID
1378 max_input_value = FixedPoint(addr + 1, table_addr_bits - 2)
1379 max_frac_wid = max(max_input_value.frac_wid, table_data_bits)
1380 value = max_input_value.to_frac_wid(max_frac_wid)
1381 value = value.rsqrt(RoundDir.DOWN)
1382 value = value.to_frac_wid(table_data_bits, RoundDir.DOWN)
1383 table.append(value)
1384
1385 # tuple for immutability
1386 return tuple(table)
1387
1388 # FIXME: add code to calculate error bounds and check that the algorithm will
1389 # actually work (like in the goldschmidt division algorithm).
1390 # FIXME: add code to calculate a good set of parameters based on the error
1391 # bounds checking.
1392
1393
1394 def goldschmidt_sqrt_rsqrt(radicand, io_width, frac_wid, extra_precision,
1395 table_addr_bits, table_data_bits, iter_count):
1396 """Goldschmidt's square-root and reciprocal-square-root algorithm.
1397
1398 uses algorithm based on second method at:
1399 https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Goldschmidt%E2%80%99s_algorithm
1400
1401 arguments:
1402 radicand: FixedPoint(frac_wid=frac_wid)
1403 the input value to take the square-root and reciprocal-square-root of.
1404 io_width: int
1405 the number of bits in the input (`radicand`) and output values.
1406 frac_wid: int
1407 the number of fraction bits in the input (`radicand`) and output
1408 values.
1409 extra_precision: int
1410 the number of bits of internal extra precision.
1411 table_addr_bits: int
1412 the number of address bits for the look-up table.
1413 table_data_bits: int
1414 the number of data bits for the look-up table.
1415
1416 returns: tuple[FixedPoint, FixedPoint]
1417 the square-root and reciprocal-square-root, rounded down to the
1418 nearest representable value. If `radicand == 0`, then the
1419 reciprocal-square-root value returned is zero.
1420 """
1421 assert (isinstance(radicand, FixedPoint)
1422 and radicand.frac_wid == frac_wid
1423 and 0 <= radicand.bits < (1 << io_width))
1424 assert isinstance(io_width, int) and io_width >= 1
1425 assert isinstance(frac_wid, int) and 0 <= frac_wid < io_width
1426 assert isinstance(extra_precision, int) and extra_precision >= io_width
1427 assert isinstance(table_addr_bits, int) and table_addr_bits >= 1
1428 assert isinstance(table_data_bits, int) and table_data_bits >= 1
1429 assert isinstance(iter_count, int) and iter_count >= 0
1430 expanded_frac_wid = frac_wid + extra_precision
1431 s = radicand.to_frac_wid(expanded_frac_wid)
1432 sqrt_rshift = extra_precision
1433 rsqrt_rshift = extra_precision
1434 while s != 0 and s < 1:
1435 s = (s * 4).to_frac_wid(expanded_frac_wid)
1436 sqrt_rshift += 1
1437 rsqrt_rshift -= 1
1438 while s >= 4:
1439 s = s.div(4, expanded_frac_wid)
1440 sqrt_rshift -= 1
1441 rsqrt_rshift += 1
1442 table = goldschmidt_sqrt_rsqrt_table(table_addr_bits=table_addr_bits,
1443 table_data_bits=table_data_bits)
1444 # core goldschmidt sqrt/rsqrt algorithm:
1445 # initial setup:
1446 table_addr_frac_wid = table_addr_bits
1447 table_addr_frac_wid -= GOLDSCHMIDT_SQRT_RSQRT_TABLE_ADDR_INT_WID
1448 addr = s.to_frac_wid(table_addr_frac_wid, RoundDir.DOWN)
1449 assert 0 <= addr.bits < (1 << table_addr_bits), "table addr out of range"
1450 f = table[addr.bits]
1451 assert f is not None, "accessed invalid table entry"
1452 # use with_frac_wid to fix IDE type deduction
1453 f = FixedPoint.with_frac_wid(f, expanded_frac_wid, RoundDir.DOWN)
1454 x = (s * f).to_frac_wid(expanded_frac_wid, RoundDir.DOWN)
1455 h = (f * 0.5).to_frac_wid(expanded_frac_wid, RoundDir.DOWN)
1456 for _ in range(iter_count):
1457 # iteration step:
1458 f = (1.5 - x * h).to_frac_wid(expanded_frac_wid, RoundDir.DOWN)
1459 x = (x * f).to_frac_wid(expanded_frac_wid, RoundDir.DOWN)
1460 h = (h * f).to_frac_wid(expanded_frac_wid, RoundDir.DOWN)
1461 r = 2 * h
1462 # now `x` is approximately `sqrt(s)` and `r` is approximately `rsqrt(s)`
1463
1464 sqrt = FixedPoint(x.bits >> sqrt_rshift, frac_wid)
1465 rsqrt = FixedPoint(r.bits >> rsqrt_rshift, frac_wid)
1466
1467 next_sqrt = FixedPoint(sqrt.bits + 1, frac_wid)
1468 if next_sqrt * next_sqrt <= radicand:
1469 sqrt = next_sqrt
1470
1471 next_rsqrt = FixedPoint(rsqrt.bits + 1, frac_wid)
1472 if next_rsqrt * next_rsqrt * radicand <= 1 and radicand != 0:
1473 rsqrt = next_rsqrt
1474 return sqrt, rsqrt