code: def test_sparse_retain():
      def check_sparse_retain(shape, density, index_type=np.int64):
          num_rows = shape[0]
          rsp, _ = rand_sparse_ndarray(
              shape=shape, stype="row_sparse", density=density
          )
          length = np.random.randint(1, num_rows + 1)
          idx = random_sample(list(range(0, num_rows)), length)
          idx.sort()
          dns = rsp.asnumpy()
          tensor_retained_expected = np.zeros(shape)
          for i in idx:
              tensor_retained_expected[i][:] = dns[i]
          indices = mx.nd.array(idx, dtype=index_type)
          rsp_retained = mx.nd.sparse.retain(rsp, indices=indices)
          assert same(tensor_retained_expected, rsp_retained.asnumpy())
  
          # check numeric gradient
          data = mx.symbol.Variable("data")
          idx = mx.symbol.Variable("indices")
          sym = mx.sym.sparse.retain(data=data, indices=idx)
          check_numeric_gradient(
              sym,
              [rsp, indices],
              grad_nodes=["data"],
              grad_stype_dict={"data": "row_sparse"},
          )
  
      shape = rand_shape_2d()
      shape_3d = rand_shape_3d()
      densities = [0.01, 0.5, 1.0]
      index_types = [np.float32, np.int32, np.int64]
      for density in densities:
          for itype in index_types:
              check_sparse_retain(shape, density, itype)
              check_sparse_retain(shape_3d, density, itype)
  
imports: from mxnet.test_utils import *
  from mxnet.base import MXNetError
  import pytest
  from common import assertRaises
  import random
  import warnings
label_desc: Use image node_id 22 for calling a global function with example usage: test_sparse_retain() without return types