Skip to content

Commit a0ba28e

Browse files
Metal backend: compile metal with precise and safe flags on (#16598)
This pull request updates the Metal shader compilation process to improve numerical accuracy and safety when compiling shaders on newer versions of macOS and iOS. The main change is the introduction of specific compile options for math operations when supported by the operating system. In the compileLibrary() function, added `MTLCompileOptions` when running on macOS 15.0, iOS 18.0, or newer, to ensure safer and more precise math operations during shader compilation: * `mathMode` set to `MTLMathModeSafe` (equivalent to -fmetal-math-mode=safe) * `mathFloatingPointFunctions` set to `MTLMathFloatingPointFunctionsPrecise` (equivalent to -fmetal-math-fp32-functions=precise)
1 parent 9cbe754 commit a0ba28e

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

backends/apple/metal/runtime/shims/et_metal.mm

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,13 @@ int metal_copy_memory(void* dst, const void* src, size_t nbytes, bool src_is_dev
234234
NSString* sourceString = [NSString stringWithUTF8String:shaderSource_.c_str()];
235235
NSError* error = nil;
236236

237-
library_ = [device newLibraryWithSource:sourceString options:nil error:&error];
237+
MTLCompileOptions* options = [[MTLCompileOptions new] autorelease];
238+
if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)) {
239+
options.mathMode = MTLMathModeSafe;
240+
options.mathFloatingPointFunctions = MTLMathFloatingPointFunctionsPrecise;
241+
}
242+
243+
library_ = [device newLibraryWithSource:sourceString options:options error:&error];
238244
if (!library_ || error) {
239245
ET_LOG(Error, "ETMetalShaderLibrary: Failed to compile shader library: %s",
240246
error ? [[error localizedDescription] UTF8String] : "unknown error");

0 commit comments

Comments
 (0)