Skip to content

Commit feb3a33

Browse files
Nic-Mawyli
andauthored
Add detach to the tensors in handlers (#2100)
* [DLMED] add detach for Tensor Signed-off-by: Nic Ma <[email protected]> * fixes test Signed-off-by: Wenqi Li <[email protected]> Co-authored-by: Wenqi Li <[email protected]>
1 parent 9e1a7d4 commit feb3a33

File tree

4 files changed

+11
-2
lines changed

4 files changed

+11
-2
lines changed

monai/handlers/classification_saver.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ def __call__(self, engine: Engine) -> None:
104104
self._filenames.extend(filenames)
105105
outputs = self.output_transform(engine.state.output)
106106
if outputs is not None:
107+
if isinstance(outputs, torch.Tensor):
108+
outputs = outputs.detach()
107109
self._outputs.append(outputs)
108110

109111
def _finalize(self, engine: Engine) -> None:

monai/handlers/iteration_metric.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,10 @@ def update(self, output: Sequence[torch.Tensor]) -> None:
7777
y_pred, y = output
7878

7979
def _compute(y_pred, y):
80+
if isinstance(y_pred, torch.Tensor):
81+
y_pred = y_pred.detach()
82+
if isinstance(y, torch.Tensor):
83+
y = y.detach()
8084
score = self.metric_fn(y_pred, y)
8185
return score[0] if isinstance(score, (tuple, list)) else score
8286

monai/handlers/transform_inverter.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,8 +130,11 @@ def __call__(self, engine: Engine) -> None:
130130
align_corners=None,
131131
)
132132

133+
output = engine.state.output[output_key]
134+
if isinstance(output, torch.Tensor):
135+
output = output.detach()
133136
segs_dict = {
134-
batch_key: engine.state.output[output_key],
137+
batch_key: output,
135138
transform_key: transform_info,
136139
}
137140
meta_dict_key = f"{batch_key}_{self.meta_key_postfix}"

tests/test_lmdbdataset.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ def setUp(self):
187187
def tearDown(self):
188188
shutil.rmtree(self.tempdir)
189189

190-
@DistCall(nnodes=1, nproc_per_node=2)
190+
@DistCall(nnodes=1, nproc_per_node=1)
191191
def test_mp_cache(self):
192192
items = [[list(range(i))] for i in range(5)]
193193

0 commit comments

Comments
 (0)