-
Notifications
You must be signed in to change notification settings - Fork 290
fix(pytorch): Rename layer_scale parameter to avoid quantization error #2172
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
Changes from 12 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
51fdac1
fix(pytorch): Rename layer_scale parameter to avoid quantization error
ved1beta fbda817
fix(pytorch): Rename layer_scale parameter to avoid quantization error
ved1beta 50f0f41
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 79cbded
[pre-commit.ci] pre-commit autoupdate (#2166)
pre-commit-ci[bot] b282da4
add revision for hf-internal-testing/tiny-random-gptj in UT (#2174)
changwangss 34333f4
suit transformers>=4.51 (#2171)
xin3he 7f76ab4
DOC fix --amend --signoff
ved1beta f1173df
Merge branch 'master' into layer_scale_fix
xin3he 0f6254d
Moved the CalibDataloader class outside of the test methods
ved1beta b93b5fb
Merge branch 'layer_scale_fix' of github.com:ved1beta/neural-compress…
ved1beta 614a640
precommit
ved1beta ae0701c
precommit
ved1beta 59bcd77
conflict solved
ved1beta eb98714
required stuff
ved1beta 44626a1
required chnages
ved1beta a56c9b2
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 3facba9
assertIsNotNone added
ved1beta b1baba1
Merge branch 'layer_scale_fix' of github.com:ved1beta/neural-compress…
ved1beta 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
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,151 @@ | ||
| import copy | ||
| import logging | ||
| import os | ||
| import sys | ||
| import unittest | ||
|
|
||
| import torch | ||
| import torch.nn as nn | ||
|
|
||
| # Add the root directory to the Python path | ||
| sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) | ||
xin3he marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| import neural_compressor.adaptor.pytorch as pytorch_util | ||
| from neural_compressor import quantization | ||
| from neural_compressor.adaptor import FRAMEWORKS | ||
| from neural_compressor.adaptor.pytorch import PyTorchAdaptor | ||
| from neural_compressor.config import PostTrainingQuantConfig | ||
| from neural_compressor.model.torch_model import PyTorchModel | ||
| from neural_compressor.utils import logger | ||
ved1beta marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| from neural_compressor.utils.utility import LazyImport | ||
|
|
||
| # Set up logging | ||
| logging.basicConfig(level=logging.INFO) | ||
xin3he marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| torch.manual_seed(42) | ||
|
|
||
|
|
||
| class CalibDataloader: | ||
| """Simple calibration dataloader for testing.""" | ||
|
|
||
| def __init__(self, data, label): | ||
| self.data = data | ||
| self.label = label | ||
| self.batch_size = 1 # Since we're yielding single samples | ||
|
|
||
| def __iter__(self): | ||
| yield self.data, self.label | ||
|
|
||
|
|
||
| class ConvEncoderWithLayerScale(nn.Module): | ||
| """Test model with layer_scale parameter that caused the original issue.""" | ||
|
|
||
| def __init__(self, dim=64, hidden_dim=128, kernel_size=3, drop_path=0.0, use_layer_scale=True): | ||
| super().__init__() | ||
| self.dwconv = nn.Conv2d(dim, dim, kernel_size=kernel_size, padding=kernel_size // 2, groups=dim) | ||
| self.norm = nn.BatchNorm2d(dim) | ||
| self.pwconv1 = nn.Conv2d(dim, hidden_dim, kernel_size=1) | ||
| self.act = nn.GELU() | ||
| self.pwconv2 = nn.Conv2d(hidden_dim, dim, kernel_size=1) | ||
| self.drop_path = nn.Identity() if drop_path <= 0.0 else nn.Dropout(drop_path) | ||
| self.use_layer_scale = use_layer_scale | ||
| if use_layer_scale: | ||
| self.layer_scale = nn.Parameter(torch.ones(dim).unsqueeze(-1).unsqueeze(-1), requires_grad=True) | ||
|
|
||
| def forward(self, x): | ||
| input = x | ||
| x = self.dwconv(x) | ||
| x = self.norm(x) | ||
| x = self.pwconv1(x) | ||
| x = self.act(x) | ||
| x = self.pwconv2(x) | ||
| if self.use_layer_scale: | ||
| x = self.layer_scale * x | ||
| x = input + self.drop_path(x) | ||
| return x | ||
|
|
||
|
|
||
| class ConvEncoderWithLayerGamma(nn.Module): | ||
| """Test model with renamed layer_gamma parameter (the fix).""" | ||
|
|
||
| def __init__(self, dim=64, hidden_dim=128, kernel_size=3, drop_path=0.0, use_layer_scale=True): | ||
| super().__init__() | ||
| self.dwconv = nn.Conv2d(dim, dim, kernel_size=kernel_size, padding=kernel_size // 2, groups=dim) | ||
| self.norm = nn.BatchNorm2d(dim) | ||
| self.pwconv1 = nn.Conv2d(dim, hidden_dim, kernel_size=1) | ||
| self.act = nn.GELU() | ||
| self.pwconv2 = nn.Conv2d(hidden_dim, dim, kernel_size=1) | ||
| self.drop_path = nn.Identity() if drop_path <= 0.0 else nn.Dropout(drop_path) | ||
| self.use_layer_scale = use_layer_scale | ||
| if use_layer_scale: | ||
| self.layer_gamma = nn.Parameter(torch.ones(dim).unsqueeze(-1).unsqueeze(-1), requires_grad=True) | ||
|
|
||
| def forward(self, x): | ||
| input = x | ||
| x = self.dwconv(x) | ||
| x = self.norm(x) | ||
| x = self.pwconv1(x) | ||
| x = self.act(x) | ||
| x = self.pwconv2(x) | ||
| if self.use_layer_scale: | ||
| x = self.layer_gamma * x | ||
| x = input + self.drop_path(x) | ||
| return x | ||
|
|
||
|
|
||
| <<<<<<< HEAD | ||
| ======= | ||
xin3he marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| class CalibDataloader: | ||
| """Simple calibration dataloader for testing.""" | ||
|
|
||
| def __init__(self, data, label): | ||
| self.data = data | ||
| self.label = label | ||
| self.batch_size = 1 # Since we're yielding single samples | ||
|
|
||
| def __iter__(self): | ||
| yield self.data, self.label | ||
|
|
||
|
|
||
| >>>>>>> eecb88944a1f2334eda4da01910116e7eb87d99f | ||
| class TestPyTorchLayerScale(unittest.TestCase): | ||
| @classmethod | ||
| def setUpClass(self): | ||
| self.constant_data = torch.randn(1, 64, 32, 32) | ||
| self.constant_label = torch.randint(0, 10, (1,)) | ||
|
|
||
| def test_layer_scale_error(self): | ||
| """Test that the original layer_scale parameter causes an error.""" | ||
| model = ConvEncoderWithLayerScale() | ||
| model.eval() | ||
|
|
||
| calib_dataloader = CalibDataloader(self.constant_data, self.constant_label) | ||
|
|
||
| # Configure quantization | ||
| conf = PostTrainingQuantConfig() | ||
|
|
||
| # Try to quantize and verify it fails | ||
| q_model = quantization.fit(model, conf, calib_dataloader=calib_dataloader) | ||
| # The quantization should fail and return None | ||
| self.assertIsNone(q_model, "Quantization should fail with layer_scale parameter") | ||
xin3he marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def test_layer_gamma_success(self): | ||
| """Test that the renamed layer_gamma parameter works correctly.""" | ||
| model = ConvEncoderWithLayerGamma() | ||
| model.eval() | ||
|
|
||
| calib_dataloader = CalibDataloader(self.constant_data, self.constant_label) | ||
|
|
||
| # Configure quantization | ||
| conf = PostTrainingQuantConfig() | ||
|
|
||
| # This should succeed with layer_gamma parameter | ||
| try: | ||
| q_model = quantization.fit(model, conf, calib_dataloader=calib_dataloader) | ||
| self.assertIsNotNone(q_model) | ||
| except ValueError as e: | ||
| self.fail(f"Quantization failed with layer_gamma: {str(e)}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
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.
Uh oh!
There was an error while loading. Please reload this page.