Skip to content

[Transform] apply_transform_config #348

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 88 commits into from
Jul 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
88 commits
Select commit Hold shift + click to select a range
d8a10ec
add utilities
kylesayrs May 30, 2025
d2af054
add tests
kylesayrs May 30, 2025
e32d5b5
add additional tests
kylesayrs May 30, 2025
9d0518b
add utils and tests
kylesayrs May 30, 2025
8c5a2d9
Implement transform factories
kylesayrs May 30, 2025
809e367
Merge branch 'kylesayrs/transform_utils' into kylesayrs/transform_fac…
kylesayrs May 30, 2025
8d613b3
add permutations
kylesayrs May 31, 2025
57d171a
add delete_offload_module
kylesayrs May 31, 2025
d77bcef
Merge branch 'kylesayrs/transform-accelerate-utilities' into kylesayr…
kylesayrs May 31, 2025
ab73b43
Merge branch 'kylesayrs/transform-accelerate-utilities' into kylesayr…
kylesayrs May 31, 2025
4b55733
Merge branch 'kylesayrs/transform_factory' into kylesayrs/transform_p…
kylesayrs May 31, 2025
aa7d21b
key inverses by weight
kylesayrs May 31, 2025
6901e02
fix tests
kylesayrs May 31, 2025
47ae9fe
standardize random hadamard
kylesayrs May 31, 2025
34f1343
Merge branch 'kylesayrs/transform_utils' into kylesayrs/transform_fac…
kylesayrs May 31, 2025
1039100
prepend input hooks
kylesayrs May 31, 2025
5677553
Merge remote-tracking branch 'origin' into kylesayrs/transform_utils
kylesayrs Jun 5, 2025
68ec14e
apply sqrt division first
kylesayrs Jun 5, 2025
a62418a
Merge branch 'kylesayrs/transform_utils' into kylesayrs/transform_fac…
kylesayrs Jun 5, 2025
b117523
use divided hadamards
kylesayrs Jun 5, 2025
a46f754
fix typo
kylesayrs Jun 5, 2025
cb1cb52
add random option
kylesayrs Jun 5, 2025
7c02bb2
Merge branch 'kylesayrs/transform_utils' into kylesayrs/transform_fac…
kylesayrs Jun 5, 2025
02af1e9
use random seeds, rename matrix multiply
kylesayrs Jun 5, 2025
f45f3e9
add deterministic generation to random matrix
kylesayrs Jun 5, 2025
7a7abdf
fix perm math
kylesayrs Jun 5, 2025
6e52894
update docstrings
kylesayrs Jun 5, 2025
7230933
update docstrings
kylesayrs Jun 5, 2025
f74fe3e
Merge branch 'kylesayrs/transform_factory' into kylesayrs/transform_p…
kylesayrs Jun 5, 2025
92ddea9
cleanup
kylesayrs Jun 5, 2025
779956f
cleanup 2
kylesayrs Jun 5, 2025
fbd2939
Merge branch 'kylesayrs/transform_utils' into kylesayrs/transform_fac…
kylesayrs Jun 5, 2025
dd72b6a
make seed optional
kylesayrs Jun 5, 2025
4ae491d
Merge branch 'kylesayrs/transform_factory' into kylesayrs/transform_p…
kylesayrs Jun 5, 2025
da19b0f
remove iterable check and missing return value
kylesayrs Jun 9, 2025
7ab17ce
Merge branch 'main' into kylesayrs/transform_permutations
kylesayrs Jun 10, 2025
33df50f
Merge remote-tracking branch 'origin' into kylesayrs/transform_permut…
kylesayrs Jun 10, 2025
6e1ec39
Remove unrelated changes
kylesayrs Jun 10, 2025
938e702
simplify code
kylesayrs Jun 10, 2025
27bc0b3
implement apply, use in tests
kylesayrs Jun 10, 2025
a27db62
use hadamards database file
kylesayrs Jun 11, 2025
ce63955
try manifest
kylesayrs Jun 11, 2025
7ae5863
try setup, update hadamards list
kylesayrs Jun 11, 2025
67675c3
fix setup
kylesayrs Jun 11, 2025
f061db9
add docstrings, cleanup
kylesayrs Jun 11, 2025
4a84ce1
fix setup, thank you @dbarbuzzi
kylesayrs Jun 11, 2025
cde1066
remove numpy, add tests
kylesayrs Jun 11, 2025
1ba6195
solidify dtype, add gpu tests
kylesayrs Jun 11, 2025
c373345
fix docstring
kylesayrs Jun 11, 2025
fbaf47a
add device option
kylesayrs Jun 11, 2025
5a887f4
construct on execution device, cache on offload device
kylesayrs Jun 11, 2025
310fe6d
save construction device changes for later
kylesayrs Jun 11, 2025
b715329
construct on execution device, cache on offload device
kylesayrs Jun 11, 2025
249323c
cite nja sloane
kylesayrs Jun 11, 2025
1823af4
Merge branch 'kylesayrs/extend-hadamard', remote-tracking branch 'ori…
kylesayrs Jun 11, 2025
94a0bf5
Merge remote-tracking branch 'origin' into kylesayrs/extend-hadamard
kylesayrs Jun 11, 2025
cf066e0
Merge branch 'kylesayrs/extend-hadamard' into kylesayrs/transform_con…
kylesayrs Jun 11, 2025
c1a4a34
remove dreg
kylesayrs Jun 11, 2025
5807ee1
put on device via safe_open
kylesayrs Jun 11, 2025
ccb88ed
nits and docstrings
kylesayrs Jun 12, 2025
feba695
update docstring
kylesayrs Jun 12, 2025
c8f6b53
Merge branch 'kylesayrs/extend-hadamard' into kylesayrs/transform_con…
kylesayrs Jun 12, 2025
e7f08e1
Merge branch 'kylesayrs/transform_construct_cache_device' into kylesa…
kylesayrs Jun 12, 2025
75b9307
Merge remote-tracking branch 'origin' into kylesayrs/transform_permut…
kylesayrs Jun 12, 2025
b6a0dd4
Merge remote-tracking branch 'origin' into kylesayrs/transform_constr…
kylesayrs Jun 13, 2025
955f2f5
Merge
kylesayrs Jun 23, 2025
226f367
merge with construct: construct in float32
kylesayrs Jun 23, 2025
9745acb
Merge remote-tracking branch 'origin' into kylesayrs/transform_apply
kylesayrs Jun 23, 2025
fd3390a
construct with same dtype, constructing on fp32 found no difference
kylesayrs Jun 23, 2025
3c55003
Merge branch 'kylesayrs/transform_construct_cache_device' into kylesa…
kylesayrs Jun 23, 2025
ad29c15
remove unnecessary imports
kylesayrs Jun 23, 2025
85f40b5
bugfixes (#375)
brian-dellabetta Jul 2, 2025
500af9b
use factory_kwargs
kylesayrs Jul 7, 2025
8e36540
add frozen dict to deps
kylesayrs Jul 7, 2025
48653ec
Merge remote-tracking branch 'origin' into kylesayrs/transform_permut…
kylesayrs Jul 7, 2025
56df0f7
fix style
kylesayrs Jul 7, 2025
a251569
merge
kylesayrs Jul 7, 2025
cb5a32b
Merge remote-tracking branch 'origin' into kylesayrs/transform_apply
kylesayrs Jul 7, 2025
06e0346
Merge branch 'kylesayrs/transform_permutations' into kylesayrs/transf…
kylesayrs Jul 7, 2025
0a4fea5
Merge branch 'kylesayrs/transform_construct_cache_device' into kylesa…
kylesayrs Jul 7, 2025
49740c6
use delete_offload_module
kylesayrs Jul 7, 2025
7dc182b
Merge remote-tracking branch 'origin' into kylesayrs/transform_constr…
kylesayrs Jul 7, 2025
80db2ce
Merge branch 'kylesayrs/transform_construct_cache_device' into kylesa…
kylesayrs Jul 7, 2025
e06bbad
add docstrign
kylesayrs Jul 7, 2025
438bc13
Merge remote-tracking branch 'origin' into kylesayrs/transform_apply
kylesayrs Jul 7, 2025
fd77ecc
use parametrize
kylesayrs Jul 8, 2025
bbf9533
remove random from tests
kylesayrs Jul 8, 2025
853ffcf
Merge remote-tracking branch 'origin' into kylesayrs/transform_apply
kylesayrs Jul 9, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/compressed_tensors/transform/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@
from .factory.hadamard import *
from .factory.matrix_multiply import *
from .factory.random_hadamard import *
from .apply import *
32 changes: 32 additions & 0 deletions src/compressed_tensors/transform/apply.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
#
# 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.

import torch
from compressed_tensors.transform import TransformConfig, TransformFactory


__all__ = ["apply_transform_config"]


def apply_transform_config(model: torch.nn.Module, config: TransformConfig):
"""
Apply a transform config to a model. Weight transforms are fused into weights, while
activation transforms are attached as submodules and trigger via pytorch hooks

:param model: model to apply config to
:param config: transform config to apply
"""
for name, scheme in config.config_groups.items():
factory = TransformFactory.from_scheme(scheme, name=name)
factory.apply_to_model(model)
10 changes: 6 additions & 4 deletions src/compressed_tensors/transform/factory/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
)
from compressed_tensors.utils import (
align_module_device,
delete_offload_module,
has_offloaded_params,
patch_attr,
register_offload_module,
Expand Down Expand Up @@ -100,7 +101,7 @@ def _apply_to_module(self, module: Module, args: TransformArgs):
# create transform as submodule
transform_name = f"{self.name}_{args.location.value}"
transform = self.create_transform(module, args)
register_offload_module(module, transform_name, transform) # (1)
register_offload_module(module, transform_name, transform)

# register input transformation hook
if args.location == TransformLocation.INPUT:
Expand All @@ -119,6 +120,7 @@ def input_hook(_, args):
assert isinstance(module, torch.nn.Linear)
assert module.bias is None

# fuse transform into weight
with torch.no_grad(), align_module_device(module):
update_offload_parameter(module, "weight", transform(module.weight))

Expand All @@ -129,6 +131,9 @@ def input_hook(_, args):
raise ValueError("Offloaded training is not supported")
P.register_parametrization(module, "weight", transform)

# transform is no longer needed (unfusing is not supported)
delete_offload_module(module, transform_name)

# register output transformation hook
elif args.location == TransformLocation.OUTPUT:

Expand All @@ -141,9 +146,6 @@ def output_hook(_, _input, output):
else:
raise NotImplementedError()

# (1) even in the `weight` cases, this submodule attachment is needed in order
# to support saving in the frozen state


class TransformBase(InternalModule, ABC):
"""
Expand Down
36 changes: 14 additions & 22 deletions tests/test_transform/factory/test_correctness.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,18 @@
TransformConfig,
TransformFactory,
TransformScheme,
apply_transform_config,
)
from compressed_tensors.utils import offloaded_dispatch
from tests.testing_utils import requires_accelerate, requires_gpu


def scheme_kwargs():
all_types = TransformFactory.registered_names()
base = [{"type": type} for type in all_types]
randomized = [{"type": type, "randomize": True} for type in all_types]
return base + randomized


@pytest.mark.parametrize("scheme_kwargs", scheme_kwargs())
def test_correctness_linear(scheme_kwargs):
@pytest.mark.parametrize("type", ("hadamard", "random-hadamard"))
@pytest.mark.parametrize("randomized", (True, False))
def test_correctness_linear(type, randomized):
size = (4, 8)
module = torch.nn.Linear(*size, bias=True)
scheme = TransformScheme(**scheme_kwargs)
scheme = TransformScheme(type=type, randomized=randomized)
factory = TransformFactory.from_scheme(scheme, name="")

input_tfm = factory.create_transform(
Expand All @@ -59,8 +54,9 @@ def test_correctness_linear(scheme_kwargs):
assert torch.allclose(true_output, output, atol=1e-5, rtol=0.0)


@pytest.mark.parametrize("scheme_kwargs", scheme_kwargs())
def test_correctness_model(scheme_kwargs, model_apply, offload=False):
@pytest.mark.parametrize("type", ("hadamard", "random-hadamard"))
@pytest.mark.parametrize("randomized", (True, False))
def test_correctness_model(type, randomized, model_apply, offload=False):
# load model
model = model_apply[0]
if offload:
Expand All @@ -75,15 +71,10 @@ def test_correctness_model(scheme_kwargs, model_apply, offload=False):
# apply transforms
config = TransformConfig(
config_groups={
"": TransformScheme(
**scheme_kwargs,
apply=model_apply[1],
)
"": TransformScheme(type=type, randomized=randomized, apply=model_apply[1])
}
)
for name, scheme in config.config_groups.items():
factory = TransformFactory.from_scheme(scheme, name=name)
factory.apply_to_model(model)
apply_transform_config(model, config)

# compare outputs
output = model(input)
Expand All @@ -92,6 +83,7 @@ def test_correctness_model(scheme_kwargs, model_apply, offload=False):

@requires_gpu
@requires_accelerate()
@pytest.mark.parametrize("scheme_kwargs", scheme_kwargs())
def test_correctness_model_offload(scheme_kwargs, model_apply):
test_correctness_model(scheme_kwargs, model_apply, offload=True)
@pytest.mark.parametrize("type", ("hadamard", "random-hadamard"))
@pytest.mark.parametrize("randomized", (True, False))
def test_correctness_model_offload(type, randomized, model_apply):
test_correctness_model(type, randomized, model_apply, offload=True)
39 changes: 16 additions & 23 deletions tests/test_transform/factory/test_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,18 @@
TransformArgs,
TransformBase,
TransformConfig,
TransformFactory,
TransformScheme,
apply_transform_config,
)
from compressed_tensors.utils import align_modules, offloaded_dispatch
from tests.test_transform.conftest import TransformableModel
from tests.testing_utils import requires_accelerate, requires_gpu


def scheme_kwargs():
all_types = TransformFactory.registered_names()
base = [{"type": type} for type in all_types]
randomized = [{"type": type, "randomize": True} for type in all_types]
return base + randomized


@pytest.mark.parametrize("scheme_kwargs", scheme_kwargs())
def test_memory_sharing(scheme_kwargs, offload=False):
@pytest.mark.parametrize("type", ("hadamard", "random-hadamard"))
@pytest.mark.parametrize("randomized", (True, False))
@pytest.mark.parametrize("requires_grad", (True, False))
def test_memory_sharing(type, randomized, requires_grad, offload=False):
# load model (maybe with offloading)
model = TransformableModel(2, 2, 4, 4, 8, 8)
if offload:
Expand All @@ -46,17 +41,17 @@ def test_memory_sharing(scheme_kwargs, offload=False):
config = TransformConfig(
config_groups={
"": TransformScheme(
**scheme_kwargs,
type=type,
randomzied=randomized,
requires_grad=requires_grad,
apply=[
TransformArgs(targets="Linear", location="input"),
TransformArgs(targets="Linear", location="output"),
],
)
}
)
for name, scheme in config.config_groups.items():
factory = TransformFactory.from_scheme(scheme, name=name)
factory.apply_to_model(model)
apply_transform_config(model, config)

# check that memory is shared when onloaded
with align_modules(model.modules()):
Expand Down Expand Up @@ -88,12 +83,10 @@ def test_memory_sharing(scheme_kwargs, offload=False):

@requires_gpu
@requires_accelerate()
@pytest.mark.parametrize("scheme_kwargs", scheme_kwargs())
def test_memory_sharing_offload(scheme_kwargs):
test_memory_sharing(scheme_kwargs, offload=True)


@pytest.mark.parametrize("scheme_kwargs", scheme_kwargs())
def test_memory_sharing_training(scheme_kwargs):
scheme_kwargs["requires_grad"] = True
test_memory_sharing(scheme_kwargs, offload=False)
@pytest.mark.parametrize("type", ("hadamard", "random-hadamard"))
@pytest.mark.parametrize("randomized", (True, False))
def test_memory_sharing_offload(
type,
randomized,
):
test_memory_sharing(type, randomized, requires_grad=False, offload=True)