You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@singa.apache.org by GitBox <gi...@apache.org> on 2020/04/07 17:31:21 UTC

[GitHub] [singa] dcslin opened a new pull request #662: [wip] cudnn Rnn

dcslin opened a new pull request #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662
 
 
   

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin commented on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610841188
 
 
   > I think they are there for future extension.
   
   ok thanks.
   
   Currently, fixing something related to cuda `column major order`, input are stored in `{seq length, batch size, feature dim}` manner. And `batch size` might vary.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin commented on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-611514881
 
 
   It is basically follow autograd LSTM structure, with additional arguments added. 
   And the data input and output are following previous convention, which is also the cudnn convention. Input are in a array of {batch size, feature dim} with length - seq length/time steps.
   I have not edit autograd.py before, kindly advise anything wrong. Thanks
   

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407010102
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
+    def __init__(self, handle):
+        super(_RNN_cudnn, self).__init__()
+        self.handle = handle
 
-            self.W = Tensor(shape=(self.rnn_handle.weights_size,),
-                            requires_grad=True,
-                            stores_grad=True)
-            self.W.gaussian(0.0, 1.0)
+    def forward(self, x, W):
+        y = singa.GpuRNNForwardTraining(x, W, self.handle)
+        if training:
+            self.inputs = (x, W, y)
+        return y
 
-            cpp_y = singa.GpuRNNForwardTraining(cpp_x, self.W.data,
-                                                self.rnn_handle)
-            y = self.cpp_vec_tensor_to_py_tensor(cpp_y)
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
 
-            if training:
-                self.buffer = {"cpp_y": cpp_y, "cpp_x": cpp_x}
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
 
-            return y
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
+class RNN_cudnn(Layer):
+    def __init__(self, input_size, hidden_size, rnn_mode=2):
+        """
+            Args:
+                input_size: input feature dim
+                hidden_size: hidden feature dim
+                rnn_mode: could be 0 - RNN RELU, 1 - RNN TANH, 2 - LSTM, 3 - GRU
 
 Review comment:
   use string, 'relu', 'tanh', gru'.
   does it support vanilla rnn with 'tanh' ?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
nudles commented on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-611295276
 
 
   we can just follow cudnn format and update autograd lstm.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r406223532
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,95 +3239,176 @@ def __init__(
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.nonlinearity = nonlinearity
-
-        Wx_shape = (input_size, hidden_size)
-        self.Wx = []
-        for i in range(4):
-            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wx.append(w)
-
-        Wh_shape = (hidden_size, hidden_size)
-        self.Wh = []
-        for i in range(4):
-            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wh.append(w)
-
-        Bx_shape = (hidden_size,)
-        self.Bx = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bx.append(b)
-
-        self.Bh = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bh.append(b)
-
-        self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        self.backend = backend
+        if backend == "singa":
+            self.nonlinearity = nonlinearity
+
+            Wx_shape = (input_size, hidden_size)
+            self.Wx = []
+            for i in range(4):
+                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wx.append(w)
+
+            Wh_shape = (hidden_size, hidden_size)
+            self.Wh = []
+            for i in range(4):
+                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wh.append(w)
+
+            Bx_shape = (hidden_size,)
+            self.Bx = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bx.append(b)
+
+            self.Bh = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bh.append(b)
+
+            self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        elif backend == "cudnn":
+            if not singa.USE_CUDA:
+                raise Exception("Could not use cudnn without cuda compiled.\n")
+            if not inputs:
+                raise Exception("Input is required for init cudnn LSTM.\n")
 
 Review comment:
   do you  need the inputs data or just input shape?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   done:
   - [ ] understand cudnn workflow
   - [ ] vanilla rnn cudnn 
   - [ ] operation c++ api
   todo:
   - [ ] add lstm
   - [ ] read `autograd.py` rnn and make compatible

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-611294054
 
 
   Hi @nudles , I am confused by quite a few things here and there. Primarily is the input layout. May I have your comment on the input layout please?
   Does autograd.py RNN expect input layout to be `list(Tensor, ...)`, where `len(list) == seq length/time steps`, and for each tensor, tensor shape is `batch size, input dim`?
   Does the user expect input layout to be `Tensor(shape{batchsize, timesteps, input dims})`?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   todo:
   - [x] understand cudnn workflow
   - [x] vanilla rnn cudnn 
   - [x] operation c++ api
   - [x] add lstm
   - [ ] read `autograd.py` rnn and make compatible
   - [ ] clean code, argument check

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407138223
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3330,6 +3330,94 @@ def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
         return hout, cout
 
 
+class _RNN(Operation):
+    """ RNN operation with c++ backend
+    """
+    def __init__(self, handle):
+        assert singa.USE_CUDA is True, "Not able to run without CUDA"
+        super(_RNN, self).__init__()
+        self.handle = handle
+
+    def forward(self, x, W):
+        # TODO: CPU forward
+
+        # GPU forward
+        if training:
+            y = singa.GpuRNNForwardTraining(x, W, self.handle)
+            self.inputs = (x, W, y)
+        else:
+            y = singa.GpuRNNForwardInference(x, W, self.handle)
+
+        return y
+
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
+
+        # TODO: CPU backward
+
+        # GPU backward
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
+
+class RNN_direct(Layer):
 
 Review comment:
   let's unify all the rnn implementation in this way
   
   ```python
   def RNN(hidden_size, num_layers=1, dropout=0.0, direction='one', return_seq=False, return_state=False, alg='lstm', backend='cudnn') :
      if backend == 'cudnn':
         reutrn CudnnRNN(hidden_size, num_layers, dropout, direction, mode)
      if backend == 'native':
        if mode == 'lstm':
         return LSTM()
        elif mode == 'vanilla':
          return VanillaRNN()
        ....
   ```
   
   All rnn classes inherit 
   ```python
   class RNNBase(Layer):
      def __init__(self, hidden_size, num_layers=1, dropout=0.0, direction='one', return_seq=False, return_state=False, alg='lstm')
   ```

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] lgtm-com[bot] commented on issue #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
lgtm-com[bot] commented on issue #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#issuecomment-612384759
 
 
   This pull request **introduces 1 alert** when merging 39d4f251f81c91a81119254261262e431b6cfdc3 into f3f6fe0f6f02d496c30d827d56f723f63c7d3c73 - [view on LGTM.com](https://lgtm.com/projects/g/apache/singa/rev/pr-0d143308f56d20b5736701f0acce3ad4b5900a29)
   
   **new alerts:**
   
   * 1 for Missing call to \_\_init\_\_ during object initialization

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   todo:
   - [ ] add lstm
   - [ ] read `autograd.py` rnn and make compatible

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r406236545
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,95 +3239,176 @@ def __init__(
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.nonlinearity = nonlinearity
-
-        Wx_shape = (input_size, hidden_size)
-        self.Wx = []
-        for i in range(4):
-            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wx.append(w)
-
-        Wh_shape = (hidden_size, hidden_size)
-        self.Wh = []
-        for i in range(4):
-            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wh.append(w)
-
-        Bx_shape = (hidden_size,)
-        self.Bx = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bx.append(b)
-
-        self.Bh = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bh.append(b)
-
-        self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        self.backend = backend
+        if backend == "singa":
+            self.nonlinearity = nonlinearity
+
+            Wx_shape = (input_size, hidden_size)
+            self.Wx = []
+            for i in range(4):
+                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wx.append(w)
+
+            Wh_shape = (hidden_size, hidden_size)
+            self.Wh = []
+            for i in range(4):
+                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wh.append(w)
+
+            Bx_shape = (hidden_size,)
+            self.Bx = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bx.append(b)
+
+            self.Bh = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bh.append(b)
+
+            self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        elif backend == "cudnn":
+            if not singa.USE_CUDA:
+                raise Exception("Could not use cudnn without cuda compiled.\n")
+            if not inputs:
+                raise Exception("Input is required for init cudnn LSTM.\n")
+
+            CUDNN_LSTM_MODE = 2
+
+            cinputs = singa.VecTensor()
+            [cinputs.append(i.data) for i in inputs]
+            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
+                                                   hidden_size, CUDNN_LSTM_MODE)
+        else:
+            raise Exception("Unsupported backend %s.\n" % backend)
+
+    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
+        py_tensors = list()
+        for cTensor in cpp_vec_tensor:
+            new_t = tensor.Tensor()
+            new_t.data = cTensor
+            new_t.shape = tuple(new_t.data.shape())
+            new_t.device = new_t.data.device()
+            new_t.dtype = new_t.data.data_type()
+            py_tensors.append(new_t)
+        return py_tensors
 
     def __call__(self, xs, h0_c0):
-        # xs: a tuple or list of input tensors
-        # h0_c0: a tuple of (h0, c0)
-        h0, c0 = h0_c0
-        if not isinstance(xs, list):
-            xs = list(xs)
-        inputs = xs + list((h0, c0))
-        self.device_check(*inputs)
-        # self.device_check(inputs[0], *self.params)
-        self.device_check(inputs[0], *(self.Wx + self.Wh + self.Bx + self.Bh))
-        batchsize = xs[0].shape[0]
-        out = []
-        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
-                                 self.Bh)
-        out.append(h)
-        for x in xs[1:]:
-            assert x.shape[0] == batchsize
-            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
+        if self.backend == "singa":
 
 Review comment:
   I think it's better to separate the existing LSTM with the cudnn RNN. It may get you confused.
   For the cudnnRNN Layer, it has a type, {vanilla, lstm, gru} to configure.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] lgtm-com[bot] commented on issue #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
lgtm-com[bot] commented on issue #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#issuecomment-612340760
 
 
   This pull request **introduces 1 alert** when merging df012c243ec205e279b357160f5bb0dbbe33bac5 into f3f6fe0f6f02d496c30d827d56f723f63c7d3c73 - [view on LGTM.com](https://lgtm.com/projects/g/apache/singa/rev/pr-0ce901af460d74069b03299ecb85dc5dcd79d69a)
   
   **new alerts:**
   
   * 1 for Missing call to \_\_init\_\_ during object initialization

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407009823
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
+    def __init__(self, handle):
+        super(_RNN_cudnn, self).__init__()
 
 Review comment:
   assert cuda is available.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407009802
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
 
 Review comment:
   rename to _RNN?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407067199
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3330,6 +3330,94 @@ def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
         return hout, cout
 
 
+class _RNN(Operation):
+    """ RNN operation with c++ backend
+    """
+    def __init__(self, handle):
+        assert singa.USE_CUDA is True, "Not able to run without CUDA"
+        super(_RNN, self).__init__()
+        self.handle = handle
+
+    def forward(self, x, W):
+        # TODO: CPU forward
+
+        # GPU forward
+        if training:
+            y = singa.GpuRNNForwardTraining(x, W, self.handle)
+            self.inputs = (x, W, y)
+        else:
+            y = singa.GpuRNNForwardInference(x, W, self.handle)
+
+        return y
+
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
+
+        # TODO: CPU backward
+
+        # GPU backward
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
+
+class RNN_direct(Layer):
+    """ `RNN_direct` class implements with c++ backend and run the operation
+          directly on cuDNN
+
+        While `RNN` class implements with high level singa API
+    """
+    def __init__(self, input_size, hidden_size, rnn_mode="lstm"):
+        """
+            Args:
+                input_size: input feature dim
+                hidden_size: hidden feature dim
+                rnn_mode: accepted value: "vanilla", "tanh", "relu",  "lstm", "gru"
+        """
+        assert singa.USE_CUDA is True, "Not able to run without CUDA"
+
+        self.rnn_mode = rnn_mode
+        self.input_size = input_size
+        self.hidden_size = hidden_size
+
+        # TODO: CPU parameter
+
+        # GPU parameter
+        # cudnn_rnn_mode: 0 - RNN RELU, 1 - RNN TANH, 2 - LSTM, 3 - GRU
+        if self.rnn_mode == "lstm":
+            self.cudnn_rnn_mode = 2
+        elif self.rnn_mode == "vanilla" or self.rnn_mode == "tanh":
+            self.cudnn_rnn_mode = 1
+        elif self.rnn_mode == "relu":
+            self.cudnn_rnn_mode = 0
+        elif self.rnn_mode == "gru":
+            self.cudnn_rnn_mode = 3
+
+    def __call__(self, x):
+        if not hasattr(self, "handle"):
+            cpp_x = singa.VecTensor()
+            [cpp_x.append(i.data) for i in x]
+
+            # TODO: CPU handle
+
+            # GPU handle
+            self.handle = singa.CudnnRNNHandle(cpp_x, self.input_size, self.hidden_size, self.cudnn_rnn_mode)
 
 Review comment:
   can infer the input_size from x?
   then there is not need to require input_size in the constructor.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   done:
   - [x] understand cudnn workflow
   - [ ] vanilla rnn cudnn 
   - [ ] operation c++ api
   todo:
   - [ ] add lstm
   - [ ] read `autograd.py` rnn and make compatible

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   todo:
   - [x] understand cudnn workflow
   - [x] vanilla rnn cudnn 
   - [x] operation c++ api
   - [ ] add lstm
   - [ ] read `autograd.py` rnn and make compatible

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
dcslin commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407015961
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
+    def __init__(self, handle):
+        super(_RNN_cudnn, self).__init__()
+        self.handle = handle
 
-            self.W = Tensor(shape=(self.rnn_handle.weights_size,),
-                            requires_grad=True,
-                            stores_grad=True)
-            self.W.gaussian(0.0, 1.0)
+    def forward(self, x, W):
+        y = singa.GpuRNNForwardTraining(x, W, self.handle)
 
 Review comment:
   this is resolved

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   todo:
   - [x] understand cudnn workflow
   - [x] vanilla rnn cudnn 
   - [x] operation c++ api
   - [x] add lstm
   - [x] read `autograd.py` rnn and make compatible
     It seems that these parameters are not in used in autograd:
   ```python
           num_layers=1,
           bias=True,
           batch_first=False,
           dropout=0,
           bidirectional=False,
   ```
   - [x] clean code, argument check

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
dcslin commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407015973
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
 
 Review comment:
   this is resolved

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407064103
 
 

 ##########
 File path: src/api/model_operation.i
 ##########
 @@ -188,6 +189,50 @@ Tensor GpuPoolingForward(const CudnnPoolingHandle &cph, const Tensor &x);
 
 Tensor GpuPoolingBackward(const CudnnPoolingHandle &cph, const Tensor &dy, const Tensor& x, const Tensor& y);
 
+
+class CudnnRNNHandle {
+ public:
+   CudnnRNNHandle(const std::vector<Tensor> &x,
+       const int feature_size,
+       const int hidden_size,
+       const int mode = 0,
+       const int num_layers = 1,
+       const int  bias = 1,
+       const float dropout = 0.0f,
+       const int bidirectional = 0);
 
 Review comment:
   num_layers, dropout and bidirectional can be exposed to python?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407071481
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3330,6 +3330,94 @@ def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
         return hout, cout
 
 
+class _RNN(Operation):
+    """ RNN operation with c++ backend
+    """
+    def __init__(self, handle):
+        assert singa.USE_CUDA is True, "Not able to run without CUDA"
+        super(_RNN, self).__init__()
+        self.handle = handle
+
+    def forward(self, x, W):
+        # TODO: CPU forward
+
+        # GPU forward
+        if training:
+            y = singa.GpuRNNForwardTraining(x, W, self.handle)
+            self.inputs = (x, W, y)
+        else:
+            y = singa.GpuRNNForwardInference(x, W, self.handle)
+
+        return y
+
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
+
+        # TODO: CPU backward
+
+        # GPU backward
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
+
+class RNN_direct(Layer):
+    """ `RNN_direct` class implements with c++ backend and run the operation
+          directly on cuDNN
+
+        While `RNN` class implements with high level singa API
+    """
+    def __init__(self, input_size, hidden_size, rnn_mode="lstm"):
+        """
+            Args:
+                input_size: input feature dim
+                hidden_size: hidden feature dim
+                rnn_mode: accepted value: "vanilla", "tanh", "relu",  "lstm", "gru"
+        """
+        assert singa.USE_CUDA is True, "Not able to run without CUDA"
+
+        self.rnn_mode = rnn_mode
+        self.input_size = input_size
+        self.hidden_size = hidden_size
+
+        # TODO: CPU parameter
+
+        # GPU parameter
+        # cudnn_rnn_mode: 0 - RNN RELU, 1 - RNN TANH, 2 - LSTM, 3 - GRU
+        if self.rnn_mode == "lstm":
+            self.cudnn_rnn_mode = 2
+        elif self.rnn_mode == "vanilla" or self.rnn_mode == "tanh":
+            self.cudnn_rnn_mode = 1
+        elif self.rnn_mode == "relu":
+            self.cudnn_rnn_mode = 0
+        elif self.rnn_mode == "gru":
+            self.cudnn_rnn_mode = 3
+
+    def __call__(self, x):
+        if not hasattr(self, "handle"):
+            cpp_x = singa.VecTensor()
+            [cpp_x.append(i.data) for i in x]
+
+            # TODO: CPU handle
+
+            # GPU handle
+            self.handle = singa.CudnnRNNHandle(cpp_x, self.input_size, self.hidden_size, self.cudnn_rnn_mode)
+
+            self.W = Tensor(shape=(self.handle.weights_size,),
 
 Review comment:
   if the layer parameters are set outside (e.g., after loading the checkpoint file) via set_params, there is no need to randomly initialize W.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   todo:
   - [x] understand cudnn workflow
   - [x] vanilla rnn cudnn 
   - [x] operation c++ api
   - [x] add lstm
   - [ ] read `autograd.py` rnn and make compatible
     It seems that these parameters are not in used in autograd:
   ```python
           num_layers=1,
           bias=True,
           batch_first=False,
           dropout=0,
           bidirectional=False,
   ```
   - [ ] clean code, argument check

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
dcslin commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407015879
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
+    def __init__(self, handle):
+        super(_RNN_cudnn, self).__init__()
+        self.handle = handle
 
-            self.W = Tensor(shape=(self.rnn_handle.weights_size,),
-                            requires_grad=True,
-                            stores_grad=True)
-            self.W.gaussian(0.0, 1.0)
+    def forward(self, x, W):
+        y = singa.GpuRNNForwardTraining(x, W, self.handle)
+        if training:
+            self.inputs = (x, W, y)
+        return y
 
-            cpp_y = singa.GpuRNNForwardTraining(cpp_x, self.W.data,
-                                                self.rnn_handle)
-            y = self.cpp_vec_tensor_to_py_tensor(cpp_y)
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
 
-            if training:
-                self.buffer = {"cpp_y": cpp_y, "cpp_x": cpp_x}
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
 
-            return y
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
+class RNN_cudnn(Layer):
+    def __init__(self, input_size, hidden_size, rnn_mode=2):
+        """
+            Args:
+                input_size: input feature dim
+                hidden_size: hidden feature dim
+                rnn_mode: could be 0 - RNN RELU, 1 - RNN TANH, 2 - LSTM, 3 - GRU
+        """
+        if not singa.USE_CUDA:
+            raise Exception("Could not use cudnn without cuda compiled.\n")
 
-    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
-        if self.backend == "singa":
-            y1 = matmul(x, Wx[0])
-            y1 = add_bias(y1, Bx[0], axis=0)
-            y2 = matmul(h, Wh[0])
-            y2 = add_bias(y2, Bh[0], axis=0)
-            i = add(y1, y2)
-            i = sigmoid(i)
-
-            y1 = matmul(x, Wx[1])
-            y1 = add_bias(y1, Bx[1], axis=0)
-            y2 = matmul(h, Wh[1])
-            y2 = add_bias(y2, Bh[1], axis=0)
-            f = add(y1, y2)
-            f = sigmoid(f)
-
-            y1 = matmul(x, Wx[2])
-            y1 = add_bias(y1, Bx[2], axis=0)
-            y2 = matmul(h, Wh[2])
-            y2 = add_bias(y2, Bh[2], axis=0)
-            o = add(y1, y2)
-            o = sigmoid(o)
-
-            y1 = matmul(x, Wx[3])
-            y1 = add_bias(y1, Bx[3], axis=0)
-            y2 = matmul(h, Wh[3])
-            y2 = add_bias(y2, Bh[3], axis=0)
-            g = add(y1, y2)
-            g = tanh(g)
-
-            cout1 = mul(f, c)
-            cout2 = mul(i, g)
-            cout = add(cout1, cout2)
-
-            hout = tanh(cout)
-            hout = mul(o, hout)
-            return hout, cout
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            raise Exception("Not avail for cudnn LSTM \n")
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
+        self.rnn_mode = rnn_mode
+        self.input_size = input_size
+        self.hidden_size = hidden_size
 
-    def backward(self, dy):
-        if self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+    def __call__(self, x):
+        if not hasattr(self, "handle"):
+            cpp_x = singa.VecTensor()
+            [cpp_x.append(i.data) for i in x]
+
+            self.handle = singa.CudnnRNNHandle(cpp_x, self.input_size, self.hidden_size, self.rnn_mode)
 
 Review comment:
   this is resolved

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
dcslin commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407015963
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
+    def __init__(self, handle):
+        super(_RNN_cudnn, self).__init__()
 
 Review comment:
   this is resolved

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
dcslin commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407015888
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
+    def __init__(self, handle):
+        super(_RNN_cudnn, self).__init__()
+        self.handle = handle
 
-            self.W = Tensor(shape=(self.rnn_handle.weights_size,),
-                            requires_grad=True,
-                            stores_grad=True)
-            self.W.gaussian(0.0, 1.0)
+    def forward(self, x, W):
+        y = singa.GpuRNNForwardTraining(x, W, self.handle)
+        if training:
+            self.inputs = (x, W, y)
+        return y
 
-            cpp_y = singa.GpuRNNForwardTraining(cpp_x, self.W.data,
-                                                self.rnn_handle)
-            y = self.cpp_vec_tensor_to_py_tensor(cpp_y)
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
 
-            if training:
-                self.buffer = {"cpp_y": cpp_y, "cpp_x": cpp_x}
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
 
-            return y
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
+class RNN_cudnn(Layer):
+    def __init__(self, input_size, hidden_size, rnn_mode=2):
+        """
+            Args:
+                input_size: input feature dim
+                hidden_size: hidden feature dim
+                rnn_mode: could be 0 - RNN RELU, 1 - RNN TANH, 2 - LSTM, 3 - GRU
 
 Review comment:
   this is resolved

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407071662
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3330,6 +3330,94 @@ def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
         return hout, cout
 
 
+class _RNN(Operation):
+    """ RNN operation with c++ backend
+    """
+    def __init__(self, handle):
+        assert singa.USE_CUDA is True, "Not able to run without CUDA"
+        super(_RNN, self).__init__()
+        self.handle = handle
+
+    def forward(self, x, W):
+        # TODO: CPU forward
+
+        # GPU forward
+        if training:
+            y = singa.GpuRNNForwardTraining(x, W, self.handle)
+            self.inputs = (x, W, y)
+        else:
+            y = singa.GpuRNNForwardInference(x, W, self.handle)
+
+        return y
+
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
+
+        # TODO: CPU backward
+
+        # GPU backward
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
+
+class RNN_direct(Layer):
+    """ `RNN_direct` class implements with c++ backend and run the operation
+          directly on cuDNN
+
+        While `RNN` class implements with high level singa API
+    """
+    def __init__(self, input_size, hidden_size, rnn_mode="lstm"):
+        """
+            Args:
+                input_size: input feature dim
+                hidden_size: hidden feature dim
+                rnn_mode: accepted value: "vanilla", "tanh", "relu",  "lstm", "gru"
+        """
+        assert singa.USE_CUDA is True, "Not able to run without CUDA"
+
+        self.rnn_mode = rnn_mode
+        self.input_size = input_size
+        self.hidden_size = hidden_size
+
+        # TODO: CPU parameter
+
+        # GPU parameter
+        # cudnn_rnn_mode: 0 - RNN RELU, 1 - RNN TANH, 2 - LSTM, 3 - GRU
+        if self.rnn_mode == "lstm":
+            self.cudnn_rnn_mode = 2
+        elif self.rnn_mode == "vanilla" or self.rnn_mode == "tanh":
+            self.cudnn_rnn_mode = 1
+        elif self.rnn_mode == "relu":
+            self.cudnn_rnn_mode = 0
+        elif self.rnn_mode == "gru":
+            self.cudnn_rnn_mode = 3
+
+    def __call__(self, x):
+        if not hasattr(self, "handle"):
+            cpp_x = singa.VecTensor()
+            [cpp_x.append(i.data) for i in x]
+
+            # TODO: CPU handle
+
+            # GPU handle
+            self.handle = singa.CudnnRNNHandle(cpp_x, self.input_size, self.hidden_size, self.cudnn_rnn_mode)
+
+            self.W = Tensor(shape=(self.handle.weights_size,),
+                            requires_grad=True,
+                            stores_grad=True)
+            self.W.gaussian(0.0, 1.0)
+
+        return _RNN(self.handle)(x, self.W)[0]
+
+    def get_params(self):
+        return self.W
 
 Review comment:
   since W is created after the layer is called in forward propagation, if this function is called after the layer is created, there will be error.
   we can add an assert to print some hints, e.g., W is not initialized until the layer is forwarded with data for at least once

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin commented on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-611294054
 
 
   Hi @nudles , I am confused by quite a few things here and there. Primarily is the input layout. May I have your comment on the input layout please?
   Does autograd.py RNN expect input layout to be `list(Tensor, ...)`, where `len(list) == seq length/time steps`, and for each tensor, tensor shape is `batch size, input dim`?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r406223805
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,95 +3239,176 @@ def __init__(
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.nonlinearity = nonlinearity
-
-        Wx_shape = (input_size, hidden_size)
-        self.Wx = []
-        for i in range(4):
-            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wx.append(w)
-
-        Wh_shape = (hidden_size, hidden_size)
-        self.Wh = []
-        for i in range(4):
-            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wh.append(w)
-
-        Bx_shape = (hidden_size,)
-        self.Bx = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bx.append(b)
-
-        self.Bh = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bh.append(b)
-
-        self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        self.backend = backend
+        if backend == "singa":
+            self.nonlinearity = nonlinearity
+
+            Wx_shape = (input_size, hidden_size)
+            self.Wx = []
+            for i in range(4):
+                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wx.append(w)
+
+            Wh_shape = (hidden_size, hidden_size)
+            self.Wh = []
+            for i in range(4):
+                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wh.append(w)
+
+            Bx_shape = (hidden_size,)
+            self.Bx = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bx.append(b)
+
+            self.Bh = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bh.append(b)
+
+            self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        elif backend == "cudnn":
+            if not singa.USE_CUDA:
+                raise Exception("Could not use cudnn without cuda compiled.\n")
+            if not inputs:
+                raise Exception("Input is required for init cudnn LSTM.\n")
+
+            CUDNN_LSTM_MODE = 2
 
 Review comment:
   what does 2 mean? 
   pls add some comment.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407009937
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
+    def __init__(self, handle):
+        super(_RNN_cudnn, self).__init__()
+        self.handle = handle
 
-            self.W = Tensor(shape=(self.rnn_handle.weights_size,),
-                            requires_grad=True,
-                            stores_grad=True)
-            self.W.gaussian(0.0, 1.0)
+    def forward(self, x, W):
+        y = singa.GpuRNNForwardTraining(x, W, self.handle)
 
 Review comment:
   if training is false, need to call GpuRNNForwardInference?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
dcslin commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407008964
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,95 +3239,176 @@ def __init__(
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.nonlinearity = nonlinearity
-
-        Wx_shape = (input_size, hidden_size)
-        self.Wx = []
-        for i in range(4):
-            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wx.append(w)
-
-        Wh_shape = (hidden_size, hidden_size)
-        self.Wh = []
-        for i in range(4):
-            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wh.append(w)
-
-        Bx_shape = (hidden_size,)
-        self.Bx = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bx.append(b)
-
-        self.Bh = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bh.append(b)
-
-        self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        self.backend = backend
+        if backend == "singa":
+            self.nonlinearity = nonlinearity
+
+            Wx_shape = (input_size, hidden_size)
+            self.Wx = []
+            for i in range(4):
+                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wx.append(w)
+
+            Wh_shape = (hidden_size, hidden_size)
+            self.Wh = []
+            for i in range(4):
+                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wh.append(w)
+
+            Bx_shape = (hidden_size,)
+            self.Bx = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bx.append(b)
+
+            self.Bh = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bh.append(b)
+
+            self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        elif backend == "cudnn":
+            if not singa.USE_CUDA:
+                raise Exception("Could not use cudnn without cuda compiled.\n")
+            if not inputs:
+                raise Exception("Input is required for init cudnn LSTM.\n")
+
+            CUDNN_LSTM_MODE = 2
 
 Review comment:
   This is added.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   todo:
   - [x] understand cudnn workflow
   - [x] vanilla rnn cudnn 
   - [x] operation c++ api
   - [x] add lstm
   - [ ] read `autograd.py` rnn and make compatible

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
nudles commented on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610721961
 
 
   I think they are there for future extension.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin commented on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   todo:
   [ ] add lstm
   [ ] read `autograd.py` rnn and make compatible

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] lgtm-com[bot] commented on issue #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
lgtm-com[bot] commented on issue #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#issuecomment-612395356
 
 
   This pull request **introduces 1 alert** when merging 39d4f251f81c91a81119254261262e431b6cfdc3 into 21f5689567766012969926e86853d16b38843646 - [view on LGTM.com](https://lgtm.com/projects/g/apache/singa/rev/pr-73ed4cdba9bf1c379a8b8602ec578410664ddd5f)
   
   **new alerts:**
   
   * 1 for Missing call to \_\_init\_\_ during object initialization

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] lgtm-com[bot] commented on issue #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
lgtm-com[bot] commented on issue #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#issuecomment-612325475
 
 
   This pull request **introduces 1 alert** when merging eafb707d1e594757c56c0d0b539d015e32e3ce81 into f3f6fe0f6f02d496c30d827d56f723f63c7d3c73 - [view on LGTM.com](https://lgtm.com/projects/g/apache/singa/rev/pr-c9749584e197359f44354b557161fcad28ec9380)
   
   **new alerts:**
   
   * 1 for Missing call to \_\_init\_\_ during object initialization

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407009855
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
+    def __init__(self, handle):
+        super(_RNN_cudnn, self).__init__()
 
 Review comment:
   add TODO for cpu case.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
dcslin commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407008958
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,95 +3239,176 @@ def __init__(
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.nonlinearity = nonlinearity
-
-        Wx_shape = (input_size, hidden_size)
-        self.Wx = []
-        for i in range(4):
-            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wx.append(w)
-
-        Wh_shape = (hidden_size, hidden_size)
-        self.Wh = []
-        for i in range(4):
-            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wh.append(w)
-
-        Bx_shape = (hidden_size,)
-        self.Bx = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bx.append(b)
-
-        self.Bh = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bh.append(b)
-
-        self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        self.backend = backend
+        if backend == "singa":
+            self.nonlinearity = nonlinearity
+
+            Wx_shape = (input_size, hidden_size)
+            self.Wx = []
+            for i in range(4):
+                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wx.append(w)
+
+            Wh_shape = (hidden_size, hidden_size)
+            self.Wh = []
+            for i in range(4):
+                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wh.append(w)
+
+            Bx_shape = (hidden_size,)
+            self.Bx = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bx.append(b)
+
+            self.Bh = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bh.append(b)
+
+            self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        elif backend == "cudnn":
+            if not singa.USE_CUDA:
+                raise Exception("Could not use cudnn without cuda compiled.\n")
+            if not inputs:
+                raise Exception("Input is required for init cudnn LSTM.\n")
 
 Review comment:
   this is similar to c++ operation conv handle constructor that requires input for constructing cudnn desc.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   done:
   - [ ]: understand cudnn workflow
   - [ ]: vanilla rnn cudnn 
   - [ ]: operation c++ api
   todo:
   - [ ] add lstm
   - [ ] read `autograd.py` rnn and make compatible

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   todo:
   - [ ] add lstm
   - [ ] read `autograd.py` rnn and make compatible

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407064129
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3330,6 +3330,94 @@ def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
         return hout, cout
 
 
+class _RNN(Operation):
+    """ RNN operation with c++ backend
+    """
+    def __init__(self, handle):
+        assert singa.USE_CUDA is True, "Not able to run without CUDA"
+        super(_RNN, self).__init__()
+        self.handle = handle
+
+    def forward(self, x, W):
+        # TODO: CPU forward
+
+        # GPU forward
+        if training:
+            y = singa.GpuRNNForwardTraining(x, W, self.handle)
+            self.inputs = (x, W, y)
+        else:
+            y = singa.GpuRNNForwardInference(x, W, self.handle)
+
+        return y
+
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
+
+        # TODO: CPU backward
+
+        # GPU backward
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
+
+class RNN_direct(Layer):
 
 Review comment:
   rename to RNN?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407068909
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3330,6 +3330,94 @@ def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
         return hout, cout
 
 
+class _RNN(Operation):
+    """ RNN operation with c++ backend
+    """
+    def __init__(self, handle):
+        assert singa.USE_CUDA is True, "Not able to run without CUDA"
+        super(_RNN, self).__init__()
+        self.handle = handle
+
+    def forward(self, x, W):
+        # TODO: CPU forward
+
+        # GPU forward
+        if training:
+            y = singa.GpuRNNForwardTraining(x, W, self.handle)
+            self.inputs = (x, W, y)
+        else:
+            y = singa.GpuRNNForwardInference(x, W, self.handle)
+
+        return y
+
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
+
+        # TODO: CPU backward
+
+        # GPU backward
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
+
+class RNN_direct(Layer):
+    """ `RNN_direct` class implements with c++ backend and run the operation
+          directly on cuDNN
+
+        While `RNN` class implements with high level singa API
+    """
+    def __init__(self, input_size, hidden_size, rnn_mode="lstm"):
+        """
+            Args:
+                input_size: input feature dim
+                hidden_size: hidden feature dim
+                rnn_mode: accepted value: "vanilla", "tanh", "relu",  "lstm", "gru"
+        """
+        assert singa.USE_CUDA is True, "Not able to run without CUDA"
+
+        self.rnn_mode = rnn_mode
+        self.input_size = input_size
+        self.hidden_size = hidden_size
+
+        # TODO: CPU parameter
+
+        # GPU parameter
+        # cudnn_rnn_mode: 0 - RNN RELU, 1 - RNN TANH, 2 - LSTM, 3 - GRU
+        if self.rnn_mode == "lstm":
+            self.cudnn_rnn_mode = 2
+        elif self.rnn_mode == "vanilla" or self.rnn_mode == "tanh":
+            self.cudnn_rnn_mode = 1
+        elif self.rnn_mode == "relu":
+            self.cudnn_rnn_mode = 0
+        elif self.rnn_mode == "gru":
+            self.cudnn_rnn_mode = 3
+
+    def __call__(self, x):
+        if not hasattr(self, "handle"):
+            cpp_x = singa.VecTensor()
+            [cpp_x.append(i.data) for i in x]
+
+            # TODO: CPU handle
+
+            # GPU handle
+            self.handle = singa.CudnnRNNHandle(cpp_x, self.input_size, self.hidden_size, self.cudnn_rnn_mode)
+
+            self.W = Tensor(shape=(self.handle.weights_size,),
+                            requires_grad=True,
+                            stores_grad=True)
+            self.W.gaussian(0.0, 1.0)
+
+        return _RNN(self.handle)(x, self.W)[0]
 
 Review comment:
   rnn models may return a list of tensors.
   therefore, we should not only select the first.
   but need to add some comments to interpret the returned list.
   for different modes, the returned list could be different.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   done:
   - [x] understand cudnn workflow
   - [x] vanilla rnn cudnn 
   - [x] operation c++ api
   todo:
   - [ ] add lstm
   - [ ] read `autograd.py` rnn and make compatible

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   todo:
   - [x] add lstm
   - [ ] read `autograd.py` rnn and make compatible

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   done:
   - [x] understand cudnn workflow
   - [ ] vanilla rnn cudnn 
   - [x] operation c++ api
   todo:
   - [ ] add lstm
   - [ ] read `autograd.py` rnn and make compatible

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407010143
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
+    def __init__(self, handle):
+        super(_RNN_cudnn, self).__init__()
+        self.handle = handle
 
-            self.W = Tensor(shape=(self.rnn_handle.weights_size,),
-                            requires_grad=True,
-                            stores_grad=True)
-            self.W.gaussian(0.0, 1.0)
+    def forward(self, x, W):
+        y = singa.GpuRNNForwardTraining(x, W, self.handle)
+        if training:
+            self.inputs = (x, W, y)
+        return y
 
-            cpp_y = singa.GpuRNNForwardTraining(cpp_x, self.W.data,
-                                                self.rnn_handle)
-            y = self.cpp_vec_tensor_to_py_tensor(cpp_y)
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
 
-            if training:
-                self.buffer = {"cpp_y": cpp_y, "cpp_x": cpp_x}
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
 
-            return y
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
+class RNN_cudnn(Layer):
+    def __init__(self, input_size, hidden_size, rnn_mode=2):
+        """
+            Args:
+                input_size: input feature dim
+                hidden_size: hidden feature dim
+                rnn_mode: could be 0 - RNN RELU, 1 - RNN TANH, 2 - LSTM, 3 - GRU
+        """
+        if not singa.USE_CUDA:
+            raise Exception("Could not use cudnn without cuda compiled.\n")
 
-    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
-        if self.backend == "singa":
-            y1 = matmul(x, Wx[0])
-            y1 = add_bias(y1, Bx[0], axis=0)
-            y2 = matmul(h, Wh[0])
-            y2 = add_bias(y2, Bh[0], axis=0)
-            i = add(y1, y2)
-            i = sigmoid(i)
-
-            y1 = matmul(x, Wx[1])
-            y1 = add_bias(y1, Bx[1], axis=0)
-            y2 = matmul(h, Wh[1])
-            y2 = add_bias(y2, Bh[1], axis=0)
-            f = add(y1, y2)
-            f = sigmoid(f)
-
-            y1 = matmul(x, Wx[2])
-            y1 = add_bias(y1, Bx[2], axis=0)
-            y2 = matmul(h, Wh[2])
-            y2 = add_bias(y2, Bh[2], axis=0)
-            o = add(y1, y2)
-            o = sigmoid(o)
-
-            y1 = matmul(x, Wx[3])
-            y1 = add_bias(y1, Bx[3], axis=0)
-            y2 = matmul(h, Wh[3])
-            y2 = add_bias(y2, Bh[3], axis=0)
-            g = add(y1, y2)
-            g = tanh(g)
-
-            cout1 = mul(f, c)
-            cout2 = mul(i, g)
-            cout = add(cout1, cout2)
-
-            hout = tanh(cout)
-            hout = mul(o, hout)
-            return hout, cout
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            raise Exception("Not avail for cudnn LSTM \n")
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
+        self.rnn_mode = rnn_mode
+        self.input_size = input_size
+        self.hidden_size = hidden_size
 
-    def backward(self, dy):
-        if self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+    def __call__(self, x):
+        if not hasattr(self, "handle"):
+            cpp_x = singa.VecTensor()
+            [cpp_x.append(i.data) for i in x]
+
+            self.handle = singa.CudnnRNNHandle(cpp_x, self.input_size, self.hidden_size, self.rnn_mode)
 
 Review comment:
   assert gpu is available.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
dcslin commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407015948
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
+    def __init__(self, handle):
+        super(_RNN_cudnn, self).__init__()
+        self.handle = handle
 
-            self.W = Tensor(shape=(self.rnn_handle.weights_size,),
-                            requires_grad=True,
-                            stores_grad=True)
-            self.W.gaussian(0.0, 1.0)
+    def forward(self, x, W):
+        y = singa.GpuRNNForwardTraining(x, W, self.handle)
+        if training:
+            self.inputs = (x, W, y)
+        return y
 
-            cpp_y = singa.GpuRNNForwardTraining(cpp_x, self.W.data,
-                                                self.rnn_handle)
-            y = self.cpp_vec_tensor_to_py_tensor(cpp_y)
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
 
-            if training:
-                self.buffer = {"cpp_y": cpp_y, "cpp_x": cpp_x}
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
 
-            return y
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
+class RNN_cudnn(Layer):
 
 Review comment:
   `RNN` is used for existing highlevel implementation
   After consideration, `RNN_direct` is used to name newly added C++ backed (cudnn/cpu) RNN

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
dcslin commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407066234
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3330,6 +3330,94 @@ def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
         return hout, cout
 
 
+class _RNN(Operation):
+    """ RNN operation with c++ backend
+    """
+    def __init__(self, handle):
+        assert singa.USE_CUDA is True, "Not able to run without CUDA"
+        super(_RNN, self).__init__()
+        self.handle = handle
+
+    def forward(self, x, W):
+        # TODO: CPU forward
+
+        # GPU forward
+        if training:
+            y = singa.GpuRNNForwardTraining(x, W, self.handle)
+            self.inputs = (x, W, y)
+        else:
+            y = singa.GpuRNNForwardInference(x, W, self.handle)
+
+        return y
+
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
+
+        # TODO: CPU backward
+
+        # GPU backward
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
+
+class RNN_direct(Layer):
 
 Review comment:
   RNN is used for existing highlevel implementation
   After consideration, RNN_direct is used to name newly added C++ backed (cudnn/cpu) RNN

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] lgtm-com[bot] commented on issue #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
lgtm-com[bot] commented on issue #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#issuecomment-612405815
 
 
   This pull request **introduces 1 alert** when merging 19f2020fda36032fdc26dc5910dacbfcff638e7f into 21f5689567766012969926e86853d16b38843646 - [view on LGTM.com](https://lgtm.com/projects/g/apache/singa/rev/pr-c6f84c043cb011420209f3ad4c8a1715ad407b55)
   
   **new alerts:**
   
   * 1 for Missing call to \_\_init\_\_ during object initialization

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407010003
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,176 +3238,152 @@ def __init__(self,
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.backend = backend
-        if backend == "singa":
-            self.nonlinearity = nonlinearity
-
-            Wx_shape = (input_size, hidden_size)
-            self.Wx = []
-            for i in range(4):
-                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wx.append(w)
-
-            Wh_shape = (hidden_size, hidden_size)
-            self.Wh = []
-            for i in range(4):
-                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-                w.gaussian(0.0, 1.0)
-                self.Wh.append(w)
-
-            Bx_shape = (hidden_size,)
-            self.Bx = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bx.append(b)
-
-            self.Bh = []
-            for i in range(4):
-                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-                b.set_value(0.0)
-                self.Bh.append(b)
-
-            self.params = self.Wx + self.Wh + self.Bx + self.Bh
-        elif backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
-            if not inputs:
-                raise Exception("Input is required for init cudnn LSTM.\n")
-
-            CUDNN_LSTM_MODE = 2
-
-            cinputs = singa.VecTensor()
-            [cinputs.append(i.data) for i in inputs]
-            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
-                                                   hidden_size, CUDNN_LSTM_MODE)
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
-
-    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
-        py_tensors = list()
-        for cTensor in cpp_vec_tensor:
-            new_t = tensor.Tensor()
-            new_t.data = cTensor
-            new_t.shape = tuple(new_t.data.shape())
-            new_t.device = new_t.data.device()
-            new_t.dtype = new_t.data.data_type()
-            py_tensors.append(new_t)
-        return py_tensors
+        self.nonlinearity = nonlinearity
+
+        Wx_shape = (input_size, hidden_size)
+        self.Wx = []
+        for i in range(4):
+            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wx.append(w)
+
+        Wh_shape = (hidden_size, hidden_size)
+        self.Wh = []
+        for i in range(4):
+            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+            w.gaussian(0.0, 1.0)
+            self.Wh.append(w)
+
+        Bx_shape = (hidden_size,)
+        self.Bx = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bx.append(b)
+
+        self.Bh = []
+        for i in range(4):
+            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+            b.set_value(0.0)
+            self.Bh.append(b)
+
+        self.params = self.Wx + self.Wh + self.Bx + self.Bh
 
     def __call__(self, xs, h0_c0):
-        if self.backend == "singa":
-            # xs: a tuple or list of input tensors
-            # h0_c0: a tuple of (h0, c0)
-            h0, c0 = h0_c0
-            if not isinstance(xs, list):
-                xs = list(xs)
-            inputs = xs + list((h0, c0))
-            self.device_check(*inputs)
-            # self.device_check(inputs[0], *self.params)
-            self.device_check(inputs[0],
-                              *(self.Wx + self.Wh + self.Bx + self.Bh))
-            batchsize = xs[0].shape[0]
-            out = []
-            h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+        # xs: a tuple or list of input tensors
+        # h0_c0: a tuple of (h0, c0)
+        h0, c0 = h0_c0
+        if not isinstance(xs, list):
+            xs = list(xs)
+        inputs = xs + list((h0, c0))
+        self.device_check(*inputs)
+        # self.device_check(inputs[0], *self.params)
+        self.device_check(inputs[0],
+                          *(self.Wx + self.Wh + self.Bx + self.Bh))
+        batchsize = xs[0].shape[0]
+        out = []
+        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
+                                 self.Bh)
+        out.append(h)
+        for x in xs[1:]:
+            assert x.shape[0] == batchsize
+            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
                                      self.Bh)
             out.append(h)
-            for x in xs[1:]:
-                assert x.shape[0] == batchsize
-                h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
-                                         self.Bh)
-                out.append(h)
-            return out, h, c
-        elif self.backend == "cudnn":
-            if not singa.USE_CUDA:
-                raise Exception("Could not use cudnn without cuda compiled.\n")
+        return out, h, c
 
-            cpp_x = singa.VecTensor()
-            [cpp_x.append(i.data) for i in xs]
+    def step_forward(self, x, h, c, Wx, Wh, Bx, Bh):
+        y1 = matmul(x, Wx[0])
+        y1 = add_bias(y1, Bx[0], axis=0)
+        y2 = matmul(h, Wh[0])
+        y2 = add_bias(y2, Bh[0], axis=0)
+        i = add(y1, y2)
+        i = sigmoid(i)
+
+        y1 = matmul(x, Wx[1])
+        y1 = add_bias(y1, Bx[1], axis=0)
+        y2 = matmul(h, Wh[1])
+        y2 = add_bias(y2, Bh[1], axis=0)
+        f = add(y1, y2)
+        f = sigmoid(f)
+
+        y1 = matmul(x, Wx[2])
+        y1 = add_bias(y1, Bx[2], axis=0)
+        y2 = matmul(h, Wh[2])
+        y2 = add_bias(y2, Bh[2], axis=0)
+        o = add(y1, y2)
+        o = sigmoid(o)
+
+        y1 = matmul(x, Wx[3])
+        y1 = add_bias(y1, Bx[3], axis=0)
+        y2 = matmul(h, Wh[3])
+        y2 = add_bias(y2, Bh[3], axis=0)
+        g = add(y1, y2)
+        g = tanh(g)
+
+        cout1 = mul(f, c)
+        cout2 = mul(i, g)
+        cout = add(cout1, cout2)
+
+        hout = tanh(cout)
+        hout = mul(o, hout)
+        return hout, cout
+
+
+class _RNN_cudnn(Operation):
+    def __init__(self, handle):
+        super(_RNN_cudnn, self).__init__()
+        self.handle = handle
 
-            self.W = Tensor(shape=(self.rnn_handle.weights_size,),
-                            requires_grad=True,
-                            stores_grad=True)
-            self.W.gaussian(0.0, 1.0)
+    def forward(self, x, W):
+        y = singa.GpuRNNForwardTraining(x, W, self.handle)
+        if training:
+            self.inputs = (x, W, y)
+        return y
 
-            cpp_y = singa.GpuRNNForwardTraining(cpp_x, self.W.data,
-                                                self.rnn_handle)
-            y = self.cpp_vec_tensor_to_py_tensor(cpp_y)
+    def backward(self, dy):
+        assert training is True and hasattr(
+            self, "inputs"), "Please set training as True before do BP. "
 
-            if training:
-                self.buffer = {"cpp_y": cpp_y, "cpp_x": cpp_x}
+        dx = singa.GpuRNNBackwardx(self.inputs[2], dy, self.inputs[1], self.handle)
+        dW = singa.GpuRNNBackwardW(self.inputs[0], self.inputs[2], self.handle)
+        return dx, dW
 
-            return y
-        else:
-            raise Exception("Unsupported backend %s.\n" % backend)
+class RNN_cudnn(Layer):
 
 Review comment:
   Rename to RNN.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] nudles commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
nudles commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r406234132
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,95 +3239,176 @@ def __init__(
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.nonlinearity = nonlinearity
-
-        Wx_shape = (input_size, hidden_size)
-        self.Wx = []
-        for i in range(4):
-            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wx.append(w)
-
-        Wh_shape = (hidden_size, hidden_size)
-        self.Wh = []
-        for i in range(4):
-            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wh.append(w)
-
-        Bx_shape = (hidden_size,)
-        self.Bx = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bx.append(b)
-
-        self.Bh = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bh.append(b)
-
-        self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        self.backend = backend
+        if backend == "singa":
+            self.nonlinearity = nonlinearity
+
+            Wx_shape = (input_size, hidden_size)
+            self.Wx = []
+            for i in range(4):
+                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wx.append(w)
+
+            Wh_shape = (hidden_size, hidden_size)
+            self.Wh = []
+            for i in range(4):
+                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wh.append(w)
+
+            Bx_shape = (hidden_size,)
+            self.Bx = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bx.append(b)
+
+            self.Bh = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bh.append(b)
+
+            self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        elif backend == "cudnn":
+            if not singa.USE_CUDA:
+                raise Exception("Could not use cudnn without cuda compiled.\n")
+            if not inputs:
+                raise Exception("Input is required for init cudnn LSTM.\n")
+
+            CUDNN_LSTM_MODE = 2
+
+            cinputs = singa.VecTensor()
+            [cinputs.append(i.data) for i in inputs]
+            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
+                                                   hidden_size, CUDNN_LSTM_MODE)
+        else:
+            raise Exception("Unsupported backend %s.\n" % backend)
+
+    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
+        py_tensors = list()
+        for cTensor in cpp_vec_tensor:
+            new_t = tensor.Tensor()
+            new_t.data = cTensor
+            new_t.shape = tuple(new_t.data.shape())
+            new_t.device = new_t.data.device()
+            new_t.dtype = new_t.data.data_type()
+            py_tensors.append(new_t)
+        return py_tensors
 
     def __call__(self, xs, h0_c0):
