[
https://issues.apache.org/jira/browse/NUMBERS-220?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18150551#comment-18150551
]
Alex Herbert commented on NUMBERS-220:
--------------------------------------
I have modified the DD class to use Math.fma to compute the round-off part of
multiplications. Use of FMA is only supported on HotSpot Virtual Machines (VMs)
starting from Java 9. The following conditions must be met:
* The {{Math.fma}} method is found by a public look-up in the Math class using
the MethodHandle API;
* The HotSpotDiagnosticMXBean reports the VM option "UseFMA" as {{true}};
* The method can be invoked and returns the correct finite result when the
intermediate product {{a * b}} of {{Math.fma(a, b, c)}} overflows, i.e. the
operation is fused.
Otherwise, e.g. on Java 8 or VMs that are not based on HotSpot, the software
implementation is used. The use of FMA can be disabled with the system property
{{-Dorg.apache.commons.numbers.core.DD.fma=false}} (see Start-up cost).
This is a performance-only change. Results are identical with and without FMA
where the software implementation computes the exact product: the product is
finite, the round-off part is not sub-normal, and the split arguments have a
base 2 exponent below 996. Outside this range results may differ; for example
FMA can compute a finite round-off where the software split overflows and
creates NaN. On Java 9 and above the tests for DD and ExtendedPrecision are
repeated 4 times: 2 runs using either {{-XX:-UseFMA}} or {{-XX:+UseFMA}}; and 2
runs with the {{org.apache.commons.numbers.core.DD.fma}} property set to
{{true}} or {{false}}. This verifies functionality is identical within the
range supported by the software implementation (version 1.3 behaviour).
The class documentation recommends that results from use of the DD class are
checked with the {{isFinite}} method. Methods are provided for efficient
scaling of DD numbers to avoid over and underflow: {{DD.frexp}} and
{{DD.scalb}}. Users should rely only on the range documented for the software
implementation and use scaling where appropriate. This ensures consistent
results on all platforms, and increased performance where hardware FMA is
available.
The round-off part of products is used in the {{Norm}} and {{Sum}} classes for
Euclidean norms or sum of products respectively. Both classes use scaling to
ensure that the software implementation is within the supported range. Scaling
has not been changed in the Norm class. Scaling is used to ensure the scaled
sum of squares is finite and a normal number. This is so that the sqrt can be
performed on a normal number before rescaling the result. The only change to
Norm is use of FMA when available instead of the slower software implementation
in the computation of an extended precision sum-of-squares. The Sum class
checks when the product {{x*y}} is finite and normal and the round-off part is
required. When FMA is available this is used to compute the round-off;
otherwise the software implementation is used with appropriate scaling to avoid
overflow or underflow. Both variants compute the exact round-off and results
are identical.
h2. Performance
The change was tested using the JMH benchmark in the examples package. This was
modified to:
* Allow use of a fixed seed for the DD, Sum and Norm benchmarks. Use of a
fixed seed allows the same data to be used across JVM runs for consistency when
comparing results.
* Allow building the JMH benchmark code against a specified version of
commons-numbers-core. This allows testing the same benchmark with the 1.3 and
1.4 versions.
* Allow a configurable number of data points for the power benchmarks, which
are shuffled before each measurement iteration. This allowed investigation of
how the CPU branch predictor can learn the branches in the power method (see
results below).
h3. Environment
* Platform: Apple M2 Pro (aarch64), macOS; Temurin 17.0.19 and 21.0.11.
* JMH: 5 warm-up and 5 measurement iterations of 1 s each, 3 rounds of one
fork per configuration, with the configuration order rotated each round; fixed
seed (12345).
* The main tables are for aarch64. The section on power functions and branch
prediction also includes x86-64 (Intel Xeon E5-1680 v3, Haswell, Linux, OpenJDK
21.0.13).
h3. Configurations
* 1.3: the released core with the same benchmark code, built with
{{-Dnumbers.core.version=1.3}}.
* 1.4 with {{-XX:-UseFMA}}: the fallback path, which is what Java 8 and CPUs
without FMA use. Java 8 itself wasn't run, because the JMH module needs Java 9+.
* 1.4 with {{-XX:+UseFMA}}.
The benchmarks process a batch of data (1000 DD operations, 500 powers, 100,000
arrays (Sum) or vectors (Norm)). Timings are platform specific in ns/operation.
Each row should be compared within the row only. Note that at 500 points the
branches within power can be learned by the CPU and timings reflect the speed
difference when using a learned sequence of branches with or without FMA (see
Power functions and branch prediction).
The results show mean ± 95% CI over 3 rounds (one fork each). Results are
flagged where the 95% CI of the ratio FMA/noFMA excludes 1 (i.e. the use of FMA
is faster or slower). The only row where the ratio noFMA/1.3 excludes 1 is
NormPerformance.euclideanArray (0.995 ± 0.004): 1.4 is marginally faster. With
about 30 comparisons one or two false positives are expected.
Controls were run that contain code that does not use FMA. These should not
have performance changes across configurations. These are the add operators,
the Sum.of method, and the directEuclideanArray method which computes the
Euclidean norm (square root of the sum of squares) in standard precision.
The baseline measures the overhead of the JMH loop over the data sample. For
the DD operator performance it creates a new DD for each of the random samples
(using {{DD.of(double)}}) so includes the object creation required for a DD
result. For the Sum performance the data is many samples of a single array to
sum, or a pair of arrays to compute the dot product. The Sum and Norm baselines
return the result for each random sample as zero. The baselines have not been
subtracted from the operator results before computation of ratios. The speed-up
of the operation itself is therefore larger than the ratio shows (see the
column without baseline in the summary table).
Results for:
{noformat}
host: Darwin 25.6.0 arm64
cpu: Apple M2 Pro
java: openjdk version "21.0.11" 2026-04-21 LTS OpenJDK Runtime Environment
Temurin-21.0.11+10 (build 21.0.11+10-LTS)
{noformat}
||Benchmark||Parameters||1.3 (ns/op)||1.4 FMA off (ns/op)||1.4 FMA on
(ns/op)||noFMA/1.3||FMA/noFMA||FMA/noFMA CI excludes 1||
|DDPerformance.binaryOperator|implementation=add|2225 ± 248|2326 ± 126|2208 ±
61|1.046 ± 0.129|0.949 ± 0.058| |
|DDPerformance.binaryOperator|implementation=addDouble|1957 ± 210|1965 ±
161|1929 ± 179|1.004 ± 0.136|0.982 ± 0.122| |
|DDPerformance.binaryOperator|implementation=baseline|1474 ± 44|1472 ± 7|1475 ±
15|0.999 ± 0.031|1.002 ± 0.011| |
|DDPerformance.binaryOperator|implementation=divide|20762 ± 597|20533 ±
424|15659 ± 276|0.989 ± 0.035|0.763 ± 0.021|Y|
|DDPerformance.binaryOperator|implementation=divideDouble|17300 ± 489|17382 ±
241|13119 ± 72|1.005 ± 0.032|0.755 ± 0.011|Y|
|DDPerformance.binaryOperator|implementation=multiply|2291 ± 8|2355 ± 143|1864
± 65|1.028 ± 0.062|0.791 ± 0.055|Y|
|DDPerformance.binaryOperator|implementation=multiplyDouble|2250 ± 186|2276 ±
142|1886 ± 188|1.011 ± 0.105|0.829 ± 0.098|Y|
|DDPerformance.binaryOperator|implementation=reciprocal|15899 ± 97|15904 ±
153|11157 ± 88|1.000 ± 0.011|0.702 ± 0.009|Y|
|DDPerformance.binaryOperator|implementation=sqrt|2295 ± 29|2314 ± 37|1995 ±
10|1.008 ± 0.021|0.862 ± 0.015|Y|
|DDPerformance.binaryOperator|implementation=square|1999 ± 5|2005 ± 23|1690 ±
24|1.003 ± 0.012|0.843 ± 0.016|Y|
|NormPerformance.baseline| |1921 ± 22|1935 ± 43|1951 ± 116|1.007 ± 0.025|1.008
± 0.064| |
|NormPerformance.directEuclideanArray| |165762 ± 1484|165304 ± 1006|166254 ±
2141|0.997 ± 0.011|1.006 ± 0.014| |
|NormPerformance.euclidean2d| |1242208 ± 7234|1243778 ± 8500|1066178 ±
12186|1.001 ± 0.009|0.857 ± 0.011|Y|
|NormPerformance.euclidean3d| |1047625 ± 6341|1048635 ± 14034|799129 ±
18703|1.001 ± 0.015|0.762 ± 0.021|Y|
|NormPerformance.euclideanArray| |1053323 ± 3842|1048435 ± 261|846602 ±
13722|0.995 ± 0.004|0.807 ± 0.013|Y|
|DDPerformance.pow|implementation=accuratePowScaled|186516 ± 2136|186637 ±
1862|155385 ± 932|1.001 ± 0.015|0.833 ± 0.010|Y|
|DDPerformance.pow|implementation=pow|40435 ± 596|40516 ± 202|15995 ± 138|1.002
± 0.016|0.395 ± 0.004|Y|
|DDPerformance.pow|implementation=powScaled|46844 ± 2112|47012 ± 561|21358 ±
293|1.004 ± 0.047|0.454 ± 0.008|Y|
|DDPerformance.powScaled|implementation=accuratePowScaled,
range=1048576:2097152|417221 ± 4457|416154 ± 4697|347653 ± 3649|0.997 ±
0.016|0.835 ± 0.013|Y|
|DDPerformance.powScaled|implementation=accuratePowScaled, range=2:64|78454 ±
501|78637 ± 489|61404 ± 849|1.002 ± 0.009|0.781 ± 0.012|Y|
|DDPerformance.powScaled|implementation=accuratePowScaled,
range=50000000:60000000|525511 ± 3604|525649 ± 6869|443303 ± 5462|1.000 ±
0.015|0.843 ± 0.015|Y|
|DDPerformance.powScaled|implementation=accuratePowScaled,
range=512:2048|195799 ± 1868|196019 ± 2109|160444 ± 1598|1.001 ± 0.014|0.819 ±
0.012|Y|
|DDPerformance.powScaled|implementation=powScaled, range=1048576:2097152|119846
± 910|120596 ± 854|49465 ± 1194|1.006 ± 0.010|0.410 ± 0.010|Y|
|DDPerformance.powScaled|implementation=powScaled, range=2:64|14427 ± 215|14491
± 161|7077 ± 23|1.004 ± 0.019|0.488 ± 0.006|Y|
|DDPerformance.powScaled|implementation=powScaled,
range=50000000:60000000|157965 ± 2785|157106 ± 1145|72375 ± 3111|0.995 ±
0.019|0.461 ± 0.020|Y|
|DDPerformance.powScaled|implementation=powScaled, range=512:2048|45554 ±
495|45543 ± 143|18400 ± 137|1.000 ± 0.011|0.404 ± 0.003|Y|
|SumPerformance.baselineDouble| |1923 ± 113|1908 ± 23|1906 ± 35|0.993 ±
0.059|0.999 ± 0.022| |
|SumPerformance.baselineSingle| |1923 ± 20|1919 ± 13|1923 ± 22|0.998 ±
0.012|1.002 ± 0.013| |
|SumPerformance.sum| |4543112 ± 63520|4554805 ± 114131|4563036 ± 81590|1.003 ±
0.029|1.002 ± 0.031| |
|SumPerformance.sumOfProducts| |16878861 ± 80875|16851615 ± 15271|6525270 ±
53396|0.998 ± 0.005|0.387 ± 0.003|Y|
For simplicity, results for JDK 17 are not shown.
Results have been compared using a ratio between configurations. This includes
a column for the operators where the baseline has been subtracted. For the
operators heavily biased to the computation of the product round-off (multiply;
square) the baseline contributes significant magnitude to the overall runtime.
||Operation||FMA off / 1.3 (JDK 21)||FMA on / FMA off (JDK 21)||without
baseline (JDK 21)||FMA on / FMA off (JDK 17)||
|DD multiply(DD)|1.03 ± 0.06|0.79 ± 0.06|0.44|0.84 ± 0.07|
|DD multiply(double)|1.01 ± 0.10|0.83 ± 0.10|0.51|0.84 ± 0.07|
|DD square()|1.00 ± 0.01|0.84 ± 0.02|0.40|0.85 ± 0.03|
|DD divide(DD)|0.99 ± 0.04|0.76 ± 0.02|0.74|0.77 ± 0.04|
|DD divide(double)|1.00 ± 0.03|0.75 ± 0.01|0.73|0.75 ± 0.04|
|DD reciprocal()|1.00 ± 0.01|0.70 ± 0.01|0.67|0.70 ± 0.01|
|DD sqrt()|1.01 ± 0.02|0.86 ± 0.01|0.62|0.87 ± 0.05|
|DD pow(int)|1.00 ± 0.02|0.39 ± < 0.01| |0.39 ± 0.01|
|DD pow(int, long\[\]) (scaled)|0.99 to 1.01|0.40 to 0.49| |0.40 to 0.48|
|DDMath pow(DD, int, long\[\])|1.00|0.78 to 0.84| |0.79 to 0.84|
|Sum.ofProducts|1.00 ± < 0.01|0.39 ± < 0.01| |0.47 ± 0.02|
|Norm.L2 of(x, y)|1.00 ± 0.01|0.86 ± 0.01| |0.86 ± 0.03|
|Norm.L2 of(x, y, z)|1.00 ± 0.01|0.76 ± 0.02| |0.76 ± 0.01|
|Norm.L2 of(double\[\]) (length 3)|1.00 ± < 0.01|0.81 ± 0.01| |0.76 ± 0.01|
|DD add(DD) (control)|1.05 ± 0.13|0.95 ± 0.06| |1.01 ± 0.05|
|DD add(double) (control)|1.00 ± 0.14|0.98 ± 0.12| |1.02 ± 0.05|
|Sum.of(double\[\]) (control)|1.00 ± 0.03|1.00 ± 0.03| |1.00 ± 0.03|
|Norm: plain sqrt of sum of squares (control)|1.00 ± 0.01|1.01 ± 0.01| |1.00 ±
0.01|
The {{DDMath.pow}} rows were repeated on the M2 Pro (JDK 21) after the fix for
the x86-64 performance regression (see below), with the same results: FMA off /
1.3 1.00; FMA on / FMA off 0.77 to 0.84.
h3. Power functions and branch prediction
The scaled power functions compute x^n by repeated squaring. The loop has
branches that depend on the data: one test per bit of the exponent n; a sign
test on n (a negative n requires the reciprocal); and rescaling of the
intermediate result when its magnitude exceeds a safe limit. The other
operators have no data-dependent branches.
The benchmarks above repeat the same 500 (x, n) values in every iteration. The
CPU branch predictor can learn this sequence, so the power ratios in the tables
above are for a learned sequence of branches. To measure performance when the
branches cannot be learned, the benchmark was changed to shuffle the order of
the data before each iteration, and the number of values was increased. On the
M2 Pro the time per call with FMA rises between 3,000 and 30,000 values (random
n), then stays constant up to 1,000,000 values. A data size of 100,000 values
is beyond the size the branch predictor can learn on both test machines.
The power functions were run in three modes:
* learned: n random in \[-1022, 1022), 500 values (as in the tables above);
* fixed n: n = 400, 100,000 values. Every call takes the same branches; no
rescale is needed;
* random n: n random in \[-1022, 1022), 100,000 values. About half of the bit
tests and the sign test are unpredictable.
In all modes x is random in ±\[0.5, 2). The configurations were 1.4 with
{{-XX:-UseFMA}} and {{-XX:+UseFMA}}, JDK 21, 3 rounds of one fork with the
configuration order rotated each round. Results are the mean ns per call; the
rounds agree within 3% (M2 Pro) and 0.3% (x86-64).
Platforms:
* Apple M2 Pro (aarch64), macOS, Temurin 21.0.11;
* Intel Xeon E5-1680 v3 (Haswell, x86-64), Linux, OpenJDK 21.0.13. The branch
misses per call were counted with the JMH {{perfnorm}} profiler (Linux perf,
one fork). Counters are not available on macOS.
||Method||Mode||M2 Pro FMA off||M2 Pro FMA on||M2 Pro FMA/noFMA||x86-64 FMA
off||x86-64 FMA on||x86-64 FMA/noFMA||x86-64 branch misses per call (off / on)||
|DD.pow(int)|learned|79.4|32.5|0.410|125.2|69.0|0.552|0.12 / 0.25|
|DD.pow(int)|fixed n|52.1|21.7|0.415|98.2|54.5|0.555|0.02 / 0.01|
|DD.pow(int)|random n|82.9|38.6|0.466|129.0|72.7|0.564|5.49 / 5.59|
|DDMath.pow(DD, int, long\[\])|learned|374.8|310.9|0.829|478.0|387.0|0.810|2.26
/ 1.51|
|DDMath.pow(DD, int, long\[\])|fixed n|259.4|203.1|0.783|338.9|274.8|0.811|0.04
/ 0.04|
|DDMath.pow(DD, int, long\[\])|random
n|384.6|320.0|0.832|481.1|390.1|0.811|5.66 / 5.63|
With random n the x86-64 CPU mispredicts about 5.5 branches per call, as
expected. The mispredictions add a similar time per call with and without FMA:
about 3 to 6 ns for {{DD.pow}} and 3 to 10 ns for {{DDMath.pow}}. On x86-64
each misprediction costs only about 4 cycles: the exponent bit tests use
integer operations on n that complete early, so the branch is resolved while
the floating-point computation of the previous step is still in progress.
As the added time is similar in both configurations, the effect on the FMA
ratio depends on the length of the call:
* {{DD.pow}} on the M2 Pro: the ratio rises from 0.41 (learned) to 0.47
(random n). The FMA call is short (33 ns), so the added time is a larger share
of it.
* {{DD.pow}} on x86-64: 0.55 to 0.56.
* {{DDMath.pow}}: unchanged on both platforms (0.83 on the M2 Pro and 0.81 on
x86-64). The call is 300 to 480 ns, so the added time is small in comparison.
The performance gain is lower in this method. It uses triple-double arithmetic
and most of the work is to compute exact additions of terms; the products that
can be computed using FMA are a smaller part of the work.
In summary, when the exponents are unpredictable, FMA reduces the runtime of
{{DD.pow}} to about 0.47 (M2 Pro) and 0.56 (x86-64) of the software
implementation, and of {{DDMath.pow}} to about 0.83 and 0.81. The power ratios
in the tables above (0.39 to 0.49 for {{DD.pow}}) are for learned branches and
overstate the gain on the M2 Pro. The other operators have no data-dependent
branches, so their ratios do not depend on the data order.
h3. Use case: Kolmogorov-Smirnov distribution
The DD class was designed for the computation of the one-sided one-sample
Kolmogorov-Smirnov distribution survival function. The JMH benchmark includes
this computation using the DD class (implementation "OO immutable"). Each term
of the sum uses two scaled DD powers ({{DD.pow}}, or {{DDMath.pow}} for the
Smirnov-Dwass method), three {{multiply}} and two {{fromQuotient}} calls. The
data is deterministic (evenly spaced x for ksRange; fixed n and x for
ksSample). The benchmark cases sum about 600 to 90,000 terms per call. Only 2
of 500 ksRange cases use {{DDMath.pow}} for 3 terms of about 295,000 in the
ksRange batch. So the timings measure heavy usage of {{DD.pow}} and
{{multiply}}.
||Benchmark||Parameters||FMA off / 1.3 (JDK 21)||FMA on / FMA off (JDK 21)||FMA
off / 1.3 (JDK 17)||FMA on / FMA off (JDK 17)||
|ksRange|n=1000, 500 values of x in \[0.001, 0.5\]|0.99 ± 0.02|0.61 ± 0.08|1.00
± 0.01|0.60 ± 0.01|
|ksSample|n=10000, x=0.01|1.01 ± 0.02|0.55 ± 0.03|1.00 ± 0.01|0.49 ± 0.04|
|ksSample|n=10000, x=0.05|1.01 ± 0.06|0.56 ± 0.04|1.00 ± 0.02|0.52 ± 0.02|
|ksSample|n=100000, x=0.01|1.02 ± 0.01|0.54 ± 0.01|1.00 ± 0.01|0.50 ± 0.01|
|ksSample|n=100000, x=0.05|0.99 ± 0.05|0.56 ± 0.01|1.05 ± 0.03|0.50 ± 0.01|
Use of FMA reduces the runtime of the KS survival function to 0.49 to 0.61 of
the software implementation.
Without FMA the 1.4 implementation matches 1.3 within ±2% on all cases except
one on JDK 17 (ksSample n=100000, x=0.05: 1.05 ± 0.03), which is 0.99 on JDK
21. The JIT inlining decisions for the KS computation are identical between 1.3
and 1.4 (checked with {{-XX:+PrintInlining}}); the difference is attributed to
JDK-specific code generation. The JDK 21 ksRange FMA result has a wide interval
as one of the three forks compiled to slower code (49.3 ms/op against 45 ms/op,
stable across its iterations).
h3. Start-up cost
The detection of hardware FMA is performed once per JVM when the first DD
product is computed (by DD, DDMath, Sum or Norm). The cost was measured in
fresh JVMs running a minimal program (20 runs per configuration, interleaved):
the time of the first DD multiply; the wall time of the JVM process; the number
of classes loaded; and a cold loop of 1000 iterations of (multiply, multiply,
divide) before the code is compiled by the JIT. JMH was not used: its forked
JVM initialises the management API (ManagementFactory, RuntimeMXBean) and the
method handle infrastructure before the benchmark runs, so even a single-shot
measurement in a new fork shows only the final part of the first-use cost
(reading the HotSpotDiagnosticMXBean). A minimal program in a fresh JVM
includes all the class loading.
||Measure||JDK||1.3||1.4 FMA off||1.4 FMA on||1.4 {{DD.fma=false}}||
|First multiply|17|3.6 µs|10.6 ms|10.9 ms|0.28 ms|
|First multiply|21|3.4 µs|13.0 ms|13.1 ms|0.28 ms|
|JVM wall time|17|50.6 ms|58.4 ms|58.8 ms|51.3 ms|
|JVM wall time|21|57.3 ms|66.7 ms|68.0 ms|58.6 ms|
|Classes loaded|17|833|963|967|835|
|Cold loop (1000 iterations)|17|829 µs|816 µs|1350 µs|878 µs|
|Cold loop (1000 iterations)|21|834 µs|896 µs|1261 µs|871 µs|
The detection cost is the same with FMA off as the {{UseFMA}} flag is still
read. Most of the cost is the initialisation of the management API to read the
{{UseFMA}} flag from the HotSpotDiagnosticMXBean. If the application has
already initialised the management API, lambdas and method handles the first
multiply costs 0.7 to 0.9 ms (JDK 17) or 2.0 to 2.2 ms (JDK 21).
Before the JIT compiles the calling code the FMA operation is called through a
MethodHandle. This is slower than the software implementation in interpreted
code. The cold loop of 3000 DD operations is about 0.4 to 0.5 ms slower with
FMA (up to 1.7 ms in other runs on JDK 21; cold timings vary with the
background JIT compilation). This is a one-off cost before the code is compiled.
The use of FMA can be disabled with the system property
{{-Dorg.apache.commons.numbers.core.DD.fma=false}}. In this case no detection
is performed and the software implementation is used. This restores the
start-up and cold performance of 1.3: the remaining cost is loading the FMA
support class once (0.3 ms). This option is intended for start-up cost
sensitive users. It also provides the same results on all platforms outside the
range supported by the software implementation.
h3. Inlining regression
The JVM can identify methods that are used frequently as hot methods and inline
the method. In the 1.3 implementation the private method that computes the
scaled power ({{computePowScaled}}, 313 bytes of bytecode) was below the
default byte size threshold for inlining a hot method
({{-XX:FreqInlineSize=325}}) and was inlined into {{DD.pow(int, long\[\])}}. A
first iteration to support FMA increased the size of the method to 338 bytes,
above the threshold. The JMH performance analysis showed a 6% slowdown for the
scaled {{DD.pow}} without FMA for small exponents (n in \[2, 64)); the cost is
fixed per call, so it is only visible when the power loop is short. This was
verified by repeating the benchmark with an increased JVM threshold for
inlining ({{-XX:FreqInlineSize=340}}), which removed the slowdown. The first
iteration of the code was revised to reduce the size of the method to 299
bytes, below the inlining threshold. This also improved the FMA path for small
exponents (ratio FMA/noFMA 0.52 to 0.48). Results as shown are for the JVM run
with the current implementation and default inlining thresholds.
h3. x86-64 regression
Testing on x86-64 showed a slowdown in {{DDMath.pow}} when comparing 1.3 to 1.4
with FMA disabled. {{DDMath.pow}} (FMA off / 1.3) was 1.038 on JDK 21 x86-64,
every round. The M2 Pro was not affected. The first version computed products
required by both branches before the branch. This moved computation of the
product further away from operations where the software implementation required
it. The HotSpot optimizing JIT compiler (C2) on x86-64 keeps the source order
of operations; the longer distance between each product and its use increased
the register spills in the compiled code. Analysis using perf showed it was not
an inlining or cache effect. The code now has separate paths for FMA or the
software implementation; the software implementation uses the order of
operations from version 1.3. The path is chosen using a static final boolean
set once when checking if FMA is supported and allowed. C2 treats this as a
constant and removes the unused path. After the fix the ratio (FMA off / 1.3)
on x86-64 was 0.999 (JDK 21) and 1.001 (JDK 17).
h2. Disclaimer
I wrote the DD changes based on a proof-of-concept prototype by Claude Code
(detection of hardware FMA). Claude Code wrote the JMH benchmark changes
(seeds, sampling of the scaled power, building against a released core), which
I reviewed, and the scripts to run and tabulate the benchmarks; it also
diagnosed the inlining regression and the x86-64 {{DDMath.pow}} regression
(operation order). Claude Code wrote and ran the start-up measurement program
(first DD multiply, JVM wall time, classes loaded and the cold loop),
identified the management API as the main start-up cost, and advised on the
design of the opt-out system property, which I proposed and implemented. Claude
Code changed the power function benchmarks to shuffle the data, ran the branch
prediction measurements on both platforms (including the perf counters) and
analysed the results.
> Use hardware supported FMA to accelerate the double-double (DD) computation
> of multiplication round-off
> -------------------------------------------------------------------------------------------------------
>
> Key: NUMBERS-220
> URL: https://issues.apache.org/jira/browse/NUMBERS-220
> Project: Commons Numbers
> Issue Type: Improvement
> Components: core
> Reporter: Alex Herbert
> Priority: Minor
>
> The DD (double-double) class supports computation of the exact 106-bit result
> from the multiplication of two 53-bit double values. The round-off from the
> product x * y is created using Dekker's split method to split each factor
> into two parts that can be multiplied exactly. The product low part is
> computed as a helper method:
> {code:java}
> xy = x * y
> xy_lo = twoProductLow(x, y, xy) // 16 FLOPS{code}
> The low part can be computed in 2 FLOPS using fused-multiply-add (FMA):
> {noformat}
> xy_lo = Math.fma(x, y, -xy){noformat}
> FMA was added in Java 9 and the library targets Java 8. The method can be
> used via the MethodHandle API to lookup the public method within the Math
> class. However if hardware supported FMA is not available the software
> fallback to support exact rounding for all cases is slow as it typically uses
> BigDecimal. So detection of the method and the ability to invoke it through a
> MethodHandle is not sufficient to ensure performance gains.
> The HotSpot JVM has a UseFMA flag that can be read using the JDK management
> API using the com.sun.management.HotSpotDiagnosticMXBean. This flag is
> documented as a configurable option and can be enabled/disabled using
> `-XX:[+-]UseFMA` on HotSpot JVMs. The default setting is enabled on hardware
> that supports FMA instructions.
> If the FMA method is detected on first use of the DD class, and a reference
> to the method to compute (a * b + c) is held in a static final constant, then
> invocation of the method is efficiently inlined to the correct FMA call. A
> JMH performance test showed no measurable difference between calling Math.fma
> directly and using a static final reference to an interface accepting the 3
> arguments:
> {code:java}
> interface FMAOperator {
> double fma(double a, double b, double c);
> }
> static final FMAOperator FMA = // create method to use{code}
> I propose to modify DD to detect hardware supported FMA. All functions that
> compute the round-off from multiplications can switch from the 16 FLOP
> current implementation to the 2 FLOP FMA call. A performance test should be
> used to demonstrate the difference between enabled and disabled, and verify
> the current software-only DD implementation performs the same as the FMA
> disabled version. Any failure to detect FMA should revert to the current
> implementation.
> h3. Behavioural change
> Results from all operations in the DD class should be identical with or
> without FMA where the non-FMA supported result is finite and does not
> underflow (i.e. computes a double-double number above 2^-969; below this the
> round-off is sub-normal). The DD class is not documented to support
> non-finite IEEE arithmetic.
> The current 16 FLOP implementation requires Dekker's method to split a 53-bit
> number. This requires multiplication by a factor of approximately 2^27. Any
> multiplication involving factors above 2^996 can overflow in the intermediate
> during splitting. This is already known behaviour noted in the class javadoc.
> Multiply and divide operations should only be used with terms less than
> 2^996. Use of FMA would extend support for the exact 106-bit double to be
> computed up to the limit of a double. This increases the supported range.
> Users who previously relied on the DD result returning false from the
> isFinite() method after a multiply or divide may no longer obtain the same
> results they expect. The solution is to use correct scaling on arguments
> before combined operations that could overflow. This is supported by a
> fractional representation method (frexp) and scaling method (scalb) that
> transform the number by exact power-of-2 scaling operations.
> There are locations other than computing product round-off where FMA can be
> used in the DD class that would increase accuracy by eliminating 1 rounding
> for chained multiply-add operations. This change does not support this usage.
> FMA should only be used in round-off computations for products where the
> performance gain is the most significant (16 to 2 FLOPS). For this reason the
> use of FMA should be internal to the DD class specialised to its particular
> use case. It should not be exposed via a public API.
> h3. Disclaimer
> Claude code was used to investigate how to detect hardware-enabled FMA at
> runtime and performed a JMH benchmark on a prototype. This demonstrated that
> failure to look for the UseFMA flag can have significant slowdown when the
> fall back is the software implementation of Math.fma.
>
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)