Skip to content

Metal: U32 remainder returns 4294967295 for 4294967294 % 3 #824

Closed

Description

@nicolas-abril

What you did

Compile the following remainder.bend on an Apple Silicon Mac and run the same binary on CPU and Metal:

import Base

def rem(d: U32) -> U32:
  (4294967294 % d : U32)

def main() -> IO(Unit):
  IO.print(U32.show(rem!(3)))

#|2
bend remainder.bend -o remainder
./remainder --gpu off
./remainder --gpu on

The divisor is a function parameter, and ! sends the call to the GPU when enabled.

What happened

CPU:

2

Metal:

4294967295

Expected 2 on both backends: 4294967294 = 3 * 1431655764 + 2. The Metal result is even larger than the divisor. The JS backend also correctly prints 2.

Reproduced against a clean checkout of public commit b4929c2d0d9d1e9598954aa37758954bab4d8a77, using bun bend2/main.ts in place of bend. Repeated Metal runs give the same wrong result.

Compiler / Metal details

u32_mod in bend2/comp.ts emits native % with a zero-divisor guard. The generated code for this function is:

u32 d_0 = r0;
Term a_0 = 4294967294ull;
r0 = ((u32)(d_0) == 0 ? a_0 : U32_BIN(a_0, %, d_0));

where U32_BIN(a, o, b) expands to ((u64)((u32)(a) o (u32)(b))).

Standalone Metal reproducer

This complete Objective-C program reproduces the underlying Metal failure independently of Bend. Save it as repro.m, then compile and run it without arguments:

clang -fobjc-arc -framework Metal -framework Foundation repro.m -o repro
./repro
#import <Metal/Metal.h>
#include <stdio.h>
int main(int argc, char** argv) {
  unsigned d = argc + 2;
  printf("cpu %u\n", 4294967295u % d);
  id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
  NSString* src = @""
    "#include <metal_stdlib>\n"
    "kernel void k(device uint* o [[buffer(0)]], "
    "uint id [[thread_position_in_grid]]) {"
    "  uint d = id + 3;"
    "  o[0] = 4294967295u % d;"
    "}";
  for (int safe = 0; safe < 2; safe++) {
    NSError* err = nil;
    MTLCompileOptions* opts = safe ? [MTLCompileOptions new] : nil;
    if (safe) opts.mathMode = MTLMathModeSafe;
    id<MTLLibrary> lib = [dev newLibraryWithSource:src options:opts error:&err];
    if (!lib) { NSLog(@"%@", err); return 1; }
    id<MTLComputePipelineState> ps = [dev newComputePipelineStateWithFunction:[lib newFunctionWithName:@"k"] error:&err];
    id<MTLBuffer> out = [dev newBufferWithLength:4 options:MTLResourceStorageModeShared];
    id<MTLCommandBuffer> cb = [[dev newCommandQueue] commandBuffer];
    id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoder];
    [enc setComputePipelineState:ps];
    [enc setBuffer:out offset:0 atIndex:0];
    [enc dispatchThreads:MTLSizeMake(1, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
    [enc endEncoding];
    [cb commit];
    [cb waitUntilCompleted];
    printf("gpu safe=%d %u\n", safe, *(unsigned*)out.contents);
  }
}

Expected: 0 for the CPU and both GPU runs. Observed on Apple M4 (10 GPU cores), macOS 26.3.1 (25D2128):

cpu 0
gpu safe=0 2147483525
gpu safe=1 2147483525

safe=0 uses default Metal compile options; safe=1 explicitly enables MTLMathModeSafe. The divisor comes from runtime input (argc + 2 on the CPU, thread_position_in_grid + 3 on the GPU). Bend already sets MTLMathModeSafe, so that setting does not eliminate the problem.

The equivalent Bend wrapper using 4294967295 happened to return the correct 0; using 4294967294 above exposes the failure in Bend itself. This appears to be an Apple Metal integer-remainder lowering bug that Bend needs to work around.

Environment

  • bend --version: bend 2.0.7
  • uname -sm: Darwin arm64
  • GPU: Apple M4, 10 GPU cores
  • macOS: 26.3.1 (25D2128)
  • clang --version: Apple clang version 17.0.0 (clang-1700.6.4.2)

Activity

  1. added
    bug
    on Sep 18, 2026
  2. jasisz commented on Sep 18, 2026

    @jasisz
    Contributor

    The same repro also affects U32.div on v2.0.9:

    CPU: 4294967294 / 3 = 1431655764
    Metal: 4294967294 / 3 = 1431655766

    Looks like the same root cause; mentioning it so the workaround covers both operators.

  3. VictorTaelin commented on Sep 19, 2026

    @VictorTaelin
    Contributor

    Fixed in 2.0.12. Cause: Apple's Metal compiler folds a constant U32 dividend in [2^32-128, 2^32-1] through an f32, so / and % come out wrong for any divisor (runtime dividends were fine). The U32 division templates now divide the halved dividend and fix the odd bit, on every lane; 4294967294 % 3 prints 2 on the GPU and the CPU. Update with bend update.

    Note: this reply was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions