NVIDIA CodingFree previewFree
FP32 Tensor to Int8 Quantization
Last asked
Problem
Given an FP32 tensor and a floating-point scale, convert the tensor to INT8. Follow-ups add asymmetric quantization with zero point and ask how scale / zero point should change when the input distribution is not symmetric.
Implement a function that takes:
def quantize_fp32_to_int8(x: np.ndarray, scale: float) -> np.ndarray:
...Base behavior:
xis an FP32 tensor of any shape.- Divide every value by
scale. - Round or cast into signed
int8range. - Return an
int8tensor with the same shape.
Variant — OJ
The OJ variant states the formulas explicitly, treating x as a 1-D array / contiguous buffer: base (symmetric) q[i] = (int8)(x[i] / scale); follow-up (asymmetric) q[i] = (int8)(x[i] / scale + zero_point), and requires discussing why zero_point is needed for non-symmetric input distributions and how scale + zero_point work together.
Constraints
Let n be the number of elements:
1 <= n <= 10^7; implementation should be O(n) with a single pass. (OJ variant.)
Examples
Example 1
Input
x=[0.0, 1.0, -1.0], scale=0.5, zero_point=0
Output
q=[0, 2, -2]
Explanation
OJ sample test.
Example 2
Input
x=[0.0, 1.0, -1.0], scale=0.5, zero_point=10
Output
q=[10, 12, 8]
Explanation
OJ sample test.
Example 3
Input
x=[2.5], scale=0.5, zero_point=0
Output
q=[5]
Explanation
OJ sample test.
Example 4
Input
x=[-2.5], scale=0.5, zero_point=0
Output
q=[-5]
Explanation
OJ sample test.
Example 5
Input
x=[0.2, 0.3], scale=0.1, zero_point=0
Output
q=[2, 3]
Explanation
OJ sample test.
Example 6
Input
3 0.0 1.0 -1.0 0.5 0
Output
0 2 -2
Explanation
OJ's literal stdin/stdout test format for the first sample test above.
Follow-ups
Add a
zero_pointparameter for asymmetric quantization.Explain when symmetric quantization is insufficient.
Derive how scale and
zero_pointare used together.Discuss clipping / saturation when values exceed
[-128, 127].Explain what happens to error when the input distribution is skewed or has outliers.
Discuss why
zero_pointis needed for non-symmetric input distributions and how scale +zero_pointwork together. (OJ variant phrasing.)
Loading the solution…
