Skip to content

wgsl: add way to get special values for a given numeric type (e.g. max, min, lowest) #3431

Open

Description

@dneto0

Since infinity and NaN can't be relied upon, it would be useful to have an easy way to get special values for specific types.
E.g. max value, min value, lowest (smallest positive number, including subnormal), lowest normal number.
Things like max and min are useful as seed values for reductions.

A few ideas:

  • Use predeclared names like FLT_MAX, etc like in C. That uses a lot of names.
  • Create @const functions for them, e.g. max<f32>()
  • Create a @const limit function whose first template parameterization is a context-dependent name, e.g.:
    • limit<max,f32>() is like FLT_MAX
    • limit<min,f32>() is like FLT_MIN
    • limit<lowest,f32>() is like C++ std::numeric_limits::lowest<f32>
    • Since subnormals might be flushed to zero, limit<lowest_normal,f32>() could be useful too as a more portable thing

We can't spell abstract types, and we want to keep the ability to expand the range of the abstract numeric types. So consider carefully whether to make this feature for them.

Activity

  1. added
    wgsl
    on Sep 10, 2022
  2. added this to the V1.0 milestone on Sep 10, 2022
  3. dneto0 commented on Sep 13, 2022

    @dneto0
    ContributorAuthor

    @ben-clayton suggested wording like highest<f32> lowest<f32> smallest<f32>. He dislikes min and max as confusing.

  4. dneto0 commented on Sep 20, 2022

    @dneto0
    ContributorAuthor

    The concept of "lowest" is confusing.

    From an example at cppreference:

    type lowest() min() max()
    bool 0 0 1
    uchar 0 0 255
    int -2147483648 -2147483648 2147483647
    float -3.40282e+38 1.17549e-38 3.40282e+38
    double -1.79769e+308 2.22507e-308 1.79769e+308

    For float and double I would have swapped "lowest" and "min". Sigh.

  5. kdashg commented on Sep 20, 2022

    @kdashg
    Contributor
    WGSL 2022-09-20 Minutes
    • DN: Because inf and nan is not reliable, and want to have max, want the most negative or positive thing would be nice to have way to say that. C has macros, c++ has stuff. Names are confusing. Some mechanism to do that would be nice, not dogmatic on what that is.
    • MM: This is a good feature in general. From experimentation, HLSL doesn't seem to have this
    • TR: Think that's right
    • MM: For GLSL not in compiler explorer. For MSL uses FLT_MAX processor defines. Little sad with that as think ergonomics of global isn't great. because some GPUs support inf and some dont', saying largest or biggest isn't quite right as there is a bigger number.
    • AB: Could be verbose largest_positive_normal().
    • ds: FYI there’s this too: https://shader-playground.timjones.io/
    • MM: Idea by BC to have highest<type> but making functions rather then variables. Increases probability that adding feature that deals with <> will play nicely.
    • DN: Right, wasn't implying variables. Function form is nice.
    • MM: Don't want std::numeric_limits. Went back and looked and we don't have namespaces.
    • KG: When you say functions do you mean smallest&lt;f32>() that gives smallest
    • AB: Dislike exposing template like params outside types.
    • MM: DG had similar thoughts. Grammar distinguishes between type constructors and function calls. Doesn't have to be true. Adds a bit of complexity to grammar and spec but doesn't necessarily add implementation complexity.
    • KG: smallest(a: T) -> T
    • MM:
      • let x = 3;
      • let y = smallest(x);
    • DN: Give me the thing which is the smallest of whatever this thing is.
    • MM: Names smallest is confusing, expect that to act like min. Would expect min(x) to just return x.
    • KG: Right, maybe ergonomics don't work out.
    • DN: Left unit for comparison of this type
    • MM: Good as it internalizes the the [...] but is useful when you compare them.
    • KG: Worth thinking about, but don't' want to spend innovation budget here. JB, what does rust do?
    • JB: Rust has associated constant on type f32::max not sure if it's type or module. Both a type f32 and module std::f32. Some kind of scoped associated constant. Probably not what we want here.
    • MM: Use case to consider, imagine buffer of float and want minimum float. Variable lives outside loop and is initialize,d loop goes over all and comparse current to outside. Usecase here is the outside gets initialized to largest thing, there is no comparison to pass in. There is no x it's a standalone. Should make sure we can satisfy the use case.
    • KG: +1. Might end up with smallest_like or smallest_of and could just have smallest_u32. Also like u32.min or f32.smallest. Think about it a bit and give some time.
    • MM: That’s also what Swift does, e.g. int.min
    • Let’s table and think more before deciding here
  6. dneto0 commented on Sep 20, 2022

    @dneto0
    ContributorAuthor
    1. FYI. The mathematical term we were looking for is "unit".

    https://encyclopediaofmath.org/wiki/Unit

    An element e in a set M is called a left (right) unit (left (right) identity) with respect to a binary operation ∗ defined on M if for any a∈M the following equation holds:
    e∗a=a ( a∗e=a ) .

    So for

    • negative-infinity is the unit, for floats over 'min'
    • 0u is the unit for u32 for 'min'
    • -2,147,483,648 is the unit for i32 for 'min'

    So that maybe gives a naming direction for min and max, e.g. unitMin and unitMax.
    Taking @kdashg suggestion of giving a sample value to deduce the type:

     unitMin(e:T) -> T   //   computes  the value  e such that    min(e,a) = min(a,e) = a for all a in T
    
    1. We may want to separate finite and infinite units. E.g.

      unitMinFinite(e:T) -> T // computes the finite value e in T such that min(e,a) = min(a,e) for all finite a in T

    2. We still have a naming issue for "smallest normal number" or "smallest subnormal number", which we could usefully have for floating point types.
      In that regard, we could reuse the 'nextafter' pattern from C++ https://en.cppreference.com/w/cpp/numeric/math/nextafter and OpenCL C https://man.opencl.org/nextafter.html

    But you'd probably want normal and subnormal variations.
    E.g.
    const smallest_normal_float = nextNormal(0.0f,500.0f); // the second param tells you which direction to go
    const smallest_subnormal_float = nextSubnormal(0.0f, 5f);

    Note that nextNormal and nextSubnormal would be extremely useful for ULP calculations. :-)


    edit: min(e,a) = min(a,e) = a was missing the = a part

  7. dneto0 commented on Oct 3, 2022

    @dneto0
    ContributorAuthor

    Let's make this concrete:

    Proposal 1:

    • unitMinFinite(T) -> T
      • the value e such that min(e,a) = min(a,e)=a for all finite a in T
      • T is any type for which min(T,T) overload exists
    • unitMaxFinite is defined analogously, w.r.t. max

    Proposal 2:

    If/when we add an extension that makes infinities reliable, then add:

    • unitMin(T) -> T
      • the value e such that min(e,a)=min(a,e)=a for any a in T, including infinities.
    • unitMax define analogously

    For as long as infinity is unreliable, there's no sensible way to define unitMin, I think.

    Proposal 3:

    • smallestNormal(e:T)
      • T is a floating point type.
      • The smallest positive normal floating point value in T
    • smallestSubnormal(e:T)
      • T is a floating point type
      • The smallest positive normal floating point value in T
  8. litherum commented on Oct 4, 2022

    @litherum
    Contributor

    FYI. The mathematical term we were looking for is "unit".
    https://encyclopediaofmath.org/wiki/Unit

    An element e in a set M is called a left (right) unit (left (right) identity) with respect to a binary operation ∗ defined on M if for any a∈M the following equation holds:
    e∗a=a ( a∗e=a ) .

    Is that really what we're looking for?

    "An element e in a set M is called a ... unit ... if for any a∈M the following equation holds: e∗a=a ( a∗e=a )."

    If FLT_MAX is a unit, then we'd set e = FLT_MAX and a = 7 (for example) and get FLT_MAX * 7 = 7, which seems to be false.

    Maybe I'm misunderstanding?

  9. dj2 commented on Oct 4, 2022

    @dj2
    Member

    Do all those proposals require me to have an existing var? I can't say unitMin<i32>() ?

    The unit also looks very very similar to uint.

  10. dneto0 commented on Oct 4, 2022

    @dneto0
    ContributorAuthor

    FYI. The mathematical term we were looking for is "unit".
    https://encyclopediaofmath.org/wiki/Unit
    An element e in a set M is called a left (right) unit (left (right) identity) with respect to a binary operation ∗ defined on M if for any a∈M the following equation holds:
    e∗a=a ( a∗e=a ) .

    Is that really what we're looking for?

    "An element e in a set M is called a ... unit ... if for any a∈M the following equation holds: e∗a=a ( a∗e=a )."

    If FLT_MAX is a unit, then we'd set e = FLT_MAX and a = 7 (for example) and get FLT_MAX * 7 = 7, which seems to be false.

    Maybe I'm misunderstanding?

    In the math text the * stands in for abstract binary operations. And we're interested in min and max.

    So we want the e such that min(e,a) = min(a,e) = a

  11. dneto0 commented on Oct 4, 2022

    @dneto0
    ContributorAuthor

    I'm hearing a lot of "meh" so:

    Proposal 4: In the spec, give an example, note, or table that spells out the literals for the special values.

    e.g. :

    Note: The largest finite f32 value is 0x1.fffffep+127

  12. kdashg commented on Oct 5, 2022

    @kdashg
    Contributor
    WGSL 2022-10-04 Minutes
    • DN: All options seem bad. Proper mathematical names confuse programmers. Let’s [just make a table?]. Maybe no change, but better docs would help. Unless someone has a better set of name ideas.
    • DG: MM and I were kinda confused by unit, but maybe that’s coming from category theory or something?
    • DN: Yeah maybe? [...] It still ends up being confusing if you don’t have a background in group theory.
    • DG: Even though other options may not be the perfect option, it would be preferable to match what existing APIs do.
    • DG: E.g. GLSL doesn’t define these
    • DN: I’m going to withdraw my proposal here, and I encourage someone else to make a different proposal.
    • MM: Could do what C does. [for example]
    • DN: As you add new data types, it has to grow, and FLT_MAX is not good for that.
    • DG: I agree that min and max are natural names for this, but we have this overloading with our builtins.
    • KG
    • MM: If I came with with a proposal that was like three words long for each, would that be objectionable? (“no, make a proposal [please]”)
  13. dneto0 commented on Oct 14, 2022

    @dneto0
    ContributorAuthor

    Hey @litherum will you have a proposal for this?

    A fallback is to give examples in the spec text rather than defining new things.

  14. 5 remaining items

  15. dneto0 commented on Nov 2, 2022

    @dneto0
    ContributorAuthor

    The proposal was posted live in the meeting and we didn't have the normal preparation period.
    I've found some problems with how it interacts with parsing.

    The bitcast precedent works because it's a keyword, and can be slotted in as a special case in primary_expression.

    The minValue and maxValue forms with template arguments would need special exceptions like that, meaning they can't be normal identifiers, and can't follow normal scoping rules. (E.g. can't be shadowed by a user declaration). This is unanticipated and rather a jagged edge in the proposal.

    The proposal needs a rethink.

  16. dneto0 commented on Nov 2, 2022

    @dneto0
    ContributorAuthor

    To be concrete about it, consider:

    type myfloat = f32;
    const a = 1;
    const b = 2;
    
    const blah = b<a;  // Fine.  blah is false
    const bloom = minValue<myfloat>(); 
    //  In the parse of 'bloom', we have to parse 4 tokens (until `>` to see it isn't
    // like the parse for blah.
    
  17. kdashg commented on Nov 2, 2022

    @kdashg
    Contributor

    Here's my strawman:
    https://doc.rust-lang.org/std/f32/constant.MIN_POSITIVE.html

    let a = f32::MAX;
    let b = f32::MIN;
    let c = f32::MIN_POSITIVE;
    
  18. kdashg commented on Nov 2, 2022

    @kdashg
    Contributor
    WGSL 2022-11-01 Minutes
    • DN wrote and landed Document extreme values for concrete numeric scalar types #3561 which documents the extreme values for scalar concrete numeric types. That’s the “let’s document this” solution without adding functionality.
    • Proposal:
      • f32 maxNormal<f32>();
      • f16 maxNormal<f16>();
      • f32 minNormal<f32>();
      • f16 minNormal<f16>();
      • i32 max<i32>();
      • u32 max<u32>();
      • i32 min<i32>();
      • u32 min<u32>();
    • KG: Looking at C++, min and max give the min and max for normal range, and you have to ask specially for the denormal value. So that would be max<f32>() to give the above.
    • AB: Still in favor of David’s PR, to avoid templated parameters on function calls.
    • KG: I would like to have these things. Unless you find it onerous or actively gross.
    • AB: I don’t like foot in the door for templates. Would rather bake it into the name.
    • KG: Would be more tolerable if it were max_f32?
    • AB: Yes, that’s more palatable
    • DN: We do have bitcast which takes template-likes, fwiw.
    • MM: which of e.g. min() and min(x,y) are more common?
    • DN: min(x,y)
    • MM: How about we rename max<i32>() to maximum<i32>()?
    • DN: That would help
    • JB: Think there’s value to having something you can write.
    • AB: Define your own const
    • KG: Prefer to have a builtin.
    • KG: minValue maxValue would be nicer for me, but don’t care that much.
    • MM: That makes it harder to mess things up. Probably a better idea than “maximum”
    • KG: confusing either way you slice it. Verb vs. noun.
    • MM: Ok, next iteration:
      • Functions named maxValue<T>(), minValue<T>(). We have precedence of the bitcast with type template.
    • TR: Think it would also be tolerable to have max_f32(), min_i32(). (Without expressing a preference).
    • MM: The reason I prefer angle brackets, it seems cleaner.
    • AB: I can live with Myles’ 2nd iteration.
    • Resolved.
    • TR: It’s confusing for integer min to be a very negative thing, but min float being a small-magnitude positive value.
    • KG: Historical precedent from C++. There is “lowest” for the most negative value in float types.
    • TR: Can always use sign bit.
    • ZJ: Other names are “lowest” and “smallest”
    • TR: It’s inconsistent with the min(x,y) function.
    • KG: Need to check, make sure min says what we think it is. Otherwise, we have consensus for maxValue<T>().
  19. kdashg commented on Nov 9, 2022

    @kdashg
    Contributor
    WGSL 2022-11-08 Minutes
    • KG
    • BC: min vs lowest is tricky and really does mix people up. Rust’s min is different than c++’s min.
    • AB: Not fond of the :: syntax, since we don’t use that anywhere else in the language
    • KG: We kind of had consensus on the syntax, so my proposal was more about the names, fit into whatever syntax was agreed upon (e.g. max<T>, min<T>, and minPositive<T>)
    • AB: Template style works for bitcast because it’s a keyword - it doesn’t work for other identifiers that could be redefined
    • KG: We had a rough consensus on using brackets - did that break?
    • AB: Yes, I think so - [since last meeting,] DN thought it was going to require too much lookahead to use angle brackets on ordinary identifiers
    • (DG: Does the IEEE standard give these values names?)
    • KG:** Tabled for more discussion.**
  20. dneto0 commented on Nov 9, 2022

    @dneto0
    ContributorAuthor

    From the minutes:

    (DG: Does the IEEE standard give these values names?)

    No.
    I checked IEEE 754-2008 (the 2008 edition of the 1985 standard).

    The closest it gets is:

    The smallest positive normal floating-point number is bemin and the largest is bemax×(b−b1−p). The non-zero
    floating-point numbers for a format with magnitude less than bemin are called subnormal because their
    magnitudes lie between zero and the smallest normal magnitude. They always have fewer than p significant
    digits. Every finite floating-point number is an integral multiple of the smallest subnormal magnitude
    bemin×b1−p.

  21. dneto0 commented on Nov 21, 2022

    @dneto0
    ContributorAuthor

    A few things have been discussed in recent meetings:

    • Use a dot syntax, e.g. u32.max

      • That would break new ground for WGSL. We deliberately steered away object.method style naming when creating the texture builtins.
    • Naming:

      • Some propose max and min naming for the float constants, to line up with C++ std::numeric_limits::min and because the idea is that it goes along with the use with the min and max builtins.
      • Google strongly opposes this naming because min would denote the smallest-magnitude finite value (normalized or denormalized, doesn't matter).
        * cppreference says "For floating-point types with denormalization, min returns the minimum positive normalized value. Note that this behavior may be unexpected, especially when compared to the behavior of min for integral types. To find the value that has no values less than it, use numeric_limits::lowest."
        * We have lived experience with this confusion causing bugs in real code.
        * The interaction with the 'min' builtin is wrong. e.g. min(-1.0f, f32.min) would equal -1.0f
    • What type is the result.

      • Suppose we have a u16 type. Then what type is u16.max?
      • Some would expect it to be u16, or it could be an AbstractInt.
      • But folks would expect to use it to be able to mask the lowest 16 bits of a u32, and write my_u32 & u16.max. But that would fail type-checking. So it shouldn't be type u16.
      • If it's the abstract numeric type, then you should follow the same pattern for f16. Then what is the type of f in let f = f16.max; Surprisingly, the type of f is f32.

    Together, Google's opinion is that this feature is not important enough and not settled enough for v1. We recommend pushing this out of the V1 milestone.

  22. kdashg commented on Nov 22, 2022

    @kdashg
    Contributor
    WGSL 2022-11-15 Minutes
    • DN: Against proposal that adds new keywords. So angle bracket thing.
    • DN: Solution shape is likely i32.lowest i32.highest.
    • BC: Against using underscored-names.
    • BC: James internally wondered if array-type.length might be another kind of thing that fits under this. Would be happier with type.member rather than underscores.
    • KG: Can do dots.
    • DN: Think highest and lowest, not smallest subnormal smallest normal.
    • KG: Arg is to make people see the contrast. Prefer min and max
    • BC: Prefer lowest and highest to avoid ambiguities across different languages.
    • KG: Don’t like to type long names like lowest and highest. And we have min and max functions. Don’t want to do better than rust here.
    • Table it for now.
  23. dneto0 commented on Nov 28, 2022

    @dneto0
    ContributorAuthor

    In the 2022-11-22 meeting we agreed to push this out of v1.0

  24. modified the milestones: V1.0, post-V1 on Nov 28, 2022
  25. kdashg commented on Nov 29, 2022

    @kdashg
    Contributor
    WGSL 2022-11-22 Minutes
    • DN: This should be pushed out of v1 because it’s too unsettled, and there are further things we were talking about that uncover even more design issues. Details in the issue.
    • KG: a bit sad, but tolerable. We will still be cool.
    • RESOLVED: pushed out to post-v1
  26. m-schuetz commented on Mar 3, 2023

    @m-schuetz

    Here's my strawman: https://doc.rust-lang.org/std/f32/constant.MIN_POSITIVE.html

    let a = f32::MAX;
    let b = f32::MIN;
    let c = f32::MIN_POSITIVE;
    

    Please make this happen, this is as good as it gets. Actively preventing +-infinity but providing no alternative to get largest/smallest values makes WGSL, yet again, pretty inconvenient.

  27. ben-clayton commented on Mar 3, 2023

    @ben-clayton
    Contributor

    We've been through the bikeshedding of this before, but to restate - my preferred syntax would be:

    f32.highest   // most positive, finite f32 value (0x1.fffffep+127f)
    f32.lowest    // most negative, finite f32 value (-0x1.fffffep+127f)
    f32.smallest  // smallest finite, normal f32 value (0x1.0p-126f)
    
    f16.highest   // most positive, finite f16 value (65504h)
    f16.lowest    // most negative, finite f16 value (-65504h)
    f16.smallest  // smallest finite, normal f16 value (0x1p-14h)
    
    i32.highest   // most positive i32 value (2147483647i)
    i32.lowest    // most negative i32 value (-2147483648i)
    
    u32.highest   // most positive u32 value (4294967295u)
    u32.lowest    // (0u)

    The day you enable non-finites, we'd also have:

    f32.infinity
    f32.highest_subnormal   // highest subnormal f32 value (0x1.fffffcp-127f)
    f32.smallest_subnormal  // smallest subnormal f32 value (0x1p-149f)
    
    f16.infinity
    f16.highest_subnormal   // highest subnormal f16 value (0x1.ff8p-15h)
    f16.smallest_subnormal  // smallest subnormal f16 value (0x1p-24h)

    This avoids the continual tripping hazzard around min, and keeps the grammar simple (. is used everywhere, instead of a mix of . and ::).

  28. alienself commented on Mar 15, 2025

    @alienself

    Any updates on this?

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

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions