Caffe2 - Python API
A deep learning, cross platform ML framework
rnn_cell_test_util.py
1 from __future__ import absolute_import
2 from __future__ import division
3 from __future__ import print_function
4 from __future__ import unicode_literals
5 
6 from caffe2.python import workspace, scope
7 from caffe2.python.model_helper import ModelHelper
8 
9 import numpy as np
10 
11 
12 def sigmoid(x):
13  return 1.0 / (1.0 + np.exp(-x))
14 
15 
16 def tanh(x):
17  return 2.0 * sigmoid(2.0 * x) - 1
18 
19 
20 def _prepare_rnn(
21  t, n, dim_in, create_rnn, outputs_with_grads,
22  forget_bias, memory_optim=False,
23  forward_only=False, drop_states=False, T=None,
24  two_d_initial_states=None, dim_out=None,
25  num_states=2,
26  **kwargs
27 ):
28  if dim_out is None:
29  dim_out = [dim_in]
30  print("Dims: ", t, n, dim_in, dim_out)
31 
32  model = ModelHelper(name='external')
33 
34  if two_d_initial_states is None:
35  two_d_initial_states = np.random.randint(2)
36 
37  def generate_input_state(n, d):
38  if two_d_initial_states:
39  return np.random.randn(n, d).astype(np.float32)
40  else:
41  return np.random.randn(1, n, d).astype(np.float32)
42 
43  states = []
44  for layer_id, d in enumerate(dim_out):
45  for i in range(num_states):
46  state_name = "state_{}/layer_{}".format(i, layer_id)
47  states.append(model.net.AddExternalInput(state_name))
48  workspace.FeedBlob(
49  states[-1], generate_input_state(n, d).astype(np.float32))
50 
51  # Due to convoluted RNN scoping logic we make sure that things
52  # work from a namescope
53  with scope.NameScope("test_name_scope"):
54  input_blob, seq_lengths = model.net.AddScopedExternalInputs(
55  'input_blob', 'seq_lengths')
56 
57  outputs = create_rnn(
58  model, input_blob, seq_lengths, states,
59  dim_in=dim_in, dim_out=dim_out, scope="external/recurrent",
60  outputs_with_grads=outputs_with_grads,
61  memory_optimization=memory_optim,
62  forget_bias=forget_bias,
63  forward_only=forward_only,
64  drop_states=drop_states,
65  static_rnn_unroll_size=T,
66  **kwargs
67  )
68 
69  workspace.RunNetOnce(model.param_init_net)
70 
71  workspace.FeedBlob(
72  seq_lengths,
73  np.random.randint(1, t + 1, size=(n,)).astype(np.int32)
74  )
75  return outputs, model.net, states + [input_blob]