Skip to content

Proposal of FP16 WGSL extension #2512

Closed

Description

@jiangzhaoming

1. Introduction

In this issue we propose an extension to enable FP16, the 16-bit floating point types, to be allowed in WGSL for proposed usages. To keep the issue in a reasonable length, detailed information of each backend’s (D3D12, Metal, Vulkan, and OpenGL) support for each usage is omitted, and can be found in a more detailed proposal design doc for this extension.

Although other low-bit-width data types, e.g. INT16 and INT8, may also be supported by backends, we focus on FP16 in this extension.

2. Proposal usages

This proposed extension, tentatively named fp16-in-shaders-and-storage, enables certain usages of FP16 in WGSL.

The considered usages of FP16 in WGSL and their support of different backends can be summarized in the table below. We propose to enable all usages except atomic FP16, using in uniform storage class and pipeline input/output in this extension, as a tradeoff between functionality and capability (some Vulkan devices support using FP16 types within shaders and storage buffer, but don’t support using them in uniform buffer). Usages of uniform storage class and pipeline input/output can also be emulated on devices that don’t support them natively. If such emulation is enabled, we can enable all usages except atomic FP16 in this extension, making this extension more general. Otherwise, the uniform storage class or pipeline input/output usages may be enabled by other extensions.

WGSL usage Vulkan (SPIR-V) D3D12 (HLSL) Metal (MSL) OpenGL (GLSL)
Defining FP16 scalar, vector and matrix types Requiring at least one Vulkan feature listed in this column Require SM6.2 or higher, using DXIL, and Native16BitShaderOpsSupported == true Support Requiring extension AMD_gpu_shader_half_float
Defining array and structure types with FP16
Conversion and bit-casting between FP16 and other types
Atomic type/operation of FP16 No support
Using variables of FP16 types in private, function and workgroup storage classes Require Vulkan feature shaderFloat16 (overall support rate 39.6%, reported by gpuinfo.org, the same for others in this column) Require SM6.2 or higher, using DXC, and Native16BitShaderOpsSupported == true Support Requiring extension AMD_gpu_shader_half_float
Using FP16 as parameters and results of user-defined value
Using FP16 with built-in function (arithmetical)
Using FP16 types in uniform storage class Require Vulkan feature uniformAndStorageBuffer16BitAccess (overall support rate 53.1%)
Using FP16 types in Storage storage class Require Vulkan feature storageBuffer16BitAccess (overall support rate 58.6%)
Using FP16 types in pipeline input/output user-defined variables Require Vulkan feature storageInputOutput16 (overall support rate 24.4%)

Please see the capability chapter in the proposed design doc for detailed investigation of different backends’ support for different usages.

The following sections will describe these usages.

3. FP16 data types

FP16 data types are supported with different requirements on each backend.If the backend supports above features, we will be able to enable using FP16 types in WGSL. We also propose to add value conversion and bitcast expressions for FP16.

Atomic type or operation for FP16 is not allowed.

3.1. Scalar, vector and matrix types of FP16

Currently in WGSL we only have 32-bits floating scalar type, f32, floating point vectors and matrices all have component type of f32. Here we propose the 16-bit floating point scalar type, f16, and corresponding vector and matrix types. If the backend meets the requirement of supporting FP16, the proposed WGSL types may be used in WGSL code.

A brief list of WGSL f16 types enabled by this extension is shown below. A detailed table for WGSL FP16 types and corresponding backend types is listed in the appendix of design doc.

WGSL Type Description
f16 The f16 type is the set of 16-bit floating point values of the IEEE-754 binary16 (half precision) format.
vecN<f16> Vector of N elements of type f16
matNxM<f16> Matrix of N columns and M rows

3.2. Array and structure with FP16 types

HLSL, MSL, SPIRV, and GLSL all support defining FP16 members in arrays and structures, if FP16 is supported. Therefore, we may enable FP16 types in arrays and structures when FP16 scalar, vector and matrix types are enabled.

Using FP16 types in uniform buffers and storage buffers may have additional memory layout restrictions, please see the corresponding chapters in the proposed design doc(uniform, storage).

3.3. Type constructor expressions and conversion expressions

This extension proposes the scalar, vector and matrix constructor expressions for f16 in WGSL in the same ways as f32.

We also propose value conversion expressions between f16 and any other types (f32, u32, i32 and bool). Value conversion expressions between matrix types (f16 and f32 matrices) are introduced in this extension, which do not exist before as there is only f32 type of matrix in WGSL. Please see the appendix for a detailed table.

Bit-casting between f16 and u32 can be done by packing and unpacking WGSL built-in functions. The most natural bit-casting, between f16 and u16, are not proposed in this extension because we don’t have u16 types yet. Bit-casting between f16 and types other than u16 or u32 shall not be allowed in WGSL.

3.4. Atomic type of FP16

No backend has a useful support of atomic FP16 types and/or operations. Therefore, we are unlikely going to support atomic type for FP16. The details for each backend are summarized in the table below.

Backend Details
D3D12 HLSL does not support atomic operations for float16.
Vulkan SPIR-V only supports OpAtomicFAddEXT for 32-bit and 64-bit floating point, requiring AtomicFloat32AddEXT and AtomicFloat64AddEXT. The extension SPV_EXT_shader_atomic_float_min_max adds atomic min and max instruction on floating-point numbers, and the extension SPV_EXT_shader_atomic_float16_add proposes supporting atomically adding to 16-bit floating-point numbers in memory. However these are still in internal status. Vulkan extension VK_EXT_shader_atomic_float2 (features) suggests 16-bit floating-point atomic operations on buffer and workgroup memory as well as floating-point atomic minimum and maximum operations on buffer, workgroup, and image memory. However, such features are generally unsupported (reported 99.8%).
Metal MSL only supports atomic types of int, uint and bool.
OpenGL OpenGL only supports atomic types of int, uint and bool.

OpenGL only has the atomic counter of integer type.

3.5. FP16 literal

In WGSL we have floating suffix f for f32. Following the GLSL extension, we propose the suffix hf for f16. The form of a numeric literal will be as shown below.

Type form
decimal_float_literal /((-?[0-9]*\.[0-9]+|-?[0-9]+\.[0-9]*)((e|E)(\+|-)?[0-9]+)?(h?f)?)|(-?[0-9]+(e|E)(\+|-)?[0-9]+(h?f)?)/
hex_float_literal /-?0[x|X]((([0-9a-fA-F]*\.[0-9a-fA-F]+|[0-9a-fA-F]+\.[0-9a-fA-F]*)((p|P)(\+|-)?[0-9]+(h?f)?)?)|([0-9a-fA-F]+(p|P)(\+|-)?[0-9]+(h?f)?))/

Some examples for the proposed FP16 literal are -.23E+8hf, 123e-4hf, 0xABC.DEFhf and 1A2BP-3hf.

Note

HLSL and MSL use the suffix h instead of hf for FP16.

4. Defining FP16 variables in private, function and workgroup storage class

This extension will enable using FP16 types in defining variables in private, function and workgroup storage classes. If a backend device is suitable to enable this extension, we can directly translate the variable definitions of these storage classes into the backend’s shader code.

5. Using FP16 types as function parameter and result

This extension enables using FP16 types as parameters and results of built-in and user-defined functions, in the same way of using FP32 types. Some FP16-specific built-in functions should be added into WGSL. In this section we will discuss this usage.

5.1. User defined function

All backends support defining functions with 16-bit floating point parameters and/or return values, as long as they support using fp16 in function storage class. Therefore, WGSL functions using fp16 as input/output can map to backends as same as other functions.

5.2. Built-in functions

All WGSL built-in functions that take f32 should support using f16 as parameters and results, as most floating point built-in functions have half-precision reload on all backends.

All data packing and unpacking built-in functions should have overloads that take FP16 types as parameters and results where originally f32 goes. Bit-casting between f16 and u32 can be done by these packing and unpacking functions. HLSL seems to have no packing/unpacking functions for FP16, nor bitCast between FP16 and uint32, and we may manually implement them.

6. Using FP16 types in uniform and storage storage class

The variables with uniform and storage storage classes work as the interactions between gpu and host memory, therefore they have to meet more requirements. We will propose the memory layout requirements for FP16 in this chapter.

6.1. Alignment and Size

The following table should be merged into WGSL Spec table Alignment and size for host-shareable types.

WGSL Type Alignment (bytes) Size (bytes)
f16 2 2
vec2<f16> 4 4
vec3<f16> 8 6
vec4<f16> 8 8
mat2x2<f16> 4 8
mat2x3<f16> 8 16
mat2x4<f16> 8 16
mat3x2<f16> 4 12
mat3x3<f16> 8 24
mat3x4<f16> 8 24
mat4x2<f16> 4 16
mat4x3<f16> 8 32
mat4x4<f16> 8 32

These values match the MSL and Vulkan Spec. If the size or alignment of structure members is not explicitly defined in WGSL code, the listed value should be used. If explicitly defined, they should satisfy the layout constraints for corresponding storage classes shown below.

Note

The Internal Layout of Values in WGSL Spec should be also updated.

6.2. Using FP16 types in uniform storage class

When using FP16 types in uniform storage class, besides the alignment requirement above should be met, the extra buffer layout constraints for uniform is also required, as is shown below. These requirements are identical to the current WGSL spec.

Host-shareable type S RequiredAlignOf(S, uniform)
i32, u32, f32, or f16 AlignOf(S)
atomic<T>, T is i32, u32, or f32 AlignOf(S)
vecN<T> AlignOf(S)
matNxM<T>, T is f32 or f16 AlignOf(S)
array<T, N> round(16, AlignOf(S))
array<T> round(16, AlignOf(S))
struct S round(16, AlignOf(S))

The matrix matNxM<f16> types should be stored as N distinct vecM<f16> (not an array of vectors), and constructed back to a matrix by generated code. In this way we workaround the matrix stride requirements in different backends.

We can do emulation for Vulkan devices with no native support for this usage (uniformAndStorageBuffer16BitAccess) by packing FP16 into UINT32 in the backend buffer structure and do the unpacking in the backend when loading in WGSL.

6.3. Using FP16 types in storage storage class

When using FP16 types in the storage storage class, the buffer layout constraints for storage are validated, as is shown below.

Host-shareable type S RequiredAlignOf(S, storage)
i32, u32, f32, or f16 AlignOf(S)
atomic<T>, T is i32, u32, or f32 AlignOf(S)
vecN<T> AlignOf(S)
matNxM<T>, T is f32 or f16 AlignOf(S)
array<T, N> AlignOf(S)
array<T> AlignOf(S)
struct S AlignOf(S)

In fact this is just requesting everything aligned to its type's alignment.

7. Using FP16 as pipeline input and output

It is possible to use FP16 in user-defined pipeline input/output variables. However some Vulkan devices, which support other usages in this extension like FP16 built-in function and storage buffer, don’t support this usage. For capabilities reasons, we may suggest not enabling using FP16 as pipeline input or output with this extension. However, this usage can also be emulated on Vulkan devices with no native support for this usage (storageInputOutput16).

7.1. Built-in input/output variable

Built-in floating-point pipeline input and output variables (e.g. position and frag_depth) should be kept as f32.

7.2. User-defined input/output variable

Using user-defined variables of FP16 types as shader input and output (and intra-shader variables) is partially supported by backends. MSL, HLSL (if supporting native 16-bit mode) and GLSL (with AMD_gpu_shader_half_float extension) supports this usage, but Vulkan devices diverged. E.g., Nvidia Vulkan Windows drivers, Intel Linux Mesa drivers, and Google Pixel (before Pixel 6) all don’t support the required Vulkan feature storageInputOutput16. It is possible to emulate using FP16 types as intra-shader variables for devices not supporting storageInputOutput16.

8. Capability

Different vendors seem to have different support for FP16 related features, and different backend drivers of a vendor also have different support competence.

Detailed investigation on devices’ support are shown in the proposed design doc.

Activity

  1. added
    wgsl
    on Jan 16, 2022
  2. dneto0 commented on Jan 18, 2022

    @dneto0
    Contributor

    f16 is definitely a desirable feature.

    Google's position is:

    • f16 is an optional feature. An implementation should only expose it if it has high performance or "native" support for a large majority of the functionality.
    • Make a single option that turns on f16 functionality "everywhere":
      • all arithmetic
      • let declarations and variables in any storage class
      • function call and return
      • pipeline IO. (Even if this is emulated!)
      • and maybe other places I'm not listing here.
    • Agree that f16 atomics should be out of scope.

    This proposal is missing:

    We (Google) haven't discussed the literal suffix specifically.
    I dislike 'hf' as a suffix, because it doesn't generalize clearly. I guess 'h' is for 'half' which itself is a weird name.
    I hope that we can avoid needing a type-specific suffix; that is one of the benefits of the "literal unification" #2227 proposal that we very recently got consensus on. Or, if we really want type-specific suffix then I would like to see a general scheme for it, e.g. 1234'f16 (that is not a proposal, but an illustration). I think this aspect should be avoided or decoupled and deferred.

  3. kdashg commented on Jan 22, 2022

    @kdashg
    Contributor
    WGSL meeting minutes 2022-01-18
    • a much more detailed design doc is proposed at https://docs.google.com/document/d/1TdHVV8NgQYANAq967L_rRHdJ7Uq_L8CGvq7_VY6G4OQ.
    • GR: The data from gpuinfo.org is by ratios of #skus rather than # of units in the field. So take the stats with a “grain of salt”.
    • MM: Question about D3D f16 coverage?
    • GR: Has been wanting this it the default in D3D land, but have not been able to make it so. Assuming f16 would simplify (.... D3D support ?)
    • GR: Browsers collect this info. May have metrics.
    • AB: It’s not pervasive enough to make it core in the Android space. So don’t think it should be core required feature.
    • GR: Very much dislike precision-ambiguous types. Would be 32-bit on some machines, 16 on others. Affects interfaces, which is hard to debug.
      • [dn: I think min10float, min16loat in HLSL]
    • AB: The analog in GLSL is lowp, mediump, highp.
    • ZJ: We propose only supporting the extension where it’s natively supported, rather than adding flexible-precision types.
    • GR: Great!
    • ZJ: Native 16bit implementation only. Basically fp16 anywhere fp32 is except atomics. Not sure about uniform or pipeline IO.
    • GR: floats are default to f16?
    • ZJ: no, just a new type, f16
    • MM: two questions: proposing webgpu feature to corresponds to all the vulkan extensions?
    • ZJ: to be discussed. At least shaderFloat16 and storageBuffer16Bit. Allows all but uniform and shader IO (and push constant). Could emulate them.
    • MM: tested 5 gpus: 11x regression, 12x, 20x, 40x, 120x. Tested the polyfill of atomic xor for writes.
    • AB: We think the way Vulkan designed this was rather unfortunate. Don’t want to repeat that complexity. Want basically a single feature. We think it’s ok to emulate f16 in pipeline IO and uniform. It’s better than dividing it into a bunch of confusing and interacting features.
    • KG: The lowest coverage is on input-output. For input-output, those seem like we could polyfill.
    • AB: using f16 on input output, you’re not saving any IO locations, so a valid implementation is use f32 on underlying pipeline, and quantize in ALUs on read and on write. It should be very cheap, relatively.
    • ZJ: For uniform, since it is readonly, then there is no need to polyfill with atomics. So it’s just a data conversion (and figure out which half-word to read).
    • ZJ: Think the key feature to turn on this feature in WGSL is whether storageBuffer16BitAccess is supported and also shaderFloat16.
    • AB: W3C can’t force that choice on the implementation. But I agree that’s a very good place to start.
    • DN: There is no atomic<f32> anyway..
    • MM: This is only about f16, not integral types.
    • ZJ: Yes.
    • MM: Don’t think integers are fundamentally more difficult.
    • AB: Google also interested in integral. May want another optional feature.
    • MM: f16 is really important to us. They are very much faster and smaller. Integers don’t have all those extra benefits (in magnitude.) Integral is good for ML.
    • GR: How is the feature modeled on Vulkan
    • AB: Storage feature bits are same between 16 bit types (float and integral). 8bit integer is its own independent feature.
    • GR: Similar in D3D: 16bit types feature are grouped.
    • MM: Metrics that would be helpful. Correlation of features, e.g. if there would be different extensions that would have the same user base.
    • KG: Kai reported (via email or an issue) worked with Sascha Willems, to get the data out under Creative Commons, with a more sophisticated query. Should be able to support compound queries. It’s still SKUs but useful.
    • KG: Want to get telemetry into Firefox to gather this.
    • DN: Want to be clear about which builtin functions work with f16. Also need to have table of accuracies. Don’t care that it’s tight bounds, but that only that they are written down and testable.
    • AB: E.g. derivatives. Also sampling may be interesting.
    • … may be easy to polyfill
    • AB: When we compiled OpenCL to Vulkan SPIR-V we did polyfills.
    • KG: May add non-normative notes to indicate when the polyfill is going to be likely and therefore slower than using f32 directly.
    • GR: Let’s discuss the suffix on literal.
    • DN: I don’t like ‘hf’. (put some notes on the issue). I hope that with literal typing consensus, we would have very much less need to use these suffixes. Would like to segregate this discussion if necessary.
    • KG: Like Rust’s pattern where you use the intended type as the suffix.
    • DN: I like that because it generalizes very clearly.
    • GR: Like that explicitness.
    • MM: Where it will become important is when we want overloads for user-defined functions. Our attitude is f16 is great and should be used as much as possible.
    • AB: The overload selected is based on the arguments, and you will have at least one non-literal argument in almost all cases. eg. Even for Clamp.
  4. jiangzhaoming commented on Jan 26, 2022

    @jiangzhaoming
    ContributorAuthor

    This comment proposes:

    1. What built in functions have f16 support, and
    2. Accuracy requirements for basic operations, and builtin functions.

    Bulit-in functions supporting f16

    I have tested all float, matrix and vector built-in functions on D3D12 (using DXC) and check the SPIR-V Spec for them.
    In conclusion, all these built-in functions defined in WGSL for f32 can be used with f16, except for quantizeToF16 (which is just an no-op for f16 inputs).

    We propose not to support using f16 with derivative built-in functions, since currently SPIR-V spec required their operands to be 32-bits (although DXIL allow using 16-bits variables in derivative operators).

    The detailed table of all built-in functions having f16 overload is shwon below.

    Parameterization Overload
    T is f16 or vecN<f16> abs(e: T ) -> T
    T is f16 or vecN<f16> acos(e: T ) -> T
    T is f16 or vecN<f16> asin(e: T ) -> T
    T is f16 or vecN<f16> atan(e: T ) -> T
    T is f16 or vecN<f16> atan2(e1: T ,e2: T ) -> T
    T is f16 or vecN<f16> ceil(e: T ) -> T
    T is f16 or vecN<f16> clamp(e1: T ,e2: T ,e3: T) -> T
    T is f16 or vecN<f16> cos(e: T ) -> T
    T is f16 or vecN<f16> cosh(e: T ) -> T
    T is f16 cross(e1: vec3<T> ,e2: vec3<T>) -> vec3<T>
    T is f16 or vecN<f16> degrees(e1: T ) -> T
    T is f16 or vecN<f16> distance(e1: T ,e2: T ) -> f16
    T is f16 or vecN<f16> exp(e1: T ) -> T
    T is f16 or vecN<f16> exp2(e: T ) -> T
    T is vecN<f16> faceForward(e1: T ,e2: T ,e3: T ) -> T
    T is f16 or vecN<f16> floor(e: T ) -> T
    T is f16 or vecN<f16> fma(e1: T ,e2: T ,e3: T ) -> T
    T is f16 or vecN<f16> fract(e: T ) -> T
    T is f16 frexp(e: T) -> __frexp_result
    T is vecN<f16> frexp(e: T) -> __frexp_result_vecN
    T is f16 or vecN<f16> inverseSqrt(e: T ) -> T
    T is f16 or vecN<f16>, I is i32 or vecN<i32>, where I is a scalar if T is a scalar, or a vector when T is a vector ldexp(e1: T ,e2: I ) -> T
    T is f16 or vecN<f16> length(e: T ) -> f16
    T is f16 or vecN<f16> log(e: T ) -> T
    T is f16 or vecN<f16> log2(e: T ) -> T
    T is f16 or vecN<f16> max(e1: T ,e2: T ) -> T
    T is f16 or vecN<f16> min(e1: T ,e2: T ) -> T
    T is f16 or vecN<f16> mix(e1: T ,e2: T ,e3: T) -> T
    T is vecN<f16> mix(e1: T ,e2: T ,e3: f16 ) -> T
    T is f16 modf(e: T ) -> __modf_result
    T is vecN<f16> modf(e: T) -> __modf_result_vecN
    T is f16 normalize(e: vecN<T> ) -> vecN<T>
    T is f16 or vecN<f16> pow(e1: T ,e2: T ) -> T
    T is f16 or vecN<f16> radians(e1: T ) -> T
    T is vecN<f16> reflect(e1: T ,e2: T ) -> T
    T is vecN<f16>, I is f16 refract(e1: T ,e2: T ,e3: I ) -> T
    T is f16 or vecN<f16> round(e: T ) -> T
    T is f16 or vecN<f16> sign(e: T ) -> T
    T is f16 or vecN<f16> sin(e: T ) -> T
    T is f16 or vecN<f16> sinh(e: T ) -> T
    T is f16 or vecN<f16> smoothStep(e1: T ,e2: T ,e3: T ) -> T
    T is f16 or vecN<f16> sqrt(e: T ) -> T
    T is f16 or vecN<f16> step(e1: T ,e2: T ) -> T
    T is f16 or vecN<f16> tan(e: T ) -> T
    T is f16 or vecN<f16> tanh(e: T ) -> T
    T is f16 or vecN<f16> trunc(e: T ) -> T
    T is f16 determinant(e: matNxN<T> ) -> T
    T is f16 transpose(e: matMxN<T> ) -> matNxM<T>
    T is f16 dot(e1: vecN<T>, e2: vecN<T>) -> T

    Accuracy requirements for basic operations and built-in functions with f16

    The precision requirements of FP16 instructions should follow the precision requirements in Vulkan spec.

    In conclusion, the precision requirements for operations and built-in functions for f16 are the same with precision requirements for f32 currently listed in WGSL spec (which are aligned with requirements in Vulkan spec), except for the functions listed below.

    Instruction Precision requirement for f32 Precision requirement for f16
    exp(x), exp2(x) 3 + 2 * |x| ULP 1 + 2 * |x| ULP
    sin(x), cos(x) Absolute error ≤ 2-11 inside the range of [-π, π] Absolute error ≤ 2-7 inside the range of [-π, π]
    atan(x), atan2(y, x) 4096 ULP 5 ULP
  5. litherum commented on Feb 2, 2022

    @litherum
    Contributor

    Polyfilling

    I wanted to answer the question "what if, instead of adding FP16 as an optional feature, we put it in non-optional core, and polyfilled it on devices which don't support it?" Here, I'm considering "polyfilling" to mean "execute more instructions to produce the exact same result as you would have gotten", rather than "silently promote all FP16 to FP32 and just get the extra precision" as HLSL does.

    For polyfilling math on FP16, and for using FP16 in input/output user-defined variables, the polyfill would be pretty straightforward - you'd just do the operation on FP32 and then do some bit manipulation to clear out bits that wouldn't occur in a FP16 value. So that's probably not a big deal.

    For polyfilling FP16 reads on buffers, polyfilling would also be straightforward - just load more data than you need, and throw away the extra information. No problem.

    However, polyfilling FP16 writes is more complicated, because if two threads write two adjacent FP16 values, those writes should not race.

    Google recently described how the polyfill for FP16 writes would work - the write would be implemented by an atomic xor which would flip just the bits in the destination that need to be flipped. In order to determine which bits need to be flipped, the polyfill first has to read the value in the destination, and because Metal uses atomic types rather than atomic operations, on Metal the read would have to be atomic too.

    Benchmark

    So I wrote a little benchmark that compares the performance of real FP16 stores against the performance of the polyfill. It's a super simple benchmark - it just does n writes to a buffer, filling it up.

    (Note that, if this polyfill were actually employed, regular reads would have to be promoted to atomic loads too so they could see the results of the atomic xor. This benchmark doesn't measure that. The benchmark just measures stores.)

    The benchmark compares the speeds of doing n writes to fill a buffer, in 3 different ways:

    1. True FP16 writes
    2. The FP16 polyfill
    3. FP32 writes (same number of writes; buffer 2x as long)

    Results

    The results here are the ratio of the runtime of version 2 divided by the runtime of version 1.

    • Intel Iris Pro Graphics: Polyfill is 12.9x slower
    • NVIDIA GeForce GT 750M: Polyfill is 11.9x slower
    • AMD Radeon Pro 580X: Polyfill is 18.6x slower
    • AMD Radeon Pro Vega 56: Polyfill is 47.8x slower
    • Apple M1: Polyfill is 127.2x slower

    Here are some graphs. For all the graphs, the X axis is the number of writes into the buffer, and the Y axis is runtime (lower is better). The top row of graphs is comparing the runtime of version 1 against version 3 - that is, FP16 writes against FP32 writes. The bottom row of graphs is comparing the runtime of version 1 against version 2 - that is, FP16 writes against the Xor polyfill.

    The left column of graphs is plotting the raw amount of time it takes to execute that many writes. The right column of graphs is plotting how long it takes to execute each individual write (aka the right graph is the left graph divided by x)

    Intel Iris Pro Graphics:
    Screen Shot 2022-01-18 at 7 35 27 PM

    NVIDIA GeForce GT 750M:
    Screen Shot 2022-01-18 at 7 35 48 PM

    AMD Radeon Pro 580X:
    Screen Shot 2022-01-18 at 7 36 07 PM

    AMD Radeon Pro Vega 56:
    Screen Shot 2022-01-18 at 7 36 26 PM

    Apple M1:
    Screen Shot 2022-01-18 at 7 36 44 PM

    Conclusion

    The Nvidia and AMD devices show that it takes just as long to write FP16 as FP32, which I thought was interesting, because the FP32 writes should involve twice as many cache flushes since it’s writing 2x as much data.

    On the other hand, the M1 shows it’s faster to write an FP16 than an FP32, but the Intel device shows the opposite - it’s faster there to write an F32 than an F16. Maybe Intel is internally doing some kind of polyfill?

    Anyway, here are some possible options:

    1. Silently polyfill FP16 on devices which don't support it. Slowdowns of 12.9x to 127.2x are probably not acceptable, so this probably is a bad option.
    2. Polyfill FP16 on devices, but do it loudly - put a bit on the Adapter which means "this device polyfills FP16." This still would probably be too error-prone, because developers would have to check some seemingly unrelated bit, far away from their use site.
    3. Split this feature into two pieces. Put shaderFloat16, uniformAndStorageBuffer16BitAccess, and storageInputOutput16 non-optionally into core, and put storageBuffer16BitAccess in a WGSL extension.
    4. Add FP16 as a single optional feature, only enabled on devices that don't have to use the polyfill.

    I don't want to say just yet whether option 3 or option 4 seems better, but this evidence does suggest that option 1 and option 2 should probably not be used.

  6. added this to the V1.0 milestone on Feb 3, 2022
  7. jiangzhaoming commented on Feb 10, 2022

    @jiangzhaoming
    ContributorAuthor

    Updated extension requirement proposal

    While still suggesting to enable all FP16 usages in one extension, we propose that this extension can be available on devices that meeting the following requirements.

    Backend Requirements
    Vulkan Vulkan device features shaderFloat16 and storageBuffer16BitAccess are both required.
    Vulkan device feature uniformAndStorageBuffer16BitAccess or storageInputOutput16 is optional.
    D3D12 SM6.2 or higher is required. Native16BitShaderOpsSupported in D3D12_FEATURE_D3D12_OPTIONS4 should be true. DXIL is required. (I.e., we must be able to generate executable DXIL code)
    Metal All metal devices support FP16.
    OpenGL Extension AMD_gpu_shader_half_float required.

    Some investigation on FP16 support of Vulkan devices

    In the design doc appendix some typical Vulkan devices are checked (based on GPUInfo database).

  8. kvark commented on Feb 14, 2022

    @kvark
    Contributor

    I finally had a chance to review the proposal here. Thanks Intel for the titanic work of collecting this, and Google with Apple for help in unifying the proposal to a single extension!

    General approach sounds good! TL;DR: expose an optional f16 extension that allows using the WGSL type pretty much everywhere in the shader (inter-stage, vertex in, fragment out, uniform and storage buffers, privates and workgroups, builtin functions). Poly-filling for uniform but not storage buffers sounds good as well.

    A few minor notes:

    1. Bitcasting - please don't cast 16-bit to 32-bit, it's just not a bitcast. Can we instead just have pack2x16float and unpack2x16float overloads that work with vec2<f16> instead? That seems straightforward and implementable.
    2. The "hf" suffix - I don't think we should have that. The 32-bit types are "privileged" by the fact they are supported universally, and so having "f" implying "f32" is fine. But we don't need to invent a suffix for every possible type, and we shouldn't.
    3. There shouldn't be separate grammar for "f16" literals. I'd expect there to be grammar for floating-point literals in general, and f16 suffix just makes it materialize in place.
    4. I wish we consistently used Markdown for all investigations. Google Docs discoverability is not good, and some of the links out from that document lead to something I don't have access to. We briefly discussed if HackMD should be used instead, since it allows collaborating and commenting, and I'd strongly recommend the group members consider it for future work.
  9. kdashg commented on Feb 16, 2022

    @kdashg
    Contributor
    WGSL meeting minutes 2022-02-09
    • Slides
    • (Intel)
      • Presentation discusses when the emulation can be high performance. Writing is the one that can slow down a lot when emulated.
        • Overview of Vulkan feature bits, and how well they are supported in the field
        • Metal supports f16 everywhere
        • D3D12 requires DXIL support.
    • ZJ: When should the extension be published?
    • AB: Happy to include it in the spec now, as non-required feature.
    • AB: Question: Are there changes required from the API side?
    • ZJ: No API changes required, except to enable the extension.
    • MM: Should we add half-precision types to the Vertex-type enum
    • KN: Why is that relevant?
    • MM: If people want to use those in a vertex buffer.
    • ZJ: Vertex buffer attributes already include half-precision, but the values will be converted automatically to 32-bit floats when feeding the pipeline inputs.
    • MM: I was thinking of a case where an application uses a compute shader to write the vertex buffer. In that situation, the graphics pipeline needs to understand that each scalar value is only 2 bytes, so it can cause the translation to occur as required.
    • KN: the half-float vertex format already exists in the API.
    • KN: It’s an entirely different feature to do 32bit-format-to-f16 or 16bit-format-to-f32 format.
    • KN: The vertex formats are already whatever is supported by underlying APIs. There’s no dependence on shader features’ ability to write 16bit values from a shader as they don’t care if you write the vertex buffer by compute or from the CPU.
    • KG: Should we anticipate features building on top of each other. So we don’t have to change this extension later.
    • KN: Right Might be able to get performance by avoiding a conversion from 16-to-32 bit on pipeline input boundary. Came up recently that maybe this is possible for textures too (#2469/#2561), as well as vertex attributes.
    • KG: Some GL drivers (Apple?) does require annotating texture samplers as highp in order to get f32s out of them, since samplers technically default to lowp. This doesn’t give strong indication on our modern APIs, but there is some prior art here.
    • AB: Vulkan requires sample type to be 32-bit components. Did exploration with 16bit format data, and it was hit or miss as to whether you would get performance wins.
    • DM: Does that apply to storage textures?
    • AB: Any sampled type is 32-bits
    • DN: And when you got the value (from texture sample or texture load) it would always have 32-bit components.
    • MM: Should determine if it is any faster on any hardware.
    • DM: If it’s supported on some API, we can polyfill on the others.
    • MM: The polyfill is easy. But if you offer something developers have to know whether to use it. If it’s faster in some places but not others, then they don’t know whether to use it. The performance characteristics shapes the feature offered.
    • KG: It would be backward compatible if we added it later. Don’t want to get into situation by having extensions on top of other extensions.
    • GR: Its an optional extension. Don’t tie it to a v1 timeline. It comes out when ready.
    • MM: It’s important, let’s not wait months to do this.
    • DN: To me it’s human time allocation. As long as someone is pushing it forward, that’s great. We’ll do reviews, but our teams are bandwidth limited. No intent to block or ignore.
    • DM: Where should the list of investigations be listed.
    • ZJ: I will update the GitHub issue.
    • KN: Regarding v1. No opinion. Want to clarify that our optional features are not written in separate documents. They would be included in the v1 version of the doc. But it’s a living spec, so the “1.0” release is not important. I do think it’s ok to add stuff to optional features in the spec over time, as long as it’s feature-detectable. Doesn’t have to be yet another optional feature bit. Can be feature detected by a different mechanism.
    • AB: Agree much with Kai. We don’t strictly have versions. V1 is a concept we’re using to drive conversion.
    • MM: Question about Vulkan bits. storageBuffer16bitAccess, uniformAndStorageBuffer16bitAccess. Is one a superset of the other.
    • AB: Yes.
    • DN: The uniformAndStorge .. encompasses the other one.
    • AB: Vulkan extension, when enabled, requires storageBuffer16BitAccess to be supported.
    • MM: There are just a few devices in the diagram, there are some devcies that can do 16bit shader arithmetic but not do 16bit storage buffer access.
    • KN: Few device models, but those models are really popular. Likely many devices in the wild.
    • AB: My Pixel 3 (Adreno 630) is in that slice. I’m the reason that slice exists at all.
      • Pixel 4 (Adreno 640) too. Pixel 5 is OK (Adreno 620).
    • MM: One option is to cut the feature in half: do fp16 ALU in core, and put the storagebuffer access as the optional part. Then you can get the ALU speed everywhere.
    • ZJ: The diagram shows that if a device supports fp16 ALU, then it very likely also supports storageBuffer16BitAccess. In some use cases, like TF.js the storage buffer feature is very important.
    • MM: the converse, if there is a device that does not support writing to storage buffer, then it probably does not support ALU, and so that device probably won’t support fp16 ALU.
    • KG: How important is it to group this.
    • MM: Ideally we would never have to split. But fp16 is good. Want to give authors the ability to use it.
    • KG: I’m slightly frowny face about having two extensions.
    • DN: I dislike having a split-functioality feature. I suspect it’s likely that the devices that are in the “benefit from one and not the other” may be aging out (their OS security updates may be ending soon enough). I also would love to see market split across NorthAmerica, EMEA, APAC for mid-range and above models. I think we can drum up that data, but have not yet done so.
    • MM: There is at least one option on the table where there is a core feature, so we should not delay getting the info we need to make this decision.
    • MM: Suggest next step is to make a draft PR, and many of us will review it.
  10. dneto0 commented on Feb 24, 2022

    @dneto0
    Contributor

    Bitcasting - please don't cast 16-bit to 32-bit, it's just not a bitcast. Can we instead just have pack2x16float and unpack2x16float overloads that work with vec2<f16> instead? That seems straightforward and implementable.

    The pack/unpack are good ideas.

    There is still a bitcast that does make sense, which is between vec2<f16> and u32 (or any other 32-bit type), and vec4<f16> and vec2<T> where T is 32-bit. Those are supported directly by SPIR-V OpBitcast, and they do make sense.

    The bit representations are spelled out by the "internal layout of values" section, and so the bitcast conversions like these are well defined and useful.

  11. jiangzhaoming commented on Feb 25, 2022

    @jiangzhaoming
    ContributorAuthor

    Extension draft

    I have wrote a draft for FP16 spec extension here, wishing to discuss in the next WGSL WG meeting.
    Some changes in this draft from last meeting are listed below:

    • Tentatively name this extension fp16-in-shader-and-buffer.
    • Require using “enable f16;” directive in WGSL code to enable the f16 feature. Using “enable f16;” directive with unsupported device will result in a shader-creation error defined in WGSL spec and fail the shader compilation.
    • Define internal types __frexp_result_f16, __frexp_result_vecN_f16, __modf_result_f16, and __modf_result_vecN_f16 for frexp and modf built-in function using f16. Details here.
    • Propose new data unpack built-in function for f16, avoiding having overloads that are of the same name and input types but of different return types. Details here.
    • Decide not to add the f16 literal, all floating point literal will be interpreted as f32.
    • No bitcast between f16 scalar and other scalar types allowed. Add bitcast between vec2<f16> or vec4<f16> and other types that having the same bits number, e.g. vec2<f16> to f32, and vec2<i32> to vec4<f16>. Packing and unpacking built-in functions pack2x16float(vec2<f16>) -> u32 and unpack2x16floatf16(u32) -> vec2<f16> are identical to bitcast<u32>(vec2<f16>) -> u32 and bitcast<vec2<f16>>(u32) -> vec2<f16>. E.g., pack2x16float(vec2<f16>) -> u32 and bitcast<u32>(vec2<f16>) -> u32 both map the first element V.x of input f16 vector V into the low 16 bits of result u32 (bits 0 through 15).

    Hoping to have your comments and suggestions, thanks!

  12. kdashg commented on Mar 2, 2022

    @kdashg
    Contributor
    WGSL meeting minutes 2022-03-01
    • Intel
    • ZJ: Have slides to present. Updates
      • Name the extension “fp16-in-shader-and-buffer”
      • WGSL source requires “enable f16”. If used with unsupported device, produces shader-creation-error.
      • Q: When to raise the error: shader-creation time, pipeline-creation time.
      • Define special structus for return value of frexp and modf; follow the pattern seen before.
      • Data-packing and unpacking builtins.
        • For unpacking need a new name to avoid having overload that differs only in return type.
      • No literal suffix specific to f16. Rely on type-construction form: f16(1.0) when needed.
      • Bitcast:
        • No bitcast between f16 and other scalars
        • Add bitcast vec2<f16> with 32-bit scalars, vec4<16> and vec2 of 32-bit types
      • Idea: maybe add raw-bit types like raw32, raw64, raw128.
    • AB: For packing/unpacking, the SPIR-V versions always use the fp32 for intermediates, so there’s no profit. Think we can drop the packing/unpacking additions.
    • MM: The packing doesn’t need to be in the extension at all. It’s bit manipulation.
    • ZJ: The slide deck is not shared. Everything is in the comments, will put link to the comment.
    • KG: In that comment is the hackMD document.
    • AB: Suggest take the hackMD and make it into a PR.
    • KG: directly into the main spec.
    • ZJ: The packing functions. If we don’t change the name of the unpack functions, then we have the same function name and input types, but two different return types.
    • AB: The point I was trying to make. In the SPIR-V backend, we would have to insert a conversion from fp32 to fp16. Don’t think there is too much cost for the user to write that conversion themselves.
    • ZJ: Agree with just keeping unpack built-in functions that return f32.
    • Discussion about whether one form same as a bitcast
    • AB: Yes, for one of them. But snorm and unorm need ALU.
    • MM: Questions is whether to have (a) part in core part optional (b) all options . Dividing line is whether you can store fp16 scalars.
    • AB: Our stance is that should be a single feature, and optional_._
    • AB: We don’t want to emulate fp16 arithmetic. So don’t add that behind the scenes. Prefer a single optional feature for all of it.
    • ZJ: Difficulty in supporting f16 on DXIL-based. Not supported on all devices.
    • AB: We’re confused on what “core” means. The feature is in the main spec but not supported by a device.
    • MM: In the option where half the feature is in core, the operations on f16 would be polyfilled on devices that don’t have native HW support for that.
    • AB: f16 can get infinities in intermediate. Introduces nonportabilities.
    • AB: Also, user expects higher density ALU operation. Don’t pull the rug out from them.
    • KG: Don’t want to make f32 pretend to have lower precision.
    • AB: Would consider separate feature for “relaxed precision”.
    • MM: There’s memory use, and ALU density.
    • AB: Experience in Vulkan: it’s a mistake to split the feature. It’s split between storage and arithmetic.
    • AB: Important to signal to the author that they have to apply vectorization etc. Give the user the info they need to make it fast.
    • KG: Propose we land it as all in optional single feature. If there is anything in the optional feature that we want in the core, address that later.
    • KG: We know there’s a feature that defines some of this functionality.
    • AB: Google does not want any of this functionality in core-as-required.
  13. added a commit that references this issue on Mar 7, 2022
  14. jiangzhaoming commented on Mar 18, 2022

    @jiangzhaoming
    ContributorAuthor

    Can pipeline-overridable constant be of f16?

    Currently according to WGSL spec a pipeline-overridable constant can be of any scalar type (currently bool, i32, u32, and f32), although in WebGPU spec these four types is spelled out. If the FP16 extension (as currently proposed) is enabled, f16 will be one of the WGSL scalar types too, so we may decide if we allow a pipeline-overridable constant being of f16.
    One problem is that ECMAScript use Number, i.e. f64, and WebGPU states that the conversion to corresponding WGSL data type is via an IDL value, but there is no f16/half in IDL types.
    A possible solution is rephrase the WGSL spec to disable f16 pipeline-overridable constants, like:

    • The declared type, if present, must be a scalar bool, i32, u32, or f32.
    • The initializer expression, if present, must:
      • evaluate to a scalar bool, i32, u32, or f32 type.
  15. litherum commented on Mar 18, 2022

    @litherum
    Contributor

    It’s probably valuable to allow f16 overridable constants. We can spec our own conversion rules for it.

  16. jiangzhaoming commented on Mar 21, 2022

    @jiangzhaoming
    ContributorAuthor

    It’s probably valuable to allow f16 overridable constants. We can spec our own conversion rules for it.

    If f16 pipeline-overridable constants is allowed, a possible WebGPU spec changes in this extension may be:

    • Modify the 4th paragraph of constants in 10.1.2. GPUProgrammableStage section:

      Values are specified as GPUPipelineConstantValue, which is a double which is converted to the WGSL data type of the corresponding pipeline-overridable constant. For WGSL data types bool, i32, u32, and f32, the conversion is via an IDL value (boolean, long, unsigned long, or float).
      If the extension fp16-in-shaders-and-storage is enabled, GPUPipelineConstantValue may represent WGSL's f16 by converting to an IEEE 754 binary16 value. An GPUPipelineConstantValue (i.e. double) value V is converted to an IEEE 754 binary16 value by running the following algorithm:

      1. Let x be ? ToNumber(V).
      2. If x is NaN, +∞, or −∞, then throw a TypeError.
      3. Let S be the set of finite IEEE 754 binary16 values except −0, but with two special values added: 2^16 and −2^16.
      4. Let y be the number in S that is closest to x, selecting the number with an even significand if there are two equally close values. (The two special values 2^16 and −2^16 are considered to have even significands for this purpose.)
      5. If y is 2^16 or −2^16, then throw a TypeError.
      6. If y is +0 and x is negative, return −0.
      7. Return y.

    The algorithm above is adapted from conversion algorithm for float in Web IDL.

    Edited: The TypeError is not a WebGPU concept. We should specific what WebGPU should do when a GPUPipelineConstantValue can not be converted into an IDL value, i.e. a type error occurred, for example rise a validation error.

  17. Kangz commented on Mar 21, 2022

    @Kangz
    Contributor

    We can't use JS exception in the algorithm that are for shader / pipeline compilation because it happens on the GPU process asynchronously with respect to JS execution.

    If we add support for F16 in overridable constants, does this mean that the implementations will need some emulation of f16 for arithmetic operations on the CPU? This could be complicated to implement.

  18. jiangzhaoming commented on Mar 27, 2022

    @jiangzhaoming
    ContributorAuthor

    To reduce the complexity of conversion from GPUPipelineConstantValue to f16, we suggest that an implementation can first convert the double values into float via standard IDL conversion, then do the binary32 to binary16 conversion in the backend (e.g. GPU process).
    The updated proposal for f16 pipeline-overridable constants in WebGPU spec changes in this extension:

    • Modify the 4th paragraph of constants in 10.1.2. GPUProgrammableStage section:

      Values are specified as GPUPipelineConstantValue, which is a double which is converted to the WGSL data type of the corresponding pipeline-overridable constant (bool, i32, u32, or f32) via an IDL value (boolean, long, unsigned long, or float). If the "fp16-in-shader-and-buffer" feature is enabled, a pipeline-overridable constant may be of WGSL data type f16. The specified GPUPipelineConstantValue for a pipeline-overridable constant of f16 is convert to float via an IDL value, then convert to WGSL type f16 via IEEE-754 binary32 to IEEE-754 binary16 conversion.

  19. jiangzhaoming commented on Mar 30, 2022

    @jiangzhaoming
    ContributorAuthor

    Update

    In the PR against spec (#2696), following changes are made:

    • WebGPU Spec:
      • Rename WebGPU extension to "shader-f16"
      • Allow using pipeline-overridable f16 constants, and use f32 to f16 conversion defined in WGSL spec floating point conversion section
    • WGSL Spec:
      • Add f16 literal based on the literal unification (Literal unification, bottom-up #2227)
      • Add AbstractFloat to f16 and AbstractInt to f16 feasible automatic conversions in the "ConversionRank from one type to another" table, right after the corresponding f32 conversion. The proposed ConversionRank are:
        Src Dest ConversionRank(Src,Dest) Notes
        T T 0 Identity. No conversion performed.
        ref<S,T,A> where A is read or read_write T 0 Apply the Load Rule to load a value from a memory reference.
        AbstractFloat f32 1  
        AbstractFloat f16 2  
        AbstractInt i32 3  
        AbstractInt u32 4  
        AbstractInt AbstractFloat 5  
        AbstractInt f32 6 Behaves as AbstractInt to AbstractFloat, and then AbstractFloat to f32
        AbstractInt f16 7 Behaves as AbstractInt to AbstractFloat, and then AbstractFloat to f16
        S T where above cases don’t apply infinity There are no automatic conversions between other types.
  20. dneto0 commented on Apr 5, 2022

    @dneto0
    Contributor

    I like this!

    I like having a regular scheme on the API side for naming shader extensions: shader, then hyphen, then the enable-name in the shader.

    The update to the conversion rank table looks right. Backward compatibility of "existing" code requires that conversion from abstract type T to f16 have higher rank than T to f32.

  21. dneto0 commented on Apr 5, 2022

    @dneto0
    Contributor

    I know we gave guidance to add an h suffix for f16 literals.

    There was discussion in an office hour last week to avoid adding h. The use case is to give authors a mechanism to very easily write source that uses f16 conversions. There was some idea of adding a syntax to indicate that the source that follows should use a different conversion rank table, conversions to f16 have lower rank than f32. Then no suffix is required; the reader just has to remember the context.

  22. jiangzhaoming commented on Apr 14, 2022

    @jiangzhaoming
    ContributorAuthor

    The PR against spec #2696 has been merged, and the document PR #2647 is closed. Thanks!

  23. kdashg commented on Apr 15, 2022

    @kdashg
    Contributor

    Awesome work!

  24. kdashg commented on Apr 26, 2022

    @kdashg
    Contributor

    I think this is done then?

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