Skip to content

Commit

Permalink
wgsl: Convert quantizeToI32/U32 to used Math.trunc (#3120)
Browse files Browse the repository at this point in the history
Another small bump (~5%) to be gained through using a builtin instead
of trampolining through a TypedArray.
  • Loading branch information
zoddicus authored Nov 1, 2023
1 parent 2f3b68c commit ab09ed4
Showing 1 changed file with 22 additions and 12 deletions.
34 changes: 22 additions & 12 deletions src/webgpu/util/math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down

0 comments on commit ab09ed4

Please sign in to comment.