Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wgsl: Convert quantizeToI32/U32 to use Math.trunc #3120

Merged
merged 1 commit into from
Nov 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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