-
Notifications
You must be signed in to change notification settings - Fork 599
[ET-VK][Ops] choose_qparams op shaders and impl #11769
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
Merged
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Pull Request resolved: #11369 # Operator Description The quantization operator converts floating-point tensors (fp16/fp32) to lower-precision integer formats (uint8/int8/int32) using affine quantization. This operator supports two quantization modes: - **Per-tensor quantization**: Uses a single scale and zero_point for the entire tensor - **Per-token quantization**: Uses different scale and zero_point values for each "token" (typically rows or channels) The quantization formula is: `quantized_value = clamp(round(input_value / scale) + zero_point, quant_min, quant_max)` **Example**: For a float value `2.5` with `scale=0.1`, `zero_point=128`, `quant_min=0`, `quant_max=255`: - `round(2.5 / 0.1) + 128 = round(25) + 128 = 153` - `clamp(153, 0, 255) = 153` (uint8 output) The quantization parameters serve these purposes: - **scale**: Controls the granularity of quantization (smaller scale = finer precision) - **zero_point**: Maps the floating-point zero to an integer value - **quant_min/quant_max**: Define the valid range for the quantized output type # Shader Algorithm Overview ## Texture Storage Implementation (`quantize_texture.glsl`) The texture-based implementation operates on 3D textures where data is stored in RGBA texel format (4 components per texel): **Per-tensor Mode**: Each compute thread processes one texel position. It loads a 4-component texel from the input texture, and applies quantization to each of the 4 components using shared scale/zero_point. It then writes the quantized 4-component result to the output texture. This method is fairly linear. **Per-token Mode**: We need to calculate the token index based on the spatial position, it'll differ between various cases like 3D and 2D. For instand we might define the token_idx as `z * dims.y + y` for 3D, or just `y` for 2D cases. We then retrieve the per-token scale/zero_point from the texture storage according to the token_idx. We need to do component indexing based on the texel_idx and token_idx: `texel_idx = token_idx / 4`, along with the component id `comp_idx = token_idx % 4` to get the necessary scale/zero_point. We then apply quantization with the corresponding token-specific parameters to the 4 components of the current texel. ## Buffer Storage Implementation (`quantize_buffer.glsl`) The buffer-based implementation operates on linear memory buffers with stride-based indexing: **Per-tensor Mode**: In this case, each compute thread will process one element at its global position. It converts the 3D position to linear buffer indices using stride calculations `tidx_to_bufi(pos, strides)`. It then loads single scalar values from the input buffer and applies quantization using shared scale/zero_point parameters. We then store the quantized result to the output buffer at the corresponding index. **Per-token Mode**: We first calculate the logical tensor position from the linear buffer index through dimension unwrapping. We then determine the token index based on the tensor dimensionality: - 4D: `token_idx = w * (z * y) + z * y + y` - 3D: `token_idx = z * y + y` - 2D: `token_idx = y` We then directly index into scale/zero_point buffers using token_idx and also apply quantization with the token-specific parameters. # Performance Considerations / Future Improvements Current implementation uses default workgroup sizing. Profiling different local workgroup sizes could improve occupancy and cache utilization. Buffer implementation processes one element per thread. Could be optimized to process multiple elements per thread. NOTE: Currently the only input types supported are **half** (fp16) and **float** (fp32). The only output types supported are **byte** (uint8), **char** (int8), **int** (int32). A future diff plans to implement **double** (fp64) input dtype support. ghstack-source-id: 291010148 @exported-using-ghexport Differential Revision: [D75959064](https://our.internmc.facebook.com/intern/diff/D75959064/)
Pull Request resolved: #11483 # Operator Description The dequantization operator converts lower-precision integer tensors (uint8/int8/int32) back to floating-point formats (fp16/fp32) using affine dequantization. This operator supports two dequantization modes: - **Per-tensor dequantization**: Uses a single scale and zero_point for the entire tensor - **Per-token dequantization**: Uses different scale and zero_point values for each "token" (typically rows or channels) The dequantization formula is: `dequantized_value = (quantized_value - zero_point) * scale` **Example**: For a quantized uint8 value `153` with `scale=0.1`, `zero_point=128`: - `(153 - 128) * 0.1 = 25 * 0.1 = 2.5` (float output) The dequantization parameters serve these purposes: - **scale**: Controls the granularity of reconstruction (same scale used during quantization) - **zero_point**: Maps the integer zero representation back to floating-point zero - **quant_min/quant_max**: Define the valid range that was used during original quantization (for validation) # Shader Algorithm Overview ## Texture Storage Implementation (`dequantize_texture.glsl`) The texture-based implementation operates on 3D textures where data is stored in RGBA texel format (4 components per texel): **Per-tensor Mode**: Each compute thread processes one texel position. It loads a 4-component integer texel from the input texture, and applies dequantization to each of the 4 components using shared scale/zero_point parameters. It then writes the dequantized 4-component floating-point result to the output texture. This method processes all components uniformly with the same dequantization parameters. **Per-token Mode**: We need to calculate the token index based on the spatial position, it'll differ between various cases like 3D and 2D. For instance we might define the token_idx as `z * dims.y + y` for 3D, or just `y` for 2D cases. We then retrieve the per-token scale/zero_point from the texture storage according to the token_idx. We need to do component indexing based on the texel_idx and token_idx: `texel_idx = token_idx / 4`, along with the component id `comp_idx = token_idx % 4` to get the necessary scale/zero_point values. We then apply dequantization with the corresponding token-specific parameters to the 4 components of the current texel, converting each integer component to its floating-point representation. ## Buffer Storage Implementation (`dequantize_buffer.glsl`) The buffer-based implementation operates on linear memory buffers with stride-based indexing: **Per-tensor Mode**: In this case, each compute thread will process one element at its global position. It converts the 3D position to linear buffer indices using stride calculations `tidx_to_bufi(pos, strides)`. It then loads single quantized integer values from the input buffer and applies dequantization using shared scale/zero_point parameters. We then store the dequantized floating-point result to the output buffer at the corresponding index. **Per-token Mode**: We first calculate the logical tensor position from the linear buffer index through dimension unwrapping. We then determine the token index based on the tensor dimensionality: - 4D: `token_idx = w * (z * y) + z * y + y` - 3D: `token_idx = z * y + y` - 2D: `token_idx = y` We then directly index into scale/zero_point buffers using token_idx and apply dequantization with the token-specific parameters, converting the quantized integer value back to its original floating-point representation. # Performance Considerations / Future Improvements Current implementation uses default workgroup sizing. Buffer implementation processes one element per thread. Could be optimized to process multiple elements per thread for better throughput. NOTE: Currently the only input types supported are **byte** (uint8), **char** (int8), **int** (int32). The only output types supported are **half** (fp16) and **float** (fp32). A future diff plans to implement **double** (fp64) output dtype support. ghstack-source-id: 291010146 @exported-using-ghexport Differential Revision: [D76267107](https://our.internmc.facebook.com/intern/diff/D76267107/)
Pull Request resolved: #11557 # Operator Description The choose_qparams operator computes optimal quantization parameters (scale and zero_point) from floating-point input tensors. This operator analyzes the statistical distribution of input data to determine the best quantization mapping for subsequent quantization operations. It supports two computation modes: - **Per-tensor quantization**: Computes a single scale and zero_point for the entire tensor based on global min/max values - **Per-token quantization**: Computes separate scale and zero_point values for each "token" (typically rows or channels) based on per-token min/max values The parameter calculation formulas are: - `scale = (data_max - data_min) / (quant_max - quant_min)` - `zero_point = clamp(round(quant_min - data_min/scale), quant_min, quant_max)` **Example**: For input data with `min=-2.5`, `max=7.3`, `quant_min=0`, `quant_max=255`: - `scale = (7.3 - (-2.5)) / (255 - 0) = 9.8 / 255 = 0.0384` - `zero_point = clamp(round(0 - (-2.5)/0.0384), 0, 255) = clamp(65, 0, 255) = 65` The quantization parameters serve these purposes: - **scale**: Determines the precision/granularity of the quantization mapping - **zero_point**: Ensures that floating-point zero maps to an exact integer value - **quant_min/quant_max**: Define the target quantization range (e.g., 0-255 for uint8) # Shader Algorithm Overview ## Texture Storage Implementation (`choose_qparams_texture.glsl`) The texture-based implementation uses a parallel reduction algorithms to efficiently compute min/max values across 3D textures with RGBA texel format: **Per-tensor Mode**: Each compute thread processes multiple texels using strided access patterns across the entire tensor. For each texel, it converts linear indices to 3D coordinates using `z = idx/(x*y), y = (idx%(x*y))/x, x = idx%x`, then loads 4-component texel data. The implementation validates each component against padding boundaries by calculating `valid_elements = min(4, remaining_elements)` to avoid processing padded data. Thread-local min/max reduction processes valid components while filtering NaN and infinity values. The algorithm then performs intra-workgroup reduction using shared memory arrays `shared_min[NWORKERS]` and `shared_max[NWORKERS]`. A tree reduction pattern halves the stride iteratively: `stride = workgroup_size/2; stride > 0; stride >>= 1`, combining results from `shared_min[local_id + stride]` with proper infinity handling. Finally, the master thread (local_id == 0, group_id == 0) computes the final scale and zero_point using the `calculate_scale_and_zero_point()` function and writes results to output textures. **Per-token Mode**: This mode implements a more complex multi-workgroup coordination strategy where each workgroup processes multiple tokens. The algorithm calculates `tokens_per_workgroup = (num_tokens + total_workgroups - 1) / total_workgroups` to distribute work evenly. For each assigned token, it determines the texel range using `token_start_texel = token_id * texels_per_token` and processes texels within that range using strided access `texel_idx = token_start_texel + local_id; texel_idx < token_end_texel; texel_idx += workgroup_size`. The same padding validation and component processing logic applies, but scoped to the current token's data. After thread-local reduction, it performs the same tree reduction pattern within the workgroup. The master thread computes token-specific scale/zero_point and converts the linear token_id back to 3D output coordinates using `out_z = token_id/(x*y), out_y = (token_id%(x*y))/x, out_x = token_id%x` for writing results. Workgroup synchronization via `barrier()` ensures proper coordination between token processing iterations. ## Buffer Storage Implementation (`choose_qparams_buffer.glsl`) The buffer-based implementation operates on linear memory with simpler indexing but maintains the same parallel reduction strategy: **Per-tensor Mode**: Each compute thread processes multiple elements using strided access across the entire linear buffer: `for (i = global_id; i < total_elements; i += total_threads)`. Direct buffer access `t_in[i]` loads scalar values with NaN/infinity filtering. Thread-local min/max reduction accumulates valid values. The same shared memory tree reduction pattern applies: threads store results in `shared_min[local_id]` and `shared_max[local_id]`, then perform logarithmic reduction with stride halving. The master thread (local_id == 0) computes final parameters and directly writes to output buffers: `t_scale[0] = scale_val; t_zero_point[0] = zero_point_val`. **Per-token Mode**: This mode distributes tokens across workgroups using `tokens_per_workgroup = (num_tokens + total_workgroups - 1) / total_workgroups` for load balancing. Each workgroup processes its assigned token range `[start_token, end_token)`. For each token, it calculates the linear element range: `token_start = token_id * token_size; token_end = token_start + token_size`. Threads process elements within the token using strided access: `for (i = token_start + local_id; i < token_end; i += workgroup_size)`. The same thread-local reduction and shared memory tree reduction patterns apply, but scoped to the current token's data. The master thread computes token-specific parameters and writes directly to the output arrays: `t_scale[token_id] = scale_val; t_zero_point[token_id] = zero_point_val`. Workgroup synchronization ensures proper coordination between token processing iterations. # Performance Considerations / Future Improvements Current implementation uses a parallel reduction algorithms with shared memory optimization, but several areas offer improvement opportunities: - The tree reduction pattern achieves O(log N) complexity within workgroups, but the current implementation uses fixed 64-thread workgroups. Dynamic workgroup sizing based on tensor dimensions could improve occupancy. - Fixed 64-thread workgroups match the NWORKERS constant, but profiling different sizes (32, 128, 256) could reveal better performance characteristics for different tensor sizes and GPU architectures. NOTE: Currently the only input type supported is **float** (fp32). The output types are **float** for scale and **int** for zero_point. ghstack-source-id: 290041468 @exported-using-ghexport ghstack-source-id: 291010147 Differential Revision: [D76436933](https://our.internmc.facebook.com/intern/diff/D76436933/)
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/11769
Note: Links to docs will display an error until the docs builds have been completed. ⏳ No Failures, 9 PendingAs of commit e44a3d1 with merge base 3b1c7fd ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
ahmtox
approved these changes
Jun 17, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Labels
CLA Signed
This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR was created by the merge bot to help merge the original PR into the main branch.
ghstack PR number: #11557 by @ahmtox
^ Please use this as the source of truth for the PR details, comments, and reviews
ghstack PR base: https://github.com/pytorch/executorch/tree/gh/ahmtox/22/base
ghstack PR head: https://github.com/pytorch/executorch/tree/gh/ahmtox/22/head
Merge bot PR base: https://github.com/pytorch/executorch/tree/gh/ahmtox/16/orig
Merge bot PR head: https://github.com/pytorch/executorch/tree/gh/ahmtox/22/orig
@diff-train-skip-merge