-        # xs: a tuple or list of input tensors
-        # h0_c0: a tuple of (h0, c0)
-        h0, c0 = h0_c0
-        if not isinstance(xs, list):
-            xs = list(xs)
-        inputs = xs + list((h0, c0))
-        self.device_check(*inputs)
-        # self.device_check(inputs[0], *self.params)
-        self.device_check(inputs[0], *(self.Wx + self.Wh + self.Bx + self.Bh))
-        batchsize = xs[0].shape[0]
-        out = []
-        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
-                                 self.Bh)
-        out.append(h)
-        for x in xs[1:]:
-            assert x.shape[0] == batchsize
-            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
+        if self.backend == "singa":
 
 Review comment:
   LSTM is a Layer subclass.
   It should call lstm function to do the forward by passing the parameters to it.
   lstm function creates _LSTM operation, which implements the forward() and backward().
   
   Pls check the _Conv2d(Operation), conv2d() function and Conv2d(Layer).

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin edited a comment on issue #662: [wip] cudnn Rnn

Posted by GitBox <gi...@apache.org>.
dcslin edited a comment on issue #662: [wip] cudnn Rnn
URL: https://github.com/apache/singa/pull/662#issuecomment-610521190
 
 
   todo:
   - [x] understand cudnn workflow
   - [x] vanilla rnn cudnn 
   - [x] operation c++ api
   - [x] add lstm
   - [x] read `autograd.py` rnn and make compatible
     It seems that these parameters are not in used in autograd:
   ```python
           num_layers=1,
           bias=True,
           batch_first=False,
           dropout=0,
           bidirectional=False,
   ```
   - [ ] clean code, argument check

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [singa] dcslin commented on a change in pull request #662: CUDNN LSTM

