Skip to content

Commit 4e89184

Browse files
minsukingclaudeericspod
authored
Accept torch tensors as DiNTS arch_code for weights_only=True checkpoints (#9053)
Addresses the MONAI-side portion of #9025. This PR does not fully resolve that issue on its own — see "Follow-up required" below for the bundle-artifact half. ### Description `TopologyConstruction.__init__` converted the `arch_code` entries with `torch.from_numpy(...)`, which raises `TypeError: expected np.ndarray (got Tensor)` when the architecture codes are already tensors. Checkpoints such as `search_code_18590.pt` from the `pancreas_ct_dints_segmentation` and `multi_organ_segmentation` bundles currently store numpy arrays, which `torch.load(..., weights_only=True)` rejects; once those files are re-saved with tensors, the DiNTS network must accept tensor arch codes to load them. This PR replaces the two `torch.from_numpy(...)` calls with `torch.as_tensor(...)` (`monai/networks/nets/dints.py`), which handles numpy arrays and tensors identically: - **numpy path unchanged**: `torch.as_tensor(ndarray)` is equivalent to `torch.from_numpy` — zero-copy (same `data_ptr()`), dtype preserved, followed by the same `.to(self.device)`. - **tensor path**: `torch.as_tensor(tensor)` returns the input as-is (no copy, no warning), unlike `torch.tensor(...)` which always copies and warns. - `arch_code_c` still goes through `.to(torch.int64)` before `F.one_hot`, so the one-hot output dtype (`int64`) is identical for both input types; all downstream consumers (`== 1` gates, `arch_c > 0` in `MixedOp`, forward-path activation checks) already operated on tensors after the conversion site, so their behavior is unchanged. Credit where due: another contributor (@Theerth1) independently traced the same root cause to `TopologyConstruction.__init__` in the issue discussion before this PR was prepared. ### Follow-up required (not resolved by this PR) This change alone does not make the affected bundles loadable with `weights_only=True`: the shipped `search_code_18590.pt` files contain pickled numpy arrays, which the `weights_only` unpickler rejects at `torch.load` time regardless of this fix. The checkpoints for `pancreas_ct_dints_segmentation` and `multi_organ_segmentation` (including their identical HuggingFace mirrors) need to be re-saved with tensors and re-uploaded in Project-MONAI/model-zoo. This PR is the prerequisite that lets those re-saved tensor checkpoints construct the network. Per the investigation in #9025, no other model-zoo bundles are affected. ### Notes / disclosed risks - `torch.as_tensor` also accepts Python lists/scalars, so the accepted input is slightly broader than the documented `numpy arrays or torch tensors`; this is benign. - `arch_code_a`'s stored dtype now follows a tensor input's dtype (previously always the numpy dtype); all consumers are dtype-agnostic comparisons, and no functional difference was found. - Verified locally (Windows, Python 3.11): full `tests/networks/nets/test_dints_network.py` module passes via unittest (including the TorchScript tests); the new `TestDintsArchCode` cases pass; `ruff check` clean on both changed files; `mypy monai/networks/nets/dints.py` clean. `black` was not available locally, so formatting is deferred to CI. ### Types of changes - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [x] New tests added to cover the changes. - [x] In-line docstrings updated. --------- Signed-off-by: Minsu Kim <minsu.kim08@gmail.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>
1 parent b7f23cc commit 4e89184

2 files changed

Lines changed: 62 additions & 3 deletions

File tree

‎monai/networks/nets/dints.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -522,7 +522,8 @@ class TopologyConstruction(nn.Module):
522522
The base class for `TopologyInstance` and `TopologySearch`.
523523
524524
Args:
525-
arch_code: `[arch_code_a, arch_code_c]`, numpy arrays. The architecture codes defining the model.
525+
arch_code: `[arch_code_a, arch_code_c]`, numpy arrays or torch tensors. The architecture codes defining
526+
the model.
526527
For example, for a ``num_depths=4, num_blocks=12`` search space:
527528
528529
- `arch_code_a` is a 12x10 (10 paths) binary matrix representing if a path is activated.
@@ -608,8 +609,8 @@ def __init__(
608609
arch_code_a = torch.ones((self.num_blocks, len(self.arch_code2out))).to(self.device)
609610
arch_code_c = torch.ones((self.num_blocks, len(self.arch_code2out), self.num_cell_ops)).to(self.device)
610611
else:
611-
arch_code_a = torch.from_numpy(arch_code[0]).to(self.device)
612-
arch_code_c = F.one_hot(torch.from_numpy(arch_code[1]).to(torch.int64), self.num_cell_ops).to(self.device)
612+
arch_code_a = torch.as_tensor(arch_code[0]).to(self.device)
613+
arch_code_c = F.one_hot(torch.as_tensor(arch_code[1]).to(torch.int64), self.num_cell_ops).to(self.device)
613614

614615
self.arch_code_a = arch_code_a
615616
self.arch_code_c = arch_code_c

‎tests/networks/nets/test_dints_network.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,64 @@ def test_dints_search(self, dints_grid_params, dints_params, input_shape, expect
153153
self.assertTrue(isinstance(net.weight_parameters(), list))
154154

155155

156+
class TestDintsArchCode(unittest.TestCase):
157+
"""arch_code entries loaded with `torch.load(..., weights_only=True)` are tensors, not numpy arrays."""
158+
159+
def setUp(self):
160+
"""Create a small CPU search space and numpy architecture codes shared by the tests.
161+
162+
Builds ``grid_params`` for a ``num_blocks=6, num_depths=3`` topology, a binary
163+
``arch_code_a`` path-activation matrix of ones, and a random integer ``arch_code_c``
164+
cell-operation matrix valid for the ``Cell`` operation set.
165+
"""
166+
self.grid_params = {
167+
"channel_mul": 0.2,
168+
"num_blocks": 6,
169+
"num_depths": 3,
170+
"device": "cpu",
171+
"use_downsample": False,
172+
"spatial_dims": 3,
173+
}
174+
_cell = Cell(1, 1, 0, spatial_dims=self.grid_params["spatial_dims"])
175+
num_paths = 3 * self.grid_params["num_depths"] - 2
176+
self.arch_code_a = np.ones((self.grid_params["num_blocks"], num_paths))
177+
self.arch_code_c = np.random.randint(len(_cell.OPS), size=(self.grid_params["num_blocks"], num_paths))
178+
179+
def test_tensor_arch_code_matches_numpy(self):
180+
"""Tensor arch codes yield the same topology as the equivalent numpy arch codes.
181+
182+
Constructs ``TopologyInstance`` from numpy and from tensor inputs and asserts that
183+
``arch_code_a``, ``arch_code_c``, and the instantiated cell tree are identical.
184+
"""
185+
grid_np = TopologyInstance(arch_code=[self.arch_code_a, self.arch_code_c], **self.grid_params)
186+
grid_pt = TopologyInstance(
187+
arch_code=[torch.as_tensor(self.arch_code_a), torch.as_tensor(self.arch_code_c)], **self.grid_params
188+
)
189+
torch.testing.assert_close(grid_pt.arch_code_a, grid_np.arch_code_a)
190+
torch.testing.assert_close(grid_pt.arch_code_c, grid_np.arch_code_c)
191+
self.assertEqual(set(grid_pt.cell_tree.keys()), set(grid_np.cell_tree.keys()))
192+
193+
def test_dints_forward_tensor_arch_code(self):
194+
"""DiNTS built from tensor arch codes runs a forward pass with the expected output shape.
195+
196+
Feeds a random ``(1, 1, 16, 16, 16)`` volume through the network and asserts the
197+
segmentation output shape is ``(1, 2, 16, 16, 16)``.
198+
"""
199+
grid = TopologyInstance(
200+
arch_code=[torch.as_tensor(self.arch_code_a), torch.as_tensor(self.arch_code_c)], **self.grid_params
201+
)
202+
net = DiNTS(
203+
dints_space=grid,
204+
in_channels=1,
205+
num_classes=2,
206+
spatial_dims=3,
207+
use_downsample=False,
208+
node_a=torch.ones((self.grid_params["num_blocks"] + 1, self.grid_params["num_depths"])),
209+
)
210+
result = net(torch.randn(1, 1, 16, 16, 16))
211+
self.assertEqual(result.shape, (1, 2, 16, 16, 16))
212+
213+
156214
class TestDintsTS(unittest.TestCase):
157215
@parameterized.expand(TEST_CASES_3D + TEST_CASES_2D)
158216
def test_script(self, dints_grid_params, dints_params, input_shape, _):

0 commit comments

Comments
 (0)