Skip to content

FMod vs FRem semantics #1696

Closed
Closed

Description

@kvark

WGSL currently has x % x described as OpFMod.
SPIR-V semantics for OpFMod this is x - y * floor(x / y)
Metal semantics for fmod is x - y * trunc(x / y), which matches HLSL semantics for %, and also SPIR-V semantics for OpFRem.

Given the mostly consensus here among the APIs, I suggest we change the semantics of % to match. Thus, it should be described as OpFRem in SPIR-V.

Thanks @expenses for raising this in gfx-rs/naga#802

Activity

  1. added
    wgsl
    on Apr 29, 2021
  2. dneto0 commented on Apr 29, 2021

    @dneto0
    Contributor

    Good point. Looking closer, both MSL and GLSL have % only operating on integer scalars and vectors.
    My instinct is to remove % for floating point, and replace it with frem and fmod.

    (I haven't worked it out again, but I recall the difference is how to handle mixed signedness of the operands.)

  3. dneto0 commented on Apr 29, 2021

    @dneto0
    Contributor

    Well there you go:
    OpFRem "The floating-point remainder whose sign matches the sign of Operand 1."
    OpFMod "The floating-point remainder whose sign matches the sign of Operand 2."

  4. dneto0 commented on Apr 29, 2021

    @dneto0
    Contributor

    I found this clarifying:

    x y floor(x/y) x-y*(floor(x/y)) OpFMod trunc(x/y) x-y*trunc(x/y) OpFRem
    5 2 2 1 1 2 1 1
    5 -2 -3 -1 -1 -2 1 1
    -5 2 -3 1 1 -2 -1 -1
    -5 -2 2 -1 -1 2 -1 -1
  5. dneto0 commented on Apr 29, 2021

    @dneto0
    Contributor

    And what we're left with is a naming mess.

  6. dneto0 commented on Apr 29, 2021

    @dneto0
    Contributor

    Looks like fmod is in the standard C99 library. https://en.cppreference.com/w/c/numeric/math/fmod
    And MSL matches that. For fmod(x,y) "The returned value has the same sign as x and is less or equal to y in magnitude."

  7. added this to the MVP milestone on Apr 29, 2021
  8. dneto0 commented on Apr 29, 2021

    @dneto0
    Contributor

    Using different numbers (so it's more clear what's going on)

    x y floor(x/y) x-y*(floor(x/y)) OpFMod trunc(x/y) x-y*trunc(x/y) OpFRem
    15 4 3 3 3 3 3 3
    15 -4 -4 -1 -1 -3 3 3
    -15 4 -4 1 1 -3 -3 -3
    -15 -4 3 -3 -3 3 -3 -3
  9. RobinMorisset commented on May 4, 2021

    @RobinMorisset
    Contributor

    btw, JS seems to match HLSL/MSL/C++ here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder (it is FRem).

    I would also be ok with David's suggestion to not have '%' and just have two functions with explicit names.

  10. litherum commented on May 4, 2021

    @litherum
    Contributor

    So I thiiiiiiink where we ended up in the call today is:

    1. Add a function named fmod() that has the same semantics as OpFRem in SPIR-V. It accepts scalar floats and vectors of floats. Nothing else.
    2. Add the % operator which only operates on signed and unsigned ints, which has the same behavior regarding negative numbers as fmod() does.
  11. kvark commented on May 4, 2021

    @kvark
    ContributorAuthor

    @litherum MSL, SPIRV (and I think HLSL?) allow %/OpSrem on vectors of integers. Any reason we don't want this?

  12. dneto0 commented on May 4, 2021

    @dneto0
    Contributor

    Note: Until C++11, if one or both operands to binary operator % were negative, the sign of the remainder was implementation-defined, as it depends on the rounding direction of integer division. The function std::div provided well-defined behavior in that case.

  13. dneto0 commented on May 4, 2021

    @dneto0
    Contributor

    Also from cppreference. Since C++11, for integer division /:

    The quotient is truncated towards zero (fractional part is discarded)."

  14. kdashg commented on May 5, 2021

    @kdashg
    Contributor
    WGSL meeting minutes 2021-05-04
    • (To specify is human. To test is divine)
    • We will do an investigation into builtins in MSL and HLSL, and come back to this
    • DN: Because they are sort of named backwards in SPIR-V, I wish I could go back in time to swap them
    • AB: We sometimes choose to polyfill, and these would be easy
    • JG: But is the polyfill that useful?
    • MM: If we only have one of these supported, seems like we should just pick that one
    • TR: HLSL has mod(s) but DXIL doesn’t have builtins for it
    • MM: Proposal: Both % and the builtin, which allows us to add both later maybe
    • DN: And that it would be C99 fmod, spir-v OpFRem
    • DM: Why operator? (taste)
    • DN: Weak against float%float because e.g. C doesn’t support that anyway, but not strong feeling.
    • MM: So fmod(floats), and uint/sint %-operator
    • MM to write PR
  15. alan-baker commented on May 10, 2021

    @alan-baker
    Contributor

    To follow up up on OpSRem and OpSMod, the spec currently says it is OpSMod, but probably shouldn't. Worse than that is that Vulkan specifically says OpSRem and OpSMod with any negative input is undefined.

    For the OpSRem and OpSMod instructions, if either operand is negative the result is undefined.

  16. 13 remaining items

  17. kvark commented on Jul 21, 2021

    @kvark
    ContributorAuthor

    @dneto0 why would we need to expose OpFMod?
    What I see is - this is an operation that's only available on 1/3 backends. Unless it's actually used/desired by ISVs (1) and it has any performance benefit versus the polyfill (2), it seems straightforward to me that we'd just skip it.

    For (1) - since people don't write SPIR-V, and instead write GLSL/HLSL, which do not have an analogue to OpFMod, their programs aren't expected to use this instruction. I did a quick check on the shader playground, and % translates to OpFRem, as expected.
    For (2) we don't have any data.

  18. kainino0x commented on Sep 10, 2021

    @kainino0x
    Contributor

    munrocket:

    comparison of OpFMod vs OpFRem
    (from https://en.wikipedia.org/wiki/Modulo_operation#Variants_of_the_definition)

    axinging:

    We are working on converting glsl to wgsl in TFJS. In order to convert glsl mod to wgsl, we first use %, but it not work. Then we implement mod as below:

      // From https://github.com/tensorflow/tfjs/pull/5589/files
      fn mod(a : f32, b : f32) -> f32 {
        return a - b * floor(a/b);
      }
      fn modVec4(a : vec4<f32>, b : vec4<f32>) -> vec4<f32> {
        return a - b * floor(a/b);
      }
    

    Based on our experience, it's straightforward to use % as mod. So we strongly agree % should have its conventional OpFMod behavior

    @axinging What was the original GLSL using - mod(), I assume? It seems GLSL doesn't define % for floats.

    Also can you give some info about why you rely on the OpFMod behavior specifically? Is it just generally because you want to port code more directly from GLSL?

  19. kainino0x commented on Sep 10, 2021

    @kainino0x
    Contributor

    Reopening for discussion

  20. axinging commented on Sep 10, 2021

    @axinging

    axinging:

    We are working on converting glsl to wgsl in TFJS. In order to convert glsl mod to wgsl, we first use %, but it not work. Then we implement mod as below:

      // From https://github.com/tensorflow/tfjs/pull/5589/files
      fn mod(a : f32, b : f32) -> f32 {
        return a - b * floor(a/b);
      }
      fn modVec4(a : vec4<f32>, b : vec4<f32>) -> vec4<f32> {
        return a - b * floor(a/b);
      }
    

    Based on our experience, it's straightforward to use % as mod. So we strongly agree % should have its conventional OpFMod behavior

    @axinging What was the original GLSL using - mod(), I assume? It seems GLSL doesn't define % for floats.

    Also can you give some info about why you rely on the OpFMod behavior specifically? Is it just generally because you want to port code more directly from GLSL?

    Yes, if mod and % behave the same, we can port code from GLSL to WGSL more directly.
    Below is the use case (Note: the mod in WGSL is implemented by us, to make it the same as GLSL mod):

    const POW = `
      if(a < 0.0 && floor(b) < b) {
        return NAN;
      }
      if (b == 0.0) {
        return 1.0;
      }
      // For GLSL, use mod.
      return (round(mod(b, 2.0)) != 1) ?
          pow(abs(a), b) : sign(a) * pow(abs(a), b);
      `;
    
    const POW_WGSL = `
      if(a < 0.0 && floor(b) < b) {
        return f32(uniforms.NAN);
      }
      if (b == 0.0) {
        return 1.0;
      }
      // For WGSL, use mod implemented by us
      if (i32(round(mod(b, 2.0))) != 1) {
        return pow(abs(a), b);
      }
      return sign(a) * pow(abs(a), b);
      `;
    
  21. munrocket commented on Sep 10, 2021

    @munrocket
    Contributor

    @axinging I believe it can be fixed like this

    return (round(mod(b, 2.0)) != 1) ? // before
    if ((i32(round(b)) % 2) != 1) { // after, same in wgsl and glsl

    Also I will share my fixes

    // hsv2rgb
    mod(c.x * 6.0 + vec3(0.0, 4.0, 2.0), 6.0) // before
    fract(vec3<f32>(c.x, c.x + 2./3., c.x + 1./3.)) * 6. // after
    return (p + 0.5 * c % c) - 0.5 * c; // before
    return p - c * round(p / c); // after
    let bn = (atan2(p.x, p.y) % (2. * an)) - an; // before
    let bn = (atan2(abs(p.x), p.y) % (2. * an)) - an; // after
  22. munrocket commented on Sep 10, 2021

    @munrocket
    Contributor

    How this functions disassembles in MSL and HLSL? Should we be restricted by OpFRem semantic because this function exist on hardware level? Seems current specification mixing different conventions for int's and float's.

  23. ben-clayton commented on Sep 10, 2021

    @ben-clayton
    Contributor

    How this functions disassembles in MSL and HLSL?

    See the top of this issue and #1913 (comment).
    HLSL and MSL have intrinsics that map to OpFRem, which is why we went with it.
    GLSL is the odd one out here.

  24. munrocket commented on Sep 10, 2021

    @munrocket
    Contributor

    Nice to hear it, thanks! So we can count each FLOP just by using current spec. GLSL mod polyfill in WGSL will not give that possibility.

  25. kvark commented on Sep 10, 2021

    @kvark
    ContributorAuthor

    Seems current specification mixing different conventions for int's and float's.

    I specifically wanted us to have the same behavior for ints and floats. Both should be OpFRem today. What is different?

  26. munrocket commented on Sep 10, 2021

    @munrocket
    Contributor

    Current spec:
    T is i32 or vecN -> OpSMod -> sign matches the sign of Operand 2
    T is u32 or vecN -> OpUMod -> sign matches the sign of Operand 2
    T is f32 or vecN -> OpFRem -> sign matches the sign of Operand 1
    Result sign matches to another operand for floats. Better to create fmod() for consistency.

    Also I checked HLSL output in DXBC, seems that fmod just a syntax sugar there and gives 3 vectorised FLOP. Metal IR have such thing as fast_fmod, but I can imagine world when this IR become 3 FLOP eventually.

    OpFMod is periodic function which is a good property, also expression let uv = (xy % vec2<f32>(10.)); gives you tiled texture if you using OpFMod. So in the wild even HLSL/MSL programmers creating #define mod(x, y) (x - y * floor(x / y)) helper sometimes.

  27. kvark commented on Sep 10, 2021

    @kvark
    ContributorAuthor

    @munrocket the current spec doesn't reflect the group consensus on integer division. #1830 does, instead.
    @dneto0 I think we should just land it.

  28. munrocket commented on Sep 10, 2021

    @munrocket
    Contributor

    the current spec doesn't reflect the group consensus on integer division.

    I didn't know that, I am simple man that fixing my WGSL according to spec.

  29. added a commit that references this issue on Apr 23, 2025
    fc091f1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

wgsl

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions