Skip to content

Commit

Permalink
Add detach to the tensors in handlers (#2100)
Browse files Browse the repository at this point in the history
* [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]>
  • Loading branch information
Nic-Ma and wyli committed Apr 27, 2021
1 parent 9e1a7d4 commit feb3a33
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 2 deletions.
2 changes: 2 additions & 0 deletions monai/handlers/classification_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ def __call__(self, engine: Engine) -> None:
self._filenames.extend(filenames)
outputs = self.output_transform(engine.state.output)
if outputs is not None:
if isinstance(outputs, torch.Tensor):
outputs = outputs.detach()
self._outputs.append(outputs)

def _finalize(self, engine: Engine) -> None:
Expand Down
4 changes: 4 additions & 0 deletions monai/handlers/iteration_metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ def update(self, output: Sequence[torch.Tensor]) -> None:
y_pred, y = output

def _compute(y_pred, y):
if isinstance(y_pred, torch.Tensor):
y_pred = y_pred.detach()
if isinstance(y, torch.Tensor):
y = y.detach()
score = self.metric_fn(y_pred, y)
return score[0] if isinstance(score, (tuple, list)) else score

Expand Down
5 changes: 4 additions & 1 deletion monai/handlers/transform_inverter.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,11 @@ def __call__(self, engine: Engine) -> None:
align_corners=None,
)

output = engine.state.output[output_key]
if isinstance(output, torch.Tensor):
output = output.detach()
segs_dict = {
batch_key: engine.state.output[output_key],
batch_key: output,
transform_key: transform_info,
}
meta_dict_key = f"{batch_key}_{self.meta_key_postfix}"
Expand Down
2 changes: 1 addition & 1 deletion tests/test_lmdbdataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def setUp(self):
def tearDown(self):
shutil.rmtree(self.tempdir)

@DistCall(nnodes=1, nproc_per_node=2)
@DistCall(nnodes=1, nproc_per_node=1)
def test_mp_cache(self):
items = [[list(range(i))] for i in range(5)]

Expand Down

0 comments on commit feb3a33

Please sign in to comment.