Repository: Project-MONAI/MONAI

Issue:
unsupported operation: more than one element of the written-to tensor refers to a single memory location
**Describe the bug**
running the docker image on Mac OS raises an error:
```
Traceback (most recent call last):
  File "/opt/monai/tests/test_png_rw.py", line 78, in test_write_output_shape
    write_png(img, image_name, (4, 4), scale=255)
  File "/opt/monai/monai/data/png_writer.py", line 61, in write_png
    data = xform(data)
  File "/opt/monai/monai/transforms/spatial/array.py", line 332, in __call__
    input=torch.as_tensor(img[None], dtype=torch.float),
RuntimeError: unsupported operation: more than one element of the written-to tensor refers to a single memory location
```
related to https://github.com/pytorch/pytorch/issues/33812

**To Reproduce**
Steps to reproduce the behavior:
1. `docker run --rm -ti --ipc=host projectmonai/monai:0.2.0`
2. `python -m tests.test_png_rw`

**Expected behavior**
no RuntimeError

**Environment (please complete the following information):**
 - OS mac OS 10.15.5
 - Python version 3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 19:07:31)  [GCC 7.3.0]
 - MONAI version [e.g. git commit hash]
 - CUDA/cuDNN version 0.2.0
 - GPU models and configuration N/A

unsupported operation: more than one element of the written-to tensor refers to a single memory location
**Describe the bug**
running the docker image on Mac OS raises an error:
```
Traceback (most recent call last):
  File "/opt/monai/tests/test_png_rw.py", line 78, in test_write_output_shape
    write_png(img, image_name, (4, 4), scale=255)
  File "/opt/monai/monai/data/png_writer.py", line 61, in write_png
    data = xform(data)
  File "/opt/monai/monai/transforms/spatial/array.py", line 332, in __call__
    input=torch.as_tensor(img[None], dtype=torch.float),
RuntimeError: unsupported operation: more than one element of the written-to tensor refers to a single memory location
```
related to https://github.com/pytorch/pytorch/issues/33812

**To Reproduce**
Steps to reproduce the behavior:
1. `docker run --rm -ti --ipc=host projectmonai/monai:0.2.0`
2. `python -m tests.test_png_rw`

**Expected behavior**
no RuntimeError

**Environment (please complete the following information):**
 - OS mac OS 10.15.5
 - Python version 3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 19:07:31)  [GCC 7.3.0]
 - MONAI version [e.g. git commit hash]
 - CUDA/cuDNN version 0.2.0
 - GPU models and configuration N/A



Discussion:

Resolving patch:
diff --git a/monai/data/nifti_writer.py b/monai/data/nifti_writer.py
--- a/monai/data/nifti_writer.py
+++ b/monai/data/nifti_writer.py
@@ -124,7 +124,7 @@ def write_nifti(
         data_ = data.reshape(list(spatial_shape) + [-1])
         data_ = np.moveaxis(data_, -1, 0)  # channel first for pytorch
         data_ = affine_xform(
-            torch.from_numpy((data_.astype(np.float64))[None]),
+            torch.from_numpy(data_.astype(np.float64)).unsqueeze(0),
             torch.from_numpy(transform.astype(np.float64)),
             spatial_size=output_spatial_shape[:3],
         )
diff --git a/monai/transforms/spatial/array.py b/monai/transforms/spatial/array.py
--- a/monai/transforms/spatial/array.py
+++ b/monai/transforms/spatial/array.py
@@ -163,7 +163,7 @@ def __call__(
             reverse_indexing=True,
         )
         output_data = affine_xform(
-            torch.from_numpy((data_array.astype(np.float64))[None]),  # AffineTransform requires a batch dim
+            torch.from_numpy((data_array.astype(np.float64))).unsqueeze(0),  # AffineTransform requires a batch dim
             torch.from_numpy(transform_.astype(np.float64)),
             spatial_size=output_shape,
         )
@@ -329,7 +329,7 @@ def __call__(
             )
         spatial_size = fall_back_tuple(self.spatial_size, img.shape[1:])
         resized = _torch_interp(
-            input=torch.as_tensor(img[None], dtype=torch.float),
+            input=torch.as_tensor(img, dtype=torch.float).unsqueeze(0),
             size=spatial_size,
             mode=self.mode.value if mode is None else InterpolateMode(mode).value,
             align_corners=self.align_corners if align_corners is None else align_corners,
@@ -419,7 +419,7 @@ def __call__(
             reverse_indexing=True,
         )
         output = xform(
-            torch.from_numpy(img.astype(np.float64)[None]),
+            torch.from_numpy(img.astype(np.float64)).unsqueeze(0),
             torch.from_numpy(transform.astype(np.float64)),
             spatial_size=output_shape,
         )
@@ -476,7 +476,7 @@ def __call__(  # type: ignore # see issue #495
         """
         self.zoom = ensure_tuple_rep(self.zoom, img.ndim - 1)  # match the spatial image dim
         zoomed = _torch_interp(
-            input=torch.as_tensor(img[None], dtype=torch.float),
+            input=torch.as_tensor(img, dtype=torch.float).unsqueeze(0),
             scale_factor=list(self.zoom),
             mode=self.mode.value if mode is None else InterpolateMode(mode).value,
             align_corners=self.align_corners if align_corners is None else align_corners,
@@ -1003,8 +1003,8 @@ def __call__(
         grid = grid[index_ordering]
         grid = grid.permute(list(range(grid.ndim))[1:] + [0])
         out = torch.nn.functional.grid_sample(
-            img[None].float(),
-            grid[None].float(),
+            img.unsqueeze(0).float(),
+            grid.unsqueeze(0).float(),
             mode=self.mode.value if mode is None else GridSampleMode(mode).value,
             padding_mode=self.padding_mode.value if padding_mode is None else GridSamplePadMode(padding_mode).value,
             align_corners=True,
@@ -1298,7 +1298,7 @@ def __call__(
             grid = self.deform_grid(spatial_size=sp_size)
             grid = self.rand_affine_grid(grid=grid)
             grid = _torch_interp(
-                input=grid[None],
+                input=grid.unsqueeze(0),
                 scale_factor=list(self.deform_grid.spacing),
                 mode=InterpolateMode.BICUBIC.value,
                 align_corners=False,
@@ -1409,7 +1409,7 @@ def __call__(
             assert self.rand_offset is not None
             grid = torch.as_tensor(np.ascontiguousarray(grid), device=self.device)
             gaussian = GaussianFilter(3, self.sigma, 3.0).to(device=self.device)
-            offset = torch.as_tensor(self.rand_offset[None], device=self.device)
+            offset = torch.as_tensor(self.rand_offset, device=self.device).unsqueeze(0)
             grid[:3] += gaussian(offset)[0] * self.magnitude
             grid = self.rand_affine_grid(grid=grid)
         return self.resampler(img, grid, mode=mode or self.mode, padding_mode=padding_mode or self.padding_mode)
diff --git a/monai/transforms/spatial/dictionary.py b/monai/transforms/spatial/dictionary.py
--- a/monai/transforms/spatial/dictionary.py
+++ b/monai/transforms/spatial/dictionary.py
@@ -463,7 +463,7 @@ def __call__(self, data):
             grid = self.rand_2d_elastic.deform_grid(spatial_size=sp_size)
             grid = self.rand_2d_elastic.rand_affine_grid(grid=grid)
             grid = _torch_interp(
-                input=grid[None],
+                input=grid.unsqueeze(0),
                 scale_factor=list(self.rand_2d_elastic.deform_grid.spacing),
                 mode=InterpolateMode.BICUBIC.value,
                 align_corners=False,
@@ -563,7 +563,7 @@ def __call__(self, data):
             device = self.rand_3d_elastic.device
             grid = torch.tensor(grid).to(device)
             gaussian = GaussianFilter(spatial_dims=3, sigma=self.rand_3d_elastic.sigma, truncated=3.0).to(device)
-            offset = torch.tensor(self.rand_3d_elastic.rand_offset[None], device=device)
+            offset = torch.tensor(self.rand_3d_elastic.rand_offset, device=device).unsqueeze(0)
             grid[:3] += gaussian(offset)[0] * self.rand_3d_elastic.magnitude
             grid = self.rand_3d_elastic.rand_affine_grid(grid=grid)
 


Test patch: