Skip to content

Commit ab09ed4

Browse files
authored
wgsl: Convert quantizeToI32/U32 to used Math.trunc (#3120)
Another small bump (~5%) to be gained through using a builtin instead of trampolining through a TypedArray.
1 parent 2f3b68c commit ab09ed4

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

src/webgpu/util/math.ts

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2023,22 +2023,32 @@ export function quantizeToF16(num: number): number {
20232023
return hfround(num);
20242024
}
20252025

2026-
/** Statically allocate working data, so it doesn't need per-call creation */
2027-
const quantizeToI32Data = new Int32Array(new ArrayBuffer(4));
2028-
2029-
/** @returns the closest 32-bit signed integer value to the input */
2026+
/**
2027+
* @returns the closest 32-bit signed integer value to the input, rounding
2028+
* towards 0, if not already an integer
2029+
*/
20302030
export function quantizeToI32(num: number): number {
2031-
quantizeToI32Data[0] = num;
2032-
return quantizeToI32Data[0];
2031+
if (num >= kValue.i32.positive.max) {
2032+
return kValue.i32.positive.max;
2033+
}
2034+
if (num <= kValue.i32.negative.min) {
2035+
return kValue.i32.negative.min;
2036+
}
2037+
return Math.trunc(num);
20332038
}
20342039

2035-
/** Statically allocate working data, so it doesn't need per-call creation */
2036-
const quantizeToU32Data = new Uint32Array(new ArrayBuffer(4));
2037-
2038-
/** @returns the closest 32-bit signed integer value to the input */
2040+
/**
2041+
* @returns the closest 32-bit unsigned integer value to the input, rounding
2042+
* towards 0, if not already an integer
2043+
*/
20392044
export function quantizeToU32(num: number): number {
2040-
quantizeToU32Data[0] = num;
2041-
return quantizeToU32Data[0];
2045+
if (num >= kValue.u32.max) {
2046+
return kValue.u32.max;
2047+
}
2048+
if (num <= 0) {
2049+
return 0;
2050+
}
2051+
return Math.trunc(num);
20422052
}
20432053

20442054
/** @returns whether the number is an integer and a power of two */

0 commit comments

Comments
 (0)