Skip to content

Should clamp be only defined for low <= high? #2557

Closed

Description

@zoddicus

Currently all of the versions of clamp ( for u32, i32, f32) are defined with language along these lines:

clamp(e: T , low: T, high: T) -> T

    Returns min(max(e, low), high). Component-wise when T is a vector.

with no restrictions on low and high.

All of the definitions of clamp I have looked at (C++, MSL, SPIR-V, GLSL, HLSL) either explicitly state that it only applies to low <= high, and high > low is undefined behaviour, or have language talking about the parameters being the lower and upper bounds, thus implicitly implying those restrictions.

This means that any implementation of WebGPU will have to do a polyfill when translating down to the native backend shader language, to flip low and high if needed, to avoid causing undefined behaviour, instead of just directly calling the native implementation of clamp.

Additionally the current WGSL definition of clamp has unexpected/unusual behaviour when high < low. For the common case, low <= high the result is as expected:

clamp(1, 0, 2) = min(max(1, 0), 2)
                       = min(1, 2)
                       = 1

But if we flip low and high we end up with unintuitive behaviour:

clamp(1, 2, 0) = min(max(1, 2), 0)
                       = min(2, 0)
                       = 0

If we are viewing clamp as a general function that ensures a value is on the range defined by arbitrary a and b I wouldn't expect it to clamp in this case, since 1 falls between 2 and 0.

It is actually going to return whatever the third param is, since first max operation is going to guarantee that larger of the two values is passed to the min operation, and that will always be greater that the third param when high < low.

I am proposing adding language to the spec to restrict clamp so that it is only defined if low <= high, otherwise the behaviour is undefined.

