code: def test_dropout_forward_backward(p, seed, ctx, func_name):
      from nbla_test_utils import cap_ignore_region
  
      # Note: each backward execution requires a forward execution in NNabla.
  
      with nn.context_scope(ctx):
          # Create inputs
          rng = np.random.RandomState(seed)
          inputs = [
              cap_ignore_region(
                  rng.randn(2, 3, 4).astype(np.float32) * 2,
                  (-1e-3, 1e-3),
              )
          ]  # Ensure there is no zero.
          x = nn.Variable(inputs[0].shape, need_grad=True)
          x.d = inputs[0]
          init_dx = rng.randn(*x.shape).astype(x.data.dtype)
          init_dy = rng.randn(*x.shape).astype(x.data.dtype)
  
          # Construct graph
          y = F.dropout(x, p)
  
          # Reference parameter
          scale = 1.0 / (1.0 - p)
  
          # Test forward
          y.forward(clear_buffer=True)
          mask = y.d != 0
          ref_y = x.d * mask * scale
          assert_allclose(y.d, ref_y)
          assert y.parent.name == func_name
  
          # Test backward
          x.g[...] = init_dx
          y.backward(init_dy, clear_buffer=True)
          ref_dx = init_dy * mask * scale
          assert_allclose(x.g, init_dx + ref_dx)
  
          # Test accumulation
          y.forward(clear_no_need_grad=True)
          mask = y.d != 0
          x.g[...] = 1
          y.g = init_dy
          y.parent.backward([x], [y], [False])
          ref_dx = init_dy * mask * scale
          assert_allclose(x.g, ref_dx)
  
          # Test accum=False with NaN gradient
          y.forward(clear_no_need_grad=True)
          x.g = np.float32("nan")
          y.parent.backward([x], [y], [False])
          assert not np.any(np.isnan(x.g))
  
          # Test need_grad
          y.forward(clear_no_need_grad=True)
          x.g[...] = 0
          x.need_grad = False
          y.backward(init_dy)
          assert np.all(x.g == 0)
  
file_path: nnabla/python/test/function/test_dropout.py
imports: from six.moves import range
  import pytest
  import numpy
  import nnabla
  import nnabla.functions
  from nbla_test_utils import list_context
  from nnabla.testing import assert_allclose
label_desc: Use image node_id 2 for calling a global function with example usage: test_dropout_forward_backward(p, seed, ctx, func_name) without return types