openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / workloads / softmax / reference.py
| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | import numpy as np |
| 3 | |
| 4 | U = 2.0 ** -24 |
| 5 | |
| 6 | |
| 7 | def _g(n): |
| 8 | return n * U / (1.0 - n * U) |
| 9 | |
| 10 | |
| 11 | def reference(p, x): |
| 12 | D = p["D"] |
| 13 | v = x["x"].astype(np.float64) |
| 14 | a = v - v.max(axis=1, keepdims=True) |
| 15 | e = np.exp(a) |
| 16 | y = e / e.sum(axis=1, keepdims=True) |
| 17 | # error bound; derivation in workload.json tolerance.why |
| 18 | eps = (1.0 + 6.0 * U) * np.exp(U * np.abs(a)) - 1.0 |
| 19 | E = eps.max(axis=1, keepdims=True) |
| 20 | gs, g2 = _g(D - 1), _g(2) |
| 21 | hi = (1.0 + eps) * (1.0 + g2) / ((1.0 - E) * (1.0 - gs)) - 1.0 |
| 22 | lo = 1.0 - (1.0 - eps) * (1.0 - g2) / ((1.0 + E) * (1.0 + gs)) |
| 23 | return {"y": (y, y * np.maximum(hi, lo))} |