From ab09ed4f6c0811289d2d27a968b69f469cbf1d0c Mon Sep 17 00:00:00 2001 From: Ryan Harrison Date: Wed, 1 Nov 2023 11:00:01 -0400 Subject: [PATCH] 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. --- src/webgpu/util/math.ts | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/webgpu/util/math.ts b/src/webgpu/util/math.ts index 9b901bfa6da4..851db40c7157 100644 --- a/src/webgpu/util/math.ts +++ b/src/webgpu/util/math.ts @@ -2023,22 +2023,32 @@ export function quantizeToF16(num: number): number { return hfround(num); } -/** Statically allocate working data, so it doesn't need per-call creation */ -const quantizeToI32Data = new Int32Array(new ArrayBuffer(4)); - -/** @returns the closest 32-bit signed integer value to the input */ +/** + * @returns the closest 32-bit signed integer value to the input, rounding + * towards 0, if not already an integer + */ export function quantizeToI32(num: number): number { - quantizeToI32Data[0] = num; - return quantizeToI32Data[0]; + if (num >= kValue.i32.positive.max) { + return kValue.i32.positive.max; + } + if (num <= kValue.i32.negative.min) { + return kValue.i32.negative.min; + } + return Math.trunc(num); } -/** Statically allocate working data, so it doesn't need per-call creation */ -const quantizeToU32Data = new Uint32Array(new ArrayBuffer(4)); - -/** @returns the closest 32-bit signed integer value to the input */ +/** + * @returns the closest 32-bit unsigned integer value to the input, rounding + * towards 0, if not already an integer + */ export function quantizeToU32(num: number): number { - quantizeToU32Data[0] = num; - return quantizeToU32Data[0]; + if (num >= kValue.u32.max) { + return kValue.u32.max; + } + if (num <= 0) { + return 0; + } + return Math.trunc(num); } /** @returns whether the number is an integer and a power of two */