-
Notifications
You must be signed in to change notification settings - Fork 180
Stream targeted block re-quantization's calibration pass #2064
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
aquilarubra
wants to merge
8
commits into
intel:main
Choose a base branch
from
aquilarubra:pr/targeted-block-calib
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
8 commits
Select commit
Hold shift + click to select a range
3f26e3c
calibration: stream targeted block re-quantization's calibration pass
aquilarubra 709630f
Merge branch 'main' into pr/targeted-block-calib
wenhuach21 8f89538
Remove duplicate AR_DISK_STREAM_MODEL/AR_RESUME_DIR doc sections
aquilarubra e559701
Merge branch 'main' into pr/targeted-block-calib
wenhuach21 ae4ed51
Merge branch 'main' into pr/targeted-block-calib
chensuyue 4aea0c5
Move new disk-stream tests to the CUDA tier; drop unused last_grad_input
aquilarubra 6075eee
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] d576716
Merge branch 'main' into pr/targeted-block-calib
wenhuach21 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
103 changes: 103 additions & 0 deletions
103
test/unit/test_cuda/auto_scheme/test_auto_scheme_disk_stream.py
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,103 @@ | ||
| # Copyright (c) 2026 Intel Corporation | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """ | ||
| Unit tests for AutoScheme's disk-streaming mode (AR_DISK_STREAM_MODEL). | ||
|
|
||
| Verifies that streaming per-block sensitivity scoring from disk (instead of | ||
| fully materializing the checkpoint on CPU RAM up front) produces the same | ||
| mixed-bit layer_config as the non-streaming baseline, and that the underlying | ||
| materialize/free primitives round-trip correctly. | ||
| """ | ||
|
|
||
| import os | ||
| import shutil | ||
|
|
||
| import pytest | ||
| import torch | ||
|
|
||
| from auto_round import AutoRound, AutoScheme | ||
| from auto_round.utils.disk_stream_util import build_meta_model, free_module, materialize_module, total_resident_bytes | ||
|
|
||
| pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="test requires CUDA") | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def _clean_disk_stream_env(): | ||
| # AR_DISK_STREAM_MODEL is read lazily by auto_round.envs; make sure a test | ||
| # that sets it can't leak into whichever test runs next. | ||
| previous = os.environ.get("AR_DISK_STREAM_MODEL") | ||
| yield | ||
| if previous is None: | ||
| os.environ.pop("AR_DISK_STREAM_MODEL", None) | ||
| else: | ||
| os.environ["AR_DISK_STREAM_MODEL"] = previous | ||
|
|
||
|
|
||
| class TestAutoSchemeDiskStream: | ||
| @pytest.fixture(autouse=True) | ||
| def setup_save_dir(self, tmp_path): | ||
| self.save_dir = str(tmp_path / "saved") | ||
| yield | ||
| shutil.rmtree(self.save_dir, ignore_errors=True) | ||
|
|
||
| def _gen_layer_config(self, model_name, target_bits=3.5): | ||
| # iters=1 (the standard tuning loop) rather than iters=0 (RTN): RTN's | ||
| # separate block-materialization path doesn't support disk streaming yet | ||
| # and is unrelated to this PR, which only streams AutoScheme's own | ||
| # sensitivity-scoring pass. | ||
| scheme = AutoScheme(avg_bits=target_bits, options=("W2A16", "W4A16", "BF16"), nsamples=1) | ||
| ar = AutoRound(model=model_name, scheme=scheme, iters=1, nsamples=1) | ||
| _, layer_config = ar.quantize() | ||
| return {name: cfg["bits"] for name, cfg in layer_config.items() if "bits" in cfg} | ||
|
|
||
| def test_disk_stream_matches_baseline_layer_config(self, tiny_opt_model_path): | ||
| """AR_DISK_STREAM_MODEL=1 must select the exact same per-layer bits as the | ||
| non-streaming baseline -- streaming changes *how* weights are loaded during | ||
| scoring, not the scores themselves.""" | ||
| os.environ.pop("AR_DISK_STREAM_MODEL", None) | ||
| baseline_bits = self._gen_layer_config(tiny_opt_model_path) | ||
|
|
||
| os.environ["AR_DISK_STREAM_MODEL"] = "1" | ||
| streamed_bits = self._gen_layer_config(tiny_opt_model_path) | ||
|
|
||
| assert streamed_bits == baseline_bits | ||
|
|
||
| def test_disk_stream_default_off(self): | ||
| """With AR_DISK_STREAM_MODEL unset, behavior must be the unstreamed default.""" | ||
| os.environ.pop("AR_DISK_STREAM_MODEL", None) | ||
| from auto_round import envs | ||
|
|
||
| assert envs.AR_DISK_STREAM_MODEL is False | ||
|
|
||
|
|
||
| class TestDiskStreamUtilRoundTrip: | ||
| """Tests for the materialize/free primitives directly, independent of AutoScheme.""" | ||
|
|
||
| def test_materialize_then_free_round_trip(self, tiny_opt_model_path): | ||
| model, _tokenizer, index = build_meta_model(tiny_opt_model_path) | ||
| block = model.model.decoder.layers[0] | ||
|
|
||
| for _, tensor in list(block.named_parameters()): | ||
| assert str(tensor.device) == "meta" | ||
|
|
||
| materialize_module(block, "model.decoder.layers.0", index, device="cpu") | ||
| for _, tensor in list(block.named_parameters()): | ||
| assert str(tensor.device) != "meta" | ||
| assert total_resident_bytes(block) > 0 | ||
|
|
||
| free_module(block) | ||
| for _, tensor in list(block.named_parameters()): | ||
| assert str(tensor.device) == "meta" | ||
| assert total_resident_bytes(block) == 0 |
99 changes: 99 additions & 0 deletions
99
test/unit/test_cuda/calibration/test_targeted_block_calib_stream.py
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,99 @@ | ||
| # Copyright (c) 2026 Intel Corporation | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """ | ||
| Integration test for targeted block re-quantization (``to_quant_block_names``) | ||
| combined with disk streaming (``AR_DISK_STREAM_MODEL``). | ||
|
|
||
| Regression coverage for: restricting tuning to a block that isn't the first | ||
| one left every block *before* the target on the meta device, and the | ||
| "cache block inputs" calibration forward silently propagated that meta-ness | ||
| until it collided with a genuinely-materialized module -- "Tensor on device | ||
| meta is not on the expected device cpu!". A full (unrestricted) run never | ||
| hits this, since every block is already covered by quant_block_list in that | ||
| case. | ||
| """ | ||
|
|
||
| import os | ||
|
|
||
| import pytest | ||
| import torch | ||
|
|
||
| from auto_round import AutoRound | ||
|
|
||
| pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="test requires CUDA") | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def _clean_disk_stream_env(): | ||
| previous = os.environ.get("AR_DISK_STREAM_MODEL") | ||
| yield | ||
| if previous is None: | ||
| os.environ.pop("AR_DISK_STREAM_MODEL", None) | ||
| else: | ||
| os.environ["AR_DISK_STREAM_MODEL"] = previous | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def tiny_opt_3layer_model_path(): | ||
| from test.helpers import save_tiny_model | ||
|
|
||
| path = save_tiny_model("facebook/opt-125m", "./tmp/tiny_opt_3layer_model_path", num_layers=3) | ||
| yield path | ||
| import shutil | ||
|
|
||
| shutil.rmtree(path, ignore_errors=True) | ||
|
|
||
|
|
||
| class TestTargetedBlockCalibStream: | ||
| def test_targeted_block_with_disk_streaming_does_not_crash(self, tiny_opt_3layer_model_path): | ||
| """Restricting to_quant_block_names to the LAST of 3 blocks leaves | ||
| blocks 0 and 1 meta-only (never in quant_block_list) while the | ||
| calibration forward pass still needs to run through them to reach | ||
| block 2 -- exactly the scenario that used to crash.""" | ||
| os.environ["AR_DISK_STREAM_MODEL"] = "1" | ||
|
|
||
| ar = AutoRound( | ||
| model=tiny_opt_3layer_model_path, | ||
| scheme="W4A16", | ||
| iters=1, | ||
| nsamples=1, | ||
| to_quant_block_names="model.decoder.layers.2", | ||
| ) | ||
| _, layer_config = ar.quantize() | ||
|
|
||
| quantized_layers = {name for name, cfg in layer_config.items() if "bits" in cfg} | ||
| assert quantized_layers, "expected the target block's layers to be quantized" | ||
| assert all(name.startswith("model.decoder.layers.2.") for name in quantized_layers) | ||
| assert not any( | ||
| name.startswith(("model.decoder.layers.0.", "model.decoder.layers.1.")) for name in quantized_layers | ||
| ) | ||
|
|
||
| def test_targeted_block_without_disk_streaming_still_works(self, tiny_opt_3layer_model_path): | ||
| """Baseline: the same targeted re-quantization without disk streaming | ||
| never hit this bug (nothing is meta), so it must keep working too.""" | ||
| os.environ.pop("AR_DISK_STREAM_MODEL", None) | ||
|
|
||
| ar = AutoRound( | ||
| model=tiny_opt_3layer_model_path, | ||
| scheme="W4A16", | ||
| iters=1, | ||
| nsamples=1, | ||
| to_quant_block_names="model.decoder.layers.2", | ||
| ) | ||
| _, layer_config = ar.quantize() | ||
|
|
||
| quantized_layers = {name for name, cfg in layer_config.items() if "bits" in cfg} | ||
| assert quantized_layers | ||
| assert all(name.startswith("model.decoder.layers.2.") for name in quantized_layers) |
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.
For non-MoE models, Transformers already works this way, so no extra ops or code are needed. For MoE models, however, the current PR is not sufficient. The main branch already includes an attempt to address the MoE issue.
So I suppose there is no need for this PR. Please feel free to correct me if I am wrong.
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.
Thanks for looking — agreed that non-MoE models need nothing here, and this PR isn't about MoE. The remaining diff addresses a narrower case that I can still reproduce on current main (6afaecd): with
AR_DISK_STREAM_MODEL=1the model is a meta-device skeleton, and whento_quant_block_namestargets a block other than the first, the blocks before it are never materialized. The calibration forward then propagates meta tensors until it fails withRuntimeError: Tensor on device meta is not on the expected device cpu!.test_targeted_block_with_disk_streaming_does_not_crashfails on main with exactly that error and passes with this PR. It's gated on the env var, so default behavior is unchanged.I've also moved the new tests to
test/unit/test_cuda/as requested (the CPU run was timing out) and removed an unused variable. If you'd prefer this not live incalibration/llm.py, I'm glad to restructure it or close the PR.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.
@wenhuach21 pushed 852b112 with the tests moved to the CUDA tier — could you please re-run
/azp run Unit-Test-CUDA-AutoRoundon it when you get a chance? Thanks!