fix view call on discontiguous tensor in to_sparse_backward (#31223)

Summary:
Fixes https://github.com/pytorch/pytorch/issues/30820
Pull Request resolved: https://github.com/pytorch/pytorch/pull/31223

Differential Revision: D19044172

Pulled By: ngimel

fbshipit-source-id: ac9fa71197d4f6c5b90a26e8d23360250745a2e2
diff --git a/aten/src/ATen/native/sparse/cuda/SparseCUDATensor.cpp b/aten/src/ATen/native/sparse/cuda/SparseCUDATensor.cpp
index 4ed50a2..6328d7d 100644
--- a/aten/src/ATen/native/sparse/cuda/SparseCUDATensor.cpp
+++ b/aten/src/ATen/native/sparse/cuda/SparseCUDATensor.cpp
@@ -46,7 +46,11 @@
     view_size[d + 1] = mask.size(mask.sparse_dim() + d);
   }
 
-  Tensor t_view = t.view(view_size);
+  Tensor t_view;
+  if (t.is_contiguous())
+      t_view = t.view(view_size);
+  else
+      t_view = t.contiguous().view(view_size);
   // TODO: Re-audit this; it used to be an indexSelect directly into r_values
   at::index_select_out(r_values, t_view, 0, indices);
 
diff --git a/test/common_methods_invocations.py b/test/common_methods_invocations.py
index 2164a1c..57f22fd 100644
--- a/test/common_methods_invocations.py
+++ b/test/common_methods_invocations.py
@@ -892,9 +892,7 @@
         ('__getitem__', torch.randn(S, S, S), (dont_convert([[0, 3], Ellipsis]),), 'adv_index_sub_3'),
         ('__getitem__', torch.randn(S, S, S), (dont_convert([[0, 2, 3], [1, 3, 3],
                                                              torch.LongTensor([0, 0, 2])]),), 'adv_index_var'),
-        # I'm not too sure why this one is failing on CUDA.
-        # More discussion at https://github.com/pytorch/pytorch/issues/30820
-        ('to_sparse', (S, S), (), '', (), (), [expectedFailureCUDA], lambda x: x.to_dense()),
+        ('to_sparse', (S, S), (), '', (), (), [], lambda x: x.to_dense()),
     ]
 
 def create_input(call_args, requires_grad=True, non_contiguous=False, call_kwargs=None, device=None):