From c65725da8f81643b4e94f13b9183f04134b14b04 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 14 Oct 2026 02:45:51 +0200 Subject: [PATCH] CultMath Cycles: arcsine, arccosine and arctan2 with Cycles' guards; per-function oracle seeds; the ruled unfused reference, empty Tolerances and the class table Fixtures and the regenerated GLSL follow in the next commit, so the tests that read the new rows (InverseTrigonometry..., OperandStreams...) are red at this commit. Co-Authored-By: Claude Opus 5.5 --- .../cultmath/shaders/CultMath.Cycles.hlsl | 13 +- packages/cultmath/src/CultMath/math.Cycles.cs | 20 ++- .../tests/CultMath.Tests/CyclesOracleTests.cs | 160 ++++++++++++++++-- .../tests/CultMath.Tests/GlslLowering.cs | 4 +- .../tests/CultMath.Tests/GlslMirrorTests.cs | 9 +- .../HlslSourceCompatibilityTests.cs | 2 +- .../cultmath/tools/cycles-oracle/README.md | 36 +++- .../cultmath/tools/cycles-oracle/oracle.py | 31 +++- .../Shaders/CultMath.Cycles.hlsl | 13 +- 9 files changed, 251 insertions(+), 37 deletions(-) diff --git a/packages/cultmath/shaders/CultMath.Cycles.hlsl b/packages/cultmath/shaders/CultMath.Cycles.hlsl index 829a27b3..7098394a 100644 --- a/packages/cultmath/shaders/CultMath.Cycles.hlsl +++ b/packages/cultmath/shaders/CultMath.Cycles.hlsl @@ -81,10 +81,10 @@ float cultmath_cycles_modulo(float a, float b) return b != 0.0 ? (a < 0.0 ? -remainder : remainder) : 0.0; } -// safe_floored_modulo +// safe_floored_modulo; a build that contracts it differs by a bound stated at cycles_floored_modulo in math.Cycles.cs and the README float cultmath_cycles_floored_modulo(float a, float b) { return b != 0.0 ? a - floor(a / b) * b : 0.0; } -// wrapf (note the argument order: value, max, min) +// wrapf (note the argument order: value, max, min); contraction bound as for floored_modulo float cultmath_cycles_wrap(float value, float max_value, float min_value) { float range = max_value - min_value; @@ -129,6 +129,15 @@ float cultmath_cycles_fract(float a) { return a - floor(a); } // compatible_signf float cultmath_cycles_sign(float a) { return a == 0.0 ? 0.0 : (a < 0.0 ? -1.0 : 1.0); } +// safe_asinf +float cultmath_cycles_arcsine(float a) { return asin(clamp(a, -1.0, 1.0)); } + +// safe_acosf +float cultmath_cycles_arccosine(float a) { return acos(clamp(a, -1.0, 1.0)); } + +// compatible_atan2 (a is y, b is x) +float cultmath_cycles_arctan2(float a, float b) { return (b == 0.0 && a == 0.0) ? 0.0 : atan2(a, b); } + // ---- Map Range node (kernel/svm/map_range.h svm_node_map_range) ---- // A Map Range node's Clamp option is a Clamp node of type Range on its result (MapRangeNode::expand): // compose cultmath_cycles_clamp_range over these. diff --git a/packages/cultmath/src/CultMath/math.Cycles.cs b/packages/cultmath/src/CultMath/math.Cycles.cs index 120d6f24..9144ef9c 100644 --- a/packages/cultmath/src/CultMath/math.Cycles.cs +++ b/packages/cultmath/src/CultMath/math.Cycles.cs @@ -92,10 +92,17 @@ public static partial class math return b != 0.0f ? (a < 0.0f ? -remainder : remainder) : 0.0f; } - /// Math node Floored Modulo (safe_floored_modulo): a - floor(a / b) b, or 0 when b is 0. + /// Math node Floored Modulo (safe_floored_modulo): a - floor(a / b) b, or 0 when b is 0, with one IEEE single + /// rounding per operation (the reference of ruling cycles-kernel-reference-ruled). A build that contracts + /// a - floor(a / b) b into one fused operation differs by at most 2^-23 (|a / b| + 1) |b| (measured 0.91 of 2^-24 (|a| + |b|) + /// on Blender 5.2.2's AVX2 kernel); a fast-math build may also move floor(a / b) by one near an integer quotient, + /// so the result differs by a whole |b|. See tools/cycles-oracle/README.md. public static float cycles_floored_modulo(float a, float b) => b != 0.0f ? a - floor(a / b) * b : 0.0f; - /// Math node Wrap (wrapf; note the argument order): value wrapped into [min_value, max_value), or min_value for an empty range. + /// Math node Wrap (wrapf; note the argument order): value wrapped into [min_value, max_value), or min_value for an empty range, + /// with one IEEE single rounding per operation. A build that contracts value - range floor(...) into one fused operation differs by at + /// most 2^-23 (|value| + |min_value| + |range|) (measured 0.77 of 2^-24 on the AVX2 kernel); a fast-math build may also move floor by one, + /// a whole |range|. See tools/cycles-oracle/README.md. public static float cycles_wrap(float value, float max_value, float min_value) { var range = max_value - min_value; @@ -138,6 +145,15 @@ public static partial class math /// Math node Sign (compatible_signf): 0 for 0, -1 below, 1 above. public static float cycles_sign(float a) => a == 0.0f ? 0.0f : (a < 0.0f ? -1.0f : 1.0f); + /// Math node Arcsine (safe_asinf, util/math_base.h): asin of a clamped to [-1, 1]. + public static float cycles_arcsine(float a) => asin(clamp(a, -1.0f, 1.0f)); + + /// Math node Arccosine (safe_acosf, util/math_base.h): acos of a clamped to [-1, 1]. + public static float cycles_arccosine(float a) => acos(clamp(a, -1.0f, 1.0f)); + + /// Math node Arctan2 (compatible_atan2, util/math_base.h; a is y, b is x): 0 at the origin, else atan2(a, b). + public static float cycles_arctan2(float a, float b) => (b == 0.0f && a == 0.0f) ? 0.0f : atan2(a, b); + // ---- Map Range node (kernel/svm/map_range.h svm_node_map_range) ---- // A Map Range node's Clamp option is a Clamp node of type Range on its result (MapRangeNode::expand): // compose cycles_clamp_range over these. diff --git a/packages/cultmath/tests/CultMath.Tests/CyclesOracleTests.cs b/packages/cultmath/tests/CultMath.Tests/CyclesOracleTests.cs index e1a2bc8a..a26d53b0 100644 --- a/packages/cultmath/tests/CultMath.Tests/CyclesOracleTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/CyclesOracleTests.cs @@ -6,25 +6,24 @@ namespace CultMath.Tests; /// /// math.cycles_* and the shader mirror's cultmath_cycles_* (shaders/CultMath.Cycles.hlsl, compiled as C#) against -/// the results of Blender 5.2.2's own Cycles on the CPU. The fixtures under fixtures/cycles-oracle are written by +/// the results of Blender 5.2.2's own Cycles on the CPU, the reference of ruling +/// cultmath-tapes:ruling:cycles-kernel-reference-ruled: Cycles' formulas with one IEEE single rounding per +/// operation. The fixtures under fixtures/cycles-oracle are written by /// tools/cycles-oracle/oracle.py (never by hand): each case is the operands and the node's baked results as /// float32 bit patterns. Every function is compared at every case within the tolerance named in /// ; a function not named there is held to 0 ulp. Signed zeros are not distinguished (-0 /// equals 0), and NaN equals NaN. The fixtures come from Cycles' SSE4.2 CPU kernel, which does not fuse -/// multiply-adds as C# does not (oracle.py checks this before it bakes). Cycles' film writes 0 for an infinite or +/// multiply-adds as C# does not (oracle.py checks this before it bakes); other builds are other tolerance classes +/// (tools/cycles-oracle/README.md). Cycles' film writes 0 for an infinite or /// NaN result, so a case whose result here is not finite and whose fixture result is 0 holds nothing to compare. /// public sealed class CyclesOracleTests { - // The ulp distance a function is allowed from Cycles. The two that call the platform's libm have the bound the - // golden fixture gives a platform libm family (GlslMirrorTests, Platform.Ulp): Blender's powf and logf are - // glibc's, measured here at 0 ulp from MathF.Pow and MathF.Log on Linux, and another OS's libm may differ by - // one. That allowance is the golden fixture's, not a measurement on another OS. - private static readonly Dictionary Tolerances = new() - { - ["cycles_power"] = (1, "0 ulp on Linux"), - ["cycles_logarithm"] = (1, "0 ulp on Linux"), - }; + // The ulp distance a function is allowed from the reference. Empty: the fixtures are the SSE4.2 kernel's results + // and every function equals them, power and logarithm included (glibc's powf and logf, 0 ulp from MathF on Linux). + // An entry needs a measured case on the reference named in it (a failing case's bits and ulp); other builds' + // tolerances belong to the class table in tools/cycles-oracle/README.md, not here. + private static readonly Dictionary Tolerances = new(); private const string CSharp = "C#"; private const string Mirror = "HLSL mirror"; @@ -234,6 +233,145 @@ public sealed class CyclesOracleTests Assert.Equal(0.0f, One("cycles_floored_modulo", 1.0f, 0.0f)); } + [Theory] + [MemberData(nameof(Targets))] + public void InverseTrigonometryFollowsTheCyclesGuards(string target) + { + // util/math_base.h: safe_asinf and safe_acosf clamp to [-1, 1] before asinf and acosf; compatible_atan2 returns 0 + // at the origin (x == 0 && y == 0) and is atan2f everywhere else, so its guard is only the origin. + float One(string function, params float[] arguments) => (float)Call(target, function, arguments.Cast().ToArray()); + Assert.Equal(MathF.Asin(1.0f), One("cycles_arcsine", 2.0f)); + Assert.Equal(MathF.Asin(-1.0f), One("cycles_arcsine", -1.5f)); + Assert.Equal(MathF.Asin(1.0f), One("cycles_arcsine", 1.0000001f)); + Assert.Equal(0.0f, One("cycles_arccosine", 2.0f)); + Assert.Equal(MathF.Acos(-1.0f), One("cycles_arccosine", -2.0f)); + Assert.Equal(0.0f, One("cycles_arctan2", 0.0f, 0.0f)); + Assert.Equal(0.0f, One("cycles_arctan2", 0.0f, -0.0f)); + Assert.Equal(0.0f, One("cycles_arctan2", -0.0f, -0.0f)); + Assert.Equal(MathF.Atan2(-0.0f, -1.0f), One("cycles_arctan2", -0.0f, -1.0f)); + Assert.Equal(MathF.Atan2(0.0f, -1.0f), One("cycles_arctan2", 0.0f, -1.0f)); + Assert.Equal(MathF.Atan2(1.0f, 0.0f), One("cycles_arctan2", 1.0f, 0.0f)); + Assert.Equal(MathF.Atan2(-1.0f, 0.0f), One("cycles_arctan2", -1.0f, 0.0f)); + // The guard is the origin alone: a guard on either zero would zero these (the plain atan2 values are pi and pi/2). + Assert.NotEqual(0.0f, One("cycles_arctan2", 0.0f, -1.0f)); + Assert.NotEqual(0.0f, One("cycles_arctan2", 1.0f, 0.0f)); + foreach (var value in new[] { One("cycles_arcsine", 2.0f), One("cycles_arccosine", -2.0f), One("cycles_arctan2", 0.0f, -0.0f), One("cycles_arctan2", 1.0f, 0.0f) }) + Assert.True(float.IsFinite(value)); + } + + [Theory] + [MemberData(nameof(Targets))] + public void MapRangeSmoothStepDecidesTheTopEdgeBeforeDividing(string target) + { + // util/math_base.h smoothstep returns 1 for x >= edge1 before it forms t. With an overflowing range + // (high - low = infinity) the division would be infinity / infinity, NaN. + float Smooth(params float[] arguments) => (float)Call(target, "cycles_map_range_smoothstep", arguments.Cast().ToArray()); + Assert.Equal(1.0f, Smooth(3.0e38f, -3.0e38f, 3.0e38f, 0.0f, 1.0f)); + Assert.Equal(0.0f, Smooth(3.0e38f, 3.0e38f, -3.0e38f, 0.0f, 1.0f)); + Assert.Equal(0.0f, Smooth(-3.0e38f, -3.0e38f, 3.0e38f, 0.0f, 1.0f)); + } + + [Fact] + public void FlooredModuloAndWrapUnderContractionStayWithinTheBound() + { + // Ruling cycles-kernel-reference-ruled: a build that contracts a - floor(a / b) b into one fused operation differs + // from the reference by at most 2^-23 (|a| + |b|), and the wrap model by 2^-23 (|value| + |min| + |range|). The fused + // model is MathF.FusedMultiplyAdd, test-only; no cycles_* function uses it. + var bound = Math.ScaleB(1.0, -23); + var worstModulo = 0.0; + var worstWrap = 0.0; + var seenPair = false; + foreach (var entry in Load("math")["functions"]!.AsArray()) + { + var name = (string)entry!["function"]!; + if (name != "cycles_floored_modulo" && name != "cycles_wrap") + continue; + foreach (var line in entry["cases"]!.AsArray()) + { + var o = ((string)line!).Split(" -> ")[0].Split(' ').Select(Float).ToArray(); + if (name == "cycles_floored_modulo") + { + float a = o[0], b = o[1]; + if (b == 0.0f) + continue; + var fused = MathF.FusedMultiplyAdd(-MathF.Floor(a / b), b, a); + var scale = Math.Abs((double)a) + Math.Abs((double)b); + var difference = Math.Abs((double)fused - math.cycles_floored_modulo(a, b)); + Assert.True(difference <= bound * scale, $"floored modulo ({line}): fused {fused} is {difference / scale} of |a| + |b| from the reference"); + worstModulo = Math.Max(worstModulo, difference / scale); + if (a == 10000.0f && b == 0.1f) + { + seenPair = true; + Assert.Equal(-1.4901161e-4f, fused); + Assert.Equal(0.0f, math.cycles_floored_modulo(a, b)); + } + } + else + { + float value = o[0], max = o[1], min = o[2]; + var range = max - min; + if (range == 0.0f) + continue; + var fused = MathF.FusedMultiplyAdd(-range, MathF.Floor((value - min) / range), value); + var scale = Math.Abs((double)value) + Math.Abs((double)min) + Math.Abs((double)range); + var difference = Math.Abs((double)fused - math.cycles_wrap(value, max, min)); + Assert.True(difference <= bound * scale, $"wrap ({line}): fused {fused} is {difference / scale} of |value| + |min| + |range| from the reference"); + worstWrap = Math.Max(worstWrap, difference / scale); + } + } + } + + Assert.True(seenPair, "the fixture holds no (10000, 0.1) floored modulo case"); + // The cases reach the contraction regime: a bound of 2^-25 would fail. + Assert.True(worstModulo > Math.ScaleB(1.0, -25), $"the worst floored modulo contraction is only {worstModulo} of |a| + |b|"); + Assert.True(worstWrap > Math.ScaleB(1.0, -25), $"the worst wrap contraction is only {worstWrap} of |value| + |min| + |range|"); + } + + // The values oracle.py draws the specials of a function from (SPECIAL, plus the arcsine and arccosine edge rows); a row with any other operand holds a random draw. + private static readonly HashSet Alphabet = new[] + { + 0.0, 1.0, -1.0, 0.5, -0.5, 2.0, -2.0, 3.0, -2.75, 0.1, -0.1, 7.5, -7.5, 1.0e-7, -1.0e-7, 100.0, -100.0, 1.0e4, 0.3, 0.7, 1.5, 1.0000001, -1.0000001, + }.Select(v => (float)v).ToHashSet(); + + [Fact] + public void OperandStreamsDifferPerFunction() + { + // oracle.py seeds every function, every blend mode's second colours and every ramp from its own name, so no two + // share a stream of draws. At e48f9488 the seed was the name's first four bytes, and 'cycles_' shared them all. + var functions = Load("math")["functions"]!.AsArray() + .Select(e => (Name: (string)e!["function"]!, Rows: e["cases"]!.AsArray().Select(l => ((string)l!).Split(" -> ")[0]).ToArray())) + .ToArray(); + Assert.True(functions.Length >= 17, "the math fixture lost functions"); + foreach (var f in functions) + { + var draws = f.Rows.Where(row => row.Split(' ').Any(token => !Alphabet.Contains(Float(token)))).ToHashSet(); + Assert.True(draws.Count >= 8, $"{f.Name} holds only {draws.Count} random-draw rows"); + foreach (var g in functions.Where(g => string.CompareOrdinal(f.Name, g.Name) < 0 && g.Rows[0].Split(' ').Length == f.Rows[0].Split(' ').Length)) + { + var shared = g.Rows.Count(row => draws.Contains(row)); + Assert.True(shared == 0, $"{f.Name} and {g.Name} share {shared} random-draw rows"); + } + } + + var modes = Load("mix")["functions"]!.AsArray() + .Where(e => ((string)e!["function"]!).StartsWith("cycles_mix_") && ((string)e["cases"]![0]!).Split(" -> ")[0].Split(' ').Length == 7) + .Select(e => (Name: (string)e!["function"]!, Rows: e["cases"]!.AsArray().Select(l => ((string)l!).Split(" -> ")[0].Split(' ')).ToArray())) + .ToArray(); + Assert.True(modes.Length >= 15, "the mix fixture lost blend modes"); + static string Multiset(IEnumerable rows, int first) => string.Join("|", rows.Select(r => string.Join(" ", r.Skip(first).Take(3))).OrderBy(x => x, StringComparer.Ordinal)); + foreach (var mode in modes) + Assert.True(Multiset(mode.Rows, 1) != Multiset(mode.Rows, 4), $"{mode.Name}: the second colours are the first colours"); + foreach (var f in modes) + foreach (var g in modes.Where(g => string.CompareOrdinal(f.Name, g.Name) < 0)) + Assert.True(Multiset(f.Rows, 4) != Multiset(g.Rows, 4), $"{f.Name} and {g.Name} draw the same second colours"); + + var ramps = Load("ramp")["functions"]!.AsArray() + .Select(e => e!["cases"]!.AsArray().Select(l => ((string)l!).Split(" -> ")[0]).ToArray()).ToArray(); + Assert.Equal(2, ramps.Length); + var tail = ramps[0].TakeLast(100).ToHashSet(); + Assert.True(!ramps[1].TakeLast(100).Any(tail.Contains), "the ramps' random t tails overlap"); + } + [Theory] [MemberData(nameof(Targets))] public void HueSaturationAndValueOfThePrimariesFollowCycles(string target) diff --git a/packages/cultmath/tests/CultMath.Tests/GlslLowering.cs b/packages/cultmath/tests/CultMath.Tests/GlslLowering.cs index 13e21808..5d119d86 100644 --- a/packages/cultmath/tests/CultMath.Tests/GlslLowering.cs +++ b/packages/cultmath/tests/CultMath.Tests/GlslLowering.cs @@ -86,13 +86,15 @@ internal static class GlslLowering source = LowerCasts(source); // 6. Intrinsic renames: lerp -> mix, frac -> fract, rsqrt -> inversesqrt, asuint -> - // floatBitsToUint, asfloat -> uintBitsToFloat, and saturate(x) -> clamp(x, 0.0, 1.0). + // floatBitsToUint, asfloat -> uintBitsToFloat, atan2 -> atan (GLSL's two-argument arctangent), + // and saturate(x) -> clamp(x, 0.0, 1.0). // Identifier boundaries keep cultmath_lerp and the rest of the cultmath_ names intact. source = Regex.Replace(source, @"\blerp\(", "mix("); source = Regex.Replace(source, @"\bfrac\(", "fract("); source = Regex.Replace(source, @"\brsqrt\(", "inversesqrt("); source = Regex.Replace(source, @"\basuint\(", "floatBitsToUint("); source = Regex.Replace(source, @"\basfloat\(", "uintBitsToFloat("); + source = Regex.Replace(source, @"\batan2\(", "atan("); source = LowerSaturate(source); // 7. Float literals pass through: HLSL's unsuffixed 0.5 and 1.0e30 are GLSL literals already. diff --git a/packages/cultmath/tests/CultMath.Tests/GlslMirrorTests.cs b/packages/cultmath/tests/CultMath.Tests/GlslMirrorTests.cs index 0419688b..f7699379 100644 --- a/packages/cultmath/tests/CultMath.Tests/GlslMirrorTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/GlslMirrorTests.cs @@ -47,7 +47,7 @@ public sealed class GlslMirrorTests // Identifier boundaries: cultmath_lerp is a CultMath function, lerp( is HLSL. private static readonly Regex HlslOnly = new( - @"\b(float|u?int|bool)[234]\b|\blerp\(|\bfrac\(|\bsaturate\(|\brsqrt\(|\basuint\(|\basfloat\(|static const|\((float|int|uint)\)|Texture2D|SamplerState|#include|precision (high|medium|low)p"); + @"\b(float|u?int|bool)[234]\b|\blerp\(|\bfrac\(|\bsaturate\(|\brsqrt\(|\basuint\(|\basfloat\(|\batan2\(|static const|\((float|int|uint)\)|Texture2D|SamplerState|#include|precision (high|medium|low)p"); [Fact] public void NoHlslOnlyTokensSurvive() @@ -625,7 +625,12 @@ public sealed class GlslMirrorTests }.Concat(new[] { "blend", "add", "mul", "screen", "overlay", "sub", "div", "diff", "exclusion", "dark", "light", "dodge", "burn", "hue", "sat", "val", "color", "soft", "linear", - }.Select(mode => new Family($"vec3 cultmath_cycles_mix_{mode}(float, vec3, vec3)", "ulp-bounded", r => new object[] { CyclesFactor(r), CyclesColor(r), CyclesColor(r) }))).ToArray(); + }.Select(mode => new Family($"vec3 cultmath_cycles_mix_{mode}(float, vec3, vec3)", "ulp-bounded", r => new object[] { CyclesFactor(r), CyclesColor(r), CyclesColor(r) }))).Concat(new[] + { + new Family("float cultmath_cycles_arcsine(float)", "ulp-bounded, platform asin", r => new object[] { Uniform(r, -1.5f, 1.5f) }, Platform: Platform.Ulp), + new Family("float cultmath_cycles_arccosine(float)", "ulp-bounded, platform acos", r => new object[] { Uniform(r, -1.5f, 1.5f) }, Platform: Platform.Ulp), + new Family("float cultmath_cycles_arctan2(float, float)", "ulp-bounded, platform atan", r => new object[] { Uniform(r, -20.0f, 20.0f), Uniform(r, -20.0f, 20.0f) }, Platform: Platform.Ulp), + }).ToArray(); // The fixture text, each case's arguments given by family and point index. private static string GoldenFixture(Func arguments) diff --git a/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs b/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs index 0d2b310c..989ddf26 100644 --- a/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/HlslSourceCompatibilityTests.cs @@ -137,7 +137,7 @@ public sealed class HlslSourceCompatibilityTests } Assert.True(mismatches.Count == 0, $"{mismatches.Count} mismatches:{Environment.NewLine}{string.Join(Environment.NewLine, mismatches.Take(12))}"); - Assert.Equal(115, compared.Count); + Assert.Equal(118, compared.Count); } /// diff --git a/packages/cultmath/tools/cycles-oracle/README.md b/packages/cultmath/tools/cycles-oracle/README.md index 777d58b9..5e60d201 100644 --- a/packages/cultmath/tools/cycles-oracle/README.md +++ b/packages/cultmath/tools/cycles-oracle/README.md @@ -17,15 +17,33 @@ script and runs only under Blender, never under a plain Python. It refuses to run under any Blender but **5.2.2 LTS, build hash `d13f752e3b9c`**, exits nonzero and names the version and build it found beside the ones it needs. Blender 5.2.2 is - (`blender-5.2.2-linux-x64.tar.xz`, or the Windows build -from Steam). The fixtures record the version, the hash and the platform they were written on. + (`blender-5.2.2-linux-x64.tar.xz`). The platform is Linux x64: the fixtures reproduce +byte for byte only there, and the Steam/Windows build is another build (see below). The fixtures record the +version, the hash and the platform they were written on, as provenance. -## The CPU kernel +## The reference and other builds -Cycles' AVX2 CPU kernel is compiled with fused multiply-add, so an expression such as `a - floor(a / b) b` is -one fused operation there, and CultMath's C# (which fuses nothing) computes the unfused one. The fixtures pin -the SSE4.2 kernel, which has no FMA, by `CYCLES_CPU_NO_AVX2=1`; the tool bakes `10000 mod 0.1` before anything -else and exits 4 if the result is the fused one, so a run on the wrong kernel writes nothing. +Ruling `cultmath-tapes:ruling:cycles-kernel-reference-ruled`: CultMath's Cycles converters mean Cycles' formulas +evaluated with IEEE single rounding per operation, and the Linux SSE4.2 oracle stays their bit-exact witness. +Every other Cycles build (AVX2 FMA-contracted, MSVC /fp:fast, GPU backends) and CultMath's own HLSL lowering are +held to a stated per-function tolerance class measured on that build; cancellation-prone functions (floored +modulo, wrap) get an error bound relative to |b| and a documented divergence note. + +Cycles' AVX2 CPU kernel is compiled with fused multiply-add, so `a - floor(a / b) b` is one fused operation +there, and CultMath's C# (which fuses nothing) computes the unfused one. The fixtures pin the SSE4.2 kernel, +which has no FMA, by `CYCLES_CPU_NO_AVX2=1`; the tool bakes `10000 mod 0.1` before anything else and exits 4 if +the result is the fused one, so a run on the wrong kernel writes nothing. Other kernels are other builds: +measured under the table below, never written to these fixtures. + +| build | how it was measured | fixture | per-function ulp or bound | +| --- | --- | --- | --- | +| Blender 5.2.2 Linux x64, SSE4.2 kernel (the reference) | `oracle.py` with `CYCLES_CPU_NO_AVX2=1`; `CyclesOracleTests` holds every function to the fixtures | `tests/CultMath.Tests/fixtures/cycles-oracle/*.json` | 0 ulp, every function | +| Blender 5.2.2 Linux x64, AVX2 kernel | the same oracle without the pin, 1024 rows per function, against the single-rounding model `fma(-floor(a / b), b, a)` (wrap: `fma(-range, floor((value - min) / range), value)`) | none committed | floored modulo: at most 2^-23 (\|a / b\| + 1) \|b\|, measured 0.91 of 2^-24 (\|a\| + \|b\|) on 151 rows; wrap: at most 2^-23 (\|value\| + \|min\| + \|range\|), measured 0.77 of 2^-24 on 30 rows; other functions unmeasured | + +The divergence note: a build compiled with fast-math may also move `floor(a / b)` by one near an integer +quotient, so the result differs by a whole \|b\| (wrap: a whole range). Further rows come from follow-up +`cultmath-tapes:follow_up:cycles-tolerance-classes`; its per-build fixtures go under +`fixtures/cycles-oracle//` with their tolerances beside `Tolerances` in `CyclesOracleTests`. ## Method @@ -42,8 +60,8 @@ whose product with 255 is the entry's index, so the first 256 cases are the ramp ## Fixtures Written by this tool and never edited by hand. Rerunning it under the same Blender build on the same -platform rewrites them byte for byte; another platform's libm can differ in the transcendental families -(`power`, `logarithm`), which is why `CyclesOracleTests` states a tolerance for them. +platform rewrites them byte for byte; `CyclesOracleTests` holds every function to them at 0 ulp. Run the +oracle on Yggdrasil-class Linux, never on the workstation. ## Licence diff --git a/packages/cultmath/tools/cycles-oracle/oracle.py b/packages/cultmath/tools/cycles-oracle/oracle.py index 82430f44..f8ef97f0 100644 --- a/packages/cultmath/tools/cycles-oracle/oracle.py +++ b/packages/cultmath/tools/cycles-oracle/oracle.py @@ -9,8 +9,11 @@ # the node under test with Cycles on the CPU and writes tests/CultMath.Tests/fixtures/cycles-oracle/.json. # Method: operands go into float, Non-Color input images read with Closest interpolation; one Emit bake per # output channel (1 sample, margin 0, no denoising) writes the node's result to a float image whose pixels are -# the results, bit for bit. The fixtures are this tool's output and are never edited by hand. +# the results, bit for bit. The fixtures are this tool's output and are never edited by hand. They witness the +# reference of ruling cultmath-tapes:ruling:cycles-kernel-reference-ruled (one IEEE single rounding per operation, +# the SSE4.2 kernel, CYCLES_CPU_NO_AVX2=1); other kernels are other builds and are never written here. +import hashlib import json import os import sys @@ -60,7 +63,8 @@ def bits(value): def rng_for(name): - return np.random.default_rng(int.from_bytes(name.encode(), "little") % (2**32)) + # One stream per name: a function, a blend mode's second colours (name + "2"), a ramp. Sharing a seed shares the draws. + return np.random.default_rng(int.from_bytes(hashlib.sha256(name.encode()).digest()[:8], "little")) def new_image(name, rgba=None): @@ -232,6 +236,9 @@ MATH = [ ("cycles_trunc", "TRUNC", 1, [SPECIAL], [(-20, 20)]), ("cycles_fract", "FRACT", 1, [SPECIAL], [(-20, 20)]), ("cycles_sign", "SIGN", 1, [SPECIAL], [(-20, 20)]), + ("cycles_arcsine", "ARCSINE", 1, [SPECIAL], [(-1.5, 1.5)]), + ("cycles_arccosine", "ARCCOSINE", 1, [SPECIAL], [(-1.5, 1.5)]), + ("cycles_arctan2", "ARCTAN2", 2, [SPECIAL, SPECIAL], [(-20, 20)] * 2), ] # Operands that must be present as exact pairs whatever the random draws: the quirks the port names. @@ -244,6 +251,10 @@ EXTRA_ROWS = { # Burn with a divisor of exactly 0 (tm + t col2 = 0) and a colour above 1: the result is 1 for the channel Cycles reads # as 0, and an infinity the film would hide for the others. "cycles_mix_burn": [(2.0, 1.5, 0.5, 2.5, 0.5, 0.5, 0.5), (0.5, 1.5, 2.0, 3.0, -1.0, -1.0, -1.0)], + # safe_asinf / safe_acosf clamp to [-1, 1]; compatible_atan2 guards only the origin (y = a, x = b). + "cycles_arcsine": [(2.0,), (-2.0,), (1.0,), (-1.0,), (1.0000001,), (-1.0000001,), (1.5,)], + "cycles_arccosine": [(2.0,), (-2.0,), (1.0,), (-1.0,), (1.0000001,), (-1.0000001,), (1.5,)], + "cycles_arctan2": [(0.0, 0.0), (0.0, -0.0), (-0.0, -0.0), (-0.0, -1.0), (0.0, -1.0), (1.0, 0.0), (-1.0, 0.0), (1.0e-7, -1.0e-7)], "cycles_modulo": [(0.3, 0.1), (-0.3, 0.1), (5.5, -2.0), (-5.5, -2.0), (1.0, 0.0), (1.0e7, 3.0), (7.0, 7.0), (-7.0, 7.0)], } @@ -309,6 +320,11 @@ def family_map_range(): columns[1][CASES - 1 - r], columns[2][CASES - 1 - r] = max(columns[1][CASES - 1 - r], columns[2][CASES - 1 - r]), min(columns[1][CASES - 1 - r], columns[2][CASES - 1 - r]) for r in range(16, 24): columns[5][CASES - 1 - r] = float(r - 18) + if kind == "SMOOTHSTEP": + # An overflowing range: from_max - from_min is infinite, and Cycles' smoothstep decides x >= edge1 before dividing. + for r, row in ((24, (3.0e38, -3.0e38, 3.0e38, 0.0, 1.0, 4.0)), (25, (3.0e38, 3.0e38, -3.0e38, 0.0, 1.0, 4.0))): + for k in range(6): + columns[k][CASES - 1 - r] = row[k] images = pack_operands(columns) def build(tree, imgs, kind=kind): @@ -526,11 +542,12 @@ def identity_check(): def kernel_check(): - """The CPU kernel must not fuse multiply-adds. + """The fixtures witness the ruled reference: Cycles' formulas with one IEEE single rounding per operation. - Cycles' AVX2 CPU kernel is compiled with FMA, so a - floor(a / b) b is one fused operation there and - 10000 mod 0.1 is -1.5e-4; the SSE4.2 kernel has none, and gives the unfused result 0 that CultMath's C# - computes. The fixtures pin the SSE4.2 kernel: run with CYCLES_CPU_NO_AVX2=1. + Ruling cultmath-tapes:ruling:cycles-kernel-reference-ruled. Cycles' AVX2 CPU kernel is compiled with FMA, so + a - floor(a / b) b is one fused operation there and 10000 mod 0.1 is -1.5e-4; the SSE4.2 kernel has none, and + gives the unfused result 0 that CultMath's C# computes. Other kernels are other builds, measured under the + tolerance classes and never written here: run with CYCLES_CPU_NO_AVX2=1. """ a = f32([10000.0] * CASES) b = f32([0.1] * CASES) @@ -547,7 +564,7 @@ def kernel_check(): got = bake("kernel", images, build, 1)[0] if not np.array_equal(got.view(np.uint32), unfused.astype(np.float32).view(np.uint32)): - sys.stderr.write("cycles-oracle: this Cycles CPU kernel fuses multiply-adds; run with CYCLES_CPU_NO_AVX2=1\n") + sys.stderr.write("cycles-oracle: this Cycles CPU kernel fuses multiply-adds, which is not the reference of ruling cycles-kernel-reference-ruled; run with CYCLES_CPU_NO_AVX2=1\n") sys.exit(4) diff --git a/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.Cycles.hlsl b/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.Cycles.hlsl index 829a27b3..7098394a 100644 --- a/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.Cycles.hlsl +++ b/packages/cultmath/unity/org.gamecult.cultmath/Shaders/CultMath.Cycles.hlsl @@ -81,10 +81,10 @@ float cultmath_cycles_modulo(float a, float b) return b != 0.0 ? (a < 0.0 ? -remainder : remainder) : 0.0; } -// safe_floored_modulo +// safe_floored_modulo; a build that contracts it differs by a bound stated at cycles_floored_modulo in math.Cycles.cs and the README float cultmath_cycles_floored_modulo(float a, float b) { return b != 0.0 ? a - floor(a / b) * b : 0.0; } -// wrapf (note the argument order: value, max, min) +// wrapf (note the argument order: value, max, min); contraction bound as for floored_modulo float cultmath_cycles_wrap(float value, float max_value, float min_value) { float range = max_value - min_value; @@ -129,6 +129,15 @@ float cultmath_cycles_fract(float a) { return a - floor(a); } // compatible_signf float cultmath_cycles_sign(float a) { return a == 0.0 ? 0.0 : (a < 0.0 ? -1.0 : 1.0); } +// safe_asinf +float cultmath_cycles_arcsine(float a) { return asin(clamp(a, -1.0, 1.0)); } + +// safe_acosf +float cultmath_cycles_arccosine(float a) { return acos(clamp(a, -1.0, 1.0)); } + +// compatible_atan2 (a is y, b is x) +float cultmath_cycles_arctan2(float a, float b) { return (b == 0.0 && a == 0.0) ? 0.0 : atan2(a, b); } + // ---- Map Range node (kernel/svm/map_range.h svm_node_map_range) ---- // A Map Range node's Clamp option is a Clamp node of type Range on its result (MapRangeNode::expand): // compose cultmath_cycles_clamp_range over these.