diff --git a/dwave/plugins/torch/models/boltzmann_machine.py b/dwave/plugins/torch/models/boltzmann_machine.py index f3e3e10..981d4a1 100644 --- a/dwave/plugins/torch/models/boltzmann_machine.py +++ b/dwave/plugins/torch/models/boltzmann_machine.py @@ -134,6 +134,8 @@ def set_quadratic(self, quadratic: dict[tuple[Hashable, Hashable], float]) -> No """ for (u, v), bias in quadratic.items(): idx = self._edge_to_idx.get((u, v), self._edge_to_idx.get((v, u))) + if idx is None: + raise ValueError(f"Edge {(u, v)!r} is not in the model.") self._quadratic.data[idx] = bias def _setup_hidden(self): diff --git a/releasenotes/notes/reject-unknown-quadratic-edges-d32fa47da9b7380f.yaml b/releasenotes/notes/reject-unknown-quadratic-edges-d32fa47da9b7380f.yaml new file mode 100644 index 0000000..057ea4c --- /dev/null +++ b/releasenotes/notes/reject-unknown-quadratic-edges-d32fa47da9b7380f.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Raise a ``ValueError`` when ``GraphRestrictedBoltzmannMachine.set_quadratic`` receives an edge + that is not in the model. Previously, an unknown edge overwrote every quadratic bias. diff --git a/tests/test_boltzmann_machine.py b/tests/test_boltzmann_machine.py index afeedde..3956571 100644 --- a/tests/test_boltzmann_machine.py +++ b/tests/test_boltzmann_machine.py @@ -82,10 +82,18 @@ def test_selfloop(self): GRBM(self.nodes, self.edges, None, {"a": 0}, {("b", "c"): 0}) def test_quadratic(self): - self.bm.set_quadratic({("d", "b"): 999}) + self.bm.set_quadratic({("b", "a"): 999}) self.assertEqual(999, self.bm.quadratic[0]) self.bm.set_quadratic({}) + def test_set_quadratic_unknown_edge(self): + quadratic = self.bm.quadratic.detach().clone() + + with self.assertRaisesRegex(ValueError, r"Edge \('d', 'b'\) is not in the model"): + self.bm.set_quadratic({("d", "b"): 999}) + + torch.testing.assert_close(self.bm.quadratic, quadratic) + def test_set_linear(self): self.bm.set_linear({"d": 999}) self.assertEqual(999, self.bm.linear[0])