Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions Docs/03_Advanced/04_Math-Functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
`<ILGPUCompilationOptions>--math Fast</ILGPUCompilationOptions>` 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
<PropertyGroup>
<ILGPUCompilationOptions>--fma Off</ILGPUCompilationOptions>
</PropertyGroup>
```

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.
Expand Down
208 changes: 208 additions & 0 deletions Src/ILGPUC.Tests/BackendTests/FusedMultiplyAddSourceTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
public sealed class FusedMultiplyAddSourceTests
{
/// <summary>
/// Subtracts two products, which native compilers fuse into a multiply-add.
/// </summary>
internal static void FusionKernel(
Index1D index,
ArrayView1D<float, Stride1D.Dense> 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);

/// <summary>
/// Returns the flags of the native compile request of the given backend.
/// </summary>
private static async Task<string> 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;
}

/// <summary>
/// Fusion is the default of the compilation properties and of the
/// command line.
/// </summary>
[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);
}

/// <summary>
/// The --fma option selects the fusion mode in any case.
/// </summary>
[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);
}

/// <summary>
/// nvcc fuses multiply-adds unless --fmad=false is passed.
/// </summary>
[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);
}

/// <summary>
/// hipcc fuses multiply-adds unless -ffp-contract=off is passed.
/// </summary>
[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"));
}

/// <summary>
/// The Metal compiler fuses multiply-adds unless -ffp-contract=off is
/// passed.
/// </summary>
[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"));
}

/// <summary>
/// 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.
/// </summary>
[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<FusedMultiplyAddMode>())
{
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));
}
}

/// <summary>
/// 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.
/// </summary>
[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);
}
}
99 changes: 98 additions & 1 deletion Src/ILGPUC.Tests/BackendTests/MetalSourceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
using ILGPUC.Tests.Kernels;
using System;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;

namespace ILGPUC.Tests.BackendTests;

/// <summary>
/// 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.
/// </summary>
public sealed class MetalSourceTests
{
Expand Down Expand Up @@ -69,6 +71,101 @@ public void Int64Atomics_ReportError()
Assert.Contains("not supported by Metal", Flatten(exception));
}

/// <summary>
/// Divides by a constant and subtracts a product in half precision.
/// </summary>
internal static void HalfDivisionKernel(
Index1D index,
ArrayView1D<Half, Stride1D.Dense> 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)!;

/// <summary>
/// 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.
/// </summary>
[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<float>(0x3EAAAAABu)"));
}

/// <summary>
/// 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.
/// </summary>
[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;
Expand Down
Loading
Loading