diff --git a/CHANGELOG.md b/CHANGELOG.md index afa517b..82cb0fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,12 @@ contract of every version is the same: each lane of each function equals any species of 128 bits or more. Every lane is bit-identical to `StrictMath.atan`, NaN payloads and signed zeros included. Lanes of magnitude `2^66` or more, the infinities and NaNs are finished per lane by `StrictMath.atan`. +- `VFdlibm.atan2`, in the two forms `atan2(y, x)` and `atan2(y, x, live)`, over `DoubleVector` + lanes of any species of 128 bits or more; a lane that is not live is `y`'s. Every lane is + bit-identical to `StrictMath.atan2`, NaN payloads and signed zeros included, except a lane where + both arguments are NaN with different bits: it is one of the two arguments' bits with the quiet + bit set, and which one is not specified, since `StrictMath`'s own choice varies by JIT tier. No + lane is finished by a call to `StrictMath`. - `VFdlibm.acos`, in the two forms `acos(x)` and `acos(x, live)`, over `DoubleVector` lanes of any species of 128 bits or more. Every lane is bit-identical to `StrictMath.acos`, NaN payloads and signed zeros included. Lanes of magnitude 1 or more and NaNs are finished per lane by diff --git a/PLAN.md b/PLAN.md index ac967e1..0c3e1fe 100644 --- a/PLAN.md +++ b/PLAN.md @@ -44,7 +44,10 @@ provisionally, until a benchmark host times them). `asin` is done too (`VFdlibm. `e_asin.c`, with `sqrt` as the Vector API's `SQRT`, one arm, and the lanes of `|x| >= 1` finished per lane), and so is `atan` (`VFdlibm.atan`, from `s_atan.c`, five ranges through one division on blended operands, the lanes from `2^66` up finished per lane), and so is `acos` -(`VFdlibm.acos`, from `e_acos.c`, built as asin is). `log`, `log10` and +(`VFdlibm.acos`, from `e_acos.c`, built as asin is), and so is `atan2` (`VFdlibm.atan2`, from +`e_atan2.c`, the first function of two arguments: the special lanes blended over the general path, +which calls `atan`'s core, no lane finished per lane, and two arms, the blended one and the guarded +one `VFdlibm` calls, provisionally). `log`, `log10` and `log1p` are done too (`VFdlibm.log`, from `e_log.c`, `VFdlibm.log10`, from `e_log10.c`, which computes through log's common path, and `VFdlibm.log1p`, from `s_log1p.c`), and so is `expm1` (`VFdlibm.expm1`, from `s_expm1.c`, whose reduction is exp's). @@ -89,13 +92,13 @@ five are a later, optional set; the large-argument reduction of the trigonometri -XX:MaxVectorSize=32`, 128 and 256 bits on every draw), on x86 with `-XX:MaxVectorSize=16` (all of it at 128 bits) and on Arm (128 bits). - **Nightly:** `.github/workflows/nightly.yml` sweeps every high word of exp, expm1, log, log10, - log1p, sinh, cosh and atan (asin and acos are in `Nightly`'s table and not yet in the night's - list) with three low words each (every branch fdlibm decides on the high word) at every width but - 128 bits on x86, where a rotating 1/32 slice a night covers it in 32 nights, and at 128 bits on - Arm every night; it fuzzes from a fresh seed at every width, and runs every proof under both - solvers; a failure opens an issue labelled `nightly-failure` with the mismatching inputs, ready - for a `hard-cases` file (`SKILLS.md`), and a dispatch that plants a fault, to test that alert, - opens one labelled `nightly-fault-test`. + log1p, sinh, cosh and atan (asin, acos and atan2 are in `Nightly`'s tables and not yet in the + night's list) with three low words each (every branch fdlibm decides on the high word) at every + width but 128 bits on x86, where a rotating 1/32 slice a night covers it in 32 nights, and at 128 + bits on Arm every night; it fuzzes from a fresh seed at every width, and runs every proof under + both solvers; a failure opens an issue labelled `nightly-failure` with the mismatching inputs, + ready for a `hard-cases` file (`SKILLS.md`), and a dispatch that plants a fault, to test that + alert, opens one labelled `nightly-fault-test`. - **Masked forms:** a masked form is checked under seeded random masks, all-true and all-false; active lanes must equal `StrictMath` and inactive lanes must keep the input's raw bits (for a two-argument function, the first argument's). @@ -160,15 +163,17 @@ five are a later, optional set; the large-argument reduction of the trigonometri and 512 bits, the preferred species and `SPECIES_MAX`. `Log1pBenchmark` does the same for `log1p`, with a third arm that blends the rare paths only when a vector holds a rare lane; `Expm1Benchmark` has the same three arms for `expm1`, `SinhBenchmark` one for `sinh`, `CoshBenchmark` two for - `cosh`, `AsinBenchmark` one for `asin`, `AtanBenchmark` one for `atan` and `AcosBenchmark` one for - `acos`. Each of the ten has rows at `SPECIES_MAX` (`*Max`), which the allocation check covers: the + `cosh`, `AsinBenchmark` one for `asin`, `AtanBenchmark` one for `atan`, `AcosBenchmark` one for + `acos` and `Atan2Benchmark` two for `atan2` (the blended and the guarded arm, over two arrays). + Each of the eleven has rows at `SPECIES_MAX` (`*Max`), which the allocation check covers: the finish of `exp`, `expm1`, `log`, `log10` and `log1p` boxed there on mixed data until its first eight lanes were written out (`bench/results/max-finish-laptop-2026-11-20.txt`, then `bench/results/max-finish-alloc-free-laptop-2026-11-21.txt`, a laptop reading of allocation only); - no file reads the earlier finish of `sinh` or `cosh`, and none has an `asin`, `atan` or `acos` - row, whose finishes were written in the new shape from the start. `ExpKindsBench` runs exp's two - arms on one kind of rare input at a time (a NaN, an overflow, an underflow, a subnormal result), - to find which kind costs an arm its time on mixed data (#41); it is named apart so that a run of + no file reads the earlier finish of `sinh` or `cosh`, and none has an `asin`, `atan`, `acos` or + `atan2` row, whose finishes were written in the new shape from the start. `ExpKindsBench` runs + exp's two arms on one kind of rare input at a time (a NaN, an overflow, an underflow, a subnormal + result), to find which kind costs an arm its time on mixed data (#41); it is named apart so that + a run of `ExpBenchmark` and the allocation check's default regex leave it out, as `CoshKindsBench`, which has cosh's small-range shares, is. A function's body is larger than C2 inlines by default, so a call from a loop passes boxed vectors; the benchmarks are also run with diff --git a/PROOFS.md b/PROOFS.md index 513a82d..feca73c 100644 --- a/PROOFS.md +++ b/PROOFS.md @@ -1240,3 +1240,116 @@ of a vector's lanes rare (`everySubsetOfLanesRare`); `scalarTranscriptionIsStric **Encoding.** No file of its own: nothing here is a fold. Informal here: that the port's blends take each branch on exactly the C's lanes, and that it computes these steps, the code's text. + +## atan2 (`Atan2.java`, from `e_atan2.c`) + +**What the core's contract is, read in `Atan.java` before calling it.** `Atan.atan(x, live)` takes +a vector of any doubles and a mask or null. A null mask computes every lane; otherwise only live +lanes are computed, an inactive lane comes back as the argument's lane, untouched, and never takes +the per-lane finish (`rare` is and-ed with `live`). It does its own sign handling: it reduces +`|x|`, negates for `hx < 0`, and returns `x` below `7/16` with no reduction, so for a +non-negative argument it is `atan` of it by the C's operations. The lanes it leaves to a per-lane +`StrictMath.atan` are `|x| >= 2^66`, the infinities and the NaNs. `atan2` calls it with `t = +fabs(y/x)` and the mask `t < 2^66` (and live), so a NaN, an infinity or a huge `t` never +reaches the finish. The lanes of `t >= 2^66` that the general path keeps (`x = 1.0` beside a huge +`y`, and a subnormal `x`, whose high word has no exponent, so that `k` understates the gap: `x = +2^-1074`, `y = 2^-1000` is `t = 2^74` with `k = 23`) take `atanhi[3] + atanlo[3]`, which is what +s_atan.c returns there for a positive argument (lines 97-102), from the same two arrays `Atan` +holds. The port copies none of `Atan`'s code. + +e_atan2.c returns `x + y` for a NaN in either argument (lines 71-73), `atan(y)` for `x = 1.0` (74), +`y` or `+-(pi + tiny)` for `y = +-0` by the signs (78-85), `+-(pi_o_2 + tiny)` for `x = +-0` (87), +the diagonals `+-(pi_o_4 + tiny)` and `+-(3.0*pi_o_4 + tiny)`, or `+-0` and `+-(pi + tiny)`, for `x += +-inf` (90-106), and `+-(pi_o_2 + tiny)` for `y = +-inf` (108). The rest take `k = (iy-ix)>>20` +(111), the result `z = pi_o_2 + 0.5*pi_lo` for `k > 60`, `z = 0.0` for `hx < 0` and `k < -60`, and +`z = atan(fabs(y/x))` otherwise (112-114), and the quadrant by `m` (115-122): `z`, `z` with its sign +flipped, `pi - (z - pi_lo)`, `(z - pi_lo) - pi`. The port computes every lane's general path and +every special lane, and blends the special lanes over it from the last of the C's tests to the +first, so that the first that matches wins as in the C. It **needs one lemma of its own, L14 below, +for `x = 1.0`**, and otherwise L13's blend argument: H1 is the C's tests as exact classifications of +the doubles (a compare with 0.0 for a zero, `IS_INFINITE`, `IS_NAN`, a compare with 1.0, and the C's +own compares of `k` and of the sign words), in the C's order of priority, which is the order of the +blends; H2 is the order of the operations in each lane (one division `y/x`, then atan's, then the +quadrant's); H3 holds since every operation on a lane is total (IEEE operations, compares, int +shifts, blends: no integer division, no indexed load); and H4 since each blend is a `blend`. The +values that a lane overwritten by a special blend takes in the general path (`y/0` is an infinity, +`0/0` a NaN) are never read. Where its text is not the C's: + +- `x = 1.0` is not a lane of its own, which L14 proves equal to the C's `atan(y)`. What the C's + early return also does is to skip the `k > 60` shortcut, which the port does too + (`kHigh.and(xOne.not())`). +- The quadrants use `z.neg()` for `__HI(z) ^= 0x80000000`: an IEEE negate is the sign-bit flip, + `-0.0` included. `z - pi_lo` is computed once for the two quadrants that compute it, the same + operation on the same operands. +- `pi + tiny`, `pi_o_2 + tiny`, `3.0*pi_o_4 + tiny` and their negatives are `static final` + expressions in Java of the same operations, so none is assumed to equal another constant; + `constantsAreTheSourcesBits` checks the words. +- `k` is computed on the high words as `int` lanes, as the C does. +- A lane of two NaNs is `x + y` in the vector, which is one of the arguments quieted, a candidate + of `OPERANDS` (the contract of a function of two arguments, above). One NaN beside a finite + value is `x + y` too: the NaN quieted with its sign, which `StrictMath.atan2` gives in every + mode of the probe (issue 33). + +### L14. x = 1.0 through the general path is atan(y) + +**Statement.** For `x = 1.0` and a `y` that is not a NaN, the port's lane is the C's `atan(y)`, bit +for bit, with `-0.0`, the infinities and the lanes of `|y| >= 2^66` included. + +**Hypotheses.** (a) `y/1.0` is `y` (division by one is exact: IEEE division is correctly rounded +and the quotient is a double); `fabs` clears the sign. (b) s_atan.c is odd: `atan(-y) = -atan(y)` +bit for bit. (c) The port's `z` for `|y|` is s_atan.c's `atan(|y|)` by the C's operations (atan's +section), or `atanhi[3] + atanlo[3]` from `2^66` up, which is the C's line 100 for a positive +argument. (d) `y = +-inf` is a special lane, `+-(pi_o_2 + tiny)`, and `pi_o_2 + tiny` is the +bits of `atanhi[3] + atanlo[3]`. + +**Proof.** By (a) the port's `t` is `|y|`, and the `k > 60` shortcut is off for `x = 1.0`, so +by (c) `z = atan(|y|)` (for `y` finite and not zero; for `y = +-0` the lane is the special lane, +which returns `y`, and `atan(+-0)` is `+-0` since s_atan.c returns `x` below `2^-29`). `m` is 0 +for `y > 0` and 1 for `y < 0` (`x = 1.0` is positive), so the port returns `z` or `-z`, the sign +flip being exact. (b) holds on each branch of s_atan.c: below `7/16` the C computes `x - +x*(s1+s2)` on the signed `x`, where `s1` and `s2` are polynomials in `z = x*x` and `w = z*z` (even +in `x`) and `x*(s1+s2)` is odd, so the result is odd by (R1) (the rounding of `fl(-v) = -fl(v)` +at each operation); below `2^-29` it returns `x`; from `7/16` up it computes on `fabs(x)` and +negates for `hx < 0`; from `2^66` it returns `+-(atanhi[3] + atanlo[3])`. So `atan(y) = -atan(|y|)` +for `y < 0`, which is what the port returns. For `y = +-inf` the special lane gives `+-(pi_o_2 + +tiny)`, which by (d) is the C's `+-(atanhi[3] + atanlo[3])`. QED. + +**What checks it.** (a) and (c) are the port's own tests: `Atan2Test.xOneIsAtanOfY` checks at every +width that `atan2(y, 1.0)` has the bits of both `StrictMath.atan(y)` and `VFdlibm.atan(y)` on +atan's thresholds, sampled values, a spread of magnitudes and dense draws, the infinities and both +zeros included (a NaN is the NaN lane); `constantsAreTheSourcesBits` checks the words of `pi_o_2`, +`pi_o_2 + tiny` and `atanhi[3] + atanlo[3]`, which (d) is about. A fault in (b) or (c) would +show there and in `xIsOne`, which draws `x = +-1.0` and its neighbours beside `|y|` from `2^50` +to `2^70`. + +**The two shortcuts of `k` are redundant in bits, which tests cannot see move by one.** Measured on +200000 draws of `t` in each binade from `2^54` up, not proved, and by a program that is not +committed, `StrictMath.atan(t)` is the bits of `pi_o_2 + 0.5*pi_lo` in every one, and for `t` below +`2^-55` the quadrant results with `z = atan(t)` and with `z = 0.0` are the same bits. They differ in +58213 of 200000 draws at `2^52` and in all at `2^50`, and the quadrant sums differ from `t` near +`2^-52` up. So `k > 60` and `hx < 0 && k < -60`, moved by one, change no result (0 of 2^19 draws in +`theShortcutsAreSeenMovedByTenAndNotByOne`), and neither does the `x = 1.0` exception. The port +follows the C anyway, and no fault is planted at them by one. The two faults `atan2.kHighMoved` and +`atan2.kLowMoved` move the thresholds by ten, to `k > 50` and `k < -50`, where `atan(t)` is not yet +`pi_o_2` (`t` near `2^50`) or the quadrant sum is not yet the same (`t` near `2^-50`), and a test of +results sees them. That is a statement about the C's values, checked by draws and not proved; the +port's correctness does not rest on it. + +**What it rests on.** (R4) for `+ - * /` and the negate, (R1) for L14, L13, atan's own section for +the core, and the contract of a function of two arguments for the lane of two NaNs. + +**Checks.** `constantsAreTheSourcesBits`, and `Atan2Test`: `VFdlibm.atan2`, `Atan2.atan2Blended` +and `Atan2.atan2Guarded` against `StrictMath.atan2` by `PairBits.matches` at every width and +`SPECIES_MAX`, unmasked and masked, on every pair of the special values (the infinities, the zeros, +the NaNs of both signs and several payloads, the subnormals, `+-1` and the neighbours of `2^60` +and `2^66`); pairs whose exponents differ by -70 to 70, so that `k` crosses both thresholds; pairs +drawn at the differences of high words the fuzz lists for atan2; `x = +-1.0` beside `|y|` from +`2^50` to `2^70`; a subnormal `x` beside a `y` of moderate exponent; sampled bit patterns; +dense draws; the 20,820 pairs of `hard-cases/atan2.txt`; and every subset of a vector's lanes +special beside lanes the core computes. +`scalarTranscriptionIsStrictMath` checks that `cAtan2`, e_atan2.c in scalar Java, is +`StrictMath.atan2` on those inputs. The planted faults are `atan2.kHighMoved`, +`atan2.kLowMoved`, `atan2.lowShortcutForPositiveX` (the shortcut without `hx < 0`), +`atan2.infOrderSwapped` (`y` infinite wins over `x` infinite), `atan2.dropPiLo`, `atan2.zeroSignOfX` +(`x < 0` by value for `y = +-0`, so `-0.0` is positive), `atan2.diagonalInf` (`pi_o_4` in every +quadrant) and `atan2.noSignFlip`. diff --git a/README.md b/README.md index ca81e5c..562cf62 100644 --- a/README.md +++ b/README.md @@ -120,10 +120,11 @@ java --module-path "target/classes:$(cat cp.txt)" -m example/example.Main ``` Each function takes a vector of any species of 128 bits or more. Released in 0.1.0: `exp`, -`expm1`, `log`, `log10` and `log1p`. On `main`, unreleased: `sinh`, `cosh`, `asin`, `atan` and -`acos`. The system property `vfdlibm.fault` plants a fault, for this project's tests only, and -works in the shipped jar too: never set it, including through `JAVA_TOOL_OPTIONS`; a JVM that has -it set prints a warning to `System.err` once. The property and the fault names are for this +`expm1`, `log`, `log10` and `log1p`. On `main`, unreleased: `sinh`, `cosh`, `asin`, `atan`, `acos` +and `atan2(y, x)`, which takes two vectors. The system property `vfdlibm.fault` plants a +fault, for this project's tests only, and works in the shipped jar too: never set it, including +through `JAVA_TOOL_OPTIONS`; a JVM that has it set prints a warning to `System.err` once. The +property and the fault names are for this project's tests only: they are not part of the public API or of the compatibility promise, and any release, a patch included, may rename or remove them. With the property unset, the results are unchanged, and each lane still equals `StrictMath`'s. diff --git a/SKILLS.md b/SKILLS.md index 77f2856..be38e7d 100644 --- a/SKILLS.md +++ b/SKILLS.md @@ -665,40 +665,37 @@ stops the next port re-trying a settled question. `NightlyTest`'s planted-fault test passes it; `dev/nightly.sh` passes only `--seconds`, so to replay a bounded run call `Fuzz` directly (its class comment has the command). - **Functions of two arguments** (`Nightly.PairFunction`, test-only code like the rest: a port - registers its function in `PairFunction.KNOWN`; none is ported yet, and `PairHarnessTest` runs the - harness on a toy, `x * 0.5 + y`, with planted faults). The workflow lists such a function in the - plan job's `pairs`, as well as in `all`, and gives its sweep jobs an `argument` and an artifact - suffix (`dev/nightly.sh` reads `NIGHTLY_ARGUMENT`, and names its log `sweep--arg-`): - the input `pair-passes` is `alternate` (the default: the first argument for a rotation of - `nights` nights, then the second for as many), `both` (two jobs a stripe) or `1` or `2`. A - function of one argument has no `argument` field, so its entries are what they were. The sweep - takes `--argument 1` (the default) or - `2`: the high words swept are that argument's, each with its three low words, and each swept value - gets a partner for the other argument drawn from the seed, the argument and the input's index - alone (`Sweep.partner`; a quarter each of special values, the swept value's exponent, an exponent - within 64 of it, and random bits), so a pair replays from the seed and its replay line says - `--argument`. A pass checks 3 * 2^32 of the 2^128 pairs, so **what it can miss**: a bug that needs - a high word of each argument at once, which a partner drawn as above meets with probability about - 2^-32 for a random partner and more where the two exponents are near, and which - the fuzz meets because its draws put both arguments at their edges at once (`toy2-xy` in - `PairHarnessTest`: both sweeps pass it, the fuzz finds it). The masked form of an arm keeps the - first argument's bits in a lane that is not live (`Oracle.assertPairMasked`'s contract). A pair - function's mismatch file, and a hard-cases file of one, say `# arity: 2` before the first input - and hold `0x 0x` on a line: `Inputs.hardCasePairs` reads one, and `Inputs.hardCases` refuses - it by that line. + registers its function in `PairFunction.KNOWN`; `atan2` is the first, and `PairHarnessTest` runs + the harness on a toy, `x * 0.5 + y`, with planted faults). The workflow lists such a function in + the plan job's `pairs`, as well as in `all`, and gives its sweep jobs an `argument` and an + artifact suffix (`dev/nightly.sh` reads `NIGHTLY_ARGUMENT`, and names its log + `sweep--arg-`): the input `pair-passes` is `alternate` (the default: the first + argument for a rotation of `nights` nights, then the second for as many), `both` (two jobs a + stripe) or `1` or `2`. A function of one argument has no `argument` field, so its entries are what + they were. The sweep takes `--argument 1` (the default) or `2`: the high words swept are that + argument's, each with its three low words, and each swept value gets a partner for the other + argument drawn from the seed, the argument and the input's index alone (`Sweep.partner`; a quarter + each of special values, the swept value's exponent, an exponent within 64 of it, and random bits), + so a pair replays from the seed and its replay line says `--argument`. A pass checks 3 * 2^32 of + the 2^128 pairs, so **what it can miss**: a bug that needs a high word of each argument at once, + which a partner drawn as above meets with probability about 2^-32 for a random partner and more + where the two exponents are near, and which the fuzz meets because its draws put both arguments at + their edges at once (`toy2-xy` in `PairHarnessTest`: both sweeps pass it, the fuzz finds it). The + masked form of an arm keeps the first argument's bits in a lane that is not live + (`Oracle.assertPairMasked`'s contract). A pair function's mismatch file, and a hard-cases file of + one, say `# arity: 2` before the first input and hold `0x 0x` on a line: + `Inputs.hardCasePairs` reads one, and `Inputs.hardCases` refuses it by that line. `hard-cases/atan2.txt` is one: Lefevre's data has no tag of a function of two arguments, so `dev/testlibm-extract.py atn atan2` derives its 20820 pairs from the 1735 `atn` inputs `t`, as - `(+-t * 2^j, +-2^j)` for `j` in 0, 1, -5 (so `|y/x| = t` exactly), which are inputs of atan's - core through `atan2`'s own code and not hard cases of its quadrants; `HardCasePairsTest` checks - the file's shape. - A branch on the two arguments' high words relative to each other (`e_atan2.c`'s `k = (iy - ix) - >> 20`, which the edges of each argument cannot reach) is listed in `Fuzz.PairEdges.wordGaps`, - the first argument's absolute high word less the second's at the values the C tests (for an - `atan2` port: `61 * 2^20` and `-60 * 2^20`, and the word below each, which no function lists - yet); one pair in ten is then drawn - at one of them, and a function that lists none draws as before. `FuzzWordGapsTest` shows a - fault at exactly one gap found by the fuzz at every width and not found when the gaps are not - listed. + `(+-t * 2^j, +-2^j)` for `j` in 0, 1, -5 (so `|y/x| = t` exactly), which are inputs of atan's core + through `atan2`'s own code and not hard cases of its quadrants; `HardCasePairsTest` checks the + file's shape. A branch on the two arguments' high words relative to each other (`e_atan2.c`'s `k = + (iy - ix) >> 20`, which the edges of each argument cannot reach) is listed in + `Fuzz.PairEdges.wordGaps`, the first argument's absolute high word less the second's at the values + the C tests (for an `atan2`: `61 * 2^20` and `-60 * 2^20`, and the word below each, which + `Nightly.PairFunction.ATAN2` lists); one pair in ten is then drawn at one of them, and a function + that lists none draws as before. `FuzzWordGapsTest` shows a fault at exactly one gap found by the + fuzz at every width and not found when the gaps are not listed. - **One comparator for a function of two arguments** (`PairBits.matches(candidates, x, y, want, got)`, test code). Every comparison of a pair function's lane goes through it: `Oracle.assertPair` and the live lanes of `assertPairMasked` (a lane that is not live keeps `x`'s raw bits), and the @@ -717,16 +714,17 @@ stops the next port re-trying a settled question. oracle's bits unchecked, or to keep the sign under `MAGNITUDES`, fails `PairNanTest` (tried by hand on this version). - **What a pass over a function of two arguments costs** (laptop, 21 November 2026, - `bench/results/pair-sweep-laptop-2026-11-21.txt`; no pair function is ported, so this is two - stand-ins run through `PairCostProbe`, not a port). A stripe of 2^24 high words at 256 bits took - 0.9 s for the harness alone (`toy2`) and 1.8 s for an arm that calls `StrictMath.atan2` lane by - lane, against 2.9 s and 3.6 s for the unary sweeps of exp and log1p, at 4 threads on 4 CPUs. - Scaled to a whole pass (256 stripes), the x86 sweep jobs of the arm-bound stand-in come to, on - that loaded laptop and so only as an indication, about 16 runner-minutes on an AVX2 draw and 23 - on an AVX-512 one, and the second argument's pass costs what the first does: both passes in one night are twice that, one alternating pass is once. The - file has the method, the three runs of each row and its limits; the nightly's own logs replace - it once a pair function runs. It also records that, on two NaNs, the oracle's `StrictMath.atan2` - and a loop of calls to it differed in the payload in 12 of 12 runs (cause not read), so a pair + `bench/results/pair-sweep-laptop-2026-11-21.txt`; it was taken before `atan2` was ported, so it is + two stand-ins run through `PairCostProbe`, not the port, and no timing of `atan2` exists). A + stripe of 2^24 high words at 256 bits took 0.9 s for the harness alone (`toy2`) and 1.8 s for an + arm that calls `StrictMath.atan2` lane by lane, against 2.9 s and 3.6 s for the unary sweeps of + exp and log1p, at 4 threads on 4 CPUs. Scaled to a whole pass (256 stripes), the x86 sweep jobs of + the arm-bound stand-in come to, on that loaded laptop and so only as an indication, about 16 + runner-minutes on an AVX2 draw and 23 on an AVX-512 one, and the second argument's pass costs what + the first does: both passes in one night are twice that, one alternating pass is once. The file + has the method, the three runs of each row and its limits; the nightly's own logs replace it once + a pair function runs. It also records that, on two NaNs, the oracle's `StrictMath.atan2` and a + loop of calls to it differed in the payload in 12 of 12 runs (cause not read), so a pair function's check may need a canonical NaN. - **Checking that the unary nightly is unchanged** (`dev/unary-output-check.sh`, run by a person after a change to `Sweep`, `Fuzz`, `Nightly` or `Inputs`, not by CI). `check ` builds @@ -1067,3 +1065,53 @@ stops the next port re-trying a settled question. - **Allocation.** CI runs `bench/alloc-check.py` on `AcosBenchmark`'s rows (`finish256`, `finishPreferred`, `finishMax`, common and mixed data). No reading of them is committed and no timing exists, so nothing is claimed of either. + +## What the atan2 port taught + +- **The first function of two arguments, and no lane finished by a call.** The special lanes + (NaN, zeros, infinities) are blends of constants, of `y` and of `x + y`; the general path calls + `Atan.atan` on `t = fabs(y/x)` and the mask `t < 2^66` (and live), and the lanes of `t >= 2^66`, + which only `x = 1.0` has, take the constant `atanhi[3] + atanlo[3]` that s_atan.c returns there. + Every lane the tests drew matched on the first run of `Atan2Test`, at every width, masked and + unmasked, with the hard-case pairs and every subset of lanes special. +- **The first body boxed on every row.** It made its masks, then called `Atan.atan` and, last, a + private `specials` method. `bench/alloc-check.py --why` named C2's refusals: `Atan::atan` and + `Atan2::specials` both failed to inline with `NodeCountInliningCutoff`. The fix is the rule in + `Atan`'s comment (every call a body makes comes first), taken further: the call into atan + comes second, right + after the quotient and one compare (`t < 2^66`) that is its whole mask, the classification masks + and the special blends follow inline (no second call), and the body then allocates nothing: + `bench/alloc-check.py` passes on the `Atan2Benchmark` rows (`blended` and `guarded`, at 256 bits, + the preferred species and `SPECIES_MAX`, common and mixed data) at this laptop's flags and as an + AVX2 host, and CI runs it. The readings are not committed as results files, so no figure of them + is quoted. No timing of `atan2` exists, so the two arms are not compared and the guarded one + is the default provisionally. +- **A lane the core must not see.** A NaN, an infinity or a huge `t` in a lane the special blends + overwrite would send the vector to atan's per-lane finish. The mask `t < 2^66` keeps them out + (a NaN compares false), and a vector with no special lane never reaches the finish. +- **The shortcuts of `k` are redundant in bits.** `atan(t)` is `pi_o_2 + 0.5*pi_lo` from `t` near + `2^54`, and the quadrant sums with `z = 0.0` and with `z = atan(t)` agree below `t` near `2^-55`, + so the C's `k > 60` and `hx < 0 && k < -60`, and its early return for `x = 1.0`, change no + result, and a fault that moves a threshold by one cannot be seen (PROOFS.md, atan2). The + design note's fault on `x = 1.0` taking the shortcut was dropped for that reason, and so was a + fault that took `k` from the exponent fields; `atan2.kHighMoved` and `atan2.kLowMoved` move the + thresholds by ten. +- **The faults, sized on 2^22 draws** (a throwaway program over `VFdlibm.atan2`, once per fault, + at 256 bits; the counts are of pairs the fault changes). Over pairs whose exponents differ by + -70 to 70: `atan2.kHighMoved` 40791, `atan2.kLowMoved` 20438, + `atan2.lowShortcutForPositiveX` 155961, `atan2.dropPiLo` 1253851, `atan2.noSignFlip` 1049118, + `atan2.infOrderSwapped`, `atan2.zeroSignOfX` and `atan2.diagonalInf` none. Over the nightly's + own draws at the `k` gaps (`Nightly.PairFunction.ATAN2`'s edges): 1452, 738, 594538, 807566, + 832241, and 240, 96 and 152 for the three that need an infinity or a zero. Over the 7225 pairs of + the special values: 4, 2 and 3 for those three, 650 for `lowShortcutForPositiveX`, 817 for + `dropPiLo` and 1150 for `noSignFlip`, and 0 for the two thresholds. The fault run's inputs + hold all of them, and the unplanted port changes 0 of each. +- **Hard cases.** Lefevre's data has no `atan2` tag, so `hard-cases/atan2.txt` is derived from its + `atn` lines (`dev/testlibm-extract.py atn atan2`): `atan2(+-t * 2^j, +-2^j)` for `j` in 0, 1, + -5, 20,820 pairs. They are inputs of atan's core through `atan2`'s own code, not hard cases of + its quadrants. +- **The masked form keeps `y`, the first argument,** in a lane that is not live, as the harness's + `assertPairMasked` requires, and a lane that is not live never takes a special blend's test: the + guard reads `special & live`. +- **The consumer of `dev/jar-check.sh`** calls `atan2` over every pair of its inputs and two NaNs of + different bits, unmasked and under four masks, and compares by a copy of `PairBits.matches`. diff --git a/dev/jar-check.sh b/dev/jar-check.sh index 3287944..a09d182 100755 --- a/dev/jar-check.sh +++ b/dev/jar-check.sh @@ -362,6 +362,7 @@ import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Set; import java.util.TreeSet; +import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleUnaryOperator; import jdk.incubator.vector.DoubleVector; import jdk.incubator.vector.VectorMask; @@ -429,6 +430,83 @@ public final class Consumer { } } + /** Two NaNs with different bits, beside the common values, for a function of two arguments. */ + private static final double[] PAIR_NANS = { + Double.longBitsToDouble(0x7ff8000000000123L), Double.longBitsToDouble(0xfff4000000000456L), + }; + + /** + * Checks f(y, x) and f(y, x, live), found by name, against the oracle, over every pair of the + * inputs and of two NaNs of different bits. A lane where both arguments are NaN with different + * bits must be one of the arguments' bits with the quiet bit set (the oracle's too), which one + * is not specified; every other lane has the oracle's bits. + */ + private static void checkPair(String name, DoubleBinaryOperator oracle) throws Exception { + Method plain = function(name, DoubleVector.class, DoubleVector.class); + Method masked = + function(name, DoubleVector.class, DoubleVector.class, VectorMask.class); + double[] values = new double[INPUTS.length + PAIR_NANS.length]; + System.arraycopy(INPUTS, 0, values, 0, INPUTS.length); + System.arraycopy(PAIR_NANS, 0, values, INPUTS.length, PAIR_NANS.length); + int count = values.length * values.length; + double[] ys = new double[count]; + double[] xs = new double[count]; + for (int i = 0; i < count; i++) { + ys[i] = values[i / values.length]; + xs[i] = values[i % values.length]; + } + int length = SPECIES.length(); + double[] y = new double[length]; + double[] x = new double[length]; + boolean[] live = new boolean[length]; + for (int from = 0; from < count; from += length) { + for (int i = 0; i < length; i++) { + y[i] = ys[(from + i) % count]; + x[i] = xs[(from + i) % count]; + } + DoubleVector vy = DoubleVector.fromArray(SPECIES, y, 0); + DoubleVector vx = DoubleVector.fromArray(SPECIES, x, 0); + double[] got = ((DoubleVector) plain.invoke(null, vy, vx)).toArray(); + for (int i = 0; i < length; i++) { + samePair(name, y[i], x[i], got[i], oracle.applyAsDouble(y[i], x[i])); + } + for (int out = 0; out < 4; out++) { + for (int i = 0; i < length; i++) { + live[i] = (from + i) % 3 != out; + } + VectorMask mask = VectorMask.fromArray(SPECIES, live, 0); + double[] gotMasked = ((DoubleVector) masked.invoke(null, vy, vx, mask)).toArray(); + for (int i = 0; i < length; i++) { + if (live[i]) { + samePair(name + " (masked)", y[i], x[i], gotMasked[i], + oracle.applyAsDouble(y[i], x[i])); + } + } + } + } + } + + /** The rule of the pair comparison: see checkPair. A copy of the suite's PairBits.matches. */ + private static void samePair(String name, double y, double x, double got, double expected) { + long yb = Double.doubleToRawLongBits(y); + long xb = Double.doubleToRawLongBits(x); + long gotBits = Double.doubleToRawLongBits(got); + long wantBits = Double.doubleToRawLongBits(expected); + boolean nans = (yb & 0x7fffffffffffffffL) > 0x7ff0000000000000L + && (xb & 0x7fffffffffffffffL) > 0x7ff0000000000000L && yb != xb; + long quiet = 0x0008000000000000L; + boolean ok = nans + ? (gotBits == (yb | quiet) || gotBits == (xb | quiet)) + && (wantBits == (yb | quiet) || wantBits == (xb | quiet)) + : gotBits == wantBits; + lanes++; + if (!ok) { + wrong++; + System.out.printf("%s(%016x, %016x): got %016x, StrictMath %016x%n", name, yb, xb, gotBits, + wantBits); + } + } + /** The public static methods of VFdlibm that were not called. */ private static Set uncalled() { Set names = new TreeSet<>(); @@ -461,8 +539,8 @@ public final class Consumer { return names; } - // A function of two arguments must compare through a copy of the rule of PairBits.matches (a - // lane of two NaNs with different bits is one of the function's declared candidates), not this. + // A function of two arguments compares through samePair, a copy of the rule of + // PairBits.matches, not through this raw comparison. private static void same(String name, double in, double got, double expected) { lanes++; if (Double.doubleToRawLongBits(got) != Double.doubleToRawLongBits(expected)) { @@ -487,6 +565,7 @@ public final class Consumer { check("asin", StrictMath::asin); check("atan", StrictMath::atan); check("acos", StrictMath::acos); + checkPair("atan2", StrictMath::atan2); Module module = VFdlibm.class.getModule(); String in = module.isNamed() ? module.getName() : ""; System.out.printf("%d lanes at %d bits, %d wrong; the library is in %s%n", lanes, diff --git a/pom.xml b/pom.xml index b3b826d..11f1f22 100644 --- a/pom.xml +++ b/pom.xml @@ -506,6 +506,86 @@ ${vfdlibm.test.argLine} -Dvfdlibm.fault=atan.hiOneUlpOff + + fault-atan2.kHighMoved + ${vfdlibm.fault.phase} + test + + fault + true + ${vfdlibm.test.argLine} -Dvfdlibm.fault=atan2.kHighMoved + + + + fault-atan2.kLowMoved + ${vfdlibm.fault.phase} + test + + fault + true + ${vfdlibm.test.argLine} -Dvfdlibm.fault=atan2.kLowMoved + + + + fault-atan2.lowShortcutForPositiveX + ${vfdlibm.fault.phase} + test + + fault + true + ${vfdlibm.test.argLine} -Dvfdlibm.fault=atan2.lowShortcutForPositiveX + + + + fault-atan2.infOrderSwapped + ${vfdlibm.fault.phase} + test + + fault + true + ${vfdlibm.test.argLine} -Dvfdlibm.fault=atan2.infOrderSwapped + + + + fault-atan2.dropPiLo + ${vfdlibm.fault.phase} + test + + fault + true + ${vfdlibm.test.argLine} -Dvfdlibm.fault=atan2.dropPiLo + + + + fault-atan2.zeroSignOfX + ${vfdlibm.fault.phase} + test + + fault + true + ${vfdlibm.test.argLine} -Dvfdlibm.fault=atan2.zeroSignOfX + + + + fault-atan2.diagonalInf + ${vfdlibm.fault.phase} + test + + fault + true + ${vfdlibm.test.argLine} -Dvfdlibm.fault=atan2.diagonalInf + + + + fault-atan2.noSignFlip + ${vfdlibm.fault.phase} + test + + fault + true + ${vfdlibm.test.argLine} -Dvfdlibm.fault=atan2.noSignFlip + + fault-sinh.splitMoved ${vfdlibm.fault.phase} diff --git a/src/jmh/java/io/github/vecbricks/vfdlibm/Atan2Benchmark.java b/src/jmh/java/io/github/vecbricks/vfdlibm/Atan2Benchmark.java new file mode 100644 index 0000000..218f757 --- /dev/null +++ b/src/jmh/java/io/github/vecbricks/vfdlibm/Atan2Benchmark.java @@ -0,0 +1,160 @@ +/* + * Licensed to the vecbricks contributors under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy of the + * License at http://www.apache.org/licenses/LICENSE-2.0. Software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.vecbricks.vfdlibm; + +import java.util.SplittableRandom; +import java.util.concurrent.TimeUnit; +import jdk.incubator.vector.DoubleVector; +import jdk.incubator.vector.VectorSpecies; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +/** + * atan2 over two arrays of 1024 doubles ({@code y} and {@code x}): the scalar {@code + * StrictMath.atan2} loop and the two arms of {@link Atan2}, {@code blended} (the special lanes' + * blends in every vector) and {@code guarded} (behind one test; {@code VFdlibm.atan2} runs it), + * at 256 bits, at the host's preferred species and at {@code SPECIES_MAX}. 128 bits is left out: + * on x86 C2 lowers no mask at two 64-bit lanes, so every 128-bit arm boxes (SKILLS.md). No + * timing of {@code atan2} exists: the benchmark is read by {@code bench/alloc-check.py} for what + * the bodies allocate, and the arms are not yet compared on a host. + * + *

{@code inputs} picks the data: {@code common} draws {@code y} and {@code x} from {@code + * (-4, 4)}, where no lane is special (NaN, zero, infinite), none has {@code x = 1.0} and none + * takes a shortcut of {@code k}; {@code mixed} replaces one pair in 16 with one that takes a + * special lane or a shortcut (a NaN, a zero, an infinity, {@code x = 1.0} beside a huge {@code + * y}, a ratio past {@code 2^60} in either direction), so many vectors hold one. Any other value + * is refused. + * + *

The vector form is larger than C2 inlines by default ({@code FreqInlineSize}), so a call + * from the loop may pass boxed vectors. To measure the body inlined, add {@code -jvmArgsAppend + * -XX:CompileCommand=inline,io.github.vecbricks.vfdlibm.*::*}. + * + *

{@code bench/alloc-check.py} runs the vector benchmarks named {@code *256}, {@code + * *Preferred} and {@code *Max} on {@code common} and {@code mixed} inputs and fails if any + * allocates, which means the body boxed. + */ +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(value = 1, jvmArgsAppend = {"--add-modules", "jdk.incubator.vector"}) +public class Atan2Benchmark { + + private static final int N = 1024; + private static final VectorSpecies S256 = DoubleVector.SPECIES_256; + private static final VectorSpecies SP = DoubleVector.SPECIES_PREFERRED; + private static final VectorSpecies SMAX = DoubleVector.SPECIES_MAX; + + @Param({"common", "mixed"}) + public String inputs; + + private double[] ys; + private double[] xs; + private double[] out; + + /** The pairs {@code mixed} puts in one place in 16: each takes a special lane or a shortcut. */ + private static final double[][] RARE = { + {Double.NaN, 1.0}, {1.0, Double.NaN}, {0.0, 1.0}, {-0.0, -1.0}, {1.0, 0.0}, + {Double.POSITIVE_INFINITY, 2.0}, {3.0, Double.NEGATIVE_INFINITY}, + {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}, {0x1p70, 1.0}, {-0x1p62, 1.0}, + {1.0e300, 1.0e-10}, {1.0e-300, -1.0e10}, + }; + + @Setup + public void setUp() { + if (!inputs.equals("common") && !inputs.equals("mixed")) { + throw new IllegalArgumentException("inputs is common or mixed, not '" + inputs + "'"); + } + SplittableRandom random = new SplittableRandom(1L); + ys = new double[N]; + xs = new double[N]; + out = new double[N]; + for (int i = 0; i < N; i++) { + ys[i] = random.nextDouble(-4.0, 4.0); + xs[i] = random.nextDouble(-4.0, 4.0); + if (inputs.equals("mixed") && random.nextInt(16) == 0) { + double[] rare = RARE[random.nextInt(RARE.length)]; + ys[i] = rare[0]; + xs[i] = rare[1]; + } + } + } + + @Benchmark + public double[] scalarStrictMath() { + for (int i = 0; i < N; i++) { + out[i] = StrictMath.atan2(ys[i], xs[i]); + } + return out; + } + + @Benchmark + public double[] blended256() { + for (int i = 0; i < N; i += S256.length()) { + Atan2.atan2Blended(DoubleVector.fromArray(S256, ys, i), DoubleVector.fromArray(S256, xs, i), + null).intoArray(out, i); + } + return out; + } + + @Benchmark + public double[] blendedPreferred() { + for (int i = 0; i < N; i += SP.length()) { + Atan2.atan2Blended(DoubleVector.fromArray(SP, ys, i), DoubleVector.fromArray(SP, xs, i), + null).intoArray(out, i); + } + return out; + } + + @Benchmark + public double[] blendedMax() { + for (int i = 0; i < N; i += SMAX.length()) { + Atan2.atan2Blended(DoubleVector.fromArray(SMAX, ys, i), + DoubleVector.fromArray(SMAX, xs, i), null).intoArray(out, i); + } + return out; + } + + @Benchmark + public double[] guarded256() { + for (int i = 0; i < N; i += S256.length()) { + Atan2.atan2Guarded(DoubleVector.fromArray(S256, ys, i), DoubleVector.fromArray(S256, xs, i), + null).intoArray(out, i); + } + return out; + } + + @Benchmark + public double[] guardedPreferred() { + for (int i = 0; i < N; i += SP.length()) { + Atan2.atan2Guarded(DoubleVector.fromArray(SP, ys, i), DoubleVector.fromArray(SP, xs, i), + null).intoArray(out, i); + } + return out; + } + + @Benchmark + public double[] guardedMax() { + for (int i = 0; i < N; i += SMAX.length()) { + Atan2.atan2Guarded(DoubleVector.fromArray(SMAX, ys, i), + DoubleVector.fromArray(SMAX, xs, i), null).intoArray(out, i); + } + return out; + } +} diff --git a/src/main/java/io/github/vecbricks/vfdlibm/Atan2.java b/src/main/java/io/github/vecbricks/vfdlibm/Atan2.java new file mode 100644 index 0000000..f586361 --- /dev/null +++ b/src/main/java/io/github/vecbricks/vfdlibm/Atan2.java @@ -0,0 +1,244 @@ +/* + * Licensed to the vecbricks contributors under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy of the + * License at http://www.apache.org/licenses/LICENSE-2.0. Software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + * + * This file ports fdlibm 5.3's e_atan2.c (reference/fdlibm-5.3/e_atan2.c), which carries this + * notice: + * + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +package io.github.vecbricks.vfdlibm; + +import jdk.incubator.vector.DoubleVector; +import jdk.incubator.vector.IntVector; +import jdk.incubator.vector.VectorMask; +import jdk.incubator.vector.VectorOperators; +import jdk.incubator.vector.VectorSpecies; + +/** + * atan2 over lanes, ported from fdlibm 5.3's {@code __ieee754_atan2} in {@code + * reference/fdlibm-5.3/e_atan2.c}; every lane is bit-identical to {@code StrictMath.atan2}, except + * that a lane of two NaNs with different bits is one of the two, quieted, as {@code PROOFS.md}'s + * "The contract of a function of two arguments" says. The first argument is {@code y}, as in the + * C and in {@code Math.atan2(y, x)}; a lane that is not live keeps {@code y}'s bits. + * + *

The lanes, in the C's order: a NaN in either argument returns {@code x+y} (lines 71-73); for + * {@code y = +-0} the result is {@code y} or {@code +-pi} by the signs (lines 78-85); for {@code + * x = +-0}, {@code +-pi/2} (line 87); for {@code x = +-inf}, the diagonals {@code +-pi/4} and + * {@code +-3pi/4}, or {@code +-0} and {@code +-pi} (lines 90-106); for {@code y = +-inf}, + * {@code +-pi/2} (line 108). The rest take {@code k = (iy-ix)>>20}: above 60 the result is + * {@code pi_o_2+0.5*pi_lo}, for a negative {@code x} below -60 it is {@code 0.0}, and otherwise it + * is {@code atan(fabs(y/x))}, then moved to the quadrant by the signs: {@code z}, {@code -z}, + * {@code pi-(z-pi_lo)} or {@code (z-pi_lo)-pi}. + * + *

{@code x = 1.0} is the C's {@code atan(y)} (line 74), taken before every test but the NaN. + * It is not a lane of its own here: it takes the general path, whose result is {@code atan(y)} + * (L14, {@code PROOFS.md}), with the {@code k > 60} shortcut off as the C's early return has it. + * The core is {@link Atan#atan}, called on {@code t = |y/x|} where {@code t < 2^66}: an inactive + * lane of its mask comes back untouched and never takes its per-lane finish. The lanes of {@code + * t >= 2^66} that the shortcuts of {@code k} leave to atan ({@code x = 1.0} beside a huge {@code + * y}, or a subnormal {@code x} whose words understate the gap) take the constant {@code + * atanhi[3]+atanlo[3]}, which is atan's value there, in the vector. Nothing in this port calls + * {@code StrictMath}. + * + *

Every special lane is computed in the vector and blended over the general result, from the + * last of the C's tests to the first, so the first that matches wins as in the C: no value of a + * lane the blend overwrites is read (L13, {@code PROOFS.md}'s section "Blends"). The core's mask + * leaves those lanes out, so that no infinity or NaN of theirs reaches its finish. Two arms + * share the body below: {@code blended} computes the special lanes' blends in every vector, + * {@code guarded} only in a vector with a live special lane, which is the one {@code VFdlibm} + * calls until a benchmark host has timed them (no timing of {@code atan2} exists). + */ +final class Atan2 { + + // The constants of e_atan2.c, as its source writes them; Atan2Test checks the words. + static final double TINY = 1.0e-300; + static final double ZERO = 0.0; + static final double PI_O_4 = 7.8539816339744827900E-01; + static final double PI_O_2 = 1.5707963267948965580E+00; + static final double PI = 3.1415926535897931160E+00; + static final double PI_LO = 1.2246467991473531772E-16; + + // What the C returns by expression, evaluated by the same operations: `pi+tiny` is not assumed + // to be `pi`, nor `3.0*pi_o_4+tiny` to be a constant of its own. + static final double PI_P = PI + TINY; + static final double N_PI = -PI - TINY; + static final double PI_O_2_P = PI_O_2 + TINY; + static final double N_PI_O_2 = -PI_O_2 - TINY; + static final double PI_O_4_P = PI_O_4 + TINY; + static final double N_PI_O_4 = -PI_O_4 - TINY; + static final double THREE_PI_O_4_P = 3.0 * PI_O_4 + TINY; + static final double N_THREE_PI_O_4 = -3.0 * PI_O_4 - TINY; + /** + * What the C's atan returns from {@code 2^66} up, for a positive argument: {@code + * atanhi[3]+atanlo[3]} (s_atan.c line 100). The general path keeps {@code |y/x| >= 2^66} in the + * lanes of {@code x = 1.0} beside a huge {@code y}, and where a subnormal {@code x} makes {@code + * k} understate the gap of the exponents. + */ + static final double ATAN_BIG = Atan.ATAN_HI[3] + Atan.ATAN_LO[3]; + /** {@code 2^66}, as s_atan.c's {@code ix>=0x44100000}: the double of that high word. */ + static final double ATAN_BIG_FROM = Lanes.fromHi(Atan.HX_BIG); + /** The shortcut for {@code |y/x| > 2^60}: {@code z=pi_o_2+0.5*pi_lo} (line 112). */ + static final double Z_HIGH = PI_O_2 + 0.5 * PI_LO; + + /** The {@code k} the C compares against: {@code k > 60} (line 112), {@code k < -60} (113). */ + static final int K_MAX = 60; + static final int K_MIN = -60; + + // Planted faults (PLAN.md section 4), read through Faults; each folds away when unplanted. + static final String K_HIGH_MOVED = "atan2.kHighMoved"; + static final String K_LOW_MOVED = "atan2.kLowMoved"; + static final String LOW_SHORTCUT_FOR_POSITIVE_X = "atan2.lowShortcutForPositiveX"; + static final String INF_ORDER_SWAPPED = "atan2.infOrderSwapped"; + static final String DROP_PI_LO = "atan2.dropPiLo"; + static final String ZERO_SIGN_OF_X = "atan2.zeroSignOfX"; + static final String DIAGONAL_INF = "atan2.diagonalInf"; + static final String NO_SIGN_FLIP = "atan2.noSignFlip"; + // Read once into constants, so the body holds no call and an unplanted fault folds away. The two + // thresholds are moved by ten: the shortcuts give the bits of atan(|y/x|) wherever they are + // taken, so moved by one they change no result (PROOFS.md, "atan2"), and a fault must be seen. + private static final int K_MAX_USED = Faults.is(K_HIGH_MOVED) ? K_MAX - 10 : K_MAX; + private static final int K_MIN_USED = Faults.is(K_LOW_MOVED) ? K_MIN + 10 : K_MIN; + private static final boolean LOW_FOR_ANY_X = Faults.is(LOW_SHORTCUT_FOR_POSITIVE_X); + private static final boolean INF_SWAPPED = Faults.is(INF_ORDER_SWAPPED); + private static final boolean DROPPING_PI_LO = Faults.is(DROP_PI_LO); + private static final boolean ZERO_BY_VALUE = Faults.is(ZERO_SIGN_OF_X); + private static final boolean ONE_DIAGONAL = Faults.is(DIAGONAL_INF); + private static final boolean KEEPING_SIGN = Faults.is(NO_SIGN_FLIP); + + /** How the special lanes are reached: blended in every vector, or behind a test. */ + private static final int BLEND = 0; + private static final int GUARDED = 1; + + private Atan2() {} + + /** + * atan2 as {@code VFdlibm.atan2} computes it, the guarded arm. {@code live} is null for every + * lane; otherwise only live lanes are computed, inactive lanes return {@code y}'s lane + * untouched, and an inactive lane never sends the vector down a rare path. + */ + static DoubleVector atan2(DoubleVector y, DoubleVector x, VectorMask live) { + return atan2(y, x, live, GUARDED); + } + + /** atan2 with the special lanes' blends computed in every vector; {@code live} as above. */ + static DoubleVector atan2Blended(DoubleVector y, DoubleVector x, VectorMask live) { + return atan2(y, x, live, BLEND); + } + + /** atan2 with the special lanes' blends behind one test; {@code live} as above. */ + static DoubleVector atan2Guarded(DoubleVector y, DoubleVector x, VectorMask live) { + return atan2(y, x, live, GUARDED); + } + + /** + * The two arms in one body; {@code mode} is a constant at each call above. The call into atan + * comes second, right after the quotient, while the compiled graph is small: C2 stops inlining + * once a method's graph is large (NodeCountInliningCutoff), and a refused call boxes its + * vectors. After it there are only Vector API operations. + */ + private static DoubleVector atan2( + DoubleVector y, DoubleVector x, VectorMask live, int mode) { + VectorSpecies species = y.species(); + VectorSpecies intSpecies = Lanes.intSpecies(species); + // Lines 67-69: hx = __HI(x); ix = hx&0x7fffffff; likewise y. + IntVector hx = Lanes.hiInt(x, intSpecies); + IntVector hy = Lanes.hiInt(y, intSpecies); + + // Line 114: z = atan(fabs(y/x)). The core takes the lanes whose |y/x| is below 2^66. From + // there up the C's atan returns atanhi[3]+atanlo[3] (s_atan.c, lines 97-102), a constant, + // blended below; those lanes are the shortcuts' (overwritten), the special lanes' (a NaN, an + // infinity: overwritten) and the general ones that the shortcuts of k leave to atan. A lane + // outside the mask comes back as |y/x| and is overwritten or takes the constant, so it is + // never read, no NaN, infinity or huge value reaches the core's per-lane finish, and an + // inactive lane never does. + DoubleVector t = y.div(x).abs(); + VectorMask small = t.compare(VectorOperators.LT, ATAN_BIG_FROM); + DoubleVector z = Atan.atan(t, live == null ? small : small.and(live)); + z = z.blend(DoubleVector.broadcast(species, ATAN_BIG), small.not()); + + IntVector ix = hx.and(0x7fffffff); + IntVector iy = hy.and(0x7fffffff); + // Line 111: k = (iy-ix)>>20, an int difference of two words in [0, 0x7ff00000]. + IntVector k = iy.sub(ix).lanewise(VectorOperators.ASHR, 20); + VectorMask kHigh = k.compare(VectorOperators.GT, K_MAX_USED).cast(species); + VectorMask kLow = k.compare(VectorOperators.LT, K_MIN_USED).cast(species); + VectorMask negX = hx.compare(VectorOperators.LT, 0).cast(species); + VectorMask negY = hy.compare(VectorOperators.LT, 0).cast(species); + + // Lines 112-113: the shortcuts. x = 1.0 returned atan(y) at line 74, before k was made. + VectorMask xOne = x.compare(VectorOperators.EQ, 1.0); + VectorMask high = kHigh.and(xOne.not()); + VectorMask low = LOW_FOR_ANY_X ? kLow : negX.and(kLow); + z = z.blend(DoubleVector.broadcast(species, Z_HIGH), high); + z = z.blend(DoubleVector.zero(species), low); + + // Lines 115-122: the quadrant, picked by m = 2*sign(x)+sign(y). z - pi_lo is one operation. + DoubleVector w = DROPPING_PI_LO ? z : z.sub(PI_LO); + DoubleVector pi = DoubleVector.broadcast(species, PI); + VectorMask posX = negX.not(); + VectorMask posY = negY.not(); + VectorMask case1 = negY.and(posX); + VectorMask case2 = posY.and(negX); + VectorMask case3 = negY.and(negX); + DoubleVector result = z; + result = result.blend(KEEPING_SIGN ? z : z.neg(), case1); + result = result.blend(pi.sub(w), case2); + result = result.blend(w.sub(pi), case3); + + // The special lanes, from the last of the C's tests to the first, so that the first that + // matches wins: y infinite (line 108), x infinite (lines 90-106), x zero (87), y zero + // (78-85), a NaN (71-73). In the guarded arm only a vector with a live special lane runs + // them; the tests are exact classifications of the doubles. + VectorMask nan = x.test(VectorOperators.IS_NAN).or(y.test(VectorOperators.IS_NAN)); + VectorMask yZero = y.compare(VectorOperators.EQ, 0.0); + VectorMask xZero = x.compare(VectorOperators.EQ, 0.0); + VectorMask xInf = x.test(VectorOperators.IS_INFINITE); + VectorMask yInf = y.test(VectorOperators.IS_INFINITE); + VectorMask special = nan.or(yZero).or(xZero).or(xInf).or(yInf); + VectorMask anySpecial = live == null ? special : special.and(live); + if (mode == BLEND || anySpecial.anyTrue()) { + // Line 108: (hy<0)? -pi_o_2-tiny: pi_o_2+tiny. + DoubleVector pio2 = DoubleVector.broadcast(species, PI_O_2_P) + .blend(DoubleVector.broadcast(species, N_PI_O_2), negY); + result = result.blend(pio2, yInf); + // Lines 90-106: x is infinite, y is too (the diagonals) or not (0 and pi), by m. + DoubleVector finite = DoubleVector.zero(species); + finite = finite.blend(DoubleVector.broadcast(species, -ZERO), case1); + finite = finite.blend(DoubleVector.broadcast(species, PI_P), case2); + finite = finite.blend(DoubleVector.broadcast(species, N_PI), case3); + DoubleVector diagonal = DoubleVector.broadcast(species, PI_O_4_P); + if (!ONE_DIAGONAL) { + diagonal = diagonal.blend(DoubleVector.broadcast(species, N_PI_O_4), case1); + diagonal = diagonal.blend(DoubleVector.broadcast(species, THREE_PI_O_4_P), case2); + diagonal = diagonal.blend(DoubleVector.broadcast(species, N_THREE_PI_O_4), case3); + } + result = result.blend(finite.blend(diagonal, yInf), xInf); + if (INF_SWAPPED) { + result = result.blend(pio2, yInf); + } + // Line 87: x = +-0 and y not: +-(pi_o_2+tiny) by y's sign. + result = result.blend(pio2, xZero); + // Lines 78-85: y = +-0: y itself for x positive, +-(pi+tiny) for x negative. + VectorMask xNegative = ZERO_BY_VALUE ? x.compare(VectorOperators.LT, 0.0) : negX; + DoubleVector zero = y; + zero = zero.blend(DoubleVector.broadcast(species, PI_P), xNegative.and(posY)); + zero = zero.blend(DoubleVector.broadcast(species, N_PI), xNegative.and(negY)); + result = result.blend(zero, yZero); + // Lines 71-73: x+y for a NaN in either argument. + result = result.blend(x.add(y), nan); + } + return live == null ? result : y.blend(result, live); + } +} diff --git a/src/main/java/io/github/vecbricks/vfdlibm/VFdlibm.java b/src/main/java/io/github/vecbricks/vfdlibm/VFdlibm.java index 22acb36..3247afb 100644 --- a/src/main/java/io/github/vecbricks/vfdlibm/VFdlibm.java +++ b/src/main/java/io/github/vecbricks/vfdlibm/VFdlibm.java @@ -14,13 +14,14 @@ /** * fdlibm's double functions over {@link DoubleVector} lanes, each lane bit-identical to the - * {@link StrictMath} method of the same name, NaN payloads and signed zeros included. + * {@link StrictMath} method of the same name, NaN payloads and signed zeros included; the one + * exception is a lane of {@code atan2} where both arguments are NaN with different bits. * *

Every method works on a vector of any species of 128 bits or more (exp, expm1, log, log10, - * log1p, sinh, cosh, asin, atan and acos hold fdlibm's {@code int} words in int lanes of half the - * vector's size). Each comes in two forms: one computes every lane, and a masked form computes - * only the lanes set in {@code live} and returns every other lane of its argument untouched, raw - * bits and all. An inactive lane never sends the vector down a slow path. + * log1p, sinh, cosh, asin, atan, acos and atan2 hold fdlibm's {@code int} words in int lanes of + * half the vector's size). Each comes in two forms: one computes every lane, and a masked form + * computes only the lanes set in {@code live} and returns every other lane of its argument + * untouched, raw bits and all. An inactive lane never sends the vector down a slow path. * *

Which species to pass. Every species of 128 bits or more gives the same bits. The files * under {@code bench/results/}, in the source repository and not in the jar, read what the body @@ -301,4 +302,31 @@ public static DoubleVector acos(DoubleVector x) { public static DoubleVector acos(DoubleVector x, VectorMask live) { return Acos.acos(x, Objects.requireNonNull(live, "live")); } + + /** + * {@code StrictMath.atan2(y, x)} in every lane, except that a lane where both arguments are NaN + * with different bits is one of the two, with the quiet bit set (which one is not specified, + * since {@code StrictMath}'s own choice varies); every other lane, a NaN beside a finite value + * included, has {@code StrictMath}'s bits. Ported from fdlibm 5.3's {@code e_atan2.c}. + * + * @param y the first arguments, the ordinates + * @param x the second arguments, the abscissae, of {@code y}'s species + * @return the angle of each lane's point {@code (x, y)} + */ + public static DoubleVector atan2(DoubleVector y, DoubleVector x) { + return Atan2.atan2(y, x, null); + } + + /** + * {@link #atan2(DoubleVector, DoubleVector)} in the lanes set in {@code live}; every other lane + * is {@code y}'s, untouched. + * + * @param y the first arguments, the ordinates + * @param x the second arguments, of {@code y}'s species + * @param live the lanes to compute, of the same species + * @return the angle of each live lane, and {@code y} in the others + */ + public static DoubleVector atan2(DoubleVector y, DoubleVector x, VectorMask live) { + return Atan2.atan2(y, x, Objects.requireNonNull(live, "live")); + } } diff --git a/src/test/java/io/github/vecbricks/vfdlibm/Atan2Test.java b/src/test/java/io/github/vecbricks/vfdlibm/Atan2Test.java new file mode 100644 index 0000000..02a4516 --- /dev/null +++ b/src/test/java/io/github/vecbricks/vfdlibm/Atan2Test.java @@ -0,0 +1,527 @@ +/* + * Licensed to the vecbricks contributors under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy of the + * License at http://www.apache.org/licenses/LICENSE-2.0. Software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.vecbricks.vfdlibm; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.SplittableRandom; +import java.util.function.Consumer; +import jdk.incubator.vector.DoubleVector; +import jdk.incubator.vector.VectorMask; +import jdk.incubator.vector.VectorShape; +import jdk.incubator.vector.VectorSpecies; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +/** + * atan2 against {@code StrictMath.atan2}, by {@link PairBits#matches} (raw bits, except a lane of + * two NaNs with different bits), at every width and at {@code SPECIES_MAX}: {@link + * VFdlibm#atan2}, {@link Atan2#atan2Blended} and {@link Atan2#atan2Guarded}, unmasked and masked, + * on every pair of special values, on e_atan2.c's tests of {@code k = (iy-ix)>>20} and of {@code + * x = 1.0}, on sampled bit patterns, dense draws over each quadrant, every subset of a vector's + * lanes special, and the pairs of {@code hard-cases/atan2.txt}. The first argument is {@code y}: + * {@code Inputs.Pairs.x()} is the first column, the {@code y} of {@code atan2(y, x)}, and {@code + * Inputs.Pairs.y()} the second, its {@code x}, everywhere below. + */ +class Atan2Test { + + private static final PairBits.Candidates OPERANDS = PairBits.Candidates.OPERANDS; + private static final int SAMPLED = 1 << 19; + + /** The arm as a masked form of two arguments; a null mask computes every lane. */ + interface Arm { + DoubleVector apply(DoubleVector y, DoubleVector x, VectorMask live); + } + + private static final Map ARMS = arms(); + + private static Map arms() { + Map arms = new LinkedHashMap<>(); + arms.put("VFdlibm.atan2", (y, x, live) -> + live == null ? VFdlibm.atan2(y, x) : VFdlibm.atan2(y, x, live)); + arms.put("Atan2.atan2Blended", Atan2::atan2Blended); + arms.put("Atan2.atan2Guarded", Atan2::atan2Guarded); + return arms; + } + + /** Every arm, unmasked, at {@code species}, over the pairs {@code p}, {@code y} first. */ + private static void assertAtan2(VectorSpecies species, Inputs.Pairs p) { + ARMS.forEach((name, arm) -> Oracle.assertPair(name, species, OPERANDS, + (y, x) -> arm.apply(y, x, null), StrictMath::atan2, p.x(), p.y())); + } + + /** Every arm, masked under seeded random masks, all-true and all-false, from {@code seed}. */ + private static void assertAtan2Masked( + VectorSpecies species, Inputs.Pairs p, long seed) { + for (Map.Entry arm : ARMS.entrySet()) { + Oracle.assertPairMasked(arm.getKey(), species, OPERANDS, arm.getValue()::apply, + StrictMath::atan2, p.x(), p.y(), seed++); + } + } + + // --------------------------------------------------------------------------------------------- + // The C in scalar Java + // --------------------------------------------------------------------------------------------- + + /** e_atan2.c in scalar Java, line by line, with atan the transcription of s_atan.c. */ + static double cAtan2(double y, double x) { + return cAtan2(y, x, Atan2.K_MAX, Atan2.K_MIN); + } + + /** {@link #cAtan2(double, double)} with the two thresholds of {@code k} given, to move them. */ + static double cAtan2(double y, double x, int kMax, int kMin) { + long xb = Double.doubleToRawLongBits(x); + long yb = Double.doubleToRawLongBits(y); + int hx = (int) (xb >>> 32); + int lx = (int) xb; + int ix = hx & 0x7fffffff; + int hy = (int) (yb >>> 32); + int ly = (int) yb; + int iy = hy & 0x7fffffff; + // Lines 71-73: a NaN in either argument. + if (((ix | ((lx | -lx) >>> 31)) > 0x7ff00000) || ((iy | ((ly | -ly) >>> 31)) > 0x7ff00000)) { + return x + y; + } + if (((hx - 0x3ff00000) | lx) == 0) { + return AtanTest.cAtan(y); + } + int m = ((hy >> 31) & 1) | ((hx >> 30) & 2); + if ((iy | ly) == 0) { + return switch (m) { + case 0, 1 -> y; + case 2 -> Atan2.PI + Atan2.TINY; + default -> -Atan2.PI - Atan2.TINY; + }; + } + if ((ix | lx) == 0) { + return hy < 0 ? -Atan2.PI_O_2 - Atan2.TINY : Atan2.PI_O_2 + Atan2.TINY; + } + if (ix == 0x7ff00000) { + if (iy == 0x7ff00000) { + return switch (m) { + case 0 -> Atan2.PI_O_4 + Atan2.TINY; + case 1 -> -Atan2.PI_O_4 - Atan2.TINY; + case 2 -> 3.0 * Atan2.PI_O_4 + Atan2.TINY; + default -> -3.0 * Atan2.PI_O_4 - Atan2.TINY; + }; + } + return switch (m) { + case 0 -> Atan2.ZERO; + case 1 -> -Atan2.ZERO; + case 2 -> Atan2.PI + Atan2.TINY; + default -> -Atan2.PI - Atan2.TINY; + }; + } + if (iy == 0x7ff00000) { + return hy < 0 ? -Atan2.PI_O_2 - Atan2.TINY : Atan2.PI_O_2 + Atan2.TINY; + } + int k = (iy - ix) >> 20; + double z; + if (k > kMax) { + z = Atan2.PI_O_2 + 0.5 * Atan2.PI_LO; + } else if (hx < 0 && k < kMin) { + z = 0.0; + } else { + z = AtanTest.cAtan(Math.abs(y / x)); + } + return switch (m) { + case 0 -> z; + case 1 -> Double.longBitsToDouble(Double.doubleToRawLongBits(z) ^ Long.MIN_VALUE); + case 2 -> Atan2.PI - (z - Atan2.PI_LO); + default -> (z - Atan2.PI_LO) - Atan2.PI; + }; + } + + // --------------------------------------------------------------------------------------------- + // Inputs + // --------------------------------------------------------------------------------------------- + + static Inputs.Pairs concatPairs(Inputs.Pairs... parts) { + double[][] ys = new double[parts.length][]; + double[][] xs = new double[parts.length][]; + for (int i = 0; i < parts.length; i++) { + ys[i] = parts[i].x(); + xs[i] = parts[i].y(); + } + return new Inputs.Pairs(Inputs.concat(ys), Inputs.concat(xs)); + } + + /** Every pair of the special values, the thresholds of k's exponents and 2^66 among them. */ + static Inputs.Pairs specialPairs() { + double[] specials = Inputs.specials(0x1p60, 0x1p61, -0x1p60, 0x1p66, 2.0, -2.0, 0.5); + return Inputs.cross(specials, specials); + } + + /** + * Pairs whose exponents differ by -70 to 70, both signs, so that {@code k} runs across both of + * its thresholds and the lanes either side of each: {@code y}'s exponent is {@code x}'s plus + * the difference, the mantissas random. + */ + static Inputs.Pairs kPairs(long seed, int n) { + SplittableRandom random = new SplittableRandom(seed); + double[] ys = new double[n]; + double[] xs = new double[n]; + for (int i = 0; i < n; i++) { + int xe = random.nextInt(-900, 901); + int ye = xe + random.nextInt(-70, 71); + xs[i] = Math.scalb(1.0 + random.nextDouble(), xe) * (random.nextBoolean() ? 1 : -1); + ys[i] = Math.scalb(1.0 + random.nextDouble(), ye) * (random.nextBoolean() ? 1 : -1); + } + return new Inputs.Pairs(ys, xs); + } + + /** + * The pairs the fuzz draws at the differences of high words that e_atan2.c's {@code k} tests, + * from the nightly's own edges ({@link Nightly.PairFunction#ATAN2}), a share of them at + * {@code iy - ix = 61 * 2^20} and the word below, {@code -60 * 2^20} and the word below. + */ + static Inputs.Pairs gapPairs(long seed, int n) { + SplittableRandom random = new SplittableRandom(seed); + double[] pair = new double[2]; + double[] ys = new double[n]; + double[] xs = new double[n]; + for (int i = 0; i < n; i++) { + Fuzz.drawPair(random, Nightly.PairFunction.ATAN2.edges(), pair); + ys[i] = pair[0]; + xs[i] = pair[1]; + } + return new Inputs.Pairs(ys, xs); + } + + /** + * {@code x = +-1.0}, the lane the C answers with {@code atan(y)}, beside {@code y} from {@code + * 2^50} up past {@code 2^66}, both signs, and the neighbours of 1.0. + */ + static Inputs.Pairs onePairs(long seed) { + double[] xs = {1.0, -1.0, Math.nextUp(1.0), Math.nextDown(1.0)}; + double[] ys = Inputs.concat( + Inputs.magnitudes(seed, 1 << 12, 50, 70), Inputs.magnitudes(seed + 1, 1 << 10, -70, 0), + Inputs.specials(0x1p60, 0x1p61, 0x1p66)); + return Inputs.cross(ys, xs); + } + + /** + * A subnormal {@code x} beside a {@code y} of moderate exponent: {@code k} then understates the + * gap of the exponents (the subnormal's high word has no exponent), so {@code t = |y/x|} can be + * {@code 2^66} or more with no shortcut taken, and the lane takes atan's constant. + */ + static Inputs.Pairs subnormalPairs(long seed, int n) { + SplittableRandom random = new SplittableRandom(seed); + double[] ys = new double[n]; + double[] xs = new double[n]; + for (int i = 0; i < n; i++) { + long mantissa = random.nextLong() & 0x000fffffffffffffL; + xs[i] = Double.longBitsToDouble(mantissa | (random.nextBoolean() ? Long.MIN_VALUE : 0L)); + ys[i] = Math.scalb(1.0 + random.nextDouble(), random.nextInt(-1022, 10)) + * (random.nextBoolean() ? 1 : -1); + } + return new Inputs.Pairs(ys, xs); + } + + static Inputs.Pairs sampledPairs(long seed, int n) { + return new Inputs.Pairs(Inputs.sampled(seed, n), Inputs.sampled(seed + 1, n)); + } + + /** Dense draws over both quadrants' worth of signs, and over the unit square. */ + static Inputs.Pairs densePairs(long seed) { + return concatPairs( + new Inputs.Pairs(Inputs.uniform(seed, 1 << 16, -6.0, 6.0), + Inputs.uniform(seed + 1, 1 << 16, -6.0, 6.0)), + new Inputs.Pairs(Inputs.uniform(seed + 2, 1 << 15, -1.0, 1.0), + Inputs.uniform(seed + 3, 1 << 15, -1.0, 1.0)), + new Inputs.Pairs(Inputs.magnitudes(seed + 4, 1 << 15, -60, 60), + Inputs.magnitudes(seed + 5, 1 << 15, -60, 60))); + } + + private static Inputs.Pairs hardCasePairs() { + return Inputs.hardCasePairs("atan2"); + } + + private static Inputs.Pairs everythingSmall() { + return concatPairs(specialPairs(), kPairs(8100L, 1 << 14), gapPairs(8101L, 1 << 14), + onePairs(8102L), subnormalPairs(8105L, 1 << 14), sampledPairs(8103L, 1 << 12), + densePairs(8104L), hardCasePairs()); + } + + // --------------------------------------------------------------------------------------------- + // The tests + // --------------------------------------------------------------------------------------------- + + @ParameterizedTest + @EnumSource(VectorWidth.class) + void specialValues(VectorWidth width) { + assertAtan2(width.species(), specialPairs()); + } + + @ParameterizedTest + @EnumSource(VectorWidth.class) + void thresholdsOfK(VectorWidth width) { + assertAtan2(width.species(), concatPairs(kPairs(8200L + width.ordinal(), SAMPLED >> 2), + gapPairs(8210L + width.ordinal(), SAMPLED >> 2))); + } + + @ParameterizedTest + @EnumSource(VectorWidth.class) + void xIsOne(VectorWidth width) { + assertAtan2(width.species(), onePairs(8300L + width.ordinal())); + } + + @ParameterizedTest + @EnumSource(VectorWidth.class) + void subnormalX(VectorWidth width) { + assertAtan2(width.species(), subnormalPairs(8350L + width.ordinal(), SAMPLED >> 2)); + } + + /** + * L14's hinge: {@code atan2(y, 1.0)} is {@code atan(y)}, by the oracle's bits and by the port's + * own, at every width, on atan's thresholds, sampled values and the hard cases of atan. + */ + @ParameterizedTest + @EnumSource(VectorWidth.class) + void xOneIsAtanOfY(VectorWidth width) { + VectorSpecies species = width.species(); + double[] ys = Inputs.concat(AtanTest.thresholds(), Inputs.sampled(8360L, 1 << 16), + Inputs.magnitudes(8361L, 1 << 14, -70, 70), Inputs.uniform(8362L, 1 << 14, -6.0, 6.0)); + for (int i = 0; i + species.length() <= ys.length; i += species.length()) { + DoubleVector y = DoubleVector.fromArray(species, ys, i); + double[] got = VFdlibm.atan2(y, DoubleVector.broadcast(species, 1.0)).toArray(); + double[] atan = VFdlibm.atan(y).toArray(); + for (int lane = 0; lane < got.length; lane++) { + double v = ys[i + lane]; + if (!Double.isNaN(v)) { + assertEquals(Double.doubleToRawLongBits(StrictMath.atan(v)), + Double.doubleToRawLongBits(got[lane]), "atan2(y, 1.0) of " + Oracle.hex(v)); + assertEquals(Double.doubleToRawLongBits(atan[lane]), + Double.doubleToRawLongBits(got[lane]), "the port's atan of " + Oracle.hex(v)); + } + } + } + } + + @ParameterizedTest + @EnumSource(VectorWidth.class) + void sampledBitPatterns(VectorWidth width) { + assertAtan2(width.species(), sampledPairs(8400L + 2L * width.ordinal(), SAMPLED)); + } + + @ParameterizedTest + @EnumSource(VectorWidth.class) + void denseOverTheQuadrants(VectorWidth width) { + assertAtan2(width.species(), densePairs(8500L + 8L * width.ordinal())); + } + + @ParameterizedTest + @EnumSource(VectorWidth.class) + void publishedPairs(VectorWidth width) { + assertAtan2(width.species(), hardCasePairs()); + } + + @ParameterizedTest + @EnumSource(VectorWidth.class) + void masked(VectorWidth width) { + assertAtan2Masked(width.species(), everythingSmall(), 8600L); + } + + /** SPECIES_MAX, which {@link VectorWidth} does not run: its int species is another shape. */ + @Test + void maxSpecies() { + Inputs.Pairs p = everythingSmall(); + assertAtan2(DoubleVector.SPECIES_MAX, p); + assertAtan2Masked(DoubleVector.SPECIES_MAX, p, 8700L); + } + + /** Pairs, one per kind of special lane, that the subsets below put in a vector's lanes. */ + private static final double[][] SPECIAL_LANES = { + {Double.NaN, 1.0}, {1.0, Double.NaN}, {Double.NaN, Double.NaN}, + {Double.longBitsToDouble(0xfff4_0000_0000_0456L), + Double.longBitsToDouble(0x7ff8_0000_0000_0123L)}, + {0.0, 1.0}, {-0.0, -2.0}, {0.0, 0.0}, {-0.0, -0.0}, {3.0, 0.0}, {-3.0, -0.0}, + {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}, + {Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY}, + {Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}, + {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY}, + {5.0, Double.POSITIVE_INFINITY}, {-5.0, Double.NEGATIVE_INFINITY}, + {Double.POSITIVE_INFINITY, 7.0}, {Double.NEGATIVE_INFINITY, -7.0}, + }; + + /** Lanes that take no special path: both quadrant signs, the shortcuts, {@code x = 1.0}. */ + private static final double[][] GENERAL_LANES = { + {1.0, 2.0}, {-1.0, 2.0}, {1.0, -2.0}, {-1.0, -2.0}, {0x1p100, 3.0}, {-0x1p100, -3.0}, + {3.0, 0x1p100}, {-3.0, -0x1p100}, {0x1p70, 1.0}, {-0x1p70, 1.0}, {0x1p-80, 1.0}, + }; + + /** + * One vector for every subset of a vector's lanes ({@link ExpTest#rareLaneSubsets}), the + * subset's lanes special and the others general, so that a vector holds special lanes beside + * lanes the core computes, in every position and mix. + */ + static Inputs.Pairs everySubsetOfLanesSpecial(int lanes) { + long[] subsets = ExpTest.rareLaneSubsets(lanes); + double[] ys = new double[subsets.length * lanes]; + double[] xs = new double[ys.length]; + int special = 0; + int general = 0; + for (int s = 0; s < subsets.length; s++) { + for (int lane = 0; lane < lanes; lane++) { + boolean isSpecial = (subsets[s] >>> lane & 1L) != 0; + double[] pair = isSpecial ? SPECIAL_LANES[special++ % SPECIAL_LANES.length] + : GENERAL_LANES[general++ % GENERAL_LANES.length]; + ys[s * lanes + lane] = pair[0]; + xs[s * lanes + lane] = pair[1]; + } + } + return new Inputs.Pairs(ys, xs); + } + + @ParameterizedTest + @EnumSource(VectorWidth.class) + void everySubsetOfLanesSpecial(VectorWidth width) { + assertEverySubset(width.species()); + } + + @Test + void everySubsetOfLanesSpecialAtMaxSpecies() { + assertEverySubset(DoubleVector.SPECIES_MAX); + } + + private static void assertEverySubset(VectorSpecies species) { + Inputs.Pairs p = everySubsetOfLanesSpecial(species.length()); + assertAtan2(species, p); + assertAtan2Masked(species, p, 8800L); + } + + /** + * The scalar transcription of e_atan2.c is {@code StrictMath.atan2} on the inputs the vector + * tests use (a lane of two NaNs with different bits by {@link PairBits}), so a hinge or a fault + * run that reads it shows the C's result. + */ + @Test + void scalarTranscriptionIsStrictMath() { + Inputs.Pairs p = everythingSmall(); + for (int i = 0; i < p.x().length; i++) { + double y = p.x()[i]; + double x = p.y()[i]; + assertTrue(PairBits.matches(OPERANDS, y, x, StrictMath.atan2(y, x), cAtan2(y, x)), + Oracle.hex(y) + ", " + Oracle.hex(x)); + } + } + + /** + * Moved by one the two shortcuts of {@code k} change no result: wherever they are taken, {@code + * pi_o_2+0.5*pi_lo} and {@code 0.0} are the bits of the C's own {@code atan(fabs(y/x))} path + * (PROOFS.md, atan2), so no test of results sees them move by one. Moved by ten they are seen, + * in the lanes of {@code k} 51 to 60 and -60 to -51: that is what the two faults plant. + */ + @Test + void theShortcutsAreSeenMovedByTenAndNotByOne() { + Inputs.Pairs p = concatPairs(kPairs(8900L, 1 << 18), gapPairs(8901L, 1 << 18)); + long[] seen = new long[4]; + int[][] moves = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + long tenHigh = 0; + long tenLow = 0; + for (int i = 0; i < p.x().length; i++) { + double y = p.x()[i]; + double x = p.y()[i]; + double want = StrictMath.atan2(y, x); + for (int m = 0; m < 4; m++) { + double moved = cAtan2(y, x, Atan2.K_MAX + moves[m][0], Atan2.K_MIN + moves[m][1]); + if (!PairBits.matches(OPERANDS, y, x, want, moved)) { + seen[m]++; + } + } + tenHigh += PairBits.matches(OPERANDS, y, x, want, + cAtan2(y, x, Atan2.K_MAX - 10, Atan2.K_MIN)) ? 0 : 1; + tenLow += PairBits.matches(OPERANDS, y, x, want, + cAtan2(y, x, Atan2.K_MAX, Atan2.K_MIN + 10)) ? 0 : 1; + } + for (int m = 0; m < 4; m++) { + assertEquals(0L, seen[m], "a shortcut moved by one, variant " + m); + } + assertTrue(tenHigh > 0 && tenLow > 0, "moved by ten: " + tenHigh + ", " + tenLow); + } + + @Test + void maskedFormRejectsANullMask() { + DoubleVector v = DoubleVector.zero(DoubleVector.SPECIES_128); + assertThrows(NullPointerException.class, () -> VFdlibm.atan2(v, v, null)); + } + + /** The constants are e_atan2.c's, by the hexadecimal words its comments give. */ + @Test + void constantsAreTheSourcesBits() { + assertBits(0x3FE921FB54442D18L, Atan2.PI_O_4); + assertBits(0x3FF921FB54442D18L, Atan2.PI_O_2); + assertBits(0x400921FB54442D18L, Atan2.PI); + assertBits(0x3CA1A62633145C07L, Atan2.PI_LO); + assertEquals(1.0e-300, Atan2.TINY); + assertEquals(60, Atan2.K_MAX); + assertEquals(-60, Atan2.K_MIN); + // pi+tiny and pi_o_2+tiny are the constants themselves; 3.0*pi_o_4+tiny is a double of its own + assertBits(0x400921FB54442D18L, Atan2.PI_P); + assertBits(0x3FF921FB54442D18L, Atan2.PI_O_2_P); + assertBits(0x4002D97C7F3321D2L, Atan2.THREE_PI_O_4_P); + assertBits(0x3FF921FB54442D18L, Atan2.Z_HIGH); + // atanhi[3]+atanlo[3] (what atan returns from 2^66 up) and 2^66, s_atan.c's word 0x44100000 + assertBits(0x3FF921FB54442D18L, Atan2.ATAN_BIG); + assertEquals(0x1p66, Atan2.ATAN_BIG_FROM); + } + + private static void assertBits(long want, double got) { + assertEquals(Long.toHexString(want), Long.toHexString(Double.doubleToRawLongBits(got))); + } + + // --------------------------------------------------------------------------------------------- + // Planted faults + // --------------------------------------------------------------------------------------------- + + /** + * Each of atan2's faults, with a check that must fail while it is planted: the vector form + * over {@link #faultRunInputs()} at every width the host has, every arm. The two shortcuts are + * moved by ten, as the test above says. Each was sized on draws before it was wired; the sizes + * are in {@code SKILLS.md}, "What the atan2 port taught". + */ + static Map faultCatchers() { + Map catchers = new LinkedHashMap<>(); + for (String fault : new String[] { + Atan2.K_HIGH_MOVED, Atan2.K_LOW_MOVED, Atan2.LOW_SHORTCUT_FOR_POSITIVE_X, + Atan2.INF_ORDER_SWAPPED, Atan2.DROP_PI_LO, Atan2.ZERO_SIGN_OF_X, Atan2.DIAGONAL_INF, + Atan2.NO_SIGN_FLIP}) { + catchers.put(fault, () -> forEachWidth(species -> ARMS.forEach((name, arm) -> + PlantedFaultTest.assertCaught(fault, () -> { + Inputs.Pairs p = faultRunInputs(); + Oracle.assertPair(name, species, OPERANDS, (y, x) -> arm.apply(y, x, null), + StrictMath::atan2, p.x(), p.y()); + })))); + } + return catchers; + } + + private static Inputs.Pairs faultRunInputs() { + return concatPairs(specialPairs(), kPairs(8950L, 1 << 16), densePairs(8951L)); + } + + @ParameterizedTest + @EnumSource(VectorWidth.class) + void faultRunInputsPass(VectorWidth width) { + assertAtan2(width.species(), faultRunInputs()); + } + + private static void forEachWidth(Consumer> check) { + int preferred = DoubleVector.SPECIES_PREFERRED.vectorBitSize(); + for (int bits = 128; bits <= preferred; bits *= 2) { + check.accept(VectorSpecies.of(double.class, VectorShape.forBitSize(bits))); + } + } +} diff --git a/src/test/java/io/github/vecbricks/vfdlibm/Fuzz.java b/src/test/java/io/github/vecbricks/vfdlibm/Fuzz.java index 5e01779..c95c633 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/Fuzz.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/Fuzz.java @@ -98,6 +98,12 @@ record PairEdges(Edges x, Edges y, double[] specials, int[] wordGaps) { PairEdges(Edges x, Edges y, double[] specials) { this(x, y, specials, new int[0]); } + + /** A copy: writing into it changes nothing the constructor checked. */ + @Override + public int[] wordGaps() { + return wordGaps.clone(); + } } /** The special values of a function of two arguments, either sign: the sweep draws them too. */ diff --git a/src/test/java/io/github/vecbricks/vfdlibm/FuzzWordGapsTest.java b/src/test/java/io/github/vecbricks/vfdlibm/FuzzWordGapsTest.java index e0be4bc..e7b5878 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/FuzzWordGapsTest.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/FuzzWordGapsTest.java @@ -9,6 +9,7 @@ package io.github.vecbricks.vfdlibm; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.file.Path; @@ -102,6 +103,17 @@ void everyGapIsDrawnAtAboutItsShare() { } } + @Test + void theGapsAreCopiedOnTheWayInAndOut() { + int[] gaps = {ABOVE}; + Fuzz.PairEdges edges = new Fuzz.PairEdges(EDGES, EDGES, Fuzz.PAIR_SPECIALS, gaps); + gaps[0] = Integer.MAX_VALUE; + edges.wordGaps()[0] = Integer.MAX_VALUE; + assertEquals(ABOVE, edges.wordGaps()[0]); + assertThrows(IllegalArgumentException.class, + () -> new Fuzz.PairEdges(EDGES, EDGES, Fuzz.PAIR_SPECIALS, new int[] {Integer.MAX_VALUE})); + } + @Test void aFunctionWithoutGapsIsNotDrawnAtThemAndKeepsItsStream() { Fuzz.PairEdges without = new Fuzz.PairEdges(EDGES, EDGES, Fuzz.PAIR_SPECIALS); diff --git a/src/test/java/io/github/vecbricks/vfdlibm/Nightly.java b/src/test/java/io/github/vecbricks/vfdlibm/Nightly.java index 066abaa..30f2e6d 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/Nightly.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/Nightly.java @@ -224,8 +224,8 @@ record Arm2(String name, BinaryOperator all, Oracle.MaskedBinary m /** * A function of two arguments: its oracle, what its result may be on a lane of two NaNs with * different bits ({@link PairBits}; no default), every arm and where its branches are (for the - * {@link Fuzz}). No ported function is one yet, so {@link #KNOWN} is empty until a test or a - * port registers one; a pair function that is not listed in nightly.yml is never run there. + * {@link Fuzz}). {@link #KNOWN} lists the ported ones, and the stand-ins a test adds; a pair + * function that is not listed in nightly.yml is never run there. */ record PairFunction( String id, DoubleBinaryOperator oracle, PairBits.Candidates candidates, List arms, @@ -243,12 +243,32 @@ record PairFunction( } } + /** + * atan2: its two arms (the guarded arm {@code VFdlibm} calls, and the blended one), the + * candidates of a lane of two NaNs, and where its branches are: the high words of zero, one, + * the infinities and (for {@code y}) {@code 2^66}, and the differences of the two words + * that {@code k = (iy-ix)>>20} compares against 60 and -60 (e_atan2.c, lines 111-113). + */ + static final PairFunction ATAN2 = new PairFunction("atan2", StrictMath::atan2, + PairBits.Candidates.OPERANDS, + List.of( + new Arm2("VFdlibm.atan2", VFdlibm::atan2, VFdlibm::atan2), + new Arm2("Atan2.atan2Blended", (y, x) -> Atan2.atan2Blended(y, x, null), + Atan2::atan2Blended)), + new Fuzz.PairEdges( + new Fuzz.Edges(new int[] {0x00000000, 0x3ff00000, 0x44100000, 0x7ff00000}, + new int[0], false, new double[] {0.0, 1.0, 0x1p66, Double.POSITIVE_INFINITY}), + new Fuzz.Edges(new int[] {0x00000000, 0x3ff00000, 0x7ff00000}, + new int[0], false, new double[] {0.0, 1.0, Double.POSITIVE_INFINITY}), + Fuzz.PAIR_SPECIALS, + new int[] {61 << 20, (61 << 20) - 1, -60 << 20, (-60 << 20) - 1})); + /** * The functions of two arguments by name, in the order they are listed. A port registers its - * function here, in {@code Nightly}, as it adds a constant to {@link Function}; a test adds - * a stand-in and removes it again. + * function here, in {@code Nightly}; a test adds a stand-in and removes it again. A function + * in this list is not in the nightly's {@code all} until nightly.yml says so. */ - static final List KNOWN = new CopyOnWriteArrayList<>(); + static final List KNOWN = new CopyOnWriteArrayList<>(List.of(ATAN2)); @Override public int arity() { diff --git a/src/test/java/io/github/vecbricks/vfdlibm/PlantedFaultTest.java b/src/test/java/io/github/vecbricks/vfdlibm/PlantedFaultTest.java index ff2ee38..5c29384 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/PlantedFaultTest.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/PlantedFaultTest.java @@ -50,6 +50,7 @@ class PlantedFaultTest { CATCHERS.putAll(AcosTest.faultCatchers()); CATCHERS.putAll(CoshTest.faultCatchers()); CATCHERS.putAll(AtanTest.faultCatchers()); + CATCHERS.putAll(Atan2Test.faultCatchers()); } /**