From 6a65dfa349444edb298bfa234bd4eeda8d87246f Mon Sep 17 00:00:00 2001 From: Marcel Koester Date: Sat, 24 Oct 2026 21:35:00 +0100 Subject: [PATCH 1/4] Added the FusedMultiplyAddMode compilation property and the --fma option, which allow multiply-add fusion on all backends by default and turn it off with --fmad=false on CUDA, -ffp-contract=off on ROCm and Metal, the FP_CONTRACT pragmas in OpenCL and Metal sources and correctly rounded half divisions by constants on Metal. Co-Authored-By: Claude --- Src/ILGPUC/Backends/Backend.cs | 14 ++++++++++ Src/ILGPUC/Backends/CUDA/CUDABackend.cs | 3 ++- Src/ILGPUC/Backends/CodeGenerator.cs | 5 ++-- Src/ILGPUC/Backends/ExpressionEmitter.cs | 14 ++++++++++ Src/ILGPUC/Backends/IntrinsicEmitter.cs | 16 +++++++++++ Src/ILGPUC/Backends/LanguageConfiguration.cs | 6 ++++- Src/ILGPUC/Backends/Metal/MetalBackend.cs | 5 ++-- .../Backends/Metal/MetalIntrinsicEmitter.cs | 27 +++++++++++++++++++ .../Metal/MetalLanguageConfiguration.cs | 26 ++++++++++++++++++ .../OpenCL/CLLanguageConfiguration.cs | 8 +++++- Src/ILGPUC/Backends/ROCm/ROCmBackend.cs | 3 ++- Src/ILGPUC/CompilationProperties.cs | 27 +++++++++++++++++++ Src/ILGPUC/IR/ModuleValues/Module.cs | 7 +++++ .../Program.CompilationPropertiesOptions.cs | 9 +++++++ 14 files changed, 162 insertions(+), 8 deletions(-) diff --git a/Src/ILGPUC/Backends/Backend.cs b/Src/ILGPUC/Backends/Backend.cs index 0175b79e3..af7d2d8a9 100644 --- a/Src/ILGPUC/Backends/Backend.cs +++ b/Src/ILGPUC/Backends/Backend.cs @@ -477,6 +477,20 @@ protected virtual CodeGenerationResult GenerateCode( where TManager : ICompilerManager => Task.FromResult(null); + /// + /// Returns the native compiler flag that disables multiply-add fusion + /// if turns it off. + /// + /// The compilation properties. + /// The flag of the native compiler. + /// The flag, or an empty string if fusion is allowed. + protected static string GetFusionFlag( + CompilationProperties properties, + string flag) => + properties.FusedMultiplyAddMode == FusedMultiplyAddMode.Off + ? flag + : string.Empty; + /// /// Translates an ILGPU to the corresponding /// . ILGPU exposes O0..O2; we offset by one diff --git a/Src/ILGPUC/Backends/CUDA/CUDABackend.cs b/Src/ILGPUC/Backends/CUDA/CUDABackend.cs index 473d2ed9f..7d06d64a1 100644 --- a/Src/ILGPUC/Backends/CUDA/CUDABackend.cs +++ b/Src/ILGPUC/Backends/CUDA/CUDABackend.cs @@ -82,7 +82,8 @@ protected override ArchitectureSpecification GetArchitectureSpecification() => Target = CompilationTarget.Cuda, OutputType = OutputType.Binary, OptimizationLevel = GetNativeOptLevel(properties.OptimizationLevel), - ExtraFlags = archFlags, + ExtraFlags = archFlags + + GetFusionFlag(properties, " --fmad=false"), }, ct).ConfigureAwait(false); } } diff --git a/Src/ILGPUC/Backends/CodeGenerator.cs b/Src/ILGPUC/Backends/CodeGenerator.cs index 863aec812..279411f29 100644 --- a/Src/ILGPUC/Backends/CodeGenerator.cs +++ b/Src/ILGPUC/Backends/CodeGenerator.cs @@ -116,10 +116,11 @@ private void GenerateHeader(GenerationContext context) context.WriteLine(); // Emit pragmas - foreach (var pragma in languageConfig.GetPragmas()) + var pragmas = languageConfig.GetPragmas(module.FusedMultiplyAddMode).ToArray(); + foreach (var pragma in pragmas) context.WriteLine(pragma); - if (languageConfig.GetPragmas().Any()) + if (pragmas.Length > 0) context.WriteLine(); } diff --git a/Src/ILGPUC/Backends/ExpressionEmitter.cs b/Src/ILGPUC/Backends/ExpressionEmitter.cs index ff062a152..600f84c42 100644 --- a/Src/ILGPUC/Backends/ExpressionEmitter.cs +++ b/Src/ILGPUC/Backends/ExpressionEmitter.cs @@ -587,6 +587,20 @@ private Emitted EmitBinaryArithmetic(BinaryArithmeticValue binary) var left = Emit(binary.Left); var right = Emit(binary.Right); + // Half divisions by constants are correctly rounded if fusion is + // turned off and no fast math mode is requested + if (binary.Kind == BinaryArithmeticKind.Div && + binary.ArithmeticBasicValueType == ArithmeticBasicValueType.Float16 && + binary.Right is PrimitiveValue divisor && + context.Module.FusedMultiplyAddMode == FusedMultiplyAddMode.Off && + context.Module.MathMode == MathMode.Default && + IntrinsicEmitter.EmitPreciseHalfDivision( + left.Text, + divisor.Float16Value) is string division) + { + return new Emitted(division, Prec.Postfix); + } + // Half operations other than the basic arithmetic are evaluated in // single precision (see WidenHalf) if (binary.ArithmeticBasicValueType == ArithmeticBasicValueType.Float16 && diff --git a/Src/ILGPUC/Backends/IntrinsicEmitter.cs b/Src/ILGPUC/Backends/IntrinsicEmitter.cs index 438f9306d..199b0037f 100644 --- a/Src/ILGPUC/Backends/IntrinsicEmitter.cs +++ b/Src/ILGPUC/Backends/IntrinsicEmitter.cs @@ -491,4 +491,20 @@ public abstract string EmitWarpScan( public abstract string EmitHalfConstant(ushort rawBits); #endregion + + #region Precise Arithmetic + + /// + /// Emits a correctly rounded Half (Float16) division by a constant divisor, + /// which is used if fusion is turned off and no fast math mode is + /// requested. + /// + /// The dividend expression. + /// The constant divisor. + /// + /// The backend-specific division, or null to emit the division operator. + /// + public virtual string? EmitPreciseHalfDivision(string left, Half divisor) => null; + + #endregion } diff --git a/Src/ILGPUC/Backends/LanguageConfiguration.cs b/Src/ILGPUC/Backends/LanguageConfiguration.cs index 89d141316..6e4c03418 100644 --- a/Src/ILGPUC/Backends/LanguageConfiguration.cs +++ b/Src/ILGPUC/Backends/LanguageConfiguration.cs @@ -132,7 +132,11 @@ public virtual string GetPointerTypeName( /// /// Gets language-specific pragmas or attributes. /// - public virtual IEnumerable GetPragmas() => []; + /// + /// Whether multiplications and additions may be fused into multiply-adds. + /// + public virtual IEnumerable GetPragmas( + FusedMultiplyAddMode fusedMultiplyAdd) => []; /// /// Formats a constant in the target language, or returns null to use the diff --git a/Src/ILGPUC/Backends/Metal/MetalBackend.cs b/Src/ILGPUC/Backends/Metal/MetalBackend.cs index 05d720a8e..19d923666 100644 --- a/Src/ILGPUC/Backends/Metal/MetalBackend.cs +++ b/Src/ILGPUC/Backends/Metal/MetalBackend.cs @@ -74,9 +74,10 @@ protected override ArchitectureSpecification GetArchitectureSpecification() => // The Metal compiler enables fast math by default, which assumes // no NaNs, infinities or signed zeros (folding e.g. x != x to // false). Only the fast math modes opt into it. - ExtraFlags = properties.MathMode == MathMode.Default + ExtraFlags = (properties.MathMode == MathMode.Default ? "-fno-fast-math" - : "-ffast-math", + : "-ffast-math") + + GetFusionFlag(properties, " -ffp-contract=off"), }, ct).ConfigureAwait(false); } } diff --git a/Src/ILGPUC/Backends/Metal/MetalIntrinsicEmitter.cs b/Src/ILGPUC/Backends/Metal/MetalIntrinsicEmitter.cs index c2fe5fe56..760e553e5 100644 --- a/Src/ILGPUC/Backends/Metal/MetalIntrinsicEmitter.cs +++ b/Src/ILGPUC/Backends/Metal/MetalIntrinsicEmitter.cs @@ -564,4 +564,31 @@ public override string EmitHalfConstant(ushort rawBits) => $"as_type((ushort)0x{rawBits:X4})"; #endregion + + #region Precise Arithmetic + + /// + /// Metal divides half values by a constant by multiplying with the + /// half-precision reciprocal of the constant, which is not correctly + /// rounded. Divisions by normal powers of two are exact multiplications and + /// zeros, infinities and NaN divide as usual; all other constants divide + /// through ilgpu_div_half (defined in the source header). + /// + public override string? EmitPreciseHalfDivision(string left, Half divisor) + { + ushort bits = BitConverter.HalfToUInt16Bits(divisor); + if (!Half.IsFinite(divisor) || divisor == Half.Zero || + Half.IsNormal(divisor) && (bits & 0x3FF) == 0) + { + return null; + } + + float value = (float)divisor; + float reciprocal = 1.0f / value; + return $"ilgpu_div_half({left}, " + + $"as_type(0x{BitConverter.SingleToUInt32Bits(value):X8}u), " + + $"as_type(0x{BitConverter.SingleToUInt32Bits(reciprocal):X8}u))"; + } + + #endregion } diff --git a/Src/ILGPUC/Backends/Metal/MetalLanguageConfiguration.cs b/Src/ILGPUC/Backends/Metal/MetalLanguageConfiguration.cs index d58687daf..57d7a98a1 100644 --- a/Src/ILGPUC/Backends/Metal/MetalLanguageConfiguration.cs +++ b/Src/ILGPUC/Backends/Metal/MetalLanguageConfiguration.cs @@ -134,6 +134,32 @@ public override IEnumerable GetHeaderIncludes() yield return " }"; yield return " return metal::signbit(x) ? -r : r;"; yield return "}"; + + // Correctly rounded half division by a constant divisor c with the + // single-precision reciprocal r of c. The quotient in single precision + // is corrected by its exact remainder and rounds to the correctly + // rounded half quotient. Zeros, infinities and NaN keep the first + // quotient, whose remainder is zero or not finite. + yield return "inline half ilgpu_div_half(half x, float c, float r) {"; + yield return " float a = (float)x;"; + yield return " float q = a * r;"; + yield return " float e = metal::fma(-q, c, a);"; + yield return " return (half)(e != 0.0f && metal::isfinite(e) " + + "? metal::fma(e, r, q) : q);"; + yield return "}"; + } + + /// + /// Disables the multiply-add fusion of the Metal compiler, which fuses + /// multiplications and additions within an expression by default, if + /// fusion is turned off. The pragma also applies when the source is + /// compiled at runtime. + /// + public override IEnumerable GetPragmas( + FusedMultiplyAddMode fusedMultiplyAdd) + { + if (fusedMultiplyAdd == FusedMultiplyAddMode.Off) + yield return "#pragma STDC FP_CONTRACT OFF"; } /// diff --git a/Src/ILGPUC/Backends/OpenCL/CLLanguageConfiguration.cs b/Src/ILGPUC/Backends/OpenCL/CLLanguageConfiguration.cs index 973cb889e..d2b75b8c7 100644 --- a/Src/ILGPUC/Backends/OpenCL/CLLanguageConfiguration.cs +++ b/Src/ILGPUC/Backends/OpenCL/CLLanguageConfiguration.cs @@ -252,7 +252,8 @@ public override string EmitNonFlattenedKernelParam( } /// - public override IEnumerable GetPragmas() + public override IEnumerable GetPragmas( + FusedMultiplyAddMode fusedMultiplyAdd) { // cl_khr_fp64 is required for any kernel that uses `double` — // OpenCL C disallows it without an explicit enable pragma. @@ -271,6 +272,11 @@ public override IEnumerable GetPragmas() yield return "#pragma OPENCL EXTENSION cl_intel_subgroups : enable"; else yield return "#pragma OPENCL EXTENSION cl_khr_subgroup_shuffle : enable"; + + // OpenCL C allows fusion by default; the pragma disables it for + // the offline compilers and for builds of the source at runtime + if (fusedMultiplyAdd == FusedMultiplyAddMode.Off) + yield return "#pragma OPENCL FP_CONTRACT OFF"; } /// diff --git a/Src/ILGPUC/Backends/ROCm/ROCmBackend.cs b/Src/ILGPUC/Backends/ROCm/ROCmBackend.cs index 5a0b5def1..afe70ac74 100644 --- a/Src/ILGPUC/Backends/ROCm/ROCmBackend.cs +++ b/Src/ILGPUC/Backends/ROCm/ROCmBackend.cs @@ -76,7 +76,8 @@ protected override ArchitectureSpecification GetArchitectureSpecification() => OptimizationLevel = GetNativeOptLevel(properties.OptimizationLevel), // AMD GPUs have no PTX-style JIT fallback: the code object must // be built for the exact gfx target it will run on. - ExtraFlags = $"--offload-arch={arch}", + ExtraFlags = $"--offload-arch={arch}" + + GetFusionFlag(properties, " -ffp-contract=off"), }, ct).ConfigureAwait(false); } } diff --git a/Src/ILGPUC/CompilationProperties.cs b/Src/ILGPUC/CompilationProperties.cs index 77e3cd5c5..5568351ae 100644 --- a/Src/ILGPUC/CompilationProperties.cs +++ b/Src/ILGPUC/CompilationProperties.cs @@ -98,6 +98,28 @@ public enum MathMode Fast32BitOnly } +/// +/// Specifies whether floating-point multiplications and additions may be fused +/// into multiply-adds. +/// +public enum FusedMultiplyAddMode +{ + /// + /// The native compilers may fuse multiplications and additions into + /// multiply-adds, which round once instead of twice. + /// + /// + /// This is the default setting. + /// + Fast, + + /// + /// Multiplications and additions are never fused into multiply-adds on any + /// backend, so that every operation rounds like it does on the host. + /// + Off, +} + /// /// Internal flags to specify the behavior in the presence of static fields. /// @@ -158,6 +180,10 @@ public enum ArrayMode /// Optimization level to use. /// Inlining mode to use. /// Math mode to use. +/// +/// Specifies whether multiplications and additions may be fused into +/// multiply-adds. +/// /// Static field mode to use. /// Array mode to use. /// @@ -173,6 +199,7 @@ public sealed record class CompilationProperties( OptimizationLevel OptimizationLevel = OptimizationLevel.O1, InliningMode InliningMode = InliningMode.Aggressive, MathMode MathMode = MathMode.Default, + FusedMultiplyAddMode FusedMultiplyAddMode = FusedMultiplyAddMode.Fast, StaticFieldMode StaticFieldMode = StaticFieldMode.Default, ArrayMode ArrayMode = ArrayMode.Default, int ConstantEvaluationBudget = CompilationProperties.DefaultConstantEvaluationBudget) diff --git a/Src/ILGPUC/IR/ModuleValues/Module.cs b/Src/ILGPUC/IR/ModuleValues/Module.cs index 4034c488f..e1331da69 100644 --- a/Src/ILGPUC/IR/ModuleValues/Module.cs +++ b/Src/ILGPUC/IR/ModuleValues/Module.cs @@ -155,6 +155,7 @@ internal void Initialize(ModuleBuilder moduleBuilder) _basicValueTypes.Add(type, moduleBuilder.GetPrimitiveType(type)); MathMode = moduleBuilder.Properties.MathMode; + FusedMultiplyAddMode = moduleBuilder.Properties.FusedMultiplyAddMode; TargetPlatform = moduleBuilder.TargetPlatform; IntPointerArithmeticType = moduleBuilder.IntPointerArithmeticType; @@ -185,6 +186,12 @@ internal void Initialize(ModuleBuilder moduleBuilder) /// public MathMode MathMode { get; private set; } + /// + /// Returns whether multiplications and additions may be fused into + /// multiply-adds. + /// + public FusedMultiplyAddMode FusedMultiplyAddMode { get; private set; } + /// /// Returns the main entry point handle. /// diff --git a/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs b/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs index 4888a5069..a529eaebb 100644 --- a/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs +++ b/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs @@ -66,6 +66,13 @@ sealed class CompilationPropertiesOptions DefaultValueFactory = static _ => MathMode.Default }; + /// Controls the fusion of multiplications and additions into multiply-adds. + readonly Option _fusedMultiplyAddOption = new("--fma") + { + Description = "Specifies whether multiplications and additions may be fused into multiply-adds (Fast, the default) or not (Off)", + DefaultValueFactory = static _ => FusedMultiplyAddMode.Fast + }; + /// Forces floating-point math to flush denormal values to zero. readonly Option _mathFlushToZeroOption = new("--ftz") { @@ -133,6 +140,7 @@ public CompilationPropertiesOptions(Command command) command.Add(_inliningModeOption); command.Add(_mathModeOption); + command.Add(_fusedMultiplyAddOption); command.Add(_mathFlushToZeroOption); command.Add(_staticFieldModeOption); command.Add(_arrayModeOption); @@ -158,6 +166,7 @@ public CompilationProperties GetProperties(ParseResult result) InliningMode = result.GetValue(_inliningModeOption), MathMode = result.GetValue(_mathModeOption), + FusedMultiplyAddMode = result.GetValue(_fusedMultiplyAddOption), EnableMathFlushToZero = result.GetValue(_mathFlushToZeroOption), StaticFieldMode = result.GetValue(_staticFieldModeOption), ArrayMode = result.GetValue(_arrayModeOption), From a307d10911a4a980351c1b671bb4db939d535e41 Mon Sep 17 00:00:00 2001 From: Marcel Koester Date: Sat, 24 Oct 2026 22:20:00 +0100 Subject: [PATCH 2/4] Added CPU and Metal execution tests for half and float divisions with fusion allowed and turned off, and Metal tests for the correctly rounded half divisions by constants and the fusion and math compile options. Co-Authored-By: Claude --- .../BackendTests/MetalSourceTests.cs | 99 ++++++++++++++- .../HalfPrecisionExecutionTests.cs | 120 ++++++++++++++++++ .../Framework/RecordingCompilerManager.cs | 42 ++++++ .../HalfPrecision/HalfDivision.cs | 119 +++++++++++++++++ .../HalfPrecision/HalfDivisionByConstants.cs | 93 ++++++++++++++ 5 files changed, 472 insertions(+), 1 deletion(-) create mode 100644 Src/ILGPUC.Tests/Framework/RecordingCompilerManager.cs create mode 100644 Src/ILGPUC.Tests/TestPrograms/HalfPrecision/HalfDivision.cs create mode 100644 Src/ILGPUC.Tests/TestPrograms/HalfPrecision/HalfDivisionByConstants.cs diff --git a/Src/ILGPUC.Tests/BackendTests/MetalSourceTests.cs b/Src/ILGPUC.Tests/BackendTests/MetalSourceTests.cs index 905ec245d..9fcd85a34 100644 --- a/Src/ILGPUC.Tests/BackendTests/MetalSourceTests.cs +++ b/Src/ILGPUC.Tests/BackendTests/MetalSourceTests.cs @@ -16,13 +16,15 @@ using ILGPUC.Tests.Kernels; using System; using System.Reflection; +using System.Threading.Tasks; using Xunit; namespace ILGPUC.Tests.BackendTests; /// /// Checks that the Metal backend rejects what Metal cannot express with a -/// clear compile-time error instead of emitting invalid source. +/// clear compile-time error instead of emitting invalid source, and that it +/// selects precise or fast math and fusion as requested. /// public sealed class MetalSourceTests { @@ -69,6 +71,101 @@ public void Int64Atomics_ReportError() Assert.Contains("not supported by Metal", Flatten(exception)); } + /// + /// Divides by a constant and subtracts a product in half precision. + /// + internal static void HalfDivisionKernel( + Index1D index, + ArrayView1D data) + { + data[index] = data[index] / (Half)3.0f - data[index + 1] * data[index + 2]; + } + + private static readonly MethodInfo HalfDivision = typeof(MetalSourceTests) + .GetMethod( + nameof(HalfDivisionKernel), + BindingFlags.NonPublic | BindingFlags.Static)!; + + /// + /// Turning fusion off disables multiply-add fusion and divides + /// half values by constants through the correctly rounded division helper + /// unless a fast math mode is requested; by default, the native division + /// and multiply-adds are kept. + /// + [Theory] + [InlineData(FusedMultiplyAddMode.Fast, MathMode.Default, false)] + [InlineData(FusedMultiplyAddMode.Fast, MathMode.Fast, false)] + [InlineData(FusedMultiplyAddMode.Off, MathMode.Default, true)] + [InlineData(FusedMultiplyAddMode.Off, MathMode.Fast, false)] + public void HalfDivision_EmitsPreciseMath( + FusedMultiplyAddMode fusedMultiplyAdd, + MathMode mathMode, + bool precise) + { + using var helper = new CompilationHelper(BackendType.Metal); + var source = helper.GenerateBackendCode( + HalfDivision, + BackendType.Metal, + new CompilationProperties( + MathMode: mathMode, + FusedMultiplyAddMode: fusedMultiplyAdd)).SourceCode; + + Assert.Equal( + fusedMultiplyAdd == FusedMultiplyAddMode.Off, + source.Contains("#pragma STDC FP_CONTRACT OFF")); + // The source header always defines the helper + Assert.Equal(precise ? 2 : 1, source.Split("ilgpu_div_half(").Length - 1); + Assert.Equal( + precise, + source.Contains("as_type(0x3EAAAAABu)")); + } + + /// + /// The Metal compiler runs with fast math disabled unless a fast math mode + /// is requested, and so does the runtime compilation of embedded source. + /// Turning fusion off disables it in the Metal compiler as well. + /// + [Theory] + [InlineData(MathMode.Default, FusedMultiplyAddMode.Fast, "-fno-fast-math", false)] + [InlineData( + MathMode.Default, + FusedMultiplyAddMode.Off, + "-fno-fast-math -ffp-contract=off", + false)] + [InlineData(MathMode.Fast, FusedMultiplyAddMode.Fast, "-ffast-math", true)] + [InlineData( + MathMode.Fast, + FusedMultiplyAddMode.Off, + "-ffast-math -ffp-contract=off", + true)] + [InlineData(MathMode.Fast32BitOnly, FusedMultiplyAddMode.Fast, "-ffast-math", true)] + public async Task MathMode_SelectsCompileOptions( + MathMode mathMode, + FusedMultiplyAddMode fusedMultiplyAdd, + string flags, + bool fastMath) + { + var properties = new CompilationProperties( + MathMode: mathMode, + FusedMultiplyAddMode: fusedMultiplyAdd); + using var helper = new CompilationHelper(BackendType.Metal); + var source = helper.GenerateBackendCode( + HalfDivision, + BackendType.Metal, + properties); + + var manager = new RecordingCompilerManager(); + var backend = CompilationHelper.CreateBackend(BackendType.Metal); + await backend.CompileSourceAsync(source, manager, properties); + Assert.Equal(flags, manager.Request?.ExtraFlags); + + var (_, wrapper) = helper.GenerateLauncher( + HalfDivision, + BackendType.Metal, + props: properties); + Assert.Equal(fastMath, wrapper.Contains("fastMath: true")); + } + private static string Flatten(Exception exception) { var message = string.Empty; diff --git a/Src/ILGPUC.Tests/ExecutionTests/HalfPrecisionExecutionTests.cs b/Src/ILGPUC.Tests/ExecutionTests/HalfPrecisionExecutionTests.cs index 067a5ee67..09030b03c 100644 --- a/Src/ILGPUC.Tests/ExecutionTests/HalfPrecisionExecutionTests.cs +++ b/Src/ILGPUC.Tests/ExecutionTests/HalfPrecisionExecutionTests.cs @@ -534,4 +534,124 @@ await VerifyProgramOutputAsync( "585", "585", "841", "73", "73", "4356" ]); } + + /// + /// The bits of the results of every lane of HalfDivision, which match + /// System.Half and float on the host. + /// + private static readonly string[] HalfDivisionOutput = + [ + "13653", "13653", "17066", "6784", "16727", "0", "1076538027", + "1051372203", "14677", "14677", "18090", "7936", "17751", "0", + "1084926635", "1059760811", "12434", "13653", "17066", "6016", "18140", + "0", "1088122295", "1051372203", "14450", "16043", "19498", "6400", + "20878", "0", "1110558492", "1070945621", "13653", "10308", "13653", + "8480", "46257", "3003121664", "3197849218", "1023969417", "47383", + "49323", "52693", "10992", "54469", "0", "3264789039", "3222623573", + "13627", "15787", "19221", "54462", "52540", "3058696192", "1113305402", + "1068848469", "16228", "15408", "18748", "47356", "16829", "0", + "1080002701", "1065749131", "31744", "29922", "31744", "-1", "64512", + "-1", "4286578688", "2123789977", "31744", "29922", "31744", "31744", + "31744", "2139095040", "2139095040", "2123789977", "64512", "62690", + "64512", "-1", "31744", "-1", "2139095040", "4271273625", "15045", + "13789", "17236", "45208", "14090", "3205854959", "0", "1052490684", + "14043", "11879", "15360", "11804", "45022", "1046466867", "847249408", + "1036831949", "30719", "30037", "31744", "64512", "-1", "4286578688", + "-1", "2125104745", "12629", "13653", "17066", "6528", "17878", "0", + "1085975211", "1051372203", "205", "341", "2729", "32915", "3239", "0", + "52647397", "20282339" + ]; + + /// + /// The number of results per lane of HalfDivision. + /// + private const int HalfDivisionResults = 8; + + /// + /// Half and float divisions and differences of quotients and products run + /// with fusion allowed. The divisions by values cannot be fused and + /// match the host; CPU kernels never fuse and match the host in every line. + /// + [SkippableFact] + public async Task HalfDivision_ProducesCorrectOutput() + { + RequireCapability(Backend, BackendCapability.Float16); + var result = await RunProgramAsync( + "TestPrograms/HalfPrecision/HalfDivision.cs", + ["Kernels.HalfDivisionKernel"]); + + Assert.False(result.TimedOut, "Test program timed out"); + Assert.Equal(0, result.ExitCode); + if (Backend == BackendType.CPU) + { + OutputVerifier.Verify(result.StdOutLines, HalfDivisionOutput); + return; + } + + Assert.Equal(HalfDivisionOutput.Length, result.StdOutLines.Length); + for (int i = 0; i < HalfDivisionOutput.Length; i += HalfDivisionResults) + { + // a / b and x / 3 + Assert.Equal(HalfDivisionOutput[i], result.StdOutLines[i]); + Assert.Equal(HalfDivisionOutput[i + 7], result.StdOutLines[i + 7]); + } + } + + /// + /// With fusion turned off, half divisions by values and by constants + /// that are not powers of two are correctly rounded, and differences of + /// quotients and products are not fused into multiply-adds, like + /// System.Half and float on the host. + /// + [SkippableFact] + public async Task HalfDivisionWithoutFusion_ProducesCorrectOutput() + { + RequireCapability(Backend, BackendCapability.Float16); + await VerifyProgramOutputAsync( + "TestPrograms/HalfPrecision/HalfDivision.cs", + ["Kernels.HalfDivisionKernel"], + HalfDivisionOutput, + new CompilationProperties( + FusedMultiplyAddMode: FusedMultiplyAddMode.Off)); + } + + /// + /// With fusion turned off, every Half value divided by constants, + /// including subnormal values, the largest finite value and powers of two, + /// matches System.Half on the host. + /// + [SkippableFact] + public async Task HalfDivisionByConstants_ProducesCorrectOutput() + { + RequireCapability(Backend, BackendCapability.Float16); + await VerifyProgramOutputAsync( + "TestPrograms/HalfPrecision/HalfDivisionByConstants.cs", + ["Kernels.HalfDivisionByConstantsKernel"], + [ + "0: 0", "1: 0", "2: 0", "3: 0", "4: 0", "5: 0", "6: 0", "7: 0", + "8: 0", "9: 0" + ], + new CompilationProperties( + FusedMultiplyAddMode: FusedMultiplyAddMode.Off)); + } + + /// + /// Half divisions by constants compile and run with fusion allowed and + /// in the fast math mode, which keep the native division of the backend. + /// + [SkippableTheory] + [InlineData(MathMode.Default)] + [InlineData(MathMode.Fast)] + public async Task HalfDivisionByConstantsNative_ProducesOutput(MathMode mathMode) + { + RequireCapability(Backend, BackendCapability.Float16); + var result = await RunProgramAsync( + "TestPrograms/HalfPrecision/HalfDivisionByConstants.cs", + ["Kernels.HalfDivisionByConstantsKernel"], + new CompilationProperties(MathMode: mathMode)); + + Assert.False(result.TimedOut, "Test program timed out"); + Assert.Equal(0, result.ExitCode); + Assert.Equal(10, result.StdOutLines.Length); + } } diff --git a/Src/ILGPUC.Tests/Framework/RecordingCompilerManager.cs b/Src/ILGPUC.Tests/Framework/RecordingCompilerManager.cs new file mode 100644 index 000000000..c4e42107a --- /dev/null +++ b/Src/ILGPUC.Tests/Framework/RecordingCompilerManager.cs @@ -0,0 +1,42 @@ +// --------------------------------------------------------------------------------------- +// ILGPU +// Copyright (c) 2026 ILGPU Project +// www.ilgpu.net +// +// File: RecordingCompilerManager.cs +// +// This file is part of ILGPU and is distributed under the University of Illinois Open +// Source License. See LICENSE.txt for details. +// --------------------------------------------------------------------------------------- + +using ILGPUC.Compilers; +using System.Threading; +using System.Threading.Tasks; + +namespace ILGPUC.Tests.Framework; + +/// +/// Records the compile request of a backend and reports a failed compilation, +/// so that tests can check the native compiler options without a toolchain. +/// +internal sealed class RecordingCompilerManager : ICompilerManager +{ + /// + /// The last compile request. + /// + public CompileRequest? Request { get; private set; } + + /// + public Task CompileAsync( + CompileRequest request, + CancellationToken ct) + { + Request = request; + return Task.FromResult(new CompilationResult { Success = false }); + } + + /// + public Task GetCapabilitiesAsync( + CancellationToken ct) => + Task.FromResult(new CompilationCapabilities { Compilers = [] }); +} diff --git a/Src/ILGPUC.Tests/TestPrograms/HalfPrecision/HalfDivision.cs b/Src/ILGPUC.Tests/TestPrograms/HalfPrecision/HalfDivision.cs new file mode 100644 index 000000000..1d646f84c --- /dev/null +++ b/Src/ILGPUC.Tests/TestPrograms/HalfPrecision/HalfDivision.cs @@ -0,0 +1,119 @@ +// --------------------------------------------------------------------------------------- +// ILGPU +// Copyright (c) 2026 ILGPU Project +// www.ilgpu.net +// +// File: HalfDivision.cs +// +// This file is part of ILGPU and is distributed under the University of Illinois Open +// Source License. See LICENSE.txt for details. +// --------------------------------------------------------------------------------------- + +// disable: max_line_length +// Test program: HalfDivision +// Half and float divisions by values and by constants and differences of +// quotients and products. With fusion turned off, the divisions are +// correctly rounded, and a / b - o * v and a * b - o * v round the quotient or +// product before the subtraction instead of fusing them into a multiply-add +// (which turns the NaN of inf - inf into an infinity). Each lane prints the +// bits of every Half and float result (-1 for NaN, whose bit pattern differs +// between the backends). + +using System; +using ILGPU; +using ILGPU.Runtime; + +static class Kernels +{ + internal const int NumResults = 8; + + internal static long Bits(Half value) => + Half.IsNaN(value) ? -1 : BitConverter.HalfToUInt16Bits(value); + + internal static long Bits(float value) => + float.IsNaN(value) ? -1 : BitConverter.SingleToUInt32Bits(value); + + public static void HalfDivisionKernel( + Index1D index, + ArrayView1D h, + ArrayView1D f, + ArrayView1D output) + { + Half a = h[index * 4], b = h[index * 4 + 1]; + Half o = h[index * 4 + 2], v = h[index * 4 + 3]; + float x = f[index * 4], y = f[index * 4 + 1]; + float p = f[index * 4 + 2], q = f[index * 4 + 3]; + int offset = index * NumResults; + output[offset] = Bits(a / b); + output[offset + 1] = Bits(a / (Half)3.0f); + output[offset + 2] = Bits(a / (Half)0.3f); + output[offset + 3] = Bits(a / b - o * v); + output[offset + 4] = Bits(a * b - o * v); + output[offset + 5] = Bits(x / y - p * q); + output[offset + 6] = Bits(x * y - p * q); + output[offset + 7] = Bits(x / 3.0f); + } +} + +static class Program +{ + // a, b, o and v of every lane + internal static readonly Half[] H = + [ + (Half)1.0f, (Half)3.0f, (Half)0.1f, (Half)3.3f, + (Half)2.0f, (Half)3.0f, (Half)1.1f, (Half)0.6f, + (Half)1.0f, (Half)7.0f, (Half)0.3f, (Half)0.47f, + (Half)5.0f, (Half)9.0f, (Half)0.7f, (Half)0.79f, + (Half)0.1f, (Half)0.3f, (Half)1.9f, (Half)0.17f, + (Half)(-7.0f), (Half)11.0f, (Half)2.3f, (Half)(-0.3f), + (Half)4.25f, (Half)13.0f, (Half)7.7f, (Half)9.9f, + (Half)3.14159f, (Half)1.7f, (Half)1.3f, (Half)1.9f, + (Half)60000.0f, (Half)0.5f, (Half)300.0f, (Half)300.0f, + (Half)60000.0f, (Half)0.5f, (Half)(-300.0f), (Half)300.0f, + (Half)(-60000.0f), (Half)0.25f, (Half)300.0f, (Half)(-300.0f), + (Half)1.1f, (Half)1.3f, (Half)1.1f, (Half)0.9f, + (Half)0.3f, (Half)0.7f, (Half)0.9f, (Half)0.37f, + (Half)65504.0f, (Half)2.0f, (Half)256.0f, (Half)300.0f, + (Half)1.0f, (Half)6.0f, (Half)0.4f, (Half)0.41f, + (Half)6.1e-5f, (Half)5.0f, (Half)0.003f, (Half)0.007f, + ]; + + // x, y, p and q of every lane + internal static readonly float[] F = + [ + 1.0f, 3.0f, 0.1f, 3.3333333f, + 2.0f, 3.0f, 1.1f, 0.6060606f, + 1.0f, 7.0f, 0.3f, 0.47619048f, + 5.0f, 9.0f, 0.7f, 0.7936508f, + 0.1f, 0.3f, 1.9f, 0.17543860f, + -7.0f, 11.0f, 2.3f, -0.27667984f, + 4.25f, 13.0f, 7.7f, 0.042457946f, + 3.14159f, 1.7f, 1.3f, 1.4215339f, + 3.0e38f, 0.5f, 2.0e19f, 3.0e19f, + 3.0e38f, 0.5f, -2.0e19f, 3.0e19f, + -3.0e38f, 0.25f, 2.0e19f, -3.0e19f, + 1.1f, 1.3f, 1.1f, 1.3f, + 0.3f, 0.7f, 0.9f, 0.23333333f, + 3.4e38f, 2.0f, 1.8446744e19f, 1.8446744e19f, + 1.0f, 6.0f, 0.4f, 0.41666666f, + 1.0e-37f, 5.0f, 3.0e-19f, 6.6666664e-20f, + ]; + + static void Main() + { + using var context = Context.Create(b => b.Default()); + using var accelerator = context.GetPreferredDevice(preferCPU: true) + .CreateAccelerator(context); + var stream = accelerator.DefaultStream; + + int numLanes = H.Length / 4; + using var h = stream.Allocate1D(H); + using var f = stream.Allocate1D(F); + using var output = stream.Allocate1D(Kernels.NumResults * numLanes); + stream.Launch((Index1D)numLanes, index => Kernels.HalfDivisionKernel(index, h.View, f.View, output.View)); + stream.Synchronize(); + + foreach (var value in output.GetAsArray1D()) + Console.WriteLine(value); + } +} diff --git a/Src/ILGPUC.Tests/TestPrograms/HalfPrecision/HalfDivisionByConstants.cs b/Src/ILGPUC.Tests/TestPrograms/HalfPrecision/HalfDivisionByConstants.cs new file mode 100644 index 000000000..2df5488ce --- /dev/null +++ b/Src/ILGPUC.Tests/TestPrograms/HalfPrecision/HalfDivisionByConstants.cs @@ -0,0 +1,93 @@ +// --------------------------------------------------------------------------------------- +// ILGPU +// Copyright (c) 2026 ILGPU Project +// www.ilgpu.net +// +// File: HalfDivisionByConstants.cs +// +// This file is part of ILGPU and is distributed under the University of Illinois Open +// Source License. See LICENSE.txt for details. +// --------------------------------------------------------------------------------------- + +// disable: max_line_length +// Test program: HalfDivisionByConstants +// Divides every Half value by constants (powers of two, subnormal values, the +// largest finite value and values that are not powers of two) in a kernel and +// compares the bits of the quotients with System.Half on the host. Prints the +// number of differing quotients per constant, which is zero with fusion +// turned off. + +using System; +using ILGPU; +using ILGPU.Runtime; + +static class Kernels +{ + internal const int NumDivisors = 10; + + internal static Half Divide(Half x, int k) => k switch + { + 0 => x / (Half)3.0f, + 1 => x / (Half)7.0f, + 2 => x / (Half)0.3f, + 3 => x / (Half)(-1.7f), + 4 => x / (Half)1000.3f, + 5 => x / (Half)0.25f, + 6 => x / (Half)65504.0f, + 7 => x / BitConverter.UInt16BitsToHalf(0x0010), + 8 => x / BitConverter.UInt16BitsToHalf(0x0005), + _ => x / (Half)11.0f, + }; + + public static void HalfDivisionByConstantsKernel( + Index1D index, + ArrayView1D output) + { + var x = BitConverter.UInt16BitsToHalf((ushort)(int)index); + int offset = index * NumDivisors; + output[offset] = BitConverter.HalfToUInt16Bits(Divide(x, 0)); + output[offset + 1] = BitConverter.HalfToUInt16Bits(Divide(x, 1)); + output[offset + 2] = BitConverter.HalfToUInt16Bits(Divide(x, 2)); + output[offset + 3] = BitConverter.HalfToUInt16Bits(Divide(x, 3)); + output[offset + 4] = BitConverter.HalfToUInt16Bits(Divide(x, 4)); + output[offset + 5] = BitConverter.HalfToUInt16Bits(Divide(x, 5)); + output[offset + 6] = BitConverter.HalfToUInt16Bits(Divide(x, 6)); + output[offset + 7] = BitConverter.HalfToUInt16Bits(Divide(x, 7)); + output[offset + 8] = BitConverter.HalfToUInt16Bits(Divide(x, 8)); + output[offset + 9] = BitConverter.HalfToUInt16Bits(Divide(x, 9)); + } +} + +static class Program +{ + const int NumValues = 1 << 16; + + static void Main() + { + using var context = Context.Create(b => b.Default()); + using var accelerator = context.GetPreferredDevice(preferCPU: true) + .CreateAccelerator(context); + var stream = accelerator.DefaultStream; + + using var output = stream.Allocate1D(NumValues * Kernels.NumDivisors); + stream.Launch((Index1D)NumValues, index => Kernels.HalfDivisionByConstantsKernel(index, output.View)); + stream.Synchronize(); + + var quotients = output.GetAsArray1D(); + for (int k = 0; k < Kernels.NumDivisors; ++k) + { + int mismatches = 0; + for (int i = 0; i < NumValues; ++i) + { + var expected = Kernels.Divide(BitConverter.UInt16BitsToHalf((ushort)i), k); + var actual = BitConverter.UInt16BitsToHalf(quotients[i * Kernels.NumDivisors + k]); + bool equal = Half.IsNaN(expected) + ? Half.IsNaN(actual) + : BitConverter.HalfToUInt16Bits(expected) == BitConverter.HalfToUInt16Bits(actual); + if (!equal) + ++mismatches; + } + Console.WriteLine($"{k}: {mismatches}"); + } + } +} From c8784ea0918b86c0d53b05523046ca8c9d3e50cb Mon Sep 17 00:00:00 2001 From: Marcel Koester Date: Sat, 24 Oct 2026 23:05:00 +0100 Subject: [PATCH 3/4] Documented the FusedMultiplyAddMode property and the --fma option, which fuse multiply-adds on all GPU backends by default and compute every operation like the host when turned off, and the fast math of Metal. Co-Authored-By: Claude --- Docs/03_Advanced/04_Math-Functions.md | 32 +++++++++++++++++++++++++++ Src/ILGPUC/CompilationProperties.cs | 30 +++++++++++++++++++++---- 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/Docs/03_Advanced/04_Math-Functions.md b/Docs/03_Advanced/04_Math-Functions.md index e4e250789..c7ebf3d63 100644 --- a/Docs/03_Advanced/04_Math-Functions.md +++ b/Docs/03_Advanced/04_Math-Functions.md @@ -18,6 +18,38 @@ like `x / y`. Context context = Context.Create(builder => builder.Math(MathMode.Fast)); ``` +On Metal, the fast math modes (`--math Fast` or `--math Fast32BitOnly`, for instance +`--math Fast` in the project file) enable the fast math of the Metal +compiler, which approximates divisions and uses the fast variants of the math functions. +Without a fast math mode, the Metal compiler runs without fast math. + +### Fused Multiply-Adds + +By default, the native compilers of all GPU backends may fuse multiplications and additions into multiply-adds +for the best performance. +A fused multiply-add rounds once instead of twice, so an expression like `a * b - c * d` or `a / b - c * d` may differ +from the host in the last bit, and an infinite product may yield an infinity instead of the NaN of `inf - inf`. + +To compute every operation like the host, turn fusion off with `--fma Off`, for instance in the project +file: + +```xml + + --fma Off + +``` + +or with `FusedMultiplyAddMode.Off` in the `CompilationProperties` passed to the compiler. +This applies to all backends: CUDA kernels are compiled with `--fmad=false`, ROCm kernels with `-ffp-contract=off`, +OpenCL sources start with `#pragma OPENCL FP_CONTRACT OFF` and Metal sources with `#pragma STDC FP_CONTRACT OFF` (and +are compiled with `-ffp-contract=off`), and the pragmas also apply when the runtime compiles the embedded source. +In addition, Metal kernels then divide `Half` values by constants with correct rounding instead of multiplying with +the rounded reciprocal of the constant (unless a fast math mode is requested), so `Half` and `float` results match +`System.Half` and `float` on the host. + +CPU kernels never fuse multiplications and additions: they are C# code compiled by the .NET JIT, which does not +fuse floating-point operations, so they match the host in both modes. + ### Forced 32-bit Math Your kernels might rely on third-party functions that are not under your control. diff --git a/Src/ILGPUC/CompilationProperties.cs b/Src/ILGPUC/CompilationProperties.cs index 5568351ae..ca5135414 100644 --- a/Src/ILGPUC/CompilationProperties.cs +++ b/Src/ILGPUC/CompilationProperties.cs @@ -87,6 +87,11 @@ public enum MathMode /// /// Use fast math functions that are less precise. /// + /// + /// On Metal, this mode enables the fast math of the Metal compiler: half and + /// float divisions are approximated and the fast variants of the math + /// functions are used. + /// Fast, /// @@ -102,21 +107,38 @@ public enum MathMode /// Specifies whether floating-point multiplications and additions may be fused /// into multiply-adds. /// +/// +/// A fused multiply-add rounds once instead of twice, so expressions like +/// a * b - c * d may differ from the host in the last bit, and the NaN of +/// an infinite difference may become an infinity. CPU kernels are C# code that +/// the .NET JIT compiles without ever fusing multiplications and additions, so +/// they match the host in both modes. +/// public enum FusedMultiplyAddMode { /// /// The native compilers may fuse multiplications and additions into - /// multiply-adds, which round once instead of twice. + /// multiply-adds on all GPU backends for the best performance. /// /// - /// This is the default setting. + /// This is the default setting (--fma Fast). /// Fast, /// - /// Multiplications and additions are never fused into multiply-adds on any - /// backend, so that every operation rounds like it does on the host. + /// Multiplications and additions are never fused into multiply-adds, so that + /// every operation rounds like it does on the host. /// + /// + /// This mode (--fma Off) passes --fmad=false to nvcc on + /// CUDA and -ffp-contract=off to hipcc on ROCm and to the Metal + /// compiler. OpenCL and Metal sources start with + /// #pragma OPENCL FP_CONTRACT OFF and + /// #pragma STDC FP_CONTRACT OFF, which also apply when the runtime + /// compiles the embedded source. Unless a fast math mode is requested, Metal + /// kernels additionally divide half values by constants with correct + /// rounding instead of multiplying with the reciprocal of the constant. + /// Off, } From 5156a4cb610c1ba166ed7e50d6a5698d313dc39b Mon Sep 17 00:00:00 2001 From: Marcel Koester Date: Sat, 24 Oct 2026 23:45:00 +0100 Subject: [PATCH 4/4] Added tests for the fusion flags and pragmas of every backend, the sources embedded for runtime compilation and the --fma option. Co-Authored-By: Claude --- .../FusedMultiplyAddSourceTests.cs | 208 ++++++++++++++++++ Src/ILGPUC.Tests/ILGPUC.Tests.csproj | 2 + .../Program.CompilationPropertiesOptions.cs | 2 +- 3 files changed, 211 insertions(+), 1 deletion(-) create mode 100644 Src/ILGPUC.Tests/BackendTests/FusedMultiplyAddSourceTests.cs diff --git a/Src/ILGPUC.Tests/BackendTests/FusedMultiplyAddSourceTests.cs b/Src/ILGPUC.Tests/BackendTests/FusedMultiplyAddSourceTests.cs new file mode 100644 index 000000000..6b934ef63 --- /dev/null +++ b/Src/ILGPUC.Tests/BackendTests/FusedMultiplyAddSourceTests.cs @@ -0,0 +1,208 @@ +// --------------------------------------------------------------------------------------- +// ILGPU +// Copyright (c) 2026 ILGPU Project +// www.ilgpu.net +// +// File: FusedMultiplyAddSourceTests.cs +// +// This file is part of ILGPU and is distributed under the University of Illinois Open +// Source License. See LICENSE.txt for details. +// --------------------------------------------------------------------------------------- + +using ILGPU; +using ILGPU.Runtime; +using ILGPUC.Backends; +using ILGPUC.Tests.Framework; +using System; +using System.CommandLine; +using System.Reflection; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Xunit; + +namespace ILGPUC.Tests.BackendTests; + +/// +/// Checks that every backend allows multiply-add fusion by default and +/// disables it in the generated source, the native compiler options and the +/// runtime compilation of embedded source if fusion is turned off. +/// +public sealed class FusedMultiplyAddSourceTests +{ + /// + /// Subtracts two products, which native compilers fuse into a multiply-add. + /// + internal static void FusionKernel( + Index1D index, + ArrayView1D data) + { + data[index] = data[index] * data[index + 1] - data[index + 2] * data[index + 3]; + } + + private static readonly MethodInfo Fusion = typeof(FusedMultiplyAddSourceTests) + .GetMethod( + nameof(FusionKernel), + BindingFlags.NonPublic | BindingFlags.Static)!; + + private static string NormalizeNames(string source) => + Regex.Replace(source, @"(?<=_)\d+", "N"); + + private static CompilationProperties GetProperties( + FusedMultiplyAddMode fusedMultiplyAdd) => + new(FusedMultiplyAddMode: fusedMultiplyAdd); + + /// + /// Returns the flags of the native compile request of the given backend. + /// + private static async Task GetCompilerFlagsAsync( + BackendType backendType, + FusedMultiplyAddMode fusedMultiplyAdd) + { + var properties = GetProperties(fusedMultiplyAdd); + using var helper = new CompilationHelper(backendType); + var source = helper.GenerateBackendCode(Fusion, backendType, properties); + + var manager = new RecordingCompilerManager(); + var backend = CompilationHelper.CreateBackend(backendType); + await backend.CompileSourceAsync(source, manager, properties); + Assert.NotNull(manager.Request); + return manager.Request.ExtraFlags ?? string.Empty; + } + + /// + /// Fusion is the default of the compilation properties and of the + /// command line. + /// + [Fact] + public void Default_AllowsFusion() + { + Assert.Equal( + FusedMultiplyAddMode.Fast, + new CompilationProperties().FusedMultiplyAddMode); + + var command = new Command("compile"); + var options = new Program.CompilationPropertiesOptions(command); + Assert.Equal( + FusedMultiplyAddMode.Fast, + options.GetProperties(command.Parse([])).FusedMultiplyAddMode); + } + + /// + /// The --fma option selects the fusion mode in any case. + /// + [Theory] + [InlineData("fast", FusedMultiplyAddMode.Fast)] + [InlineData("off", FusedMultiplyAddMode.Off)] + [InlineData("Off", FusedMultiplyAddMode.Off)] + public void CommandLine_SelectsFusion( + string value, + FusedMultiplyAddMode expected) + { + var command = new Command("compile"); + var options = new Program.CompilationPropertiesOptions(command); + var result = command.Parse(["--fma", value]); + + Assert.Empty(result.Errors); + Assert.Equal(expected, options.GetProperties(result).FusedMultiplyAddMode); + } + + /// + /// nvcc fuses multiply-adds unless --fmad=false is passed. + /// + [Theory] + [InlineData(FusedMultiplyAddMode.Fast, false)] + [InlineData(FusedMultiplyAddMode.Off, true)] + public async Task Cuda_PassesFmadFlag( + FusedMultiplyAddMode fusedMultiplyAdd, + bool disabled) + { + var flags = await GetCompilerFlagsAsync(BackendType.Cuda, fusedMultiplyAdd); + Assert.Equal(disabled, flags.Contains("--fmad=false")); + Assert.DoesNotContain("--fmad=true", flags); + } + + /// + /// hipcc fuses multiply-adds unless -ffp-contract=off is passed. + /// + [Theory] + [InlineData(FusedMultiplyAddMode.Fast, false)] + [InlineData(FusedMultiplyAddMode.Off, true)] + public async Task ROCm_PassesFusionFlag( + FusedMultiplyAddMode fusedMultiplyAdd, + bool disabled) + { + var flags = await GetCompilerFlagsAsync(BackendType.ROCm, fusedMultiplyAdd); + Assert.Equal(disabled, flags.Contains("-ffp-contract=off")); + } + + /// + /// The Metal compiler fuses multiply-adds unless -ffp-contract=off is + /// passed. + /// + [Theory] + [InlineData(FusedMultiplyAddMode.Fast, false)] + [InlineData(FusedMultiplyAddMode.Off, true)] + public async Task Metal_PassesFusionFlag( + FusedMultiplyAddMode fusedMultiplyAdd, + bool disabled) + { + var flags = await GetCompilerFlagsAsync(BackendType.Metal, fusedMultiplyAdd); + Assert.Equal(disabled, flags.Contains("-ffp-contract=off")); + } + + /// + /// OpenCL and Metal sources disable fusion with their pragmas, which + /// apply to the offline compilers and to the source the runtime compiles + /// if no binary is embedded. CUDA and ROCm sources need no pragma, as + /// their native compilers receive the flags. + /// + [Theory] + [InlineData(BackendType.OpenCL, "#pragma OPENCL FP_CONTRACT OFF")] + [InlineData(BackendType.Metal, "#pragma STDC FP_CONTRACT OFF")] + public void Source_EmitsFusionPragma(BackendType backendType, string pragma) + { + using var helper = new CompilationHelper(backendType); + foreach (var mode in Enum.GetValues()) + { + bool disabled = mode == FusedMultiplyAddMode.Off; + var source = helper.GenerateBackendCode( + Fusion, + backendType, + GetProperties(mode)).SourceCode; + Assert.Equal(disabled, source.Contains(pragma)); + Assert.DoesNotContain("FP_CONTRACT ON", source); + + // Without a binary, the wrapper embeds the source for the runtime + var (_, wrapper) = helper.GenerateLauncher( + Fusion, + backendType, + props: GetProperties(mode)); + Assert.Contains("KernelSource", wrapper); + Assert.Equal(disabled, wrapper.Contains(pragma)); + } + } + + /// + /// CUDA and ROCm sources are the same in both modes (up to the generated + /// names), and so are CPU kernels, whose C# multiplications and additions + /// the .NET JIT never fuses. + /// + [Theory] + [InlineData(BackendType.Cuda)] + [InlineData(BackendType.ROCm)] + [InlineData(BackendType.CPU)] + public void Source_IsIndependentOfFusion(BackendType backendType) + { + using var helper = new CompilationHelper(backendType); + var fast = helper.GenerateBackendCode( + Fusion, + backendType, + GetProperties(FusedMultiplyAddMode.Fast)).SourceCode; + var off = helper.GenerateBackendCode( + Fusion, + backendType, + GetProperties(FusedMultiplyAddMode.Off)).SourceCode; + Assert.Equal(NormalizeNames(fast), NormalizeNames(off)); + Assert.DoesNotContain("FP_CONTRACT", off); + } +} diff --git a/Src/ILGPUC.Tests/ILGPUC.Tests.csproj b/Src/ILGPUC.Tests/ILGPUC.Tests.csproj index 18ecb018c..864036ce5 100644 --- a/Src/ILGPUC.Tests/ILGPUC.Tests.csproj +++ b/Src/ILGPUC.Tests/ILGPUC.Tests.csproj @@ -18,6 +18,8 @@ + + diff --git a/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs b/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs index a529eaebb..b9fcfe192 100644 --- a/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs +++ b/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs @@ -20,7 +20,7 @@ sealed partial class Program /// /// Registers compilation properties command-line switches. /// - sealed class CompilationPropertiesOptions + internal sealed class CompilationPropertiesOptions { /// Debug symbols mode to embed in generated code. readonly Option _debugSymbolsOption = new("--debug-symbols")