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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- Fix BufferList negative index error reporting, reject non-integer/slice keys with TypeError, and fix __itruediv__ reciprocal precision loss [\#838](https://github.com/mllam/neural-lam/pull/838) @muskan-creates352

- Fix `InteractionNet` and `PropagationNet` dimension mismatches when `hidden_dim` differs from `input_dim` [\#836](https://github.com/mllam/neural-lam/pull/836) @Karvy-Singh

- Raise a `ValueError` for `--val_interval` below 1 in `train_model.fit`; `0` previously crashed with a `ZeroDivisionError` inside Lightning after the model was built, and negative values were silently accepted [\#847](https://github.com/mllam/neural-lam/pull/847) @nikhil3495
Expand Down
19 changes: 14 additions & 5 deletions neural_lam/utils/buffer_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,26 @@ def __getitem__(

Raises
------
TypeError
If ``key`` is neither an integer nor a slice.
IndexError
If ``key`` is an out-of-range integer.
"""
# Unpack slice indices and call recursively for each position
if isinstance(key, slice):
return [self[i] for i in range(*key.indices(len(self)))]
if not isinstance(key, int):
raise TypeError(
f"BufferList indices must be integers or slices, "
f"not {type(key).__name__}"
)
# Support negative indexing (e.g. buffer_list[-1] -> last element)
if key < 0:
key += len(self)
if not (0 <= key < len(self)):
norm_key = key + len(self) if key < 0 else key
if not (0 <= norm_key < len(self)):
raise IndexError(
f"index {key} out of range for BufferList of length {len(self)}"
)
return getattr(self, f"b{key}")
return getattr(self, f"b{norm_key}")

def __len__(self) -> int:
"""Return the number of registered buffers."""
Expand All @@ -90,7 +96,10 @@ def __itruediv__(self, other: float | torch.Tensor) -> "BufferList":
BufferList
The modified BufferList.
"""
return self.__imul__(1.0 / other)
for buffer_tensor in self:
buffer_tensor /= other

return self

def __imul__(self, other: float | torch.Tensor) -> "BufferList":
"""
Expand Down
97 changes: 96 additions & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import torch.nn.functional as F

# First-party
from neural_lam.utils import inverse_softplus
from neural_lam.utils import BufferList, inverse_softplus


@pytest.mark.parametrize("beta", [1.0, 0.5, 2.0])
Expand Down Expand Up @@ -32,3 +32,98 @@ def test_inverse_softplus_above_threshold_is_identity(threshold):
y_high = torch.tensor([threshold + 5.0, threshold + 30.0])
x_high = inverse_softplus(y_high, threshold=threshold)
torch.testing.assert_close(y_high, x_high)


def test_buffer_list_len_and_iteration():
"""BufferList reports correct length and iterates over buffers."""
tensors = [torch.tensor([1.0]), torch.tensor([2.0]), torch.tensor([3.0])]
buf = BufferList(tensors)
assert len(buf) == 3
elements = list(buf)
assert len(elements) == 3
for elem, orig in zip(elements, tensors):
torch.testing.assert_close(elem, orig)


def test_buffer_list_indexing():
"""BufferList supports positive and negative integer indexing."""
t0 = torch.tensor([10.0])
t1 = torch.tensor([20.0])
buf = BufferList([t0, t1])
torch.testing.assert_close(buf[0], t0)
torch.testing.assert_close(buf[1], t1)
torch.testing.assert_close(buf[-1], t1)
torch.testing.assert_close(buf[-2], t0)


@pytest.mark.parametrize("out_of_bounds_index", [2, 10, -3, -5, -100])
def test_buffer_list_out_of_bounds_index_error_message(out_of_bounds_index):
"""Out-of-bounds integer access reports the exact requested index."""
buf = BufferList([torch.tensor([1.0]), torch.tensor([2.0])])
expected_msg = (
f"^index {out_of_bounds_index} out of range for BufferList of length 2$"
)
with pytest.raises(IndexError, match=expected_msg):
_ = buf[out_of_bounds_index]


@pytest.mark.parametrize("invalid_key", ["invalid", 1.5, [0], None])
def test_buffer_list_invalid_key_type_raises_type_error(invalid_key):
"""Non-integer, non-slice key raises a descriptive TypeError."""
buf = BufferList([torch.tensor([1.0]), torch.tensor([2.0])])
expected_msg = (
f"BufferList indices must be integers or slices, "
f"not {type(invalid_key).__name__}"
)
with pytest.raises(TypeError, match=expected_msg):
_ = buf[invalid_key]


def test_buffer_list_slicing():
"""Slice access returns a list of tensors matching the requested slice."""
tensors = [torch.tensor([float(i)]) for i in range(5)]
buf = BufferList(tensors)
sliced = buf[1:4:2]
assert len(sliced) == 2
torch.testing.assert_close(sliced[0], torch.tensor([1.0]))
torch.testing.assert_close(sliced[1], torch.tensor([3.0]))


def test_buffer_list_imul():
"""In-place multiplication scales each buffer and returns BufferList."""
t0 = torch.tensor([1.0, 2.0])
t1 = torch.tensor([3.0, 4.0])
buf = BufferList([t0, t1])
ret = buf.__imul__(2.5)
assert ret is buf
torch.testing.assert_close(buf[0], torch.tensor([2.5, 5.0]))
torch.testing.assert_close(buf[1], torch.tensor([7.5, 10.0]))


def test_buffer_list_itruediv():
"""In-place true division performs exact tensor division across buffers."""
t0 = torch.tensor([1.0, 2.0])
t1 = torch.tensor([3.0, 4.0])
buf = BufferList([t0, t1])
ret = buf.__itruediv__(3.0)
assert ret is buf
# Exact in-place true division avoids reciprocal multiplication error
torch.testing.assert_close(buf[0], torch.tensor([1.0 / 3.0, 2.0 / 3.0]))
torch.testing.assert_close(buf[1], torch.tensor([1.0, 4.0 / 3.0]))


def test_buffer_list_itruediv_with_tensor():
"""In-place division supports scalar torch.Tensor divisors."""
t0 = torch.tensor([6.0, 8.0])
buf = BufferList([t0])
buf /= torch.tensor(2.0)
torch.testing.assert_close(buf[0], torch.tensor([3.0, 4.0]))


def test_buffer_list_persistence_flag():
"""BufferList respects persistent flag in PyTorch state dict."""
t0 = torch.tensor([1.0])
persistent_buf = BufferList([t0], persistent=True)
non_persistent_buf = BufferList([t0], persistent=False)
assert "b0" in persistent_buf.state_dict()
assert "b0" not in non_persistent_buf.state_dict()
Loading