-
Notifications
You must be signed in to change notification settings - Fork 4
Enable static quantization for Qwen3-0.6B decoder (transformer-only) #836
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
Open
spalne
wants to merge
6
commits into
main
Choose a base branch
from
feature/qwen3-quant
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
3796b7e
Add qauntization for transformers for qwen0.6B
spalne 1ee316c
Quantize transformer-only with fused GQA + GSM8k calibration
spalne 78815fd
Fix Qwen3 w8a16 quant: symmetric int8 weights + exclude GQA from QDQ
spalne 95d45d9
refactor(qwen): register transformer-only path as a declarative model…
spalne 9cecb03
fix(qwen): calibrate transformer-only decode model on real trajectory
spalne 08f05d7
Fixed small bugs
spalne File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
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
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
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| # ------------------------------------------------------------------------- | ||
| # Copyright (c) Microsoft Corporation. All rights reserved. | ||
| # Licensed under the MIT License. | ||
| # -------------------------------------------------------------------------- | ||
| """Custom ONNX export ops + the entry point that reshapes HF's Qwen3 modules | ||
| for the transformer-only export. | ||
|
|
||
| These reshape the standard HF Qwen3 modules so winml-cli can produce a | ||
| QNN-friendly, transformer-only graph: | ||
|
|
||
| - ``LpNormalization`` replaces the eager RMSNorm Mul/Pow/ReduceMean chain. | ||
| - ``com.microsoft::GroupQueryAttention`` replaces the eager QKV MatMul + | ||
| Softmax + KV-update path (with built-in rotary). | ||
| - 1x1 ``Conv`` (NHWC<->NCHW) replaces ``nn.Linear`` for QNN-friendly | ||
| projections. | ||
|
|
||
| Everything here operates only on the standard ``transformers.models.qwen3`` | ||
| module attributes. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import torch | ||
| import torch.nn as nn | ||
| from torch.onnx import symbolic_helper | ||
|
|
||
|
|
||
| # ============================================================================= | ||
| # Custom ONNX symbolic functions | ||
| # ============================================================================= | ||
|
|
||
|
|
||
| class LpNormOnnxExport(torch.autograd.Function): | ||
| """RMSNorm body → ONNX ``LpNormalization`` (p=2 along last dim).""" | ||
|
|
||
| @staticmethod | ||
| def symbolic(g, input, axis, p): # noqa: D401 | ||
| output_type = input.type().with_sizes(symbolic_helper._get_tensor_sizes(input)) | ||
| output = g.op( | ||
| "onnx::LpNormalization", | ||
| input, | ||
| axis_i=int(axis), | ||
| p_i=int(p), | ||
| ) | ||
| return output.setType(output_type) | ||
|
|
||
| @staticmethod | ||
| def forward(ctx, input, axis, p): # noqa: ARG004 | ||
| # Shape-only tracing placeholder. The real op is emitted by | ||
| # ``symbolic`` during ONNX export; ``forward`` exists solely so the | ||
| # TorchScript exporter (and Optimum's pre-export dry run) can trace | ||
| # output shapes. It returns ``input`` unchanged on purpose and is NOT a | ||
| # correct eager RMSNorm — do not call this module for real inference. | ||
| return input | ||
|
|
||
|
|
||
| class GroupQueryAttentionOnnxExport(torch.autograd.Function): | ||
| """Fused Q/K/V + KV-cache + rotary → ``com.microsoft::GroupQueryAttention``.""" | ||
|
|
||
| @staticmethod | ||
| def symbolic( | ||
| g, | ||
| query, | ||
| key, | ||
| value, | ||
| past_key, | ||
| past_value, | ||
| seqlens_k, | ||
| total_sequence_length, | ||
| cos_cache, | ||
| sin_cache, | ||
| do_rotary, | ||
| kv_num_heads, | ||
| num_heads, | ||
| ): | ||
| args = [query, key, value, past_key, past_value, seqlens_k, total_sequence_length, cos_cache, sin_cache] | ||
| attention_output, present_keys, present_values = g.op( | ||
| "com.microsoft::GroupQueryAttention", | ||
| *args, | ||
| do_rotary_i=int(do_rotary), | ||
| kv_num_heads_i=int(kv_num_heads), | ||
| num_heads_i=int(num_heads), | ||
| outputs=3, | ||
| ) | ||
|
|
||
| query_sizes = symbolic_helper._get_tensor_sizes(query) | ||
| attention_output.setType(query.type().with_sizes(query_sizes)) | ||
| present_keys.setType(past_key.type().with_sizes(symbolic_helper._get_tensor_sizes(past_key))) | ||
| present_values.setType(past_value.type().with_sizes(symbolic_helper._get_tensor_sizes(past_value))) | ||
| return attention_output, present_keys, present_values | ||
|
|
||
| @staticmethod | ||
| def forward( | ||
| ctx, | ||
| query, | ||
| key, | ||
| value, | ||
| past_key, | ||
| past_value, | ||
| seqlens_k, | ||
| total_sequence_length, | ||
| cos_cache, | ||
| sin_cache, | ||
| do_rotary, | ||
| kv_num_heads, | ||
| num_heads, | ||
| ): # noqa: ARG004 | ||
| # Shape-only tracing placeholder. The real op is emitted by | ||
| # ``symbolic`` during ONNX export; ``forward`` exists solely so the | ||
| # TorchScript exporter (and Optimum's pre-export dry run) can trace | ||
| # output shapes. It returns the inputs as stand-in present-KV on | ||
| # purpose and is NOT correct attention — do not call this module for | ||
| # real inference. | ||
| return query, past_key, past_value # placeholder shapes | ||
|
|
||
|
|
||
| # ============================================================================= | ||
| # 1x1 Conv replacement for nn.Linear | ||
| # ============================================================================= | ||
|
|
||
|
|
||
| class TransposeConv2d1x1Transpose(nn.Module): | ||
| """``nn.Linear`` → 1x1 ``Conv2d`` with NHWC<->NCHW permutes.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| in_channels: int, | ||
| out_channels: int, | ||
| weight: torch.nn.Parameter, | ||
| bias: torch.nn.Parameter | None = None, | ||
| ) -> None: | ||
| super().__init__() | ||
| # Linear weight is (out, in); Conv2d weight is (out, in, 1, 1). | ||
| self.weight = nn.Parameter(weight.data.view(out_channels, in_channels, 1, 1)) | ||
| self.bias = bias | ||
|
|
||
| def forward(self, x: torch.Tensor) -> torch.Tensor: | ||
| x = x.permute(0, 3, 1, 2) # NHWC -> NCHW | ||
| x = torch.nn.functional.conv2d(x, self.weight) | ||
| x = x.permute(0, 2, 3, 1) # NCHW -> NHWC | ||
| if self.bias is not None: | ||
| x = x + self.bias | ||
| return x | ||
|
|
||
| @classmethod | ||
| def from_linear_module(cls, linear: nn.Linear) -> TransposeConv2d1x1Transpose: | ||
| return cls(linear.in_features, linear.out_features, linear.weight, linear.bias) | ||
|
|
||
|
|
||
| __all__ = [ | ||
| "GroupQueryAttentionOnnxExport", | ||
| "LpNormOnnxExport", | ||
| "TransposeConv2d1x1Transpose", | ||
| ] | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Warning: Stale KV cache in eager mode
GroupQueryAttentionOnnxExport.forwardreturns(query, past_key, past_value)— the present_keys/present_values are the old un-updated tensors. Eager execution silently produces a KV cache that never advances. ANotImplementedErrorhere would be safer than a silently-wrong placeholder.