Skip to content

Commit 4ccef3a

Browse files
committed
clear_null_stride_columns
1 parent 8593a74 commit 4ccef3a

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

src/torchjd/sparse/_structured_sparse_tensor.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,3 +422,16 @@ def make_sst(physical: Tensor, v_to_ps: list[list[int]]) -> StructuredSparseTens
422422
physical, v_to_ps = fix_dim_of_size_1(physical, v_to_ps)
423423
physical, v_to_ps = fix_ungrouped_dims(physical, v_to_ps)
424424
return StructuredSparseTensor(physical, v_to_ps)
425+
426+
427+
def clear_null_stride_columns(physical: Tensor, strides: Tensor) -> tuple[Tensor, Tensor]:
428+
"""Remove columns of strides that are all 0 and sum the corresponding elements in the physical tensor."""
429+
all_zero_columns = (strides == 0).all(dim=0)
430+
431+
if not (all_zero_columns).any():
432+
return physical, strides
433+
434+
all_zero_columns_indices = all_zero_columns.nonzero().flatten().tolist()
435+
physical = physical.sum(dim=all_zero_columns_indices)
436+
strides = strides[:, ~all_zero_columns]
437+
return physical, strides

tests/unit/sparse/test_structured_sparse_tensor.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from torchjd.sparse._aten_function_overrides.shape import unsquash_pdim
1313
from torchjd.sparse._structured_sparse_tensor import (
1414
StructuredSparseTensor,
15+
clear_null_stride_columns,
1516
encode_by_order,
1617
fix_ungrouped_dims,
1718
get_groupings,
@@ -277,3 +278,31 @@ def test_concatenate(
277278

278279
assert isinstance(res, StructuredSparseTensor)
279280
assert torch.all(torch.eq(res.to_dense(), expected))
281+
282+
283+
@mark.parametrize(
284+
["physical", "strides", "expected_physical", "expected_strides"],
285+
[
286+
([[1, 2, 3], [4, 5, 6]], [[1, 0], [1, 0], [2, 0]], [6, 15], [[1], [1], [2]]),
287+
(
288+
[[1, 2, 3], [4, 5, 6]],
289+
[[1, 1], [1, 0], [2, 0]],
290+
[[1, 2, 3], [4, 5, 6]],
291+
[[1, 1], [1, 0], [2, 0]],
292+
),
293+
],
294+
)
295+
def test_clear_null_stride_columns(
296+
physical: list,
297+
strides: list,
298+
expected_physical: list,
299+
expected_strides: list,
300+
):
301+
physical, strides = torch.tensor(physical), torch.tensor(strides)
302+
expected_physical, expected_strides = torch.tensor(expected_physical), torch.tensor(
303+
expected_strides
304+
)
305+
306+
physical, strides = clear_null_stride_columns(physical, strides)
307+
assert_close(physical, expected_physical)
308+
assert_close(strides, expected_strides)

0 commit comments

Comments
 (0)