Activity

  1. added
    wgsl
    on Feb 1, 2022
  2. changed the title [-]Should `clamp` be only defined for `low` < `high`?[/-] [+]Should `clamp` be only defined for `low` <= `high`?[/+] on Feb 1, 2022
  3. added a commit that references this issue on Feb 1, 2022
  4. added this to the V1.0 milestone on Feb 2, 2022
  5. alan-baker commented on Feb 2, 2022

    @alan-baker
    Contributor

    I don't think we'd want undefined behaviour, but instead an undefined value. I know gpus have hardware instructions for clamps and it is a very common operation so I'm inclined to not polyfill it.

  6. kvark commented on Feb 4, 2022

    @kvark
    Contributor

    The same rule should apply to smoothStep as well.
    I remember from experience that having code not respecting this property is a recipe for portability disaster. I don't think we really want that for WGSL to happen. The prior decisions on handling x/-1 and friends would also be more consistent with handling "low > high" case here.

  7. kdashg commented on Feb 7, 2022

    @kdashg
    Contributor

    We prefer to default to well-defined (even if maybe unintuitive) unless we have a decently strong reason to be undefined.
    How much worse would it be to keep it defined-as min(max(a,v),b), versus the native clamp ops?

  8. kdashg commented on Feb 7, 2022

    @kdashg
    Contributor

    (which I believe is the same as clamp(v, a, max(a,b)), if that helps at all)

  9. added a commit that references this issue on Feb 7, 2022
  10. dneto0 commented on Feb 24, 2022

    @dneto0
    Contributor

    We prefer to default to well-defined (even if maybe unintuitive) unless we have a decently strong reason to be undefined.
    How much worse would it be to keep it defined-as min(max(a,v),b), versus the native clamp ops?

    I think that can't be cost-free:

    AMD GCN implements clamp as median-of-3. So in the clamp(1,2,0) case it gives 1, which is contrary to min(max(2,1),0).

    If we must have a polyfill, we can either define it as median-of-3 (which may look weird) or as

        min(max(v,  min(low,high)), max(low,high))
    

    which I believe is the same thing. We can massage it editorially:

       clamp(v,  bound0, bound1) = min(max(v, low), high) 
                where low = min(bound0, bound1) 
                and high = max(bound0, bound1)
    
  11. litherum commented on Mar 1, 2022

    @litherum
    Contributor
      clamp(1.f, 4.f, 2.f) clamp(3.f, 4.f, 2.f) clamp(5.f, 4.f, 2.f)
    Apple A12X GPU 2 2 2
    AMD Radeon Pro Vega 56 2 3‼️ 4‼️
    Intel Iris Pro Graphics 2 2 2
    NVIDIA GeForce GT 750M 2 2 2
  12. litherum commented on Mar 1, 2022

    @litherum
    Contributor

    I kind of feel we should just add both behaviors to the standard library, as different functions. clamp() would return min(max(e, low), high) and median() would return sorted(args)[1].

  13. alan-baker commented on Mar 1, 2022

    @alan-baker
    Contributor

    I think having both functions wouldn't be a great outcome. Clamping is too common. If anything, I'd suggest allowing both versions of the implementation to be correct (i.e. describe both in clamp). It is non-portable, but this seems like a place to favour performance.

  14. pow2clk commented on Mar 1, 2022

    @pow2clk

    min(max(a,v),b) is the result that both fxc and dxc produce

  15. dneto0 commented on Mar 2, 2022

    @dneto0
    Contributor

    DXC's SPIR-V backend produces a GLSL.std.450 FClamp instruction.

    Edit: min(max(x, minVal), maxVal). Result is undefined if minVal > maxVal.

  16. dneto0 commented on Mar 2, 2022

    @dneto0
    Contributor

    If anything, I'd suggest allowing both versions of the implementation to be correct (i.e. describe both in clamp). It is non-portable, but this seems like a place to favour performance.

    This sounds good to me.

  17. dneto0 commented on Mar 2, 2022

    @dneto0
    Contributor

    In the 2022-03-01 meeting @litherum suggested data showing a significant slowdown from clamp or min/max would be convincing.

    Issue gfx-rs/naga#1202 is "Out-of-bounds clamping brings big perf regression on TFJS ML demos. " Intel reported that Chrome's index clamping significantly affects performance. This is still open, and Google expects to ship WebGPU in production without making a significant fix in this space. See @ben-clayton's comment.

  18. dneto0 commented on Mar 2, 2022

    @dneto0
    Contributor

    Also, @kvark filed gfx-rs/wgpu#4360 to track this for Naga. It's still open.

  19. kdashg commented on Mar 2, 2022

    @kdashg
    Contributor
    WGSL meeting minutes 2022-03-01
    • DN: What’s in the spec now is not great; because.
    • MM: Proposed defining two functions.
    • AB: Against defining both. When do you tell people to use one and not the other. Preference is to accept both answers. Not a huge portability concer
    • MM: Q1. Should we polyfill (Alan says no), Q2: If polyfill, which one.
    • MM: (posted a table of results in the issue).
    • MM: Can poll the device to see which implementation it has, and adjust the compilation.
    • MM: Want to err on the side of being well defined.
    • AB: Many more vendors that I care about.
    • KG: Could say result is one of these two results. Median or the min/max composition.
    • AB: They will never disagree when they use parameters in the wrong places. And it’s a small price to pay to get highest performance.
    • DN: The function does what we say it does. Like Kelsey’s suggestion.
    • Let’s think about this.
    • GR: What API did the numbers come from.
    • MM: Metal.
    • GR: HLSL’s two compilers do the min/max polyfill.
    • AB: Expect a driver will reconstitute the clamp.
    • MM: The fact that HLSL always uses the polyfill is a good evidence that it’s fast enough.
    • MM: Another thing that would convince me is data showing a significant slowdown.
    • GR: Note that I didn’t check spir-v backend btw.
      • (After the meeting, DN verified the SPIR-V backend to DXC produces the Clamp instruction, not the min/max composition).
  20. kvark commented on Mar 4, 2022

    @kvark
    Contributor

    I don't think the bounds checking discussion is very relevant here. The way we are injecting clamping is very different from the way users use clamp() in their code, and our injection is not constrained by whatever choice is made in this issue.

  21. kdashg commented on Mar 9, 2022

    @kdashg
    Contributor
    WGSL meeting minutes 2022-03-08
    • DN: Our position is that we don’t want to be force to polyfill, and as spec’d we would need to.
    • MM: Agree that clamp needs to be fast. But we’re not talking about the claiming that browsers do, which is different from the problem we’re talking about for user code to normalize clamping behavior.
    • MM: We’re therefore talking about maybe-adding an extra instruction 1->2, where we don’t have compelling evidence the perf in user clamps is a problem, because we don’t know the frequencies here.
    • DN: In the user-clamping case, flipped low/high is a misuse of the API.
    • MM: I don’t know if I agree that it’s misuse.
    • GR: I would not call it fully-standardized on hlsl, but rather that today hlsl happens to ensure standardized behavior here.
    • MM: Hard to know what the trade-offs are here, so it’s hard to decide.
    • AB: I feel like we’ve made decisions before based on commonalities in underlying apis/hardware, and that that prior art is pretty strong pressure.
    • GR: Worth noting that maybe HLSL’s experience shows that it’s probably not a perf problem for users, since they haven’t complained, and (to my knowledge, no ihv tries to replace min(max()) with clamp().
    • DN: From another direction, one alternative is to just remove the builtin entirely. If you want min(max()) use min(max())
    • DN: No native APIs specify it as anything in particular.
    • MM: HLSL does polyfill this anyway on all devices.
    • (timebox’d)
  22. litherum commented on Mar 15, 2022

    @litherum
    Contributor

    Oh, I forgot to mention: the table I listed above is for floating point clamp(). For integral clamp(), the behavior is consistent with the min()max() polyfill on all devices.

    Edit: "all devices" means "the same devices described in #2557 (comment)"

    I’ve previously described a desire for integral operations to be a corner of the language where everything is well-defined. We should spec the polyfill behavior at least for integral values.

  23. kdashg commented on Mar 15, 2022

    @kdashg
    Contributor
    WGSL meeting minutes 2022-03-15
    • BC: Is there an int-clamp table? (no)
    • BC: Did you test mobile devices?
    • MM: Apple mobile devices, but not others, not Android.
    • BC: Worried about weird and wonderful Android driver implementations.
    • ??: If you think it’s risky, don’t emit clamp, emit min(max()).
    • KG: Maybe we could standardize clamp, and add fast_clamp later if needed.
    • MM: Apple’s philosophy is generally to be portable first, and add speed later if needed. We could even not call it clamp at first, call it min_max().
    • BC: I do think things need to be fast, and I think it’s a narrow usecase to worry about using clamp wrong.
    • JB: Having a choice of two definitions might be acceptable.
    • KG: if we accept both implementations in the spec and Metal always polyfills, is that portable enough?
    • MM: we would be disincentized if it were undefined values
    • AB: we could say it is either med3 or minmax
    • JB: similar to OOB
    • MM: think it differs because there is hardware to reduce the cost
    • Int-clamp to be consistent (min(max()), talk about floats next week.
  24. added a commit that references this issue on Mar 22, 2022
    c200643
  25. added a commit that references this issue on Mar 23, 2022
    faee2a2
  26. kdashg commented on Mar 23, 2022

    @kdashg
    Contributor
    WGSL meeting minutes 2022-03-22
    • Previously
      • Int-clamp to be consistent (min(max()), talk about floats [this] week.
    • RM: What is the expense of the polyfill on those GPUs.
    • KG: So looking for data or appeal to authority. HLSL?
    • DN: The current Microsoft HLSL compilers do. (FXC and DXC targeting D3D).
    • KG: Propose tying our ship to Microsoft: they can tweak and we can follow.
    • DN: Google’s position was to standardize as either median-of-3 or min/max. AMD’s implementation as median-of-three is the appeal to authority.
    • KG: Can let the market decide, and narrow it down in the future. If we think there is a material benefit to portability.
    • RM: Generally we aim for portability when perf data is not there. Can see the argument for the two-options..
    • KG: Propose concretely on one-of-these-two-behaviours. And keep it in timebox.
    • KG: Making this choice lets us narrow it down later (even in time for “v1”)
    • Needs spec: either of the two behaviours allowed.
    • DN: I’ll write it up that way.
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

    wgsl

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions