diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaChronoCompiler.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaChronoCompiler.java index 5f5ce0c6462e..dfab084fe0a1 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaChronoCompiler.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/VarkaChronoCompiler.java @@ -957,8 +957,8 @@ yield new Rebuilt(new IfElse(n.cond(), a.node(), b.node()), false, VarkaVectorIR.CrossLane _, VarkaVectorIR.NullValue _, VarkaVectorIR.InRanges _, VarkaVectorIR.IntArith _, IntNeg _, VarkaVectorIR.ConstDivide _, VarkaVectorIR.BoundedDivide _, VarkaVectorIR.BitOp _, VarkaVectorIR.BitCount _, - VarkaVectorIR.MathUnary _, VarkaVectorIR.RoundToIntegral _, VarkaVectorIR.CondValue _, - VarkaVectorIR.BoolOutput _, VarkaVectorIR.CanonicalFloat _, + VarkaVectorIR.MathUnary _, VarkaVectorIR.Fma _, VarkaVectorIR.RoundToIntegral _, + VarkaVectorIR.CondValue _, VarkaVectorIR.BoolOutput _, VarkaVectorIR.CanonicalFloat _, VarkaVectorIR.CanonicalBits _, VarkaVectorIR.HashStep _ -> new Rebuilt(node, false, false); }; diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/Analysis.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/Analysis.java index 980cbf26dde8..a7967b0df992 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/Analysis.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/Analysis.java @@ -74,6 +74,7 @@ import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.Least; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.LiteralSlot; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MathUnary; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.Fma; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.ReinterpretLane; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.RoundToIntegral; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MakeDate; @@ -1001,6 +1002,7 @@ void collectRefusals() { case BitOp n -> { } case BitCount n -> { } case MathUnary n -> { } + case Fma n -> { } case RoundToIntegral n -> { } case CanonicalFloat n -> { } case CanonicalBits n -> { } @@ -1101,8 +1103,8 @@ private boolean isNarrowRing(VarkaVectorIR node) { TruncDateDynamic _, DateDiff _, Greatest _, Least _, DayOfWeek _, WeekDay _, DayOfWeekIso _, ThursdayOf _, Year _, Month _, DayOfMonth _, Quarter _, DayOfYear _, LastDay _, TruncDate _, WeekOfYear _, ConstDivide _, BoundedDivide _, - BitOp _, BitCount _, MathUnary _, RoundToIntegral _, Compare _, NullSafeEqual _, - BoolColumn _, CanonicalFloat _, CanonicalBits _, HashStep _, + BitOp _, BitCount _, MathUnary _, Fma _, RoundToIntegral _, Compare _, + NullSafeEqual _, BoolColumn _, CanonicalFloat _, CanonicalBits _, HashStep _, BoolCompare _, CondIf _, BoolNullSafeEq _, CondConst _, And _, Or _, Not _, CrossLane _, IsNotNull _, InRanges _, CondValue _, NullValue _, BoolOutput _ -> false; @@ -1451,6 +1453,7 @@ private WordOwner ownerOf(VarkaVectorIR node) { case BitOp n -> andOwner(node, n.left(), n.right()); case BitCount n -> wordOwner.get(n.child()); case MathUnary n -> wordOwner.get(n.child()); + case Fma n -> andOwner(node, andOwner(node, n.a(), n.b()), wordOwner.get(n.c())); case RoundToIntegral n -> wordOwner.get(n.child()); case CanonicalFloat n -> wordOwner.get(n.child()); case CanonicalBits n -> wordOwner.get(n.child()); @@ -1484,8 +1487,14 @@ private WordOwner ownerOf(VarkaVectorIR node) { /** {@code Slots.andRef}'s folding over owners: all-true drops out, equal operands collapse. */ private WordOwner andOwner(VarkaVectorIR node, VarkaVectorIR a, VarkaVectorIR b) { - WordOwner wa = wordOwner.get(a); - WordOwner wb = wordOwner.get(b); + return andOwner(node, wordOwner.get(a), wordOwner.get(b)); + } + + /** + * The fold over two owners; a three-operand node folds its first two and then the third, as + * {@code Slots.andRef} folds the refs, the node's own word standing for an AND not folded. + */ + private static WordOwner andOwner(VarkaVectorIR node, WordOwner wa, WordOwner wb) { if (wa == WordOwner.Const.ALL_TRUE) { return wb; } @@ -1521,6 +1530,8 @@ private WordExpr pureOf(VarkaVectorIR node) { case BitOp n -> andExpr(pureWord.get(n.left()), pureWord.get(n.right())); case BitCount n -> pureWord.get(n.child()); case MathUnary n -> pureWord.get(n.child()); + case Fma n -> andExpr(andExpr(pureWord.get(n.a()), pureWord.get(n.b())), + pureWord.get(n.c())); case RoundToIntegral n -> pureWord.get(n.child()); case CanonicalFloat n -> pureWord.get(n.child()); case CanonicalBits n -> pureWord.get(n.child()); @@ -1823,6 +1834,8 @@ private void analyze(VarkaVectorIR node) { case BitCount n -> analyzeOp(node, false, n.child()); // A floating math function computes every lane and nulls none. case MathUnary n -> analyzeOp(node, false, n.child()); + // So does the fused multiply-add, over its three operands. + case Fma n -> analyzeOp(node, false, n.a(), n.b(), n.c()); case RoundToIntegral n -> analyzeOp(node, false, n.child()); case CanonicalFloat n -> analyzeOp(node, false, n.child()); case CanonicalBits n -> analyzeOp(node, false, n.child()); diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/Slots.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/Slots.java index 86745d86fea8..a5352dee6d45 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/Slots.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/Slots.java @@ -81,6 +81,7 @@ import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.Least; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.LiteralSlot; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MathUnary; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.Fma; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.ReinterpretLane; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.RoundToIntegral; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MakeDate; @@ -1225,6 +1226,9 @@ private static int planWordRef(VarkaVectorIR node, Slots s) { case BitOp n -> andRef(s.wordRef.get(n.left()), s.wordRef.get(n.right())); case BitCount n -> s.wordRef.get(n.child()); case MathUnary n -> s.wordRef.get(n.child()); + // The three operands' AND, folded as Analysis.ownerOf folds their owners. + case Fma n -> andRef(andRef(s.wordRef.get(n.a()), s.wordRef.get(n.b())), + s.wordRef.get(n.c())); case RoundToIntegral n -> s.wordRef.get(n.child()); case CanonicalFloat n -> s.wordRef.get(n.child()); case CanonicalBits n -> s.wordRef.get(n.child()); @@ -1748,6 +1752,7 @@ private void visit(VarkaVectorIR n) { case BitOp x -> { } case BitCount x -> { } case MathUnary x -> { } + case Fma x -> { } case RoundToIntegral x -> { } case CanonicalFloat x -> { } case CanonicalBits x -> { } @@ -1838,6 +1843,9 @@ private void propagate(VarkaVectorIR n) { demand(analysis.wordOwner.get(x.right())); } case BitCount x -> { } case MathUnary x -> { } + case Fma x -> { demand(analysis.wordOwner.get(x.a())); + demand(analysis.wordOwner.get(x.b())); + demand(analysis.wordOwner.get(x.c())); } case RoundToIntegral x -> { } case CanonicalFloat x -> { } case CanonicalBits x -> { } diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitBudget.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitBudget.java index 75c42bb9f2a2..f9d0523ba896 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitBudget.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitBudget.java @@ -785,6 +785,8 @@ static int weightOf(VarkaVectorIR node) { // most eight double lanes at 512 bits, the larger form as above; the scalar calls between // them are no vector op. case VarkaVectorIR.MathUnary n -> n.fn().laneCall() ? 16 : 1; + // The lanewise fused multiply-add: one call. + case VarkaVectorIR.Fma _ -> 1; // The rint construction: the absolute value, the add and subtract of 2^52, the sign's AND // and OR, the compare against 2^52 and the blend, and three reinterpretations, which the // budget counts as calls though they emit no instruction; then the NaN's compare and diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitCost.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitCost.java index 6fa585646135..5132f667d716 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitCost.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitCost.java @@ -122,6 +122,7 @@ static String kindOf(VarkaVectorIR node) { case BitOp n -> name + '/' + n.op() + '/' + n.laneType(); case BitCount n -> name + '/' + n.laneType(); case VarkaVectorIR.MathUnary n -> name + '/' + n.fn() + '/' + n.laneType(); + case VarkaVectorIR.Fma n -> name + '/' + n.laneType(); case VarkaVectorIR.RoundToIntegral n -> name + '/' + n.mode() + '/' + n.laneType(); case VarkaVectorIR.CanonicalFloat n -> name + '/' + n.laneType(); case VarkaVectorIR.CanonicalBits n -> name + '/' + n.laneType(); diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaKernelPlan.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaKernelPlan.java index 1ce87a6de019..99168520f3f9 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaKernelPlan.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaKernelPlan.java @@ -820,9 +820,9 @@ static LongNarrowRole longNarrowRole(VarkaVectorIR node) { WidenLane _, VarkaVectorIR.AddDays _, VarkaVectorIR.SubDays _, VarkaVectorIR.DateDiff _, IntArith _, VarkaVectorIR.IntNeg _, VarkaVectorIR.ConstDivide _, VarkaVectorIR.BoundedDivide _, VarkaVectorIR.BitOp _, - VarkaVectorIR.BitCount _, VarkaVectorIR.MathUnary _, VarkaVectorIR.RoundToIntegral _, - VarkaVectorIR.CanonicalFloat _, VarkaVectorIR.CanonicalBits _, - VarkaVectorIR.HashStep _, VarkaVectorIR.IfElse _, + VarkaVectorIR.BitCount _, VarkaVectorIR.MathUnary _, VarkaVectorIR.Fma _, + VarkaVectorIR.RoundToIntegral _, VarkaVectorIR.CanonicalFloat _, + VarkaVectorIR.CanonicalBits _, VarkaVectorIR.HashStep _, VarkaVectorIR.IfElse _, VarkaVectorIR.CondValue _, VarkaVectorIR.Greatest _, VarkaVectorIR.Least _, VarkaVectorIR.DayOfWeek _, VarkaVectorIR.WeekDay _, VarkaVectorIR.DayOfWeekIso _, VarkaVectorIR.NextDay _, VarkaVectorIR.ThursdayOf _, VarkaVectorIR.AddMonths _, @@ -875,8 +875,8 @@ private static LongNarrowReader longNarrowReader(VarkaVectorIR node) { VarkaVectorIR.AddDays _, VarkaVectorIR.SubDays _, VarkaVectorIR.DateDiff _, IntArith _, VarkaVectorIR.IntNeg _, VarkaVectorIR.ConstDivide _, VarkaVectorIR.BoundedDivide _, VarkaVectorIR.BitOp _, VarkaVectorIR.BitCount _, - VarkaVectorIR.MathUnary _, VarkaVectorIR.RoundToIntegral _, VarkaVectorIR.IfElse _, - VarkaVectorIR.CanonicalFloat _, VarkaVectorIR.CanonicalBits _, + VarkaVectorIR.MathUnary _, VarkaVectorIR.Fma _, VarkaVectorIR.RoundToIntegral _, + VarkaVectorIR.IfElse _, VarkaVectorIR.CanonicalFloat _, VarkaVectorIR.CanonicalBits _, VarkaVectorIR.HashStep _, VarkaVectorIR.CondValue _, VarkaVectorIR.Greatest _, VarkaVectorIR.Least _, VarkaVectorIR.DayOfWeek _, VarkaVectorIR.WeekDay _, diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperandPosition.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperandPosition.java index a65dedc8b25a..d583ee33b071 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperandPosition.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperandPosition.java @@ -105,8 +105,8 @@ public boolean admits(VarkaVectorIR node) { }; case AddDays _, SubDays _, DateDiff _, IfElse _, Greatest _, Least _, DayOfWeek _, WeekDay _, DayOfWeekIso _, NextDay _, ThursdayOf _, AddMonths _, MakeDate _, - ConstDivide _, BoundedDivide _, BitOp _, BitCount _, MathUnary _, RoundToIntegral _, - CanonicalFloat _, CanonicalBits _, HashStep _, GuardedDay _, + ConstDivide _, BoundedDivide _, BitOp _, BitCount _, MathUnary _, Fma _, + RoundToIntegral _, CanonicalFloat _, CanonicalBits _, HashStep _, GuardedDay _, GuardedRange _, ConvertLane _, ReinterpretLane _, WidenDecimal _, Year _, Month _, DayOfMonth _, Quarter _, DayOfYear _, @@ -146,8 +146,8 @@ public static List restrictedOperands(VarkaVectorIR node) { Greatest _, Least _, DayOfWeek _, WeekDay _, DayOfWeekIso _, ThursdayOf _, MakeDate _, IntArith _, IntNeg _, - ConstDivide _, BoundedDivide _, BitOp _, BitCount _, MathUnary _, RoundToIntegral _, - CanonicalFloat _, CanonicalBits _, HashStep _, GuardedDay _, + ConstDivide _, BoundedDivide _, BitOp _, BitCount _, MathUnary _, Fma _, + RoundToIntegral _, CanonicalFloat _, CanonicalBits _, HashStep _, GuardedDay _, GuardedRange _, WidenLane _, ConvertLane _, ReinterpretLane _, NarrowLane _, WidenDecimal _, Year _, Month _, DayOfMonth _, Quarter _, DayOfYear _, diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaRangeAnalysis.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaRangeAnalysis.java index 5f74aafc8716..f5ffb643cfeb 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaRangeAnalysis.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaRangeAnalysis.java @@ -56,6 +56,7 @@ import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.Least; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.LiteralSlot; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MathUnary; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.Fma; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.ReinterpretLane; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.RoundToIntegral; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MakeDate; @@ -398,6 +399,7 @@ public static Range range(VarkaVectorIR node, Kind kind, GuardPolicy policy, ? VarkaValueRange.UNKNOWN : VarkaValueRange.of(0, Long.SIZE); // A floating value has no integer range. case MathUnary n -> VarkaValueRange.UNKNOWN; + case Fma n -> VarkaValueRange.UNKNOWN; case RoundToIntegral n -> VarkaValueRange.UNKNOWN; case CanonicalFloat n -> VarkaValueRange.UNKNOWN; // The bits of a float and a hash step span their whole lanes. diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaSameAnswer.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaSameAnswer.java index 6da34b317f68..baea31cc29ae 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaSameAnswer.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaSameAnswer.java @@ -154,6 +154,13 @@ record Other(List children) implements Step {} * over an open operand. */ record Canonical() implements Step {} + + /** + * A node whose NaN no tier fixes, over any operands: an FMA, which {@code Math.fma} run in + * Java answers with the canonical NaN, and the instruction by its own rule, an operand's NaN + * or the host's default one ({@code VarkaVectorIR.Fma}). Every NaN of the node is open. + */ + record Unfixed() implements Step {} } /** One tree's view of a node on one row, all the rule reads. */ @@ -178,8 +185,9 @@ private interface Front { * greatest} or {@code least} its first child whose value is a NaN (Spark's fold keeps the first * of equal values, and every NaN compares equal to every other). A {@code rint} * ({@code RoundToIntegral} over the IR, Spark's {@code Rint} over an expression) is never - * open, whatever its operand, since it answers the canonical NaN for every NaN. Any other node - * is open where a floating child whose value is a NaN is. + * open, whatever its operand, since it answers the canonical NaN for every NaN. An FMA + * ({@code Fma} over the IR, no Catalyst expression being one) is open wherever it answers a + * NaN. Any other node is open where a floating child whose value is a NaN is. * *

The rule reads no payload it decides is open. Which values are NaNs is the same on every * tier, and an arithmetic compares its operands' bits only once neither is open, when each is @@ -202,6 +210,7 @@ private static boolean open(N node, Front front) { yield l != null ? open(a.left(), front) : r != null && open(a.right(), front); } case Step.Canonical _ -> false; + case Step.Unfixed _ -> true; case Step.Pass p -> open(p.child(), front); case Step.Pick p -> p.taken() != null && front.nanBits(p.taken()) != null && open(p.taken(), front); @@ -265,6 +274,7 @@ public static boolean openNaN(VarkaVectorIR node, IrRow row) { a.op() == VarkaVectorIR.IntOp.ADD || a.op() == VarkaVectorIR.IntOp.MUL); case VarkaVectorIR.RoundToIntegral _ -> new Step.Canonical<>(); case VarkaVectorIR.CanonicalFloat _ -> new Step.Canonical<>(); + case VarkaVectorIR.Fma _ -> new Step.Unfixed<>(); case VarkaVectorIR.IfElse i -> new Step.Pick<>(row.holds(i.cond()) ? i.thenNode() : i.elseNode()); case VarkaVectorIR.Greatest g -> new Step.FirstNaN<>(List.of(g.left(), g.right())); diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorIR.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorIR.java index 12325df84545..b84ee0d15aaf 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorIR.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorIR.java @@ -83,8 +83,9 @@ public sealed interface VarkaVectorIR VarkaVectorIR.AddMonths, VarkaVectorIR.MakeDate, VarkaVectorIR.IntArith, VarkaVectorIR.IntNeg, VarkaVectorIR.ConstDivide, VarkaVectorIR.BoundedDivide, VarkaVectorIR.BitOp, VarkaVectorIR.BitCount, - VarkaVectorIR.MathUnary, VarkaVectorIR.RoundToIntegral, VarkaVectorIR.Cond, - VarkaVectorIR.CanonicalFloat, VarkaVectorIR.CanonicalBits, VarkaVectorIR.HashStep, + VarkaVectorIR.MathUnary, VarkaVectorIR.Fma, VarkaVectorIR.RoundToIntegral, + VarkaVectorIR.Cond, VarkaVectorIR.CanonicalFloat, VarkaVectorIR.CanonicalBits, + VarkaVectorIR.HashStep, VarkaVectorIR.GuardedDay, VarkaVectorIR.GuardedRange, VarkaVectorIR.WidenLane, VarkaVectorIR.ConvertLane, VarkaVectorIR.ReinterpretLane, VarkaVectorIR.NarrowLane, VarkaVectorIR.WidenDecimal { @@ -170,6 +171,7 @@ default LaneType laneType() { case BitOp n -> n.left().laneType(); case BitCount n -> n.child().laneType(); case MathUnary n -> n.child().laneType(); + case Fma n -> n.a().laneType(); case RoundToIntegral n -> n.child().laneType(); case CanonicalFloat n -> n.child().laneType(); case CanonicalBits n -> n.lane(); @@ -239,8 +241,8 @@ static int inputOrdinal(VarkaVectorIR node) { case DecimalWord c -> c.ordinal(); case BoolColumn b -> b.ordinal(); case LiteralSlot _, IntArith _, IntNeg _, ConstDivide _, BoundedDivide _, BitOp _, - BitCount _, MathUnary _, RoundToIntegral _, Greatest _, Least _, IfElse _, CondValue _, - BoolOutput _, CanonicalFloat _, CanonicalBits _, HashStep _, + BitCount _, MathUnary _, Fma _, RoundToIntegral _, Greatest _, Least _, IfElse _, + CondValue _, BoolOutput _, CanonicalFloat _, CanonicalBits _, HashStep _, Compare _, NullSafeEqual _, CondConst _, NullValue _, BoolCompare _, CondIf _, BoolNullSafeEq _, And _, Or _, Not _, CrossLane _, IsNotNull _, InRanges _, AddDays _, SubDays _, DateDiff _, GuardedDay _, GuardedRange _, WidenLane _, @@ -347,7 +349,7 @@ private static void narrowValuesIn(VarkaVectorIR node, Set lanes, DateDiff _, Greatest _, Least _, IfElse _, CondValue _, BoolOutput _, DayOfWeek _, WeekDay _, DayOfWeekIso _, ThursdayOf _, Year _, Month _, DayOfMonth _, Quarter _, DayOfYear _, LastDay _, TruncDate _, WeekOfYear _, ConstDivide _, BoundedDivide _, - BitOp _, BitCount _, MathUnary _, RoundToIntegral _, Compare _, NullSafeEqual _, + BitOp _, BitCount _, MathUnary _, Fma _, RoundToIntegral _, Compare _, NullSafeEqual _, BoolCompare _, CondIf _, BoolNullSafeEq _, And _, Or _, Not _, CrossLane _, InRanges _, CanonicalFloat _, CanonicalBits _, HashStep _ -> { for (VarkaVectorIR child : childrenOf(node)) { @@ -394,7 +396,8 @@ private static boolean needsNarrowSpecies(VarkaVectorIR node, Set Least _, IfElse _, CondValue _, BoolOutput _, DayOfWeek _, WeekDay _, DayOfWeekIso _, ThursdayOf _, Year _, Month _, DayOfMonth _, Quarter _, DayOfYear _, LastDay _, TruncDate _, WeekOfYear _, - ConstDivide _, BoundedDivide _, BitOp _, BitCount _, MathUnary _, RoundToIntegral _, + ConstDivide _, BoundedDivide _, BitOp _, BitCount _, MathUnary _, Fma _, + RoundToIntegral _, Compare _, NullSafeEqual _, BoolCompare _, CondIf _, BoolNullSafeEq _, And _, Or _, Not _, CrossLane _, InRanges _, CanonicalFloat _, CanonicalBits _, HashStep _ -> { boolean any = false; @@ -1593,6 +1596,35 @@ record MathUnary(MathFn fn, VarkaVectorIR child, int hash) implements VarkaVecto @Override public int hashCode() { return hash; } } + /** + * {@code a * b + c} over a floating lane with one rounding, {@code Math.fma}: the lanewise + * {@code FMA}, which is IEEE's fused multiply-add on every host the Vector API intrinsifies it + * on, and {@code Math.fma}'s own exact computation in each lane elsewhere. No Spark expression + * is an FMA, so the node is built only by a lowering that needs the single rounding (the + * floating remainder and the round-to-odd narrowing, VARKA-346), and never from a multiply and + * an add: those stay two {@link IntArith} nodes, rounded twice, as Spark computes them. + * Null-intolerant: the validity is the three operands' AND. + * + *

Its NaN's bits are fixed nowhere. {@code Math.fma} run in Java answers the canonical NaN + * for any NaN and for {@code inf * 0}; the instruction answers by its own rule over its own + * operand order (x86's {@code vfmadd231}, {@code c = a * b + c}), an operand's NaN or the + * host's default one; so a NaN answer is compared by NaN-ness. + */ + record Fma(VarkaVectorIR a, VarkaVectorIR b, VarkaVectorIR c, int hash) + implements VarkaVectorIR { + public Fma { + requireSameLane("an FMA", a, b, c); + if (!a.laneType().isFloating()) { + throw VarkaErrors.illegalArgument("an FMA takes floating operands, not " + + a.laneType() + ", from a " + a.getClass().getSimpleName()); + } + hash = hashOf(a, b, c); + } + + public Fma(VarkaVectorIR a, VarkaVectorIR b, VarkaVectorIR c) { this(a, b, c, 0); } + @Override public int hashCode() { return hash; } + } + /** * Spark's {@code rint(child)} over the double lane ({@code MathUtils.rint}): the nearest * integer-valued double, a tie going to the even one, with the operand's sign kept on a zero @@ -2524,6 +2556,8 @@ static String canonicalWith(VarkaVectorIR node, + kid.apply(n.right()) + ")"; case BitCount n -> "(bitCount " + kid.apply(n.child()) + ")"; case MathUnary n -> "(math:" + n.fn().name() + " " + kid.apply(n.child()) + ")"; + case Fma n -> "(fma " + kid.apply(n.a()) + " " + kid.apply(n.b()) + " " + + kid.apply(n.c()) + ")"; case RoundToIntegral n -> "(round:" + n.mode().name() + " " + kid.apply(n.child()) + ")"; case CanonicalFloat n -> "(canon " + kid.apply(n.child()) + ")"; case CanonicalBits n -> "(canonBits " + kid.apply(n.child()) + ")"; @@ -2642,6 +2676,8 @@ static String canonicalShallow(VarkaVectorIR node, ToIntFunction + lineOf.applyAsInt(n.right()) + ")"; case BitCount n -> "(bitCount " + lineOf.applyAsInt(n.child()) + ")"; case MathUnary n -> "(math:" + n.fn().name() + " " + lineOf.applyAsInt(n.child()) + ")"; + case Fma n -> "(fma " + lineOf.applyAsInt(n.a()) + " " + lineOf.applyAsInt(n.b()) + " " + + lineOf.applyAsInt(n.c()) + ")"; case RoundToIntegral n -> "(round:" + n.mode().name() + " " + lineOf.applyAsInt(n.child()) + ")"; case CanonicalFloat n -> "(canon " + lineOf.applyAsInt(n.child()) + ")"; @@ -2940,6 +2976,7 @@ static VarkaVectorIR[] childrenOf(VarkaVectorIR node) { case BitOp n -> new VarkaVectorIR[] {n.left(), n.right()}; case BitCount n -> new VarkaVectorIR[] {n.child()}; case MathUnary n -> new VarkaVectorIR[] {n.child()}; + case Fma n -> new VarkaVectorIR[] {n.a(), n.b(), n.c()}; case RoundToIntegral n -> new VarkaVectorIR[] {n.child()}; case CanonicalFloat n -> new VarkaVectorIR[] {n.child()}; case CanonicalBits n -> new VarkaVectorIR[] {n.child()}; @@ -3024,6 +3061,7 @@ static VarkaVectorIR withChildren(VarkaVectorIR node, VarkaVectorIR... children) case BitOp n -> new BitOp(n.op(), children[0], children[1]); case BitCount n -> new BitCount(children[0]); case MathUnary n -> new MathUnary(n.fn(), children[0]); + case Fma n -> new Fma(children[0], children[1], children[2]); case RoundToIntegral n -> new RoundToIntegral(n.mode(), children[0]); case CanonicalFloat n -> CanonicalFloat.of(children[0]); case CanonicalBits n -> new CanonicalBits(children[0]); diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorTemplateWarmup.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorTemplateWarmup.java index 25047ac02df3..d9ef37b5529b 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorTemplateWarmup.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorTemplateWarmup.java @@ -800,11 +800,12 @@ private static long doubles(VectorSpecies s, double[] da, double[] db, for (Comparison op : FLOATING_COMPARISONS) { acc += x.compare(op, y).toLong(); } - // The floating arithmetic's own calls (VARKA-342): abs, the square root and the - // division's zero test against a scalar, beside the operators above. + // The floating arithmetic's own calls (VARKA-342): abs, the square root, the fused + // multiply-add and the division's zero test against a scalar, beside the operators + // above. acc += (long) (x.lanewise(VectorOperators.ABS).lane(0) - + x.lanewise(VectorOperators.SQRT).lane(0)) + y.compare(VectorOperators.EQ, 0.0) - .toLong(); + + x.lanewise(VectorOperators.SQRT).lane(0) + x.fma(y, x).lane(0)) + + y.compare(VectorOperators.EQ, 0.0).toLong(); // The rounding's calls (VARKA-344): the compare against the scalar 2^52, and the sign // bit taken from one lane view and or-ed into another. acc += x.compare(VectorOperators.LT, 0x1.0p52).toLong() @@ -842,9 +843,10 @@ private static long floats(VectorSpecies s, float[] fa, float[] fb, acc += x.compare(op, y).toLong(); } // The floating arithmetic at the FLOAT lane (VARKA-342): the three operators, - // negation and abs. + // negation, abs and the fused multiply-add. acc += (long) (x.add(y).lane(0) + x.sub(y).lane(0) + x.mul(y).lane(0) - + x.lanewise(VectorOperators.NEG).lane(0) + x.lanewise(VectorOperators.ABS).lane(0)); + + x.lanewise(VectorOperators.NEG).lane(0) + x.lanewise(VectorOperators.ABS).lane(0) + + x.fma(y, x).lane(0)); // The canonicalisation's calls (VARKA-337): the add of a scalar zero and the blend of // the scalar NaN under the NaN test; the double block above has both forms already. acc += (long) x.add(0.0f).blend(Float.NaN, x.test(VectorOperators.IS_NAN)).lane(0); diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorWalk.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorWalk.java index 8e4d37413528..d097d375194b 100644 --- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorWalk.java +++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaVectorWalk.java @@ -71,6 +71,7 @@ import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.LiteralSlot; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MathFn; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MathUnary; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.Fma; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.ReinterpretLane; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.RoundToIntegral; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MakeDate; @@ -274,6 +275,7 @@ static void emitValue(CodeBuilder cb, VarkaVectorIR node, boolean dense, case BitOp n -> emitBitOp(cb, n, dense, analysis, s, computed); case BitCount n -> emitBitCount(cb, n, dense, analysis, s, computed); case MathUnary n -> emitMathUnary(cb, n, dense, analysis, s, computed); + case Fma n -> emitFma(cb, n, dense, analysis, s, computed); case RoundToIntegral n -> VarkaRoundingLowering.emitRint(cb, n, dense, analysis, s, computed); case CanonicalFloat n -> emitCanonicalFloat(cb, n, dense, analysis, s, computed); @@ -1221,6 +1223,28 @@ private static void emitMathUnary(CodeBuilder cb, MathUnary n, boolean dense, cb.invokevirtual(lane.vector, "lanewise", MethodTypeDesc.of(lane.vector, VO_UNARY)); } + /** + * {@code Fma}: {@code a.fma(b, c)}, the operands pushed in their order, one rounding. In the + * masked body a node that owns its word stores the three operands' AND. + */ + private static void emitFma(CodeBuilder cb, Fma n, boolean dense, Analysis analysis, Slots s, + Set computed) { + emitValue(cb, n.a(), dense, analysis, s, computed); + emitValue(cb, n.b(), dense, analysis, s, computed); + emitValue(cb, n.c(), dense, analysis, s, computed); + line(cb, analysis, n); + Lane lane = analysis.laneOf(n); + cb.invokevirtual(lane.vector, "fma", MethodTypeDesc.of(lane.vector, VECTOR, VECTOR)); + if (!dense && s.ownWord.contains(n)) { + loadWord(cb, s, s.wordRef.get(n.a())); + loadWord(cb, s, s.wordRef.get(n.b())); + cb.land(); + loadWord(cb, s, s.wordRef.get(n.c())); + cb.land(); + storeWord(cb, s, s.wordRef.get(n)); + } + } + /** * A per-lane call: {@code [v] -> [v']}, each lane {@code k} of the double vector replaced by * {@code fn(v.lane(k))}, the scalar method Spark's code calls, so the bits are that method's on diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaCanonicalIr.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaCanonicalIr.java index 6a197af3f9f0..be221d743a35 100644 --- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaCanonicalIr.java +++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaCanonicalIr.java @@ -263,6 +263,7 @@ yield new GuardedRange(child, lo, hi, case "bit" -> new BitOp(BitOpKind.valueOf(parts[1]), node(), node()); case "bitCount" -> new BitCount(node()); case "math" -> new MathUnary(MathFn.valueOf(parts[1]), node()); + case "fma" -> new Fma(node(), node(), node()); case "round" -> new RoundToIntegral(RoundMode.valueOf(parts[1]), node()); case "canon" -> CanonicalFloat.of(node()); case "canonBits" -> new CanonicalBits(node()); diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitterFmaSuite.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitterFmaSuite.java new file mode 100644 index 000000000000..00670bd6d627 --- /dev/null +++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitterFmaSuite.java @@ -0,0 +1,428 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * Unless required by applicable law or agreed to in writing, 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 org.apache.spark.sql.catalyst.expressions.codegen.varka; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; +import java.util.List; +import java.util.Map; +import java.util.OptionalInt; +import java.util.OptionalLong; +import java.util.function.IntPredicate; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaEmitterFixtures.Col; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaEmitterFixtures.Output; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaKernelChecks.ValidityFill; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.ColumnRef; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.Fma; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.IntArith; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.IntNeg; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.IntOp; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.LaneType; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.LiteralSlot; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.Overflow; + +/** + * The fused multiply-add node (VARKA-342, for VARKA-346's remainder and round-to-odd): + * {@code Fma(a, b, c)} at the {@code DOUBLE} and {@code FLOAT} lanes against the reference + * evaluator's {@code Math.fma}, at two widths each, over every per-column null pattern. + * + *

No Spark expression is an FMA, so the reference is the only oracle. A non-NaN answer is + * held bit for bit, a zero's sign included: the fused operation is IEEE's on every host, rounded + * once. A NaN answer is held by NaN-ness, through {@link VarkaSameAnswer}'s row level, whose + * rule opens every NaN of the node ({@code VarkaVectorIR.Fma}). + */ +@VarkaSuite(ownJvm = true) +public final class VarkaEmitterFmaSuite { + + private static final ColumnRef X = new ColumnRef(0, LaneType.DOUBLE); + private static final ColumnRef Y = new ColumnRef(1, LaneType.DOUBLE); + private static final ColumnRef Z = new ColumnRef(2, LaneType.DOUBLE); + private static final ColumnRef F = new ColumnRef(0, LaneType.FLOAT); + private static final ColumnRef G = new ColumnRef(1, LaneType.FLOAT); + private static final ColumnRef H = new ColumnRef(2, LaneType.FLOAT); + + /** + * The operands the cells draw from, as doubles: both zeros, both infinities, a NaN, the + * extremes, the smallest subnormal and normal, and normals whose product is inexact; at the + * {@code FLOAT} lane each is narrowed, the double extremes becoming the float infinities. + */ + private static final double[] SPECIALS = { + 0.0, -0.0, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN, + Double.MAX_VALUE, -Double.MAX_VALUE, Double.MIN_VALUE, -Double.MIN_NORMAL, 1.0, -1.0, + 1.0 + 0x1.0p-27, 1.0 - 0x1.0p-27, 1.0 + 0x1.0p-13, 1.0 - 0x1.0p-13, 3.0, -0.1}; + + /** The four null patterns the emitter suites share. */ + private static final List NULL_PATTERNS = List.of( + i -> false, i -> i % 5 == 0, i -> i % 2 == 1, i -> true); + + private static final int[] LENGTHS = {1, 7, 129, SPECIALS.length * SPECIALS.length * 2}; + + /** Row {@code i}'s operand of column {@code col}: every ordered triple in turn. */ + private static double operand(int col, int i) { + int n = SPECIALS.length; + return SPECIALS[switch (col) { + case 0 -> i % n; + case 1 -> (i / n) % n; + default -> (i / (n * n) + i) % n; + }]; + } + + @Test + @DisplayName("an FMA rounds once: (1 + 2^-27)(1 - 2^-27) - 1 is -2^-54, where a multiply and " + + "an add give 0.0") + public void anFmaRoundsOnce() { + double a = 1.0 + 0x1.0p-27; + double b = 1.0 - 0x1.0p-27; + assertEquals(-0x1.0p-54, Math.fma(a, b, -1.0), "the operands are the named case"); + assertEquals(0.0, a * b - 1.0, "and the two roundings lose it"); + var fused = new Fma(X, Y, Z); + var twice = new IntArith(IntOp.ADD, Overflow.WRAP, new IntArith(IntOp.MUL, Overflow.WRAP, + X, Y), Z); + for (int lanes : new int[] {2, 8}) { + long[] got = runDouble(List.of(fused, twice), new double[][] {{a}, {b}, {-1.0}}, lanes); + assertEquals(Double.doubleToRawLongBits(-0x1.0p-54), got[0], "fused at " + lanes); + assertEquals(Double.doubleToRawLongBits(0.0), got[1], "unfused at " + lanes); + } + // The float twin: (1 + 2^-13)(1 - 2^-13) is 1 - 2^-26, which a float rounds to 1. + float fa = 1.0f + 0x1.0p-13f; + float fb = 1.0f - 0x1.0p-13f; + assertEquals(-0x1.0p-26f, Math.fma(fa, fb, -1.0f), "the float operands are the named case"); + var ffused = new Fma(F, G, H); + var ftwice = new IntArith(IntOp.ADD, Overflow.WRAP, new IntArith(IntOp.MUL, Overflow.WRAP, + F, G), H); + for (int lanes : new int[] {4, 16}) { + int[] got = runFloat(List.of(ffused, ftwice), new float[][] {{fa}, {fb}, {-1.0f}}, lanes); + assertEquals(Float.floatToRawIntBits(-0x1.0p-26f), got[0], "fused at " + lanes); + assertEquals(Float.floatToRawIntBits(0.0f), got[1], "unfused at " + lanes); + } + } + + @Test + @DisplayName("an FMA at the DOUBLE lane computes what the reference says, at both widths and " + + "over every null pattern of its three operands") + public void anFmaAtTheDoubleLaneComputesWhatTheReferenceSays() { + var k = new LiteralSlot(0, LaneType.DOUBLE); + // The node over three columns, in another operand order, over one column twice and a + // literal, and under a negation that passes its NaN on. + List roots = List.of(new Fma(X, Y, Z), new Fma(Z, X, Y), new Fma(X, X, k), + new IntNeg(Overflow.WRAP, new Fma(Y, k, X))); + long[] lits = {Double.doubleToRawLongBits(-0.1)}; + for (int lanes : new int[] {2, 8}) { + checkMatrix(roots, lits, LaneType.DOUBLE, lanes); + } + } + + @Test + @DisplayName("an FMA at the FLOAT lane computes Math.fma's float form, at both widths and over " + + "every null pattern of its three operands") + public void anFmaAtTheFloatLaneComputesWhatTheReferenceSays() { + var k = new LiteralSlot(0, LaneType.FLOAT); + List roots = List.of(new Fma(F, G, H), new Fma(H, F, G), new Fma(F, F, k), + new IntNeg(Overflow.WRAP, new Fma(G, k, F))); + long[] lits = {Float.floatToRawIntBits(-0.1f)}; + for (int lanes : new int[] {4, 16}) { + checkMatrix(roots, lits, LaneType.FLOAT, lanes); + } + } + + @Test + @DisplayName("an FMA takes three operands of one floating lane") + public void anFmaTakesThreeOperandsOfOneFloatingLane() { + var i = new ColumnRef(0); + var l = new ColumnRef(0, LaneType.LONG); + assertThrows(IllegalArgumentException.class, () -> new Fma(i, i, i)); + assertThrows(IllegalArgumentException.class, () -> new Fma(l, l, l)); + assertThrows(IllegalArgumentException.class, () -> new Fma(X, Y, H)); + assertThrows(IllegalArgumentException.class, () -> new Fma(F, Y, Z)); + assertEquals(LaneType.FLOAT, new Fma(F, G, H).laneType()); + var fma = new Fma(X, Y, new IntNeg(Overflow.WRAP, Z)); + assertEquals("(fma col:0:double col:1:double (neg:WRAP col:2:double))", + VarkaVectorIR.canonical(fma)); + assertEquals(fma, VarkaCanonicalIr.parse(VarkaVectorIR.canonical(fma)), + "the rendering parses back to the node"); + } + + @Test + @DisplayName("every NaN an FMA answers is open, even over operands that are not NaNs, and a " + + "multiply's NaN over the same operands is not") + public void everyNaNAnFmaAnswersIsOpen() { + double inf = Double.POSITIVE_INFINITY; + var fma = new Fma(X, Y, Z); + var product = new IntArith(IntOp.MUL, Overflow.WRAP, X, Y); + // inf * 0 + 1: no operand is a NaN, and the instruction answers the host's default NaN + // where Math.fma run in Java answers the canonical one. + var row = irRow(Map.of(X, inf, Y, 0.0, Z, 1.0, fma, Double.NaN, product, Double.NaN)); + assertTrue(VarkaSameAnswer.openNaN(fma, row)); + assertFalse(VarkaSameAnswer.openNaN(product, row)); + long want = Double.doubleToRawLongBits(Double.NaN); + long got = 0xfff8000000000000L; + assertTrue(VarkaSameAnswer.sameAnswer(fma, want, got, row)); + assertFalse(VarkaSameAnswer.sameAnswer(product, want, got, row)); + // A number is never another number, nor a zero the other zero. + var zeros = irRow(Map.of(X, 0.0, Y, 1.0, Z, -0.0, fma, 0.0)); + assertFalse(VarkaSameAnswer.openNaN(fma, zeros)); + assertFalse(VarkaSameAnswer.sameAnswer(fma, Double.doubleToRawLongBits(0.0), + Double.doubleToRawLongBits(-0.0), zeros)); + } + + // ------------------------------------------------------------------------------------------- + // The harness + // ------------------------------------------------------------------------------------------- + + /** A row of the IR rule whose node values are given; a node not given is null. */ + private static VarkaSameAnswer.IrRow irRow(Map values) { + return new VarkaSameAnswer.IrRow() { + @Override public OptionalLong value(VarkaVectorIR node) { + Double v = values.get(node); + return v == null ? OptionalLong.empty() + : OptionalLong.of(Double.doubleToRawLongBits(v)); + } + + @Override public boolean holds(VarkaVectorIR.Cond cond) { + return false; + } + }; + } + + /** One kernel over three valid {@code DOUBLE} columns: each output's bits at row 0. */ + private static long[] runDouble(List roots, double[][] cols, int lanes) { + var options = VarkaMatrixRuns.BASE.withLanesOverride(lanes); + var loaded = VarkaEmitterFixtures.load(VarkaEmitterFixtures.emit(roots, 3, 0, options)); + try (Arena arena = Arena.ofConfined()) { + var in = new Col[3]; + for (int c = 0; c < 3; c++) { + double[] vs = cols[c]; + in[c] = VarkaEmitterFixtures.makeLongInput(arena, vs.length, i -> false, + i -> Double.doubleToRawLongBits(vs[i]), true); + } + var outs = new Output[roots.size()]; + for (int o = 0; o < outs.length; o++) { + outs[o] = VarkaEmitterFixtures.makeLongOutput(arena, 1); + } + int status = loaded.kernel().run(dataAddresses(in), validityAddresses(in, 1), + nullCounts(in), outputData(outs), outputValidity(outs), new int[0], new long[0], 1, + VarkaEmitterTestSupport.scratch(loaded.kernel(), 1)); + assertEquals(0, status, "no batch is declined"); + var got = new long[outs.length]; + for (int o = 0; o < outs.length; o++) { + got[o] = outs[o].data().get(ValueLayout.JAVA_LONG, 0); + } + return got; + } finally { + loaded.loader().release(); + } + } + + /** {@link #runDouble}'s twin at the {@code FLOAT} lane, the int kernel's {@code run}. */ + private static int[] runFloat(List roots, float[][] cols, int lanes) { + var options = VarkaMatrixRuns.BASE.withLanesOverride(lanes); + var loaded = VarkaEmitterFixtures.load(VarkaEmitterFixtures.emit(roots, 3, 0, options)); + try (Arena arena = Arena.ofConfined()) { + var in = new Col[3]; + for (int c = 0; c < 3; c++) { + float[] vs = cols[c]; + in[c] = VarkaEmitterFixtures.makeInputData(arena, vs.length, i -> false, + i -> Float.floatToRawIntBits(vs[i]), true); + } + var outs = new Output[roots.size()]; + for (int o = 0; o < outs.length; o++) { + outs[o] = VarkaEmitterFixtures.makeOutput(arena, 1, + VarkaEmitterFixtures.outputValidityBytes(options, 1)); + } + int status = loaded.kernel().run(dataAddresses(in), validityAddresses(in, 1), + nullCounts(in), outputData(outs), outputValidity(outs), new int[0], 1, + VarkaEmitterTestSupport.scratch(loaded.kernel(), 1)); + assertEquals(0, status, "no batch is declined"); + var got = new int[outs.length]; + for (int o = 0; o < outs.length; o++) { + got[o] = outs[o].data().get(ValueLayout.JAVA_INT, 0); + } + return got; + } finally { + loaded.loader().release(); + } + } + + /** + * Emits the outputs once at {@code lanes} lanes over three columns of {@code lane}, then runs + * every length and every per-column null pattern at both validity fills, holding each row to + * the reference: the validity exactly, and the value by {@link VarkaSameAnswer#sameAnswer}. + * A {@code FLOAT}'s literal is its bits in the low half of the long. + */ + private static void checkMatrix(List roots, long[] lits, LaneType lane, + int lanes) { + boolean isDouble = lane == LaneType.DOUBLE; + var options = VarkaMatrixRuns.BASE.withLanesOverride(lanes); + var loaded = VarkaEmitterFixtures.load( + VarkaEmitterFixtures.emit(roots, 3, lits.length, options)); + int[] intLits = new int[lits.length]; + for (int j = 0; j < lits.length; j++) { + intLits[j] = (int) lits[j]; + } + try { + for (int length : LENGTHS) { + for (IntPredicate p0 : NULL_PATTERNS) { + for (IntPredicate p1 : NULL_PATTERNS) { + for (IntPredicate p2 : NULL_PATTERNS) { + IntPredicate[] combo = {p0, p1, p2}; + String ctx = lane + " at " + lanes + " lanes, length " + length + ", nulls " + + NULL_PATTERNS.indexOf(p0) + NULL_PATTERNS.indexOf(p1) + + NULL_PATTERNS.indexOf(p2); + runCase(loaded.kernel(), roots, lits, intLits, isDouble, options, length, combo, + ctx); + } + } + } + } + } finally { + loaded.loader().release(); + } + } + + private static void runCase(VarkaFusedKernel kernel, List roots, long[] lits, + int[] intLits, boolean isDouble, VarkaEmitOptions options, int length, + IntPredicate[] combo, String ctx) { + try (Arena arena = Arena.ofConfined()) { + var cols = new Col[3]; + for (int c = 0; c < 3; c++) { + int col = c; + cols[c] = isDouble + ? VarkaEmitterFixtures.makeLongInput(arena, length, combo[c], + i -> Double.doubleToRawLongBits(operand(col, i)), true) + : VarkaEmitterFixtures.makeInputData(arena, length, combo[c], + i -> Float.floatToRawIntBits((float) operand(col, i)), true); + } + for (ValidityFill fill : ValidityFill.BOTH) { + var outs = new Output[roots.size()]; + for (int o = 0; o < outs.length; o++) { + outs[o] = isDouble ? VarkaEmitterFixtures.makeLongOutput(arena, length, fill) + : VarkaEmitterFixtures.makeOutput(arena, length, + VarkaEmitterFixtures.outputValidityBytes(options, length), fill); + } + int status = isDouble + ? kernel.run(dataAddresses(cols), validityAddresses(cols, length), nullCounts(cols), + outputData(outs), outputValidity(outs), new int[0], lits, length, + VarkaEmitterTestSupport.scratch(kernel, length)) + : kernel.run(dataAddresses(cols), validityAddresses(cols, length), nullCounts(cols), + outputData(outs), outputValidity(outs), intLits, length, + VarkaEmitterTestSupport.scratch(kernel, length)); + if (status != 0) { + fail(ctx + ": the kernel declined a batch (" + fill + ", status " + status + ")"); + } + for (int i = 0; i < length; i++) { + checkRow(roots, outs, lits, intLits, isDouble, combo, i, ctx + ", " + fill); + } + } + } + } + + private static void checkRow(List roots, Output[] outs, long[] lits, + int[] intLits, boolean isDouble, IntPredicate[] combo, int i, String ctx) { + var isNull = new boolean[3]; + var longRow = new long[3]; + var intRow = new int[3]; + for (int c = 0; c < 3; c++) { + isNull[c] = combo[c].test(i); + longRow[c] = isNull[c] ? 0L : Double.doubleToRawLongBits(operand(c, i)); + intRow[c] = isNull[c] ? 0 : Float.floatToRawIntBits((float) operand(c, i)); + } + VarkaSameAnswer.IrRow row = new VarkaSameAnswer.IrRow() { + @Override public OptionalLong value(VarkaVectorIR node) { + if (isDouble) { + return VarkaReference.longValue(node, longRow, isNull, lits); + } + OptionalInt v = VarkaReference.value(node, intRow, isNull, intLits); + return v.isPresent() ? OptionalLong.of(v.getAsInt()) : OptionalLong.empty(); + } + + @Override public boolean holds(VarkaVectorIR.Cond cond) { + return false; + } + }; + for (int o = 0; o < roots.size(); o++) { + OptionalLong want = row.value(roots.get(o)); + boolean bit = validBit(outs[o].validity(), i); + String where = ctx + ", out " + o + ", row " + i; + if (bit != want.isPresent()) { + fail(where + ": validity differs (want " + want + ")"); + } + if (want.isPresent()) { + long got = isDouble ? outs[o].data().get(ValueLayout.JAVA_LONG, i * 8L) + : outs[o].data().get(ValueLayout.JAVA_INT, i * 4L); + if (!VarkaSameAnswer.sameAnswer(roots.get(o), want.getAsLong(), got, row)) { + fail(where + ": value (want " + Long.toHexString(want.getAsLong()) + ", got " + + Long.toHexString(got) + ")"); + } + } + } + } + + private static long[] dataAddresses(Col[] cols) { + var addresses = new long[cols.length]; + for (int c = 0; c < cols.length; c++) { + addresses[c] = cols[c].data().address(); + } + return addresses; + } + + private static long[] validityAddresses(Col[] cols, int length) { + var addresses = new long[cols.length]; + for (int c = 0; c < cols.length; c++) { + addresses[c] = cols[c].validityAddress(length); + } + return addresses; + } + + private static int[] nullCounts(Col[] cols) { + var counts = new int[cols.length]; + for (int c = 0; c < cols.length; c++) { + counts[c] = cols[c].nullCount(); + } + return counts; + } + + private static long[] outputData(Output[] outs) { + var addresses = new long[outs.length]; + for (int o = 0; o < outs.length; o++) { + addresses[o] = outs[o].data().address(); + } + return addresses; + } + + private static long[] outputValidity(Output[] outs) { + var addresses = new long[outs.length]; + for (int o = 0; o < outs.length; o++) { + addresses[o] = outs[o].validity().address(); + } + return addresses; + } + + private static boolean validBit(MemorySegment validity, int i) { + return (validity.get(ValueLayout.JAVA_BYTE, i / 8L) & (1 << (i % 8))) != 0; + } +} diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaGuardSpecs.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaGuardSpecs.java index 91b10e4fb5e2..263a7cbfa074 100644 --- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaGuardSpecs.java +++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaGuardSpecs.java @@ -545,7 +545,8 @@ private static boolean fires(VarkaVectorIR node, Analysis.Refusal reason, Values case ColumnRef _, DecimalColumn _, VarkaVectorIR.DecimalWord _, LiteralSlot _, DateDiff _, IfElse _, Greatest _, Least _, DayOfWeek _, WeekDay _, DayOfWeekIso _, NextDay _, ThursdayOf _, Chrono _, ConstDivide _, - BoundedDivide _, BitOp _, BitCount _, MathUnary _, RoundToIntegral _, Cond _, CondValue _, + BoundedDivide _, BitOp _, BitCount _, MathUnary _, Fma _, RoundToIntegral _, Cond _, + CondValue _, VarkaVectorIR.NullValue _, BoolOutput _, WidenLane _, NarrowLane _, ConvertLane _, ReinterpretLane _, WidenDecimal _, CanonicalFloat _, CanonicalBits _, HashStep _ -> diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaIrGrammar.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaIrGrammar.java index 2a157b8cad0b..5e50fd79117c 100644 --- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaIrGrammar.java +++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaIrGrammar.java @@ -65,7 +65,9 @@ import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.LastDay; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.Least; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.LiteralSlot; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MathFn; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MathUnary; +import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.Fma; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.ReinterpretLane; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.RoundToIntegral; import org.apache.spark.sql.catalyst.expressions.codegen.varka.VarkaVectorIR.MakeDate; @@ -220,6 +222,14 @@ private VarkaIrGrammar() { */ public static final long CANONICAL_FUZZ_SEED = 20261120L; + /** + * The seeds of the floating arithmetic sequences ({@link #drawFloatingArithShape}): the + * floating sequences' trees with the arithmetic of VARKA-342 drawn among them, on seeds of + * their own so that {@code fuzz_float} and {@code fuzz_double} do not move (`VARKA-342.md` 5.4). + */ + public static final long FLOAT_ARITH_FUZZ_SEED = 20261122L; + public static final long DOUBLE_ARITH_FUZZ_SEED = 20261123L; + // The generator's magnitude bounds saturate rather than wrap, in *every* arm that combines // two of them - `boundsOf` and the generator alike. Four nested multiplies of a column's own // bound pass 2^63, and a bound that came back negative would let `fitsUnderChrono` admit an @@ -400,6 +410,7 @@ public static Bounds boundsOf(VarkaVectorIR node) { case BitCount n -> new Bounds(Long.SIZE, guard(n.child())); // The grammar draws no floating tree, whose values have no integer bound. case MathUnary n -> throw new IllegalArgumentException("a floating node: " + n); + case Fma n -> throw new IllegalArgumentException("a floating node: " + n); case RoundToIntegral n -> throw new IllegalArgumentException("a floating node: " + n); case CanonicalFloat n -> throw new IllegalArgumentException("a floating node: " + n); case VarkaVectorIR.CanonicalBits n -> throw new IllegalArgumentException( @@ -1552,17 +1563,30 @@ private static DrawnLong drawLaneShape(Random rnd, LaneType lane, boolean nullin * {@link FloatingShapes}, or a condition root (a filter) one time in five. */ public static DrawnLong drawFloatingLaneShape(Random rnd, LaneType lane) { - return drawFloating(rnd, lane, false); + return drawFloating(rnd, lane, false, false); + } + + /** + * Shape {@code k} of a floating arithmetic sequence, {@link #FLOAT_ARITH_FUZZ_SEED}'s at + * {@code FLOAT} and {@link #DOUBLE_ARITH_FUZZ_SEED}'s at {@code DOUBLE}: + * {@link #drawFloatingLaneShape}'s roots with {@link FloatingShapes#arithmetic} drawn too. + */ + public static DrawnLong drawFloatingArithShape(Random rnd, LaneType lane) { + return drawFloating(rnd, lane, false, true); } - /** The floating draw, a value a canonicalisation one time in four with {@code canonical}. */ - private static DrawnLong drawFloating(Random rnd, LaneType lane, boolean canonical) { + /** + * The floating draw: a value a canonicalisation one time in four with {@code canonical}, and + * row 342's arithmetic among the nodes with {@code arithmetic}. + */ + private static DrawnLong drawFloating(Random rnd, LaneType lane, boolean canonical, + boolean arithmetic) { if (!lane.isFloating()) { throw new IllegalArgumentException("not a floating lane: " + lane); } int numInputs = 1 + rnd.nextInt(3); int numLiterals = rnd.nextInt(3); - var shapes = new FloatingShapes(rnd, lane, numInputs, numLiterals, canonical); + var shapes = new FloatingShapes(rnd, lane, numInputs, numLiterals, canonical, arithmetic); int depth = 1 + rnd.nextInt(4); if (rnd.nextInt(5) == 0) { return new DrawnLong(List.of(shapes.cond(depth)), numInputs, numLiterals); @@ -1582,15 +1606,16 @@ private static DrawnLong drawFloating(Random rnd, LaneType lane, boolean canonic * {@link CanonicalFloat#of} collapses into one node. From {@link #CANONICAL_FUZZ_SEED}. */ public static DrawnLong drawCanonicalShape(Random rnd, LaneType lane) { - return drawFloating(rnd, lane, true); + return drawFloating(rnd, lane, true, false); } /** * The generator at a floating lane, over the forms the floating lanes order and choose with * (VARKA-341): the leaves, the choice, {@code greatest} and {@code least}, and the conditions - * every comparison in Spark's order and the three IEEE ones a compare against a literal is - * specialised into, {@code <=>}, the null test and the connectives. The arithmetic, the casts - * and the rounding are rows 342 to 344's, and not drawn. Nothing here can overflow or checks a + * specialised into, {@code <=>}, the null test and the connectives. With {@code arithmetic} + * set it draws row 342's nodes too ({@link #arithmetic}); the casts and the rounding are rows + * 343 and 344's, and not drawn. Nothing here can overflow or checks a * bound, so the grammar carries none: a cell or a literal is any value of the type, and the * value source's edges put NaNs of several payloads and both signs, both zeros, the * infinities, the extremes and the smallest subnormal among them. @@ -1606,19 +1631,22 @@ public static final class FloatingShapes { private final int numLiterals; /** Whether a value is a canonicalisation one time in four; off in the pinned sequences. */ private final boolean canonical; + /** Whether the sequence draws row 342's arithmetic too; off in the pinned sequences. */ + private final boolean arithmetic; private int budget = 20; FloatingShapes(Random rnd, LaneType lane, int numInputs, int numLiterals) { - this(rnd, lane, numInputs, numLiterals, false); + this(rnd, lane, numInputs, numLiterals, false, false); } FloatingShapes(Random rnd, LaneType lane, int numInputs, int numLiterals, - boolean canonical) { + boolean canonical, boolean arithmetic) { this.rnd = rnd; this.lane = lane; this.numInputs = numInputs; this.numLiterals = numLiterals; this.canonical = canonical; + this.arithmetic = arithmetic; } private VarkaVectorIR leaf() { @@ -1633,15 +1661,37 @@ VarkaVectorIR value(int depth) { return leaf(); } budget -= 1; - // The coin is drawn only with the flag, so the pinned sequences draw what they always drew. + // The coins are drawn only with their flags, so the pinned sequences draw what they always + // drew. if (canonical && rnd.nextInt(4) == 0) { return CanonicalFloat.of(value(depth - 1)); } - return switch (rnd.nextInt(5)) { + int pick = rnd.nextInt(arithmetic ? 9 : 5); + return switch (pick) { case 0 -> new Greatest(value(depth - 1), value(depth - 1)); case 1 -> new Least(value(depth - 1), value(depth - 1)); case 2, 3 -> new IfElse(cond(depth - 1), value(depth - 1), value(depth - 1)); - default -> leaf(); + case 4 -> leaf(); + default -> arithmetic(depth); + }; + } + + /** + * Row 342's nodes at the lane: {@code +}, {@code -}, {@code *} and the division, unchecked + * or nulling a zero divisor (the {@code FAIL} division declines the batch on one, which a + * draw has no reference answer for; `VarkaEmitterFloatingArithSuite` holds it), negation and + * {@code abs}, the square root and the fused multiply-add. Operands keep their order: no + * rewrite is ever valid at a floating lane. + */ + private VarkaVectorIR arithmetic(int depth) { + return switch (rnd.nextInt(6)) { + case 0, 1 -> new IntArith(List.of(IntOp.ADD, IntOp.SUB, IntOp.MUL).get(rnd.nextInt(3)), + Overflow.WRAP, value(depth - 1), value(depth - 1)); + case 2 -> new IntArith(IntOp.DIV, rnd.nextBoolean() ? Overflow.WRAP : Overflow.NULL, + value(depth - 1), value(depth - 1)); + case 3 -> new IntNeg(Overflow.WRAP, value(depth - 1), rnd.nextBoolean()); + case 4 -> new MathUnary(MathFn.SQRT, value(depth - 1)); + default -> new Fma(value(depth - 1), value(depth - 1), value(depth - 1)); }; } diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperatorCensusCatalog.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperatorCensusCatalog.java index e2ac005401d5..0c4b30e3abc5 100644 --- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperatorCensusCatalog.java +++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperatorCensusCatalog.java @@ -53,6 +53,7 @@ public static VarkaOperatorCensusCatalog named(String name) { private static final String LANE_WIDTH = "lane width"; private static final String FLOAT_COMPARES = "floating compares"; private static final String FMA = "fused multiply-add"; + private static final String FLOAT_ARITH = "floating arithmetic"; private static final String MATH = "math"; private static final String UNSIGNED = "unsigned long compares"; private static final String DEINTERLEAVE = "the de-interleave"; @@ -151,11 +152,24 @@ private static VarkaOperatorCensusCatalog between(String lane, String operator, of("float", "LT", FLOAT_COMPARES, "cmp.float", "compare", "341"), of("float", "LE", FLOAT_COMPARES, "cmp.float", "compare", "341"), of("float", "IS_NAN", FLOAT_COMPARES, "test.float", "compare", "341"), + // The floating arithmetic's six operators a lane (VARKA-342 2.5, item 0.7). + of("float", "ADD", FLOAT_ARITH, "bin.float", "binaryOp", "342"), + of("float", "SUB", FLOAT_ARITH, "bin.float", "binaryOp", "342"), + of("float", "MUL", FLOAT_ARITH, "bin.float", "binaryOp", "342"), + of("float", "DIV", FLOAT_ARITH, "bin.float", "binaryOp", "342"), + of("float", "NEG", FLOAT_ARITH, "un.float", "unaryOp", "342"), + of("float", "ABS", FLOAT_ARITH, "un.float", "unaryOp", "342"), of("float", "FMA", FMA, "fma.float", "ternaryOp", "30, 346, 366"), of("double", "EQ", FLOAT_COMPARES, "cmp.double", "compare", "341"), of("double", "LT", FLOAT_COMPARES, "cmp.double", "compare", "341"), of("double", "LE", FLOAT_COMPARES, "cmp.double", "compare", "341"), of("double", "IS_NAN", FLOAT_COMPARES, "test.double", "compare", "341"), + of("double", "ADD", FLOAT_ARITH, "bin.double", "binaryOp", "342"), + of("double", "SUB", FLOAT_ARITH, "bin.double", "binaryOp", "342"), + of("double", "MUL", FLOAT_ARITH, "bin.double", "binaryOp", "342"), + of("double", "DIV", FLOAT_ARITH, "bin.double", "binaryOp", "342"), + of("double", "NEG", FLOAT_ARITH, "un.double", "unaryOp", "342"), + of("double", "ABS", FLOAT_ARITH, "un.double", "unaryOp", "342"), of("double", "FMA", FMA, "fma.double", "ternaryOp", "30, 346, 366"), of("double", "EXP", MATH, "un.double", "libraryUnaryOp", "345, 356 to 358"), of("double", "LOG", MATH, "un.double", "libraryUnaryOp", "345, 356 to 358"), diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperatorCensusProbe.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperatorCensusProbe.java index 6a283d19711f..5e47ee786a96 100644 --- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperatorCensusProbe.java +++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaOperatorCensusProbe.java @@ -412,6 +412,12 @@ static void op_fma_double() { } } + static void op_un_float() { + for (int i = 0; i < ROWS; i += FS.length()) { + FloatVector.fromArray(FS, FA, i).lanewise(UnOp.OP).intoArray(FO, i); + } + } + static void op_un_double() { for (int i = 0; i < ROWS; i += DS.length()) { DoubleVector.fromArray(DS, DA, i).lanewise(UnOp.OP).intoArray(DO, i); @@ -1181,6 +1187,7 @@ private static void call(String loop, int calls) { case "fma.float" -> op_fma_float(); case "test.double" -> op_test_double(); case "fma.double" -> op_fma_double(); + case "un.float" -> op_un_float(); case "un.double" -> op_un_double(); case "conv.B2I" -> op_conv_B2I(); case "conv.S2I" -> op_conv_S2I(); diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaReference.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaReference.java index 3329fea71310..226ef706d68d 100644 --- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaReference.java +++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaReference.java @@ -172,6 +172,7 @@ case AddMonths(var days, var months, _) -> : -Float.intBitsToFloat(v))); case MathUnary n -> map(n.child(), row, isNull, lits, v -> Float.floatToRawIntBits(mathFloat(n.fn(), Float.intBitsToFloat(v)))); + case Fma n -> floatFma(n, row, isNull, lits); case RoundToIntegral n -> throw VarkaErrors.illegalArgument( "a rounding takes a double child, which is no int-lane value: " + n); // Spark's own normaliser, NormalizeNaNAndZero's, so the reference is not the lowering. @@ -521,6 +522,7 @@ public static OptionalLong longValue(VarkaVectorIR node, long[] row, boolean[] i yield c.isEmpty() ? c : OptionalLong.of(Double.doubleToRawLongBits( mathDouble(n.fn(), Double.longBitsToDouble(c.getAsLong())))); } + case Fma n -> doubleFma(n, row, isNull, lits); // StrictMath's rint, never the lowering's construction, so the reference stays independent // of the code it checks, and the canonical NaN for a NaN, as Spark's MathUtils.rint. case RoundToIntegral n -> { @@ -752,6 +754,34 @@ private static OptionalInt floatArithmetic(IntArith n, float a, float b) { })); } + /** + * An {@code Fma} at the {@code FLOAT} lane: {@code Math.fma}'s float form, one rounding to a + * float, never the double form narrowed. Null where any operand is. + */ + private static OptionalInt floatFma(Fma n, int[] row, boolean[] isNull, int[] lits) { + var a = value(n.a(), row, isNull, lits); + var b = value(n.b(), row, isNull, lits); + var c = value(n.c(), row, isNull, lits); + if (a.isEmpty() || b.isEmpty() || c.isEmpty()) { + return OptionalInt.empty(); + } + return OptionalInt.of(Float.floatToRawIntBits(Math.fma(Float.intBitsToFloat(a.getAsInt()), + Float.intBitsToFloat(b.getAsInt()), Float.intBitsToFloat(c.getAsInt())))); + } + + /** An {@code Fma} at the {@code DOUBLE} lane: {@code Math.fma}. Null where any operand is. */ + private static OptionalLong doubleFma(Fma n, long[] row, boolean[] isNull, long[] lits) { + var a = longValue(n.a(), row, isNull, lits); + var b = longValue(n.b(), row, isNull, lits); + var c = longValue(n.c(), row, isNull, lits); + if (a.isEmpty() || b.isEmpty() || c.isEmpty()) { + return OptionalLong.empty(); + } + return OptionalLong.of(Double.doubleToRawLongBits(Math.fma( + Double.longBitsToDouble(a.getAsLong()), Double.longBitsToDouble(b.getAsLong()), + Double.longBitsToDouble(c.getAsLong())))); + } + /** A floating {@code IntArith} at the {@code DOUBLE} lane, by {@link #floatingArith}. */ private static OptionalLong doubleArith(IntArith n, long[] row, boolean[] isNull, long[] lits) { var l = longValue(n.left(), row, isNull, lits); diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaReproductionSuite.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaReproductionSuite.java index 1c7a56634f4f..e465f2f9e7d9 100644 --- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaReproductionSuite.java +++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaReproductionSuite.java @@ -128,6 +128,9 @@ private static List theRest() { // A floating lane's square root over its IEEE division, whose zero divisor nulls a lane. new MathUnary(MathFn.SQRT, new IntArith(IntOp.DIV, Overflow.NULL, new ColumnRef(0, LaneType.DOUBLE), new LiteralSlot(0, LaneType.DOUBLE))), + // The single-rounding multiply-add over double columns and a literal (VARKA-342). + new VarkaVectorIR.Fma(new ColumnRef(0, LaneType.DOUBLE), new ColumnRef(1, LaneType.DOUBLE), + new LiteralSlot(0, LaneType.DOUBLE)), // The rint construction's node over a double column (VARKA-344). new VarkaVectorIR.RoundToIntegral(VarkaVectorIR.RoundMode.RINT, new ColumnRef(0, LaneType.DOUBLE)), diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaSmtNodes.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaSmtNodes.java index 82348d1fa30e..5d58505773a5 100644 --- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaSmtNodes.java +++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaSmtNodes.java @@ -93,6 +93,7 @@ static final class Refused extends RuntimeException { entry(ConstDivide.class, DIVISION), entry(BoundedDivide.class, DIVISION), entry(BitCount.class, "a popcount has no linear integer meaning"), entry(MathUnary.class, "a floating function: the prelude has no double as a value"), + entry(Fma.class, "a fused multiply-add: the prelude has no double as a value"), entry(RoundToIntegral.class, "a rounding of the double lane: the prelude has no double"), entry(CanonicalFloat.class, "a floating canonicalisation: the prelude has no float"), entry(CanonicalBits.class, "the bits of a floating value: the prelude has no float"), @@ -268,8 +269,8 @@ yield switch (g.mode()) { case AddDays _, SubDays _, DateDiff _, DayOfWeek _, WeekDay _, DayOfWeekIso _, NextDay _, ThursdayOf _, Year _, Month _, DayOfMonth _, Quarter _, DayOfYear _, LastDay _, TruncDate _, TruncDateDynamic _, WeekOfYear _, AddMonths _, MakeDate _, GuardedDay _, - ConstDivide _, BoundedDivide _, BitCount _, MathUnary _, RoundToIntegral _, ConvertLane _, - ReinterpretLane _, + ConstDivide _, BoundedDivide _, BitCount _, MathUnary _, Fma _, RoundToIntegral _, + ConvertLane _, ReinterpretLane _, CrossLane _, InRanges _, BoolCompare _, BoolNullSafeEq _, CanonicalFloat _, CanonicalBits _, HashStep _ -> throw refused(node); diff --git a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaWordCensus.java b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaWordCensus.java index 5aa2004d30b5..640c2f53a09c 100644 --- a/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaWordCensus.java +++ b/sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaWordCensus.java @@ -162,6 +162,8 @@ static W pure(VarkaVectorIR n, boolean coalesce, boolean absorb) { absorb); case BitCount x -> pure(x.child(), coalesce, absorb); case MathUnary x -> pure(x.child(), coalesce, absorb); + case Fma x -> andW(andW(pure(x.a(), coalesce, absorb), pure(x.b(), coalesce, absorb), + absorb), pure(x.c(), coalesce, absorb), absorb); case RoundToIntegral x -> pure(x.child(), coalesce, absorb); case CanonicalFloat x -> pure(x.child(), coalesce, absorb); case CanonicalBits x -> pure(x.child(), coalesce, absorb); diff --git a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitCostSuite.scala b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitCostSuite.scala index 2618098e1c1e..41f06a8b1b35 100644 --- a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitCostSuite.scala +++ b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitCostSuite.scala @@ -80,7 +80,7 @@ class VarkaEmitCostSuite extends VarkaEmitterTestBase with VarkaOwnJvm { // Nodes whose price waits for the next refit of the model (VARKA-352). A group holding one is // unpredictable, so the budget answers it by the weights (VarkaEmitBudget); the entry leaves // this list the day the node is priced, and fails here if it is priced while still listed. - // MathUnary exists at a floating lane only, and the floating lanes are unpriced + // MathUnary and Fma exist at a floating lane only, and the floating lanes are unpriced // (`VarkaEmitCostFit.PRICED_LANES`, VARKA-342 5.1); so is the conversion, one side of which // is always floating (VARKA-343), and the lane crossing, which joins a floating condition // to an integral one (`VARKA-343.md` 2.2.1). The canonicalisation is a floating node too @@ -89,8 +89,8 @@ class VarkaEmitCostSuite extends VarkaEmitterTestBase with VarkaOwnJvm { // too (`VARKA-345.md` 10.2). val awaitingRefit = Set("NullSafeEqual", "BoolColumn", "CondConst", "BoolCompare", "CondIf", "BoolNullSafeEq", "CondValue", "BoolOutput", "DecimalColumn", "DecimalWord", "NullValue", - "WidenDecimal", "MathUnary", "RoundToIntegral", "CanonicalFloat", "ConvertLane", "CrossLane", - "CanonicalBits", "HashStep", "ReinterpretLane", "Compare/ULT", + "WidenDecimal", "MathUnary", "Fma", "RoundToIntegral", "CanonicalFloat", "ConvertLane", + "CrossLane", "CanonicalBits", "HashStep", "ReinterpretLane", "Compare/ULT", "Compare/ULE", "Compare/UGT", "Compare/UGE") assert(awaitingRefit.forall(t => !expected.exists(f => f == t || f.startsWith(t + "/"))), s"${awaitingRefit.toSeq.sorted} is priced: take it off the list of nodes awaiting a refit") diff --git a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitterBudgetSuite.scala b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitterBudgetSuite.scala index 2a63aa4dbd58..2958799780c1 100644 --- a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitterBudgetSuite.scala +++ b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaEmitterBudgetSuite.scala @@ -378,6 +378,7 @@ class VarkaEmitterBudgetSuite extends VarkaEmitterTestBase with VarkaOwnJvm { (new MathUnary(MathFn.SQRT, dc), 1, 0, VarkaMatrix.base), // A per-lane call weighs its larger form, an extract and an insert of each of eight lanes. (new MathUnary(MathFn.SIN, dc), 1, 0, VarkaMatrix.base.withLanesOverride(8)), + (new Fma(dc, dc, dc), 1, 0, VarkaMatrix.base), (new RoundToIntegral(RoundMode.RINT, dc), 1, 0, VarkaMatrix.base), // An operand that is never a NaN, or already the canonical one, takes no NaN blend. (new RoundToIntegral(RoundMode.RINT, new ConvertLane(c, LaneType.DOUBLE)), 1, 0, diff --git a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaIrFuzzSuite.scala b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaIrFuzzSuite.scala index 19c481355978..49620b95796f 100644 --- a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaIrFuzzSuite.scala +++ b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaIrFuzzSuite.scala @@ -1207,9 +1207,9 @@ class VarkaIrFuzzSuite extends SparkFunSuite with VarkaMatrixTests with VarkaOwn // the null-lane draw below; an NTZ's null is the long lane's. // The decimal output (VARKA-157) has its own draw, on its own seed, so that no shape here // moves: the decimal-store test above runs it. - // The floating math function (VARKA-342) is out with the floating lanes: the grammar draws no - // floating tree yet, the floating sequence `VARKA-341.md` 5.1 owes, and a production is a row - // of the same refit. `VarkaEmitterFloatingArithSuite` and the coverage rows cover it. + // The floating math function and the FMA (VARKA-342) are out with the floating lanes: this + // grammar draws no floating tree; the floating arithmetic sequences draw both, on seeds of + // their own, and their reach test below holds them to it. // The canonicalisation (VARKA-337) is a floating node too: its side sequence below draws it. // The hash step and a canonical value's bits (VARKA-337) have no production yet; // `VARKA-337.md` 10 names the part that adds them, in a side sequence of their own. @@ -1221,7 +1221,7 @@ class VarkaIrFuzzSuite extends SparkFunSuite with VarkaMatrixTests with VarkaOwn val missing = permitted -- seen - "NarrowLane" - "WidenLane" - "NullSafeEqual" - "BoolColumn" - "CondConst" - "BoolCompare" - "CondIf" - "BoolNullSafeEq" - "CondValue" - "BoolOutput" - "DecimalColumn" - "DecimalWord" - "NullValue" - "WidenDecimal" - "MathUnary" - - "RoundToIntegral" - "CanonicalFloat" - "HashStep" - "CanonicalBits" - + "Fma" - "RoundToIntegral" - "CanonicalFloat" - "HashStep" - "CanonicalBits" - "ConvertLane" - "CrossLane" - "ReinterpretLane" assert(missing.isEmpty, s"the generator never built: ${missing.toSeq.sorted.mkString(", ")} - add an arm, or " + @@ -1730,6 +1730,56 @@ class VarkaIrFuzzSuite extends SparkFunSuite with VarkaMatrixTests with VarkaOwn runFloatingSequence(LaneType.DOUBLE, doubleSeed) } + // The floating arithmetic sequences (VARKA-342 3.10): the floating trees with row 342's nodes + // among them, each on a seed of its own so that the two sequences above do not move. + private val floatArithSeed = sys.props.get("varka.fuzz.seed").map(_.toLong) + .getOrElse(VarkaIrGrammar.FLOAT_ARITH_FUZZ_SEED) + private val doubleArithSeed = sys.props.get("varka.fuzz.seed").map(_.toLong) + .getOrElse(VarkaIrGrammar.DOUBLE_ARITH_FUZZ_SEED) + + test(s"random FLOAT arithmetic IR trees match the reference evaluator " + + s"(seed $floatArithSeed, $floatingIterations iterations)") { + runFloatingSequence(LaneType.FLOAT, floatArithSeed, + VarkaIrGrammar.drawFloatingArithShape, "arithmetic ") + } + + test(s"random DOUBLE arithmetic IR trees match the reference evaluator " + + s"(seed $doubleArithSeed, $floatingIterations iterations)") { + runFloatingSequence(LaneType.DOUBLE, doubleArithSeed, + VarkaIrGrammar.drawFloatingArithShape, "arithmetic ") + } + + test("the floating arithmetic sequences hold floating values alone and draw every form of " + + "row 342 they own") { + for ((lane, drawSeed) <- Seq(LaneType.FLOAT -> VarkaIrGrammar.FLOAT_ARITH_FUZZ_SEED, + LaneType.DOUBLE -> VarkaIrGrammar.DOUBLE_ARITH_FUZZ_SEED)) { + val forms = scala.collection.mutable.Set[String]() + def collect(n: VarkaVectorIR): Unit = { + n match { + case a: IntArith => forms += s"${a.op} ${a.mode}" + case x: IntNeg => forms += (if (x.abs) "abs" else "negate") + case m: MathUnary => forms += m.fn.toString + case _: Fma => forms += "fma" + case _ => + } + VarkaVectorIR.childrenOf(n).foreach(collect) + } + for (k <- 0 until 2000) { + val drawn = VarkaIrGrammar.drawFloatingArithShape( + VarkaIrGrammar.shapeRandom(drawSeed, k), lane) + for (root <- drawn.roots.asScala) { + assert(VarkaVectorIR.lanesIn(root).asScala === Set(lane), + s"$lane draw $k holds another lane: ${VarkaVectorIR.canonical(root)}") + collect(root) + } + } + val wanted = Set("ADD WRAP", "SUB WRAP", "MUL WRAP", "DIV WRAP", "DIV NULL", "negate", + "abs", "SQRT", "fma") + assert((wanted -- forms).isEmpty, + s"the $lane arithmetic sequence never drew: ${(wanted -- forms).toSeq.sorted}") + } + } + test("the floating sequences hold floating values alone and draw every form they own") { // Over the committed seeds: every value of a draw is on its lane, and the draws build each // node type and each comparison the grammar holds, the IEEE ones among them. diff --git a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaLaneTypeSuite.scala b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaLaneTypeSuite.scala index 0cbcaefb875f..1788f0bdb57c 100644 --- a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaLaneTypeSuite.scala +++ b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaLaneTypeSuite.scala @@ -120,18 +120,20 @@ class VarkaLaneTypeSuite extends SparkFunSuite with VarkaTestWatchdog { // every type: a node type added without a lane rule would otherwise go unchecked here even // though the emitter walks it. // The widening is absent: its value is on the long lane by definition, over an int child - // (VARKA-28). So is the math function, which exists at a floating lane only (VARKA-342), the + // (VARKA-28). So are the math function and the FMA, which exist at a floating lane only + // (VARKA-342), the // decimal column, an unscaled long whose constructor refuses the int lane until the int arm // of VARKA-347 2.3 is built, the decimal output, which widens a long value into a decimal // slot and refuses an int child (VARKA-157), and the conversion, one side of which is // floating (VARKA-343), as is the reinterpretation's (VARKA-345). assert(everyIntNode.map(_.getClass).toSet + classOf[WidenLane] + classOf[MathUnary] + - classOf[RoundToIntegral] + classOf[CanonicalFloat] + + classOf[Fma] + classOf[RoundToIntegral] + classOf[CanonicalFloat] + classOf[DecimalColumn] + classOf[DecimalWord] + classOf[WidenDecimal] + classOf[ConvertLane] + classOf[ReinterpretLane] === concreteNodeTypes(classOf[VarkaVectorIR]) - classOf[CrossLane]) // its child: another lane val doubleCol = new ColumnRef(0, LaneType.DOUBLE) assert(new MathUnary(MathFn.SQRT, doubleCol).laneType() === LaneType.DOUBLE) + assert(new Fma(doubleCol, doubleCol, doubleCol).laneType() === LaneType.DOUBLE) everyIntNode.foreach { node => assert(node.laneType() === LaneType.INT, s"${VarkaVectorIR.canonical(node)}") } @@ -510,6 +512,7 @@ class VarkaLaneTypeSuite extends SparkFunSuite with VarkaTestWatchdog { case "WeekOfYear" => new WeekOfYear(new ThursdayOf(c)) // A floating lane's only: refused at both integral lanes, and emitted at DOUBLE below. case "MathUnary" => new MathUnary(MathFn.SQRT, c) + case "Fma" => new Fma(c, l, c) case "RoundToIntegral" => new RoundToIntegral(RoundMode.RINT, c) case "CanonicalFloat" => CanonicalFloat.of(c) // A hash step on the lane's own primitive, and a canonical floating value's bits at the @@ -550,13 +553,18 @@ class VarkaLaneTypeSuite extends SparkFunSuite with VarkaTestWatchdog { } val atLong = buildable.filter(_._1 == LaneType.LONG).map(_._2).toSet val atInt = buildable.filter(_._1 == LaneType.INT).map(_._2).toSet - assert(atInt + "MathUnary" + "RoundToIntegral" + "CanonicalFloat" === + assert(atInt + "MathUnary" + "Fma" + "RoundToIntegral" + "CanonicalFloat" === types.map(_.getSimpleName).toSet - "DecimalColumn" - "DecimalWord", "every integral node type is emittable at INT but the decimal column and the decimal word") val sqrt = new MathUnary(MathFn.SQRT, new ColumnRef(0, LaneType.DOUBLE)) val sqrtBytes = VarkaLoopEmitter.emit("VarkaReachMathUnaryDOUBLE", java.util.List.of[VarkaVectorIR](sqrt), 1, 0, null, null, VarkaMatrix.base) assert(VarkaEmitterTestSupport.verify(sqrtBytes).isEmpty, "MathUnary at DOUBLE verifies") + val fd = new ColumnRef(0, LaneType.DOUBLE) + val fmaBytes = VarkaLoopEmitter.emit("VarkaReachFmaDOUBLE", + java.util.List.of[VarkaVectorIR](new Fma(fd, fd, new ColumnRef(1, LaneType.DOUBLE))), 2, 0, + null, null, VarkaMatrix.base) + assert(VarkaEmitterTestSupport.verify(fmaBytes).isEmpty, "Fma at DOUBLE verifies") // The subset VARKA-85.md 3.1 names, and nothing else: a calendar node at the long lane // is refused by its constructor, which is why it never reaches the emitter. assert(atLong === Set("ColumnRef", "LiteralSlot", "IntArith", "IntNeg", "Greatest", "Least", diff --git a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaRangeAnalysisSuite.scala b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaRangeAnalysisSuite.scala index 2384d7788119..1edc0100c716 100644 --- a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaRangeAnalysisSuite.scala +++ b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaRangeAnalysisSuite.scala @@ -459,6 +459,7 @@ class VarkaRangeAnalysisSuite extends SparkFunSuite with VarkaTestWatchdog { case x: BitOp => value(x.left(), Kind.INT); value(x.right(), Kind.INT) case x: BitCount => value(x.child(), Kind.INT) case x: MathUnary => value(x.child(), Kind.INT) + case x: Fma => value(x.a(), Kind.INT); value(x.b(), Kind.INT); value(x.c(), Kind.INT) case x: RoundToIntegral => value(x.child(), Kind.INT) case x: CanonicalFloat => value(x.child(), Kind.INT) case x: CanonicalBits => value(x.child(), Kind.INT) @@ -567,6 +568,7 @@ class VarkaRangeAnalysisSuite extends SparkFunSuite with VarkaTestWatchdog { case x: BitOp => go(x.left(), armed) && go(x.right(), armed) case x: BitCount => go(x.child(), armed) case x: MathUnary => go(x.child(), armed) + case x: Fma => go(x.a(), armed) && go(x.b(), armed) && go(x.c(), armed) case x: RoundToIntegral => go(x.child(), armed) case x: CanonicalFloat => go(x.child(), armed) case x: CanonicalBits => go(x.child(), armed) diff --git a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaWithChildrenSuite.scala b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaWithChildrenSuite.scala index 9bfa1de377a8..819cbd8c3ec3 100644 --- a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaWithChildrenSuite.scala +++ b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/codegen/varka/VarkaWithChildrenSuite.scala @@ -66,10 +66,9 @@ class VarkaWithChildrenSuite extends SparkFunSuite { // a committed sequence would move every shape after it and the corpora the cost model is // fitted on, so its sequence comes on a seed of its own (`VARKA-347.md` 3 item 5) and its // fold into the corpora with row 352's refit. It is rebuilt directly below. - // The floating square root (VARKA-342) is in no grammar for the same reason: the grammars - // draw no floating tree, whose values have no integer bound, and a floating draw would move - // the committed sequences. `VarkaEmitterFloatingArithSuite` holds it to the reference, and it - // is rebuilt directly below. + // The floating square root and the FMA (VARKA-342) are drawn only by the floating + // arithmetic sequences, which this test's grammars do not include: their values have no + // integer bound. Each is rebuilt directly below. // No grammar draws the floating conversion (VARKA-343) yet, for the same reason; it is // rebuilt directly below. The canonicalisation (VARKA-337) is drawn by a side sequence of its // own, which these grammars are not, and is rebuilt directly below. @@ -78,7 +77,7 @@ class VarkaWithChildrenSuite extends SparkFunSuite { // which the fdlibm ports build. val undrawn = permitted -- seen - "NullSafeEqual" - "BoolColumn" - "CondConst" - "BoolCompare" - "CondIf" - "BoolNullSafeEq" - "CondValue" - "BoolOutput" - "DecimalColumn" - - "DecimalWord" - "MathUnary" - "RoundToIntegral" - "CanonicalFloat" - "ConvertLane" - + "DecimalWord" - "MathUnary" - "Fma" - "RoundToIntegral" - "CanonicalFloat" - "ConvertLane" - "HashStep" - "CanonicalBits" - "ReinterpretLane" - "CrossLane" // the crossing is drawn from 343a5 assert(undrawn.isEmpty, s"the grammars never drew: ${undrawn.toSeq.sorted.mkString(", ")}") @@ -178,6 +177,17 @@ class VarkaWithChildrenSuite extends SparkFunSuite { intercept[IllegalArgumentException](VarkaVectorIR.withChildren(bits, other)) } + test("an FMA is rebuilt over its own three operands, in order, and refuses integral ones") { + val x = new ColumnRef(0, LaneType.DOUBLE) + val y = new ColumnRef(1, LaneType.DOUBLE) + val fma = new Fma(x, y, x) + assert(VarkaVectorIR.withChildren(fma, VarkaVectorIR.childrenOf(fma): _*) == fma) + assert(VarkaVectorIR.withChildren(fma, y, x, y) == new Fma(y, x, y)) + intercept[Exception](VarkaVectorIR.withChildren(fma, x, y)) + intercept[Exception]( + VarkaVectorIR.withChildren(fma, new ColumnRef(0), new ColumnRef(1), new ColumnRef(2))) + } + test("a floating conversion is rebuilt over its own child and keeps its target") { val i = new ColumnRef(0) val l = new ColumnRef(1, LaneType.LONG) diff --git a/sql/varka/operator_census.json b/sql/varka/operator_census.json index c62c93176041..9a4f16ae25ff 100644 --- a/sql/varka/operator_census.json +++ b/sql/varka/operator_census.json @@ -4,7 +4,7 @@ "host" : { "cpu" : "AMD Ryzen AI 9 HX PRO 370 w/ Radeon 890M", "arch" : "amd64", - "jdk" : "25.0.5.0.3+1-3-26.04.1-Ubuntu", + "jdk" : "25.0.5.1+2-1-26.04.1-Ubuntu", "use_avx" : 3, "features" : "cx8, cmov, fxsr, ht, mmx, 3dnowpref, sse, sse2, sse3, ssse3, sse4a, sse4.1, sse4.2, popcnt, lzcnt, tsc, tscinvbit, avx, avx2, aes, erms, clmul, bmi1, bmi2, adx, avx512f, avx512dq, avx512cd, avx512bw, avx512vl, sha, fma, vzeroupper, avx512_vpopcntdq, avx512_vpclmulqdq, avx512_vaes, avx512_vnni, clflush, clflushopt, clwb, avx512_vbmi2, avx512_vbmi, rdtscp, rdpid, fsrm, gfni, avx512_bitalg, f16c, pku, ospke, cet_ss, avx512_ifma" }, @@ -344,6 +344,36 @@ "bytes_per_row" : 0.0, "intrinsics" : [ "load", "convert", "fromBitsCoerced", "binaryOp", "compare", "blend", "store" ] }, + "float.ADD" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.SUB" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.MUL" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.DIV" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.NEG" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, + "float.ABS" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, "float.FMA" : { "verdict" : "I", "bytes_per_row" : 0.0, @@ -373,6 +403,36 @@ "intrinsics" : [ "load", "convert", "fromBitsCoerced", "binaryOp", "compare", "blend", "store" ], "failed" : [ "compare", "convert", "blend" ] }, + "double.ADD" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.SUB" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.MUL" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.DIV" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.NEG" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, + "double.ABS" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, "double.FMA" : { "verdict" : "I", "bytes_per_row" : 0.0, @@ -1066,6 +1126,36 @@ "bytes_per_row" : 0.0, "intrinsics" : [ "load", "convert", "fromBitsCoerced", "binaryOp", "compare", "blend", "store" ] }, + "float.ADD" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.SUB" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.MUL" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.DIV" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.NEG" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, + "float.ABS" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, "float.FMA" : { "verdict" : "I", "bytes_per_row" : 0.0, @@ -1091,6 +1181,36 @@ "bytes_per_row" : 0.0, "intrinsics" : [ "load", "convert", "fromBitsCoerced", "binaryOp", "compare", "blend", "store" ] }, + "double.ADD" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.SUB" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.MUL" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.DIV" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.NEG" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, + "double.ABS" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, "double.FMA" : { "verdict" : "I", "bytes_per_row" : 0.0, @@ -1761,6 +1881,36 @@ "bytes_per_row" : 0.0, "intrinsics" : [ "load", "convert", "fromBitsCoerced", "binaryOp", "compare", "blend", "store" ] }, + "float.ADD" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.SUB" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.MUL" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.DIV" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "float.NEG" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, + "float.ABS" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, "float.FMA" : { "verdict" : "I", "bytes_per_row" : 0.0, @@ -1786,6 +1936,36 @@ "bytes_per_row" : 0.0, "intrinsics" : [ "load", "convert", "fromBitsCoerced", "binaryOp", "compare", "blend", "store" ] }, + "double.ADD" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.SUB" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.MUL" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.DIV" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "binaryOp", "store" ] + }, + "double.NEG" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, + "double.ABS" : { + "verdict" : "I", + "bytes_per_row" : 0.0, + "intrinsics" : [ "load", "unaryOp", "store" ] + }, "double.FMA" : { "verdict" : "I", "bytes_per_row" : 0.0, diff --git a/sql/varka/plans/m8/PLAN.md b/sql/varka/plans/m8/PLAN.md index 1dfbeeab3a0e..658c52fa43b3 100644 --- a/sql/varka/plans/m8/PLAN.md +++ b/sql/varka/plans/m8/PLAN.md @@ -1142,7 +1142,7 @@ catalogue keep theirs. Sizes are the house's small, medium and large. | 339 | **Started** (step 1 merged, the baseline class `VarkaTimestampNtzArithmeticBaselineBenchmark` with its results files at 256 and 128 bits from the runner; step 2 built, `VARKA-339.md` 5: `ntz - ntz`, `ntz + dt` and `ntz - dt` fuse as the checked long subtract and add, the negated interval guarded off `Long.MIN_VALUE`, with five coverage rows of a family of their own; `add_months` runs in a kernel of both lanes in the mixed-lane suite and the mixed corpus is held to drawing it; the conformance suite runs NTZ's own overflow forms, and the census marks `ntz_minus_ntz`, `ntz_plus_dt` and `datetime_sub` fused for NTZ, and both NTZ baselines list the chain and the interval column sum as fusing, as `VARKA-339.md` 5 asks of each step; left: steps 3 to 5). **Planned** (`VARKA-339.md`, 27 October 2026; the admission check: every form is UTC long arithmetic with no evaluation mode, `ntz - ntz` and `ntz + dt` being `subtractExact` and `addExact`, so each lowers to a checked long add or subtract the emitter already has; the month forms reuse `AddMonths` over the NTZ day under the calendar's day guard, which bounds the result so that 2.6's `+-106,751,991` guard is live only for `timestampadd`'s DAY and WEEK; an hour does not split as the day does, so `time_bucket` is exact over the long range for a width that divides a day or is whole days and guarded to a window otherwise, with the next bucket's overflow guarded for a width of a day or more; the conformance suite exempts NTZ from its arithmetic rather than cancelling it, so the row adds NTZ's own forms; the committed baseline times only the subtraction and interval chain and no longer runs since 338, so a baseline for the rest comes first; four open questions). `TIMESTAMP_NTZ` arithmetic: `ntz - ntz`, `ntz +/- dt`, `ntz +/- ym`, `timestampadd`, `time_bucket`, checked, with 2.6's edges: the day guarded at `+-106,751,991` then a checked add, day -106,751,992 declined whole, `dt != Long.MIN_VALUE` and `months != Integer.MIN_VALUE` guarded, `time_bucket`'s next-bucket overflow, `timestampadd`'s month units in int. *30 October 2026, from row 103's plan (`VARKA-103.md` 0 item 14):* `java.time.Duration` is no oracle for a negative interval. It keeps floor seconds and a non-negative nano part, so at `x = -D + 1` microseconds `toDays()` is -1 where Spark's `x / D` is 0, and the hour, minute and second parts differ as often; a negative day-time value is held to Spark's row engine and `BigInteger`, `java.time` serving only the edges where `Duration.plus` and `multipliedBy` raise. **Done when** each fuses, the overflowing lane declining to the row engine's error, the calendar forms proven against `java.time` over the sweep the date family uses | item 31 | medium | | 340 | **Started** (*20 November 2026:* 3.4's opt-in sweep built (`VARKA-340.md` 10.3): every field's kernel over every day `ntzDay` admits at three times of day, and the open fields over every second of 97 sampled days and the long's ends, against `java.time`, listed in `sweeps.tsv`; left: step 6, the measurement, which the runners owe; step 1, the baseline class `VarkaTimestampNtzFieldsBaselineBenchmark`, merged as #1261 and #1290 on 2 November 2026, built over `year`, `weekofyear`, `hour`, the casts to and from `TIME`, `CAST(ntz AS TIME(3))` and `make_timestamp_ntz`, fourteen sections, none fusing, its results files at 256 and 128 bits committed from the runner; steps 2 to 4 built and merged as #1397 on 8 November 2026 (the helpers `microsOfDay` and `ntzDay`, the date fields of an NTZ value over the guarded date, the weekday forms over the unguarded cast, `hour`, `minute`, `second` and `CAST(ntz AS TIME(p))` over the nanosecond of the day, with the remainder's proof, the edge and java.time tests and the census); step 5 built and merged as #1434 on 10 November 2026 (`make_timestamp_ntz(date, time)` as the day's midnight plus the time's microseconds under a checked add, the date column guarded and a date literal checked at compile time, and so `CAST(time AS TIMESTAMP_NTZ)` once the optimizer rewrites it, with the date-pinning test); then left: step 6 and the sweep of 3.4 in `VARKA-340.md` 3, the sweep since built). **Planned** (`VARKA-340.md`, 27 October 2026; the admission check: every field is total over the long at UTC, so a form fuses or declines a batch and never raises, except `make_timestamp_ntz`, which is `d * D + nanos / 1000` raising past the long, its nanoseconds truncated; the day division and its proof are 338's, already in the long-lane divisor list, and the Granlund-Montgomery form needs a 64-bit high multiply the Vector API lacks, so its constants are recorded and the arm is not built; the calendar guard is a `GuardedRange` from 1 March -12799 to 15 August 33134 under the calendar consumers only, not 339's `GuardedDay`, whose floor the week forms' Thursday shift and `trunc`'s year leave; the time fields are the `TIME` lowerings over the nanosecond of the day; `SECOND`'s decimal waits on row 157's store and row 351's arm, the rest landing before them; `TIME` to NTZ is claimed only as the rewritten `makeTimestampNTZ`, its date a literal slot outside the shape key; independent of 339's code, the first of the two to land building the shared helpers; a baseline first; no open questions, the row text settling both). *25 October 2026 (`VARKA-338.md` 0):* 338 builds the full-range floor division and its proof for the `DATE` cast, and this row reuses it; the date fields reach it as `Year(CAST(ntz AS DATE))` and decline until this row bounds the cast's day. `TIMESTAMP_NTZ` decomposition: the date fields through the exact full-range floor division of 2.6 (`>> 13`, then by 10,546,875) into the int32 prefix, declining outside the prefix's years; `hour`, `minute`, `second`, `extract` over it (`SECOND` a `DECIMAL(8, 6)`, with 351); the casts with `TIME` - to `TIMESTAMP_NTZ` by the one arm that also serves `make_timestamp_ntz(date, time)`, the query's date a per-query constant. *30 October 2026, from row 103's plan (`VARKA-103.md` 0 item 14):* `java.time.Duration` is no oracle for a negative interval. It keeps floor seconds and a non-negative nano part, so at `x = -D + 1` microseconds `toDays()` is -1 where Spark's `x / D` is 0, and the hour, minute and second parts differ as often; a negative day-time value is held to Spark's row engine and `BigInteger`, `java.time` serving only the edges where `Duration.plus` and `multipliedBy` raise. **Done when** each fuses, the date-pinning test of 2.6 passes with half the batches on the fallback, `Long.MIN_VALUE` and `Long.MAX_VALUE` pinned through the fallback, and the division proven by SMT over the whole long range in the long-lane proof file's divisor list (not `ChronoDivide`'s int-lane table), its magic constants recorded | item 31; `m5/PLAN.md` 2.6 for the long-lane division | medium | | 341 | **Started** (steps 2 to 4 built and merged as #1049, #1054 and #1065 on 27 and 28 October 2026, `VARKA-341.md` 5.1: the lane split; `FLOAT` and `DOUBLE` read and written at their own lanes; comparisons, `<=>`, `greatest`, `least`, `IN`, `isnan` and `nanvl` in Spark's order, with 40 coverage rows, the reference evaluator and the Spark oracle over bits, and the `Float` and `Double` conformance suites, and the floating lanes' warm-up blocks; the literal-specialised compares with their table rows and the fuzz grammar's floating sequences built on 9 November 2026 (`VARKA-341.md` 10), after a baseline of the literal compare in its own pull request; left: the runner measurement of the specialised compares against that baseline, the mask crossing between the kinds having closed in rows 343a3 and 343a3b (#1328, #1338); the 128-bit double refusals are recorded in `width_audit.json`). **Planned** (`VARKA-341.md`, 26 October 2026; the admission check: `LaneType` is a width ordered for widening and `Lane` integral throughout, so the split is `LaneType`'s kind and a `Lane.Integral` record; a double mask beside a long one has the same lane count, the case JDK 25's C2 miscompiles through a word, so it crosses by `VectorMask.cast`; no Varka node sees `NormalizeNaNAndZero`, so the canonicalisation node moves to 337, its first reader; `DOUBLE` beside the 64-bit integral lane and `FLOAT` beside the 32-bit one, the other mixes left to 343; after row 377's floating baseline). The floating lanes: `Lane` split into integral and floating halves, `DOUBLE` and `FLOAT` lane types, `Float8Vector` and `Float4Vector` read and written, comparisons, choice and `IN` by Spark's NaN and `-0.0` rules, `isnan`, `nanvl`, the canonicalisation node shared with `NormalizeNaNAndZero` and 337, and the NaN rule of `SCOPE_STANDARD_MODE.md` 3.5 in the oracles and the fuzzers. **Done when** item 89 bullet 1's table test, extended to NaN payload bits and the tie cells of 2.7, passes for every operator and its constant-specialised forms, the bytes oracle unchanged for every integral shape Census reading (`VARKA-376.md` 9, 20 October 2026, laptop): the float compares and `IS_NAN` are intrinsic and allocation-free at every width; the double ones are intrinsic at 512 and 256 bits and at 128 bits, two lanes, x86 C2 lowers no two-lane mask (`m7` row 374), so at the forced 128-bit species the operator is the Vector API's Java fallback loop, and the 128-bit companion records it as such. *Added 1 November 2026, from `READING_COMET.md`: a test that runs `greatest(a, b)` and `greatest(b, a)`, and the same pair for `least`, in one projection over `-0.0` and `0.0`, with whole-stage codegen on and off, since Spark treats the two as one expression under codegen; Varka's suite ran them only in separate queries.* | items 35, 89 | large | -| 342 | **Started** (step 1 built, merged as #1228 on 31 October 2026, `VARKA-342.md` 5: the row path's baseline, `VarkaFloatingArithmeticBaselineBenchmark`, over the division in LEGACY and ANSI, `try_divide`, `sqrt(abs(x))`, `-x`, `signum`, `degrees` and the two interval forms, with and without nulls, its results from the EPYC runners at both widths, committed before merge and not yet run; the baselines' fuse check per section against each class's list of the sections a row has fused, `VarkaFloatingBaselineBenchmark`'s comparison and choice listed, `-Dvarka.baseline.fuseCheck=false` lifting it for the measurement; step 3 built, merged as #1248 on 1 November 2026, `VARKA-342.md` 5.1: `+`, `-`, `*`, negation and `abs` over `DOUBLE` and `FLOAT`, and `/`, `try_divide`, `sqrt`, `signum`, `degrees` and `radians` over `DOUBLE`, fuse in every mode in a new floating arithmetic family; `IntArith` and `IntNeg` at the floating lanes with an `IntOp.DIV` whose mode is the zero divisor's disposal, null under LEGACY and TRY and a declined batch under ANSI with its own refusal bit, and a `MathUnary` node for `sqrt`; `signum` built with `x` as its last arm so a null answers null; 26 coverage rows, the reference evaluator, the cells against Spark in the three modes, every `FLOAT` pattern through negation and `abs`, and the binary `FLOAT` sweeps behind `-Dvarka.sweep=true`; the two floating baselines list the sections it fuses, every `DOUBLE` section and the chains; step 4's first piece built 8 November 2026, `VARKA-342.md` 5.2: the division and the functions over a cast to double already fuse over 343's conversions, recorded as the coverage family "Floating arithmetic over other types" (`y1 / i`, `f / f2`, `sqrt(i)`, `signum(f)` and their kin, a `BIGINT` operand declining below AVX512DQ); `signum` over both interval types fuses as `(double) ((m > 0) - (m < 0))` over `CondValue`s, null for a null count and needing no `L2D`; `fp_half_up.smt2` proves 2.4's rounding and guards against Guava under both solvers ahead of its lowering; the four interval products and quotients wait for 343b2's conversions to an integral lane, and their decline says so; left: the census cells (step 2), those four forms after 343b2 (step 4's second piece), the fuzz grammar's floating sequence, the cost model's `DIV` and `SQRT` prices and the measurement). **Planned** (`VARKA-342.md`, 27 October 2026; the admission check: `+`, `-`, `*`, negation, `abs`, `sqrt`, `degrees` and `radians` have one answer in every mode, the IEEE operation `java.lang.Math` computes, and C2 contracts no vector multiply and add, so each is bit-exact by construction; `/` is `DivModLike`, null under LEGACY and TRY (`try_divide` is LEGACY's) and raised under ANSI on a `-0.0` divisor too, unless the dividend is null; `Divide` and the functions take `DOUBLE` only, so `i / j`, `f / g` and the functions over another type arrive under casts to double and fuse once 343's conversions land, as do the interval forms, whose HALF_UP is built from 343's truncation and a half-step test, not 344's `rint`; the arithmetic reuses `IntArith` and `IntNeg` at the floating lanes, with an `IntOp.DIV` whose mode is the zero divisor's disposal, and `sqrt` opens a `MathUnary` node; `signum` tests zero and NaN before the sign, Spark's order putting NaN above every number; of this row's forms, the committed baseline times only the chain `(x + y) * z - x`, so a baseline of the other forms comes first). Floating arithmetic and the exact functions: `+`, `-`, `*`, `/` (a zero divisor null or raised, Spark the ANSI oracle; an int division through its casts; never a reciprocal), negation, `abs`, `signum`, `sqrt`, `degrees`, `radians`, `try_divide`, the interval products and quotients by a floating factor, with 2.7's signed-zero and special cells. *30 October 2026, from row 103's plan (`VARKA-103.md` 0 item 13, 8 point 2):* 3.7's pinned cells for the interval forms hold the ties and the guard's ends but not the long form's `2^53` and long-edge cells of the double factor: `(2^53 + 1) * 0.5`, where the long is rounded to a double before the multiply, `+-(2^53 - 1) * 0.5`, and `MAX * 1.0`, `(MAX - 511) * 1.0` and `MIN * -1.0` raising against `(MAX - 512) * 1.0`, `MAX * -1.0` and `MIN * 1.0`, which fit, with Guava's answers (**[A, 7]** of `results/VARKA-103-admission.txt`). This row's 2.4 cells gain them, so the lowering is pinned where it lands; row 103 keeps them as its named tests over it in 103d. **Done when** each fuses, bit-identical to the row engine over sampled regions and the fuzzer | item 35 | medium | +| 342 | **Started** (*20 November 2026*, `VARKA-342.md` 5.3: the `Fma(a, b, c)` node row 346's remainder and round-to-odd need built locally as its own part, `varka-342-floating-arith`, at both floating lanes, its NaN open wherever it answers one, with `VarkaEmitterFmaSuite` passing; and on part `varka-342b-floating-fuzz` stacked on it (5.4), the IR fuzz grammar's floating arithmetic sequences, two seeds of their own, 300 of 300 draws a lane answered; and on part `varka-342c-census` after it (5.5), step 2's twelve operator census cells, all intrinsic at 128, 256 and 512 bits on the laptop; left on the three: the registry suites, the emitted bytes, the runners' census and review; left of the row: the four interval forms after 343b2, the cost model's `DIV` and `SQRT` prices, the `--asm` check of 3.2, and the measurement on the runners; step 1 built, merged as #1228 on 31 October 2026, `VARKA-342.md` 5: the row path's baseline, `VarkaFloatingArithmeticBaselineBenchmark`, over the division in LEGACY and ANSI, `try_divide`, `sqrt(abs(x))`, `-x`, `signum`, `degrees` and the two interval forms, with and without nulls, its results from the EPYC runners at both widths, committed before merge and not yet run; the baselines' fuse check per section against each class's list of the sections a row has fused, `VarkaFloatingBaselineBenchmark`'s comparison and choice listed, `-Dvarka.baseline.fuseCheck=false` lifting it for the measurement; step 3 built, merged as #1248 on 1 November 2026, `VARKA-342.md` 5.1: `+`, `-`, `*`, negation and `abs` over `DOUBLE` and `FLOAT`, and `/`, `try_divide`, `sqrt`, `signum`, `degrees` and `radians` over `DOUBLE`, fuse in every mode in a new floating arithmetic family; `IntArith` and `IntNeg` at the floating lanes with an `IntOp.DIV` whose mode is the zero divisor's disposal, null under LEGACY and TRY and a declined batch under ANSI with its own refusal bit, and a `MathUnary` node for `sqrt`; `signum` built with `x` as its last arm so a null answers null; 26 coverage rows, the reference evaluator, the cells against Spark in the three modes, every `FLOAT` pattern through negation and `abs`, and the binary `FLOAT` sweeps behind `-Dvarka.sweep=true`; the two floating baselines list the sections it fuses, every `DOUBLE` section and the chains; step 4's first piece built 8 November 2026, `VARKA-342.md` 5.2: the division and the functions over a cast to double already fuse over 343's conversions, recorded as the coverage family "Floating arithmetic over other types" (`y1 / i`, `f / f2`, `sqrt(i)`, `signum(f)` and their kin, a `BIGINT` operand declining below AVX512DQ); `signum` over both interval types fuses as `(double) ((m > 0) - (m < 0))` over `CondValue`s, null for a null count and needing no `L2D`; `fp_half_up.smt2` proves 2.4's rounding and guards against Guava under both solvers ahead of its lowering; the four interval products and quotients wait for 343b2's conversions to an integral lane, and their decline says so; left: the census cells (step 2), those four forms after 343b2 (step 4's second piece), the fuzz grammar's floating sequence, the cost model's `DIV` and `SQRT` prices and the measurement). **Planned** (`VARKA-342.md`, 27 October 2026; the admission check: `+`, `-`, `*`, negation, `abs`, `sqrt`, `degrees` and `radians` have one answer in every mode, the IEEE operation `java.lang.Math` computes, and C2 contracts no vector multiply and add, so each is bit-exact by construction; `/` is `DivModLike`, null under LEGACY and TRY (`try_divide` is LEGACY's) and raised under ANSI on a `-0.0` divisor too, unless the dividend is null; `Divide` and the functions take `DOUBLE` only, so `i / j`, `f / g` and the functions over another type arrive under casts to double and fuse once 343's conversions land, as do the interval forms, whose HALF_UP is built from 343's truncation and a half-step test, not 344's `rint`; the arithmetic reuses `IntArith` and `IntNeg` at the floating lanes, with an `IntOp.DIV` whose mode is the zero divisor's disposal, and `sqrt` opens a `MathUnary` node; `signum` tests zero and NaN before the sign, Spark's order putting NaN above every number; of this row's forms, the committed baseline times only the chain `(x + y) * z - x`, so a baseline of the other forms comes first). Floating arithmetic and the exact functions: `+`, `-`, `*`, `/` (a zero divisor null or raised, Spark the ANSI oracle; an int division through its casts; never a reciprocal), negation, `abs`, `signum`, `sqrt`, `degrees`, `radians`, `try_divide`, the interval products and quotients by a floating factor, with 2.7's signed-zero and special cells. *30 October 2026, from row 103's plan (`VARKA-103.md` 0 item 13, 8 point 2):* 3.7's pinned cells for the interval forms hold the ties and the guard's ends but not the long form's `2^53` and long-edge cells of the double factor: `(2^53 + 1) * 0.5`, where the long is rounded to a double before the multiply, `+-(2^53 - 1) * 0.5`, and `MAX * 1.0`, `(MAX - 511) * 1.0` and `MIN * -1.0` raising against `(MAX - 512) * 1.0`, `MAX * -1.0` and `MIN * 1.0`, which fit, with Guava's answers (**[A, 7]** of `results/VARKA-103-admission.txt`). This row's 2.4 cells gain them, so the lowering is pinned where it lands; row 103 keeps them as its named tests over it in 103d. **Done when** each fuses, bit-identical to the row engine over sampled regions and the fuzzer | item 35 | medium | | 343 | **Started** (*3 November 2026*: split into nine pull requests of at most 1000 changed lines, 343a1 to 343a5 cut from #1303, 343a3b for the root-level crossing after 343a3, and 343b1 to 343b3 after them, `VARKA-343.md` 4; 343b1, built 8 November 2026 (`VARKA-343.md` 10): `BIGINT` to `DOUBLE` and `FLOAT` fuse below emit level 3 by exact AVX2 forms, the split for `L2D` (the bounded magic its `wideConversionForm` arm) and rounding to odd without a mask for `L2F`, proven over every long in `round_to_odd.smt2`, the split-and-add form kept as the named failing case, and the unknown level still declining; 343a1 and 343a2, merged as #1311 and #1317 on 3 November 2026; 343a3b, merged as #1338 on 4 November 2026, `VARKA-343.md` 10: conditions of two kinds meet in one kernel by a lane crossing, a filter's floating conjunct beside an integral one fuses, roots of one width share a kernel, and the long-literal check plans under the session's options; 343a5, built 6 November 2026 on 343a4 (`VARKA-343.md` 10): the fuzz grammar's conversions and crossings, the 2^32 sweeps of `INT` to `FLOAT` and `DOUBLE` and of `FLOAT` to `DOUBLE` and `BOOLEAN`, and the false-AND forms of `CAST(y1 AS DOUBLE)` and `CAST(s1 AS DOUBLE)` freed by admitting a narrow column's null test under a double kernel; 343a4, built 6 November 2026 (`VARKA-343.md` 10): `BIGINT` to `FLOAT` and `DOUBLE` fuse where the emit level assures AVX512DQ, level 3 from an x86 host that has it, and the unknown level declines them; 343a3, merged as #1328 on 4 November 2026, `VARKA-343.md` 10: kernels of two lane counts, `INT`, the narrow types and `BOOLEAN` to both floating types and `FLOAT` with `DOUBLE`, the same-count mask crossing `VARKA-341.md` 5.1 left owed, and the three failures of #1303's last option matrix fixed; step 1 built, merged as #1242 on 1 November 2026, `VARKA-343.md` 5: the row path's baseline, `VarkaFloatingCastBaselineBenchmark`, over `BIGINT` to `FLOAT` and `DOUBLE`, `INT` to `DOUBLE`, `DOUBLE` to `INT` in LEGACY past the int range and with NaN and the infinities and in ANSI, `try_cast` to `BIGINT` with one row in a hundred past the long range, `DOUBLE` to `FLOAT`, `DOUBLE` to `BOOLEAN` as a filter under `coalesce` and `time_from_seconds`, with and without nulls, its results from the EPYC runners at both widths, committed before merge and not yet run; its fuse check per section is row 342's baseline's, which `VarkaFloatingBaselineBenchmark` already has; no section listed as fusing, the `coalesce` keeping the optimizer from inferring an `IS NOT NULL` that would fuse under Spark's `Filter` while the cast declines). **Planned** (`VARKA-343.md`, 27 October 2026; the admission check: every floating cast declines by name and 26 pairs of `m8/casts.tsv` are this row's; no node converts between the kinds and no kernel holds two lane counts across them, so the row adds one conversion node and turns the kernel plan's lane rules into width rules; `GuardedRange` only declines, so TRY's nulls need a null disposal, which row 332 shares; C2's `L2F` on aarch64 rounds once, so round-to-odd is the AVX2 form only; the magic number rounds where the cast truncates, so the AVX2 `D2L` truncates first; on AVX2 an exact split for `L2D` and an exponent assembly for `D2L` cover the whole range, against the row's bounded form as an option arm; `time_from_seconds` needs row 342's floating multiply; the committed baseline times two of the pairs, so a baseline for the rest comes first; large, against the medium first set, and in two pull requests after the baseline, the conversions to a floating type first; two open questions). The floating casts: integral to floating (rounding as the JVM does; `BIGINT` to `FLOAT` rounded once, by round-to-odd on AVX2 and NEON), `FLOAT` and `DOUBLE` to each other, floating to integral (LEGACY's saturation with no detection, ANSI's two range compares and NaN, TRY's nulls, the mapping table of 2.7 with its boundary cells; `D2L` and its kin under AVX512DQ, the magic-number form below `2^51` on AVX2, the host named), to and from `BOOLEAN`, `time_from_seconds` over a double. **Done when** every such pair of `m8/casts.tsv` fuses in the three modes, a `FLOAT` source proven over all 2^32 bit patterns, the round-to-odd truncation stated as an SMT bit-vector claim and exhausted through `binary16`, and a split-and-add conversion kept as a named failing case (it misrounds 16.5% of random unsigned 32-bit inputs above `2^31`; 4275361147 gives 4275361280 against 4275361024, `READING_0X80.md`) | this plan, 2.2 | large | | 344 | **Started** (step 1 built, merged as #1257 on 2 November 2026, `VARKA-344.md` 5: the row path's baseline, `VarkaRoundingBaselineBenchmark`, over `rint(x)` in the session's default mode, `floor(x)`, `ceil(x)`, `floor(i)`, `round(i, -2)`, `bround(i, -2)` and `truncate(l, -3)` each in LEGACY and ANSI, `round(l, -3)` in ANSI, `factorial` over `[-2, 22]` and `width_bucket` with literal bounds, with and without nulls, `x` inside `2^51` so that 344b's `MAGIC` arm declines no batch, and `floor` and `ceil` under LEGACY over a wide column `xw` (one row in four wide, mostly past `2^51` and half of those past the long range, with NaN and infinities), on which every batch declines, added by the owner's word on 1 November 2026, and under ANSI over `xwf`, the same wide share inside `2^62.2` with NaN and no infinity, so no ANSI section raises, 40 sections, its results from the EPYC runners at both widths committed on 5 November 2026, merged as #1350 (benchmark runs 41939401101 at 256 bits and 41939588739 at 128 bits, on master 50b4fe96125); under the shared fuse check, no section listed as fusing; 344a1 built 7 November 2026, `VARKA-344.md` 10: `rint` over a double fuses in every mode as a new `RoundToIntegral` node, the `2^52` construction with the sign restored and one blend under `|x| < 2^52`, proven equal to `fp.roundToIntegral RNE` at binary32 and binary64 in `fp_round.smt2`, and `floor`, `ceil` and `ceiling` over a `BIGINT` (the operand) and over an `INT` (its widening) fuse in a new rounding family; 344a2 built 8 November 2026: `round`, `bround` and `truncate` over `TINYINT`, `SMALLINT` and `INT` at a constant scale fuse as the signed remainder of the truncating quotient by `10^k` on the int lane, ANSI's overflowing tails declined by a guard bisected over `BigDecimal`, proven in `int_round.smt2`, and `BIGINT` at a scale of 0 or more as the operand; split by the cap, so left: 344a3, `BIGINT` at a negative scale with the pre-shift, then 344b and 344c, the `rint(-NaN)` probe on the runners and the measurement against the baseline). **Planned** (`VARKA-344.md`, 30 October 2026; the admission check: no rounding operator is reachable from the Vector API on any host - `RoundDoubleModeV` is made only by SuperWord from the scalar intrinsics - so the `2^52` construction is the form everywhere, with its sign restored on the long view since the bitwise operators refuse a floating lane; every form is exact, so none is under the ULP contract, and question 2 concerns a contracted child under them, a check for 345; ANSI `floor` and `ceil` raise at `2^63`, where the ANSI cast passes it, and pass NaN to 0, so the guard reads the operand with NaN blended to `0.0`; on AVX2 the whole-range form over 343's exponent assembly is the default and the fused magic form, declining above `2^51`, the `wideConversionForm` reference arm, by 343's answered question 1; the integral rounding is the signed remainder of `ConstDivide`'s truncating quotient, its ANSI overflow two compile-time tails under a guard since a checked multiply is refused, `BIGINT` taking 2.8's pre-shift for `k >= 12` and declining beyond a guard below, the full range being row 360's widening multiply by a constant; `floor(i)` over an `INT` is the operand widened, without 343, the narrow types waiting for row 332's narrow load in a `BIGINT` kernel; a baseline first; large, in three pull requests by dependency: 344a after 341, 344b after 343b, 344c after 342 and 343; three open points for the lead). The rounding functions: `floor`, `ceil`, `rint` over a double by the `2^52` construction with its conditions written out (2.7), `floor` and `ceil` to `BIGINT` (on AVX2 through `rint`, the correction and the magic conversion, declining above `2^51`), `round`, `bround` (the Lemire, Bartlett and Kaser section 7 form) and `truncate` over integral types, `factorial`, `width_bucket`, the `rint(-NaN)` probe. **Done when** each fuses, the double forms checked over every boundary region, `rint(-0.3)` giving `-0.0`, and the integral ones by exhaustion at 32 bits | items 35, 36 | medium | | 345 | **Started** (*21 November 2026*: 345b1 built on 345a2, `VARKA-345.md` 10.2: the `PORT` frame, the bit-view node `ReinterpretLane` and `VarkaMathPort`'s word helpers, each held to its definition on the raw bits; 345b2 on it (`VARKA-345.md` 10.2): `exp` on the frame, bit for bit `StrictMath.exp` and `VFdlibm.exp`, the auto chain cap of a tree holding a port, and `vfdlibm` 0.1.0 as the test-scope oracle; step 1 merged as #1414 on 9 November 2026, `VARKA-345.md` 4 and 5: the row path's baseline, `VarkaMathBaselineBenchmark`, over `sin(x)`, `tan(x)`, `cbrt(x)`, `exp(x)`, `log(p)`, `log10(p)`, `pow(p, y)`, `atan2(y, x)`, `sinh(x)`, `hypot(x, y)`, `sec(x)` and `exp(x) * 2 + 1`, with and without nulls, `x` and `y` in `[-10, 10)` and `p` positive in `[1e-6, 1e6)` so the logarithms and `pow` take their ordinary path, 24 sections, its results from the EPYC runners at both widths, runs 42527097690 and 42537748319; under the shared fuse check, no section listed as fusing; *9 November 2026*: part 345a1 built, `VARKA-345.md` 10: the configuration, off by default, its emit option `mathUlpContract` of the new reason `CONTRACT`, the math family with every function declining by its row, `VarkaMathBound`, the docs entry and the dated corrections, merged as #1428; *21 November 2026*: 345a2 on it, the binding, the contract table and the coverage column, merged with master, the trigonometric rows of #1567 now naming their exact forms, merged as #1604). **Planned** (`VARKA-345.md`, 30 October 2026, reworked the same day after the owner's and the lead's settlements; the admission check: Spark calls `StrictMath` for `exp`, `expm1`, `log`, `log10`, `log1p`, `pow` and the two-argument `log`, and `Math` for the rest, of which `asin`, `acos`, `atan`, `atan2`, `sinh`, `cosh` and `hypot` are fdlibm on every host and `sin`, `cos`, `tan`, `tanh` and `cbrt` the host's stub, called alike by the interpreter, C1 and C2, so a per-lane call in a kernel is exact and costs the scalar call; a lane-wise copy of fdlibm's `exp` matched `StrictMath.exp` on every one of 16777216 sampled inputs and 3640 fixed vectors at both widths, while its laptop timing is provisional and says nothing about fdlibm in lanes: why it was not faster is unexplained; the timed runs forced inlining by CompileCommand, a run without it showed the 601-bytecode method refused ("hot method too big") at three call sites, so whether boxing explains the timing is not established; the IR-emitted port's run decides; the JDK's `FdLibm.java` and HotSpot's x86 stubs are GPLv2, so a port is written from Sun's fdlibm 5.3 C sources, fetched only with the owner's yes, and the JDK file is the test oracle only; outside C2 a Vector API math operator is `Math.` per lane, a masked one computes every lane, and a dead lane at `1e300` or NaN made SVML's `SIN` about six times slower until blended to `0.5`; the probe's step distance overflows for opposite signs; `results/VARKA-345-admission.txt`, `results/VARKA-345-exact-admission.txt`). The math family's exact default and its opt-in ULP contract (2.7.1; *30 October 2026, by the owner's word:* exact by default, the contract an opt-in mode off by default). **The exact default**: the thirteen fdlibm functions fuse first as a per-lane `StrictMath.` call inside the kernel, exact, the work around it vectorised; a lane-wise port of fdlibm 5.3 is a measured option arm per function (`mathPort`), kept either way, and the default only where it measures faster on the EPYC runners (the lead, 30 October 2026); the port is emitted by Varka as IR nodes in its own kernels, never called, with the standalone vector fdlibm library `vfdlibm` (https://github.com/vecbricks/vfdlibm, its own repository, filled one function at a time as Varka needs it, each function ported there from fdlibm 5.3's C sources and cross-checked bit for bit with Varka's emitted kernel, both checked against `StrictMath`) as its reference and test oracle and no runtime dependency (the owner, 30 October 2026: C2 inlines a hot callee only up to 325 bytecodes, `@ForceInline` is dropped outside the JDK, and a refused call boxes its vectors, `VARKA-345.md` 2.2); the host-dependent `sin`, `cos`, `tan`, `tanh` and `cbrt` by a per-lane `Math.` call; the compositions as Spark writes them; three bit-identity tests per form (a sampled differential of at least 2^24 inputs a function, the fixed vectors, the engine's own differentials), seeded with SLEEF's special-value list - NaN, both infinities, `+-DBL_MAX`, `+-DBL_MIN`, `+-denorm_min`, both zeros, `+-1` and their neighbours (`READING_SLEEF.md` 6.3; *27 October 2026, from `READING_TRACE.md` 2 item 6*). 345 builds the forms and their lowerings, the port's IR helpers and `exp` as the template in the library and as an IR expansion, after the owner's yes on fetching the C sources; each function is its row's (356 to 358). **The opt-in mode**, `spark.sql.codegen.varka.math.ulpContract.enabled`, off by default, its emit option in the shape key: a function may take the Vector API's library operator where its binding has a contract entry; the bound a count of representable doubles from the row engine's double (`VarkaMathBound.steps`, which 367's probe also measures with), keyed by the full JDK build, library and CPU, contracted and measured bounds kept apart, the contracted value at least every measured line and its suite failing when one exceeds it; the binding verified once per JDK build under `-Djdk.incubator.vector.DEBUG=true` and by the C2 compile itself (`dev/varka_emit.sh --asm` showing the call to the library's symbol, since the DEBUG line proves the symbol and not the call, `READING_JDK.md` 2.6); SLEEF's stated tier beside each measured bound (`READING_SLEEF.md` 6.5); null and masked-off lanes blended to a harmless argument before the library call, since a masked math operator computes every lane and blends after (`READING_JDK.md` 2.7); the oracle and fuzzers comparing a contracted value within the bound, a NaN never passing against a number, and a composition bit for bit against a C2-warmed library reference; the differential suites' configuration-on arm; question 2 applies to this mode only, does not block 356 to 358, and stays the owner's; `SCOPE_STANDARD_MODE.md` 3.4 becomes the mode's entry. Census reading (`VARKA-376.md` 9, 20 October 2026, laptop): every `Double` math operator is intrinsic and allocation-free at 512 bits; at 256 and 128 bits `POW` has no vector stub, so the loop never reaches the library call and runs the Java fallback (the canary's finding), which is the form of `pow` at those species in the opt-in mode until a host shows otherwise. **Done when** with the configuration off no kernel holds a library call and every exact form admitted through the test hook is bit-identical to Spark by the three tests; with it on, the library operator appears only on a binding with a contract entry; a test shows a within-bound comparison catches a lane two steps further out and refuses every pair of opposite signs; the binding check passes on the x86 and Arm runners; and the dated corrections of `SCOPE_FUNCTIONS.md` 3, item 36 and `SCOPE_STANDARD_MODE.md` 3.4 record the exact default (*until 30 October 2026 the done-when asked for the configuration to decline the family when off, a test showing a within-bound comparison catches a lane two steps further out, and the dated corrections of `SCOPE_FUNCTIONS.md` 3 and item 36*) | item 36; owner's decision, 14 October 2026, superseded by the owner's decision of 30 October 2026 | medium | diff --git a/sql/varka/plans/m8/VARKA-342.md b/sql/varka/plans/m8/VARKA-342.md index 957866699e1e..acf615ee2a9a 100644 --- a/sql/varka/plans/m8/VARKA-342.md +++ b/sql/varka/plans/m8/VARKA-342.md @@ -145,6 +145,10 @@ By `VARKA-475.md` 4 rule 1, the forms take existing nodes at a floating lane: a lanewise math operator is a new kind of computation, and 356 to 358 add their functions to it. - `GuardedRange` at a floating lane (2.4) holds its bounds as the lane's bits and compares by IEEE, a NaN lane being outside. +- *Added 20 November 2026 (5.3), the lead's settlement of 30 October 2026 in `VARKA-346.md` 8:* + **a second new node, `Fma(a, b, c)`**, `a * b + c` rounded once at a floating lane, evaluated by + `Math.fma`, which row 346's remainder and `FLOAT` round-to-odd use. No Spark expression builds + it, and it is never made from a multiply and an add: the no-contraction rule below stands. Two rules hold at a floating lane and are written into `IntArith`'s javadoc: **no algebraic rewrite** (`x + 0.0` is not `x` at `-0.0`, which is what 337's canonicalisation node relies on; @@ -563,6 +567,133 @@ bounded magic there (`VARKA-343.md` 8 makes the whole-range arms the default, so arise); the lowering built over `VarkaIntervalCompiler`'s guard constants, which the proof reads; the coverage rows of the four; and the baselines' fuse lists for `ym * x` and `dt / x`. +### 5.3 The FMA node, for row 346 (20 November 2026) + +Row 346's plan (`VARKA-346.md` 2.6, 8) gives this row the FMA node its remainder and its `FLOAT` +output's round-to-odd need, the earliest wave owning a shared node (`VARKA-350.md` 8, question 4, +names 342 its owner), and flags that this plan had none. It is built ahead of step 4's second +piece, which still waits for 343b2, as its own part, `varka-342-floating-arith`, so that 346a can +stack on it. + +- **The node.** `Fma(a, b, c)` in `VarkaVectorIR`, three operands of one floating lane (the + constructor refuses an integral lane and a mix), null-intolerant: its validity is the three + operands' AND, folded as a two-operand node's is (`Slots.planWordRef`, `Analysis.ownerOf`), + its pure word the AND of theirs. The emitter pushes the operands in order and calls + `a.fma(b, c)`, the call `VarkaOperatorCensusProbe` measures; the warm-up's double and float + blocks make it. The reference evaluates `Math.fma` at `DOUBLE` and `Math.fma`'s float form at + `FLOAT`, never the double form narrowed. Range analysis answers `UNKNOWN`, the budget weighs it + 1 (one lane call, the register's rule), the cost model lists it as awaiting the refit with the + other floating nodes, and the SMT renderer refuses it as it refuses `MathUnary`. +- **Its NaN is open everywhere.** `Math.fma` run in Java answers `Double.NaN`, the canonical + NaN, for any NaN (`Math.java:2393-2394` in the local `jdk-25-ga` source) and for `inf * 0` + (`:2404`); the instruction answers by the hardware's own rule over its own operand order, an + operand's NaN or the host's default NaN for `inf * 0`: HotSpot emits x86's `vfmadd231`, `c = a * + b + c` (`cpu/x86/x86.ad:8965-8966`, `macroAssembler_x86.cpp:1665`). So which bits a NaN answer + has depends on the tier even over operands that are not NaNs, and `VarkaSameAnswer` gives the node its own + step, `Unfixed`, open wherever it answers a NaN. A non-NaN answer is compared bit for bit: + IEEE's fused operation has one correctly rounded result. +- **No compiler arm.** Nothing in Spark is an FMA, so no coverage row, family or census cell + moves; the node reaches a kernel only through a lowering that builds it (346a). +- **Tests.** `VarkaEmitterFmaSuite` (JUnit 5): the single rounding, `(1 + 2^-27)(1 - 2^-27) - 1` + `-2^-54` through the node where the multiply and the add give `0.0`, and its float twin + `(1 + 2^-13)(1 - 2^-13) - 1` `-2^-26` against `0.0`; the node at both lanes and two widths each + against the reference over every ordered triple of seventeen operands (zeros, infinities, a + NaN, the extremes, a subnormal, inexact products), every null pattern of the three columns and + both validity fills, in four operand arrangements, one under a negation; the constructor's + refusals and the rendering's round trip through `VarkaCanonicalIr`; and the NaN rule, an + `inf * 0 + 1` row open for the FMA and closed for the multiply. `VarkaWithChildrenSuite` + rebuilds it, `VarkaLaneTypeSuite` emits it at `DOUBLE` and refuses it at the integral lanes, + `VarkaEmitterBudgetSuite` weighs it, and the registry lists (`VarkaIrFuzzSuite`, + `VarkaEmitCostSuite`, `VarkaRangeAnalysisSuite`) name it. +- **Predictions**, to score when the tests run: no existing shape's bytes move + (`emitted_bytes.json` unchanged, the node being reachable from no compiler arm and no fuzz + sequence, 5.4's sequences being new ones); `VarkaEmitterFmaSuite` runs under 20 s; under `-XX:UseAVX=2` the width audit has + nothing to say, since no audited shape holds the node. +- **What ran (20 November 2026, the laptop).** `build/sbt catalyst/Test/compile` passed on the + first try. `VarkaEmitterFmaSuite` ran twice, one run past the brief's one targeted run, since + the first failed on the harness: the second passed, 5 tests in 9.1 s in its own JVM, scoring the time + prediction (under 20 s): held. Its first run in the shared JVM failed three tests on + `VarkaSpeciesGuard`, the two widths of one lane in one JVM, so the class runs in a JVM of its + own (`@VarkaSuite(ownJvm = true)`), as `VarkaEmitterFloatingArithSuite` does. The registry + suites, the emitted bytes and the width audit are owed (the draft pull request lists them). + +### 5.4 The floating arithmetic fuzz sequences (20 November 2026) + +3.10's IR fuzz half, owed by step 3 (5.1, "Still owed"), on part `varka-342b-floating-fuzz`, +stacked on 5.3's. 341's floating sequences (`fuzz_float`, `fuzz_double`) draw the leaves, the +picks and the conditions only; their grammar, `VarkaIrGrammar.FloatingShapes`, gains this row's +nodes behind a flag, drawn from two seeds of their own, `FLOAT_ARITH_FUZZ_SEED` and +`DOUBLE_ARITH_FUZZ_SEED`, so that the committed sequences and their pinned bytes do not move: the +plain draw keeps its exact random calls. With the flag a value is one of row 342's nodes four +times in nine: `+`, `-` and `*` unchecked, the division unchecked or nulling a zero divisor, +negation and `abs`, the square root and 5.3's FMA, at both floating lanes (the square root and +the division at `FLOAT` too, which the IR and the reference take though the compiler builds them +at `DOUBLE`). `VarkaIrFuzzSuite` runs each sequence against the reference, 300 draws as the +floating sequences do, and a reach test holds each to every form over its first 2,000 draws. + +- **The `FAIL` division is not drawn** (decision 5); the emitter suite holds the declined batch, + as it does the guards' firing for the other corpora. +- **Not yet in the bytes oracle.** `VarkaEmittedBytesSuite` pins the floating sequences' first + two thousand shapes; pinning these is a regeneration (`emitted_bytes.json`), owed with the + pull request's other generated files. +- **The Spark fuzzer's floating productions** (3.10's other half): its grammar draws only fused + coverage rows, so it draws the family's 26 rows and their 11 cast forms already, `x / x2` + among them (5.1, the integration fixes); nothing of it is built here. +- **What ran (20 November 2026, the laptop).** `build/sbt catalyst/Test/compile`, then three runs + of `VarkaIrFuzzSuite`, past the brief's one targeted run: two by accident ran the whole suite, + the `-z` filter reaching the parent only, and the third ran the three + new tests directly in one JVM (`-Dvarka.ownJvm=true` set in the catalyst project, `-z + arithmetic`): each sequence answered 300 of 300 draws against the reference, in 3.2 s at + `FLOAT` and 2.4 s at `DOUBLE`, and the reach test found every form over 2,000 draws a lane. The first whole-suite run hit the + child JVM's nine-minute cap, a harness limit, not a failure (`testing-and-debugging.md` on + `VarkaOwnJvm`); the second, given the property at the root project, was stopped once seen. + In the first, the child's own report shows the registry tests passing with `Fma` listed: "the + generator reaches every IR node type" and the long-lane one. + +### 5.5 Step 2's code, the census cells (20 November 2026) + +Step 2 (2.5, item 0.7) on part `varka-342c-census`, stacked on 5.4's: `VarkaOperatorCensusCatalog` +gains a family, "floating arithmetic", of twelve cells, `ADD`, `SUB`, `MUL`, `DIV`, `NEG` and +`ABS` at each floating lane, over the probe's binary loops (`bin.float`, `bin.double`) and its +double unary loop, and a new `un.float` loop in `VarkaOperatorCensusProbe` for the float unary +two. The laptop's census was regenerated the same day (`VARKA_CENSUS_REGEN=true build/sbt +'catalyst/testOnly *VarkaOperatorCensusSuite'`, 200 s, its 8 tests passing): the diff adds the +twelve cells at 128, 256 and 512 bits, all 36 intrinsic with no allocation, and moves nothing +else but the host's JDK build string (25.0.5.0.3 to 25.0.5.1). Prediction 4.2, laptop half: +held. The census workflow on the EPYC 7763 and the Neoverse N2 is owed, its half of 4.2 with it. + +### Decisions taken while the owner was away (20 November 2026) + +1. **The FMA node is built now, as its own part, ahead of the rest of step 4.** The brief's + priority note puts row 346's 346a behind it, and `VARKA-346.md` 8 records the lead's + settlement that the node is this row's; the interval forms still wait for 343b2 + (`VarkaKernelPlan.conversionRefusal` refuses every conversion to an integral lane). +2. **The node's NaN is open wherever it answers one**, a `Step` of its own in `VarkaSameAnswer`, + rather than `Other`'s rule, which opens a node only where an operand's NaN is open and would + hold `inf * 0 + 1` bit for bit across tiers that disagree (5.3). Listing the causes instead (a + NaN operand, `inf * 0`, an infinite product meeting the opposite infinity) names the same rows, + since those are the only ways the operation answers a NaN. +3. **A host without an FMA instruction is not refused.** There the Vector API computes each lane + by `Math.fma`, exact and slow (a `BigDecimal` product per lane); x86 hosts with AVX2 have FMA + in practice and aarch64 always does, and the census records `double.FMA` and `float.FMA` + intrinsic at every width on the laptop and the EPYC runners. Whether 346a's lowering declines + on such a host is 346a's decision, made with its own measurement. +4. **The node is in no fuzz grammar.** The grammars draw no floating tree; the floating sequence + (3.10, still owed) draws it when it is built, on a seed of its own, so that no committed + sequence moves. *Corrected the same day:* 5.4's sequences, on part `varka-342b-floating-fuzz`, + draw it; no committed sequence draws it, which is what this decision protects. +5. **The `FAIL` division is not fuzzed** (5.4): a draw has no reference answer for the batch a + live zero divisor declines, and the floating edge values draw zeros often enough that most + draws holding one would decline. +6. **The square root and the division are drawn at `FLOAT` too** (5.4), though the compiler + builds them at `DOUBLE` only, where the narrow grammar draws only what the compiler builds at + its lane. The IR, the emitter and the reference take both at `FLOAT`, and a later row (the + float forms of 345 and 356 to 358) may build them there; a fuzzed form the compiler never + reaches costs draws, not correctness. +7. **The fuzz sequences are a stacked part although both parts fit the cap together** (750 and + 183 counted lines, and 33 for 5.5's part): the brief asks for the FMA node as its own small part, so that row 346a can + stack on it without the fuzz change. + ## 6. Out of this row `%`, `pmod` and `try_mod` (346); `try_divide` and `try_multiply` over an interval, which are diff --git a/sql/varka/skills/calibration/VARKA-342-5.3-1.md b/sql/varka/skills/calibration/VARKA-342-5.3-1.md new file mode 100644 index 000000000000..dbc7727bdb4d --- /dev/null +++ b/sql/varka/skills/calibration/VARKA-342-5.3-1.md @@ -0,0 +1,6 @@ +* task: VARKA-342 (5.3 #1) +* added: 2026-11-22 +* predicted: VarkaEmitterFmaSuite runs under 20 s +* measured: 9.1 s, 5 tests in a JVM of its own +* ratio: 0.5 +* note: one run on the laptop on 20 November 2026