Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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 changelog.d/107.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Validate that channel-structured magnitude pruning is applied to tensors with at least 2 dimensions, raising a descriptive ValueError for 1D tensors
14 changes: 11 additions & 3 deletions src/coreai_opt/pruning/spec/prune.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,14 +139,15 @@ def compute_mask(
Returns:
torch.Tensor: Binary mask (1 = keep, 0 = prune).
"""
# TODO: Replace this with generic abstractions
if isinstance(pruning_scheme, ChannelStructured):
return _MagnitudePruneImpl._compute_channel_mask(weight, sparsity, pruning_scheme.axis)

if sparsity == 0.0:
return torch.ones_like(weight)
if sparsity >= 1.0:
return torch.zeros_like(weight)

# TODO: Replace this with generic abstractions
if isinstance(pruning_scheme, ChannelStructured):
return _MagnitudePruneImpl._compute_channel_mask(weight, sparsity, pruning_scheme.axis)
return _MagnitudePruneImpl._compute_unstructured_mask(weight, sparsity)

@staticmethod
Expand All @@ -171,6 +172,13 @@ def _compute_channel_mask(
Channel importance is measured by L1 norm. The least-important
channels are pruned entirely.
"""
if weight.ndim < 2:
raise ValueError(
f"Channel-structured pruning requires a tensor with at least 2 dimensions, "
f"got shape {tuple(weight.shape)} with {weight.ndim} dims. "
f"For 1D tensors, use Unstructured pruning instead."
)

if not (-weight.ndim <= axis < weight.ndim):
raise ValueError(
f"Invalid axis. Should be in range [{-weight.ndim}, {weight.ndim}), but got {axis}"
Expand Down
19 changes: 18 additions & 1 deletion tests/pruning/test_magnitude_pruner.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@
OpMagnitudePrunerConfig,
PolynomialDecaySchedule,
)
from coreai_opt.pruning.spec import ChannelStructured, PruneImplBase, Unstructured
from coreai_opt.pruning.spec import (
ChannelStructured,
PruneImplBase,
Unstructured,
_MagnitudePruneImpl,
)


@pytest.fixture
Expand Down Expand Up @@ -462,6 +467,18 @@ def test_channel_structured_axis_out_of_range(self, axis: int) -> None:
with pytest.raises(ValueError, match="Invalid axis"):
pruner.prepare((torch.randn(1, 4),))

@pytest.mark.parametrize("target_sparsity", [0.0, 0.5])
@pytest.mark.parametrize("axis", [0, -1], ids=["axis-0", "axis-neg-1"])
def test_channel_structured_1d_tensor_raises(self, axis: int, target_sparsity: float) -> None:
"""Channel-structured pruning requires >= 2 dimensions; 1D tensors raise ValueError."""
weight = torch.tensor([1.0, 5.0, 2.0, 8.0])
scheme = ChannelStructured(axis=axis)
with pytest.raises(
ValueError,
match=r"Channel-structured pruning requires a tensor with at least 2 dimensions",
):
_MagnitudePruneImpl.compute_mask(weight, target_sparsity, scheme)

def test_linear_unstructured_conv2d_channel_structured(self) -> None:
"""Apply unstructured to Linear and channel-structured to Conv2d in same model."""

Expand Down