Posted by GitBox <gi...@apache.org>.
dcslin commented on a change in pull request #662: CUDNN LSTM
URL: https://github.com/apache/singa/pull/662#discussion_r407009673
 
 

 ##########
 File path: python/singa/autograd.py
 ##########
 @@ -3239,95 +3239,176 @@ def __init__(
             bidirectional (bool): If True, becomes a bidirectional RNN. 
                 Default: False
         """
-        self.nonlinearity = nonlinearity
-
-        Wx_shape = (input_size, hidden_size)
-        self.Wx = []
-        for i in range(4):
-            w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wx.append(w)
-
-        Wh_shape = (hidden_size, hidden_size)
-        self.Wh = []
-        for i in range(4):
-            w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
-            w.gaussian(0.0, 1.0)
-            self.Wh.append(w)
-
-        Bx_shape = (hidden_size,)
-        self.Bx = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bx.append(b)
-
-        self.Bh = []
-        for i in range(4):
-            b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
-            b.set_value(0.0)
-            self.Bh.append(b)
-
-        self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        self.backend = backend
+        if backend == "singa":
+            self.nonlinearity = nonlinearity
+
+            Wx_shape = (input_size, hidden_size)
+            self.Wx = []
+            for i in range(4):
+                w = Tensor(shape=Wx_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wx.append(w)
+
+            Wh_shape = (hidden_size, hidden_size)
+            self.Wh = []
+            for i in range(4):
+                w = Tensor(shape=Wh_shape, requires_grad=True, stores_grad=True)
+                w.gaussian(0.0, 1.0)
+                self.Wh.append(w)
+
+            Bx_shape = (hidden_size,)
+            self.Bx = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bx.append(b)
+
+            self.Bh = []
+            for i in range(4):
+                b = Tensor(shape=Bx_shape, requires_grad=True, stores_grad=True)
+                b.set_value(0.0)
+                self.Bh.append(b)
+
+            self.params = self.Wx + self.Wh + self.Bx + self.Bh
+        elif backend == "cudnn":
+            if not singa.USE_CUDA:
+                raise Exception("Could not use cudnn without cuda compiled.\n")
+            if not inputs:
+                raise Exception("Input is required for init cudnn LSTM.\n")
+
+            CUDNN_LSTM_MODE = 2
+
+            cinputs = singa.VecTensor()
+            [cinputs.append(i.data) for i in inputs]
+            self.rnn_handle = singa.CudnnRNNHandle(cinputs, input_size,
+                                                   hidden_size, CUDNN_LSTM_MODE)
+        else:
+            raise Exception("Unsupported backend %s.\n" % backend)
+
+    def cpp_vec_tensor_to_py_tensor(self, cpp_vec_tensor):
+        py_tensors = list()
+        for cTensor in cpp_vec_tensor:
+            new_t = tensor.Tensor()
+            new_t.data = cTensor
+            new_t.shape = tuple(new_t.data.shape())
+            new_t.device = new_t.data.device()
+            new_t.dtype = new_t.data.data_type()
+            py_tensors.append(new_t)
+        return py_tensors
 
     def __call__(self, xs, h0_c0):
-        # xs: a tuple or list of input tensors
-        # h0_c0: a tuple of (h0, c0)
-        h0, c0 = h0_c0
-        if not isinstance(xs, list):
-            xs = list(xs)
-        inputs = xs + list((h0, c0))
-        self.device_check(*inputs)
-        # self.device_check(inputs[0], *self.params)
-        self.device_check(inputs[0], *(self.Wx + self.Wh + self.Bx + self.Bh))
-        batchsize = xs[0].shape[0]
-        out = []
-        h, c = self.step_forward(xs[0], h0, c0, self.Wx, self.Wh, self.Bx,
-                                 self.Bh)
-        out.append(h)
-        for x in xs[1:]:
-            assert x.shape[0] == batchsize
-            h, c = self.step_forward(x, h, c, self.Wx, self.Wh, self.Bx,
+        if self.backend == "singa":
 
 Review comment:
   thank you for the explanation, this is changed to layer-operation model.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services