You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@systemml.apache.org by du...@apache.org on 2017/06/19 20:54:50 UTC

[3/4] systemml git commit: [SYSTEMML-1674] Add a new 2D depthwise convolution layer

[SYSTEMML-1674] Add a new 2D depthwise convolution layer

This adds a new 2D depthwise convolution layer.  A depthwise convolution
(1) applies a different set of M filters to each input channel
separately, thus expanding each input channel to M output channels, and
(2) concatenates the results into a single volume with C*M output
channels.  This is in contrast to a regular 2D convolution, in which all
of the filters would be applied to all of the input channels at once.

In addition to the new layer, this also adds the associated unit and
gradient tests.

Closes #542.


Project: http://git-wip-us.apache.org/repos/asf/systemml/repo
Commit: http://git-wip-us.apache.org/repos/asf/systemml/commit/f2d975f5
Tree: http://git-wip-us.apache.org/repos/asf/systemml/tree/f2d975f5
Diff: http://git-wip-us.apache.org/repos/asf/systemml/diff/f2d975f5

Branch: refs/heads/master
Commit: f2d975f5015724434590098cb1f0371b082c65a6
Parents: 585b85f
Author: Mike Dusenberry <mw...@us.ibm.com>
Authored: Mon Jun 19 13:52:56 2017 -0700
Committer: Mike Dusenberry <mw...@us.ibm.com>
Committed: Mon Jun 19 13:52:56 2017 -0700

----------------------------------------------------------------------
 scripts/nn/layers/conv2d_depthwise.dml | 190 ++++++++++++++++++++++++++++
 scripts/nn/test/grad_check.dml         | 108 +++++++++++++++-
 scripts/nn/test/run_tests.dml          |   2 +
 scripts/nn/test/test.dml               |  69 ++++++++++
 4 files changed, 363 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/systemml/blob/f2d975f5/scripts/nn/layers/conv2d_depthwise.dml
----------------------------------------------------------------------
diff --git a/scripts/nn/layers/conv2d_depthwise.dml b/scripts/nn/layers/conv2d_depthwise.dml
new file mode 100644
index 0000000..0e9abb5
--- /dev/null
+++ b/scripts/nn/layers/conv2d_depthwise.dml
@@ -0,0 +1,190 @@
+#-------------------------------------------------------------
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+#-------------------------------------------------------------
+
+/*
+ * 2D Depthwise Convolutional layer.
+ *
+ * Utilizes built-in convolution operators for higher performance.
+ */
+source("nn/util.dml") as util
+
+forward = function(matrix[double] X, matrix[double] W, matrix[double] b,
+                   int Hin, int Win, int M, int Hf, int Wf,
+                   int strideh, int stridew, int padh, int padw)
+    return (matrix[double] out, int Hout, int Wout) {
+  /*
+   * Computes the forward pass for a 2D depthwise spatial convolutional
+   * layer with C*M filters of depth 1.  The input data has N examples,
+   * each represented as a 3D volume with C channels unrolled into a
+   * single vector.  For each group of M filters, a 2D convolution is
+   * applied to 1 unique input channel, yielding M output channels per
+   * input channel.  The resulting C groups of M output channels are
+   * then concatenated together channel-wise into a single volume of C*M
+   * output channels.  This can also be interpreted as C filters of
+   * depth 1 that expand each input channel to M output channels, where
+   * M is a "depth multiplier".
+   *
+   * Inputs:
+   *  - X: Inputs, of shape (N, C*Hin*Win).
+   *  - W: Weights, of shape (C, M*Hf*Wf).
+   *  - b: Biases, of shape (C*M, 1).
+   *  - Hin: Input height.
+   *  - Win: Input width.
+   *  - M: Number of filters per input channel (i.e. depth multiplier).
+   *  - Hf: Filter height.
+   *  - Wf: Filter width.
+   *  - strideh: Stride over height.
+   *  - stridew: Stride over width.
+   *  - padh: Padding for top and bottom sides.
+   *      For same output height as input, set `padh = (Hf - 1) / 2`,
+   *      assuming `strideh = 1`.
+   *      More generally, `padh = (Hin*(strideh-1) + Hf - strideh) / 2`
+   *      preserves the spatial dimensions of the input.
+   *  - padw: Padding for left and right sides.
+   *      For same output width as input, set `padw = (Wf - 1) / 2`,
+   *      assuming `stridew = 1`.
+   *      More generally, `padw = (Win*(stridew-1) + Wf - stridew) / 2`
+   *      preserves the spatial dimensions of the input.
+   *
+   * Outputs:
+   *  - out: Outputs, of shape (N, C*M*Hout*Wout).
+   *  - Hout: Output height.
+   *  - Wout: Output width.
+   */
+  N = nrow(X)
+  C = nrow(W)
+  Hout = as.integer(floor((Hin + 2*padh - Hf)/strideh + 1))
+  Wout = as.integer(floor((Win + 2*padw - Wf)/stridew + 1))
+
+  # create output volume
+  out = matrix(0, rows=N, cols=C*M*Hout*Wout)
+
+  # depthwise convolution
+  # TODO: Explore usage of parfor loops more to determine if they can provide a performance
+  # benefit.  Initial tests show that they are slower than the regular for loop, likely because
+  # they cause a reduction from a multithreaded conv2d op to a singlethreaded version.  For a
+  # number of channels >> the number of examples, it's possible that the parfor loop could be
+  # faster.
+  #parfor (c in 1:C, check=0) {  # each channel
+  for (c in 1:C) {  # each channel
+    # run conv2d on each input channel separately, each with a different filter
+    Xc = X[,((c-1)*Hin*Win + 1):c*Hin*Win]  # shape (N, 1*Hin*Win)
+    Wc = matrix(W[c,], rows=M, cols=Hf*Wf)  # shape (M, Hf*Wf)
+    outc = conv2d(Xc, Wc, input_shape=[N,1,Hin,Win], filter_shape=[M,1,Hf,Wf],
+                  stride=[strideh,stridew], padding=[padh,padw])  # shape (N, M*Hout*Wout)
+    out[,((c-1)*M*Hout*Wout + 1):c*M*Hout*Wout] = outc
+  }
+
+  # add bias term to each output filter
+  out = bias_add(out, b)
+}
+
+backward = function(matrix[double] dout, int Hout, int Wout,
+                    matrix[double] X, matrix[double] W, matrix[double] b,
+                    int Hin, int Win, int M, int Hf, int Wf,
+                    int strideh, int stridew, int padh, int padw)
+    return (matrix[double] dX, matrix[double] dW, matrix[double] db) {
+  /*
+   * Computes the backward pass for a 2D depthwise spatial convolutional
+   * layer with C*M filters of depth 1.
+   *
+   * Inputs:
+   *  - dout: Gradient wrt `out` from upstream, of
+   *      shape (N, C*M*Hout*Wout).
+   *  - Hout: Output height.
+   *  - Wout: Output width.
+   *  - X: Inputs, of shape (N, C*Hin*Win).
+   *  - W: Weights, of shape (C, M*Hf*Wf).
+   *  - b: Biases, of shape (C*M, 1).
+   *  - Hin: Input height.
+   *  - Win: Input width.
+   *  - M: Num filters per input channel (i.e. depth multiplier).
+   *  - Hf: Filter height.
+   *  - Wf: Filter width.
+   *  - strideh: Stride over height.
+   *  - stridew: Stride over width.
+   *  - padh: Padding for top and bottom sides.
+   *  - padw: Padding for left and right sides.
+   *
+   * Outputs:
+   *  - dX: Gradient wrt `X`, of shape (N, C*Hin*Win).
+   *  - dW: Gradient wrt `W`, of shape (C, M*Hf*Wf).
+   *  - db: Gradient wrt `b`, of shape (C*M, 1).
+   */
+  N = nrow(X)
+  C = nrow(W)
+
+  # create gradient volumes
+  dX = matrix(0, rows=N, cols=C*Hin*Win)
+  dW = matrix(0, rows=C, cols=M*Hf*Wf)
+  db = matrix(0, rows=C*M, cols=1)
+
+  # partial derivatives for depthwise convolution
+  for (c in 1:C) {  # all examples
+    # extract channel c
+    doutc = dout[,((c-1)*M*Hout*Wout + 1):c*M*Hout*Wout]  # (N,M*Hout*Wout)
+    Xc = X[,((c-1)*Hin*Win + 1):c*Hin*Win]  # shape (N, 1*Hin*Win)
+    Wc = matrix(W[c,], rows=M, cols=Hf*Wf)  # shape (M, 1*Hf*Wf)
+
+    # compute gradients for channel c
+    dWc = conv2d_backward_filter(Xc, doutc, stride=[strideh,stridew], padding=[padh,padw],
+                                 input_shape=[N,1,Hin,Win], filter_shape=[M,1,Hf,Wf])
+    dXc = conv2d_backward_data(Wc, doutc, stride=[strideh,stridew], padding=[padh,padw],
+                               input_shape=[N,1,Hin,Win], filter_shape=[M,1,Hf,Wf])
+
+    # store
+    dX[,((c-1)*Hin*Win + 1):c*Hin*Win] = dXc
+    dW[c,] = matrix(dWc, rows=1, cols=M*Hf*Wf)
+  }
+
+  # partial derivatives for bias vector
+  db = util::channel_sums(dout, C*M, Hout, Wout)
+}
+
+init = function(int C, int M, int Hf, int Wf)
+    return (matrix[double] W, matrix[double] b) {
+  /*
+   * Initialize the parameters of this layer.
+   *
+   * Note: This is just a convenience function, and parameters
+   * may be initialized manually if needed.
+   *
+   * We use the heuristic by He et al., which limits the magnification
+   * of inputs/gradients during forward/backward passes by scaling
+   * unit-Gaussian weights by a factor of sqrt(2/n), under the
+   * assumption of relu neurons.
+   *  - http://arxiv.org/abs/1502.01852
+   *
+   * Inputs:
+   *  - C: Number of input channels (dimensionality of depth).
+   *  - M: Number of filters per input channel (i.e. depth multiplier).
+   *  - Hf: Filter height.
+   *  - Wf: Filter width.
+   *
+   * Outputs:
+   *  - W: Weights, of shape (C, M*Hf*Wf).
+   *  - b: Biases, of shape (C*M, 1).
+   */
+  # Note: Each filter is applied to a volume of depth 1, so we only use Hf*Wf in the scaling factor.
+  W = rand(rows=C, cols=M*Hf*Wf, pdf="normal") * sqrt(2.0/(Hf*Wf))
+  b = matrix(0, rows=C*M, cols=1)
+}
+

http://git-wip-us.apache.org/repos/asf/systemml/blob/f2d975f5/scripts/nn/test/grad_check.dml
----------------------------------------------------------------------
diff --git a/scripts/nn/test/grad_check.dml b/scripts/nn/test/grad_check.dml
index 48e470c..67aeac1 100644
--- a/scripts/nn/test/grad_check.dml
+++ b/scripts/nn/test/grad_check.dml
@@ -27,6 +27,7 @@ source("nn/layers/batch_norm1d.dml") as batch_norm1d
 source("nn/layers/batch_norm2d.dml") as batch_norm2d
 source("nn/layers/conv2d.dml") as conv2d
 source("nn/layers/conv2d_builtin.dml") as conv2d_builtin
+source("nn/layers/conv2d_depthwise.dml") as conv2d_depthwise
 source("nn/layers/conv2d_transpose.dml") as conv2d_transpose
 source("nn/layers/cross_entropy_loss.dml") as cross_entropy_loss
 source("nn/layers/dropout.dml") as dropout
@@ -347,10 +348,10 @@ conv2d = function() {
 
   # Generate data
   N = 2  # num examples
-  C = 2  # num channels
+  C = 3  # num channels
   Hin = 5  # input height
   Win = 5  # input width
-  F = 2  # num filters
+  F = 4  # num filters
   Hf = 3  # filter height
   Wf = 3  # filter width
   stride = 1
@@ -436,10 +437,10 @@ conv2d_builtin = function() {
 
   # Generate data
   N = 2  # num examples
-  C = 2  # num channels
+  C = 3  # num channels
   Hin = 5  # input height
   Win = 5  # input width
-  F = 2  # num filters
+  F = 4  # num filters
   Hf = 3  # filter height
   Wf = 3  # filter width
   stride = 1
@@ -531,10 +532,10 @@ conv2d_simple = function() {
 
   # Generate data
   N = 2  # num examples
-  C = 2  # num channels
+  C = 3  # num channels
   Hin = 5  # input height
   Win = 5  # input width
-  F = 2  # num filters
+  F = 4  # num filters
   Hf = 3  # filter height
   Wf = 3  # filter width
   stride = 1
@@ -617,6 +618,101 @@ conv2d_simple = function() {
   }
 }
 
+conv2d_depthwise = function() {
+  /*
+   * Gradient check for the 2D depthwise convolutional layer.
+   */
+  print("Grad checking the 2D depthwise convolutional layer with L2 loss.")
+
+  # Generate data
+  N = 2  # num examples
+  C = 3  # num channels
+  Hin = 5  # input height
+  Win = 5  # input width
+  M = 4  # depth multiplier
+  Hf = 3  # filter height
+  Wf = 3  # filter width
+  stride = 1
+  pad = 1
+  X = rand(rows=N, cols=C*Hin*Win)
+  y = rand(rows=N, cols=C*M*Hin*Win)
+
+  # Create layers
+  [W, b] = conv2d_depthwise::init(C, M, Hf, Wf)
+
+  # Compute analytical gradients of loss wrt parameters
+  [out, Hout, Wout] = conv2d_depthwise::forward(X, W, b, Hin, Win, M, Hf, Wf, stride, stride,
+                                                pad, pad)
+  dout = l2_loss::backward(out, y)
+  [dX, dW, db] = conv2d_depthwise::backward(dout, Hout, Wout, X, W, b, Hin, Win, M, Hf, Wf,
+                                            stride, stride, pad, pad)
+
+  # Grad check
+  h = 1e-5
+  print(" - Grad checking X.")
+  for (i in 1:nrow(X)) {
+    for (j in 1:ncol(X)) {
+      # Compute numerical derivative
+      old = as.scalar(X[i,j])
+      X[i,j] = old - h
+      [outmh, Hout, Wout] = conv2d_depthwise::forward(X, W, b, Hin, Win, M, Hf, Wf, stride, stride,
+                                                      pad, pad)
+      lossmh = l2_loss::forward(outmh, y)
+      X[i,j] = old + h
+      [outph, Hout, Wout] = conv2d_depthwise::forward(X, W, b, Hin, Win, M, Hf, Wf, stride, stride,
+                                                      pad, pad)
+      lossph = l2_loss::forward(outph, y)
+      X[i,j] = old  # reset
+      dX_num = (lossph-lossmh) / (2*h)  # numerical derivative
+
+      # Check error
+      rel_error = test_util::check_rel_grad_error(as.scalar(dX[i,j]), dX_num, lossph, lossmh)
+    }
+  }
+
+  print(" - Grad checking W.")
+  for (i in 1:nrow(W)) {
+    for (j in 1:ncol(W)) {
+      # Compute numerical derivative
+      old = as.scalar(W[i,j])
+      W[i,j] = old - h
+      [outmh, Hout, Wout] = conv2d_depthwise::forward(X, W, b, Hin, Win, M, Hf, Wf, stride, stride,
+                                                      pad, pad)
+      lossmh = l2_loss::forward(outmh, y)
+      W[i,j] = old + h
+      [outph, Hout, Wout] = conv2d_depthwise::forward(X, W, b, Hin, Win, M, Hf, Wf, stride, stride,
+                                                      pad, pad)
+      lossph = l2_loss::forward(outph, y)
+      W[i,j] = old  # reset
+      dW_num = (lossph-lossmh) / (2*h)  # numerical derivative
+
+      # Check error
+      rel_error = test_util::check_rel_grad_error(as.scalar(dW[i,j]), dW_num, lossph, lossmh)
+    }
+  }
+
+  print(" - Grad checking b.")
+  for (i in 1:nrow(b)) {
+    for (j in 1:ncol(b)) {
+      # Compute numerical derivative
+      old = as.scalar(b[i,j])
+      b[i,j] = old - h
+      [outmh, Hout, Wout] = conv2d_depthwise::forward(X, W, b, Hin, Win, M, Hf, Wf, stride, stride,
+                                                      pad, pad)
+      lossmh = l2_loss::forward(outmh, y)
+      b[i,j] = old + h
+      [outph, Hout, Wout] = conv2d_depthwise::forward(X, W, b, Hin, Win, M, Hf, Wf, stride, stride,
+                                                      pad, pad)
+      lossph = l2_loss::forward(outph, y)
+      b[i,j] = old  # reset
+      db_num = (lossph-lossmh) / (2*h)  # numerical derivative
+
+      # Check error
+      rel_error = test_util::check_rel_grad_error(as.scalar(db[i,j]), db_num, lossph, lossmh)
+    }
+  }
+}
+
 conv2d_transpose = function() {
   /*
    * Gradient check for the 2D transpose convolutional layer.

http://git-wip-us.apache.org/repos/asf/systemml/blob/f2d975f5/scripts/nn/test/run_tests.dml
----------------------------------------------------------------------
diff --git a/scripts/nn/test/run_tests.dml b/scripts/nn/test/run_tests.dml
index c9b1b3e..ec6fcff 100644
--- a/scripts/nn/test/run_tests.dml
+++ b/scripts/nn/test/run_tests.dml
@@ -45,6 +45,7 @@ grad_check::batch_norm2d()
 grad_check::conv2d()
 grad_check::conv2d_builtin()
 grad_check::conv2d_simple()
+grad_check::conv2d_depthwise()
 grad_check::conv2d_transpose()
 grad_check::dropout()
 grad_check::lstm()
@@ -86,6 +87,7 @@ print("---")
 test::batch_norm1d()
 test::batch_norm2d()
 test::conv2d()
+test::conv2d_depthwise()
 test::conv2d_transpose()
 test::cross_entropy_loss()
 test::im2col()

http://git-wip-us.apache.org/repos/asf/systemml/blob/f2d975f5/scripts/nn/test/test.dml
----------------------------------------------------------------------
diff --git a/scripts/nn/test/test.dml b/scripts/nn/test/test.dml
index 94965bf..c60aab9 100644
--- a/scripts/nn/test/test.dml
+++ b/scripts/nn/test/test.dml
@@ -26,6 +26,7 @@ source("nn/layers/batch_norm1d.dml") as batch_norm1d
 source("nn/layers/batch_norm2d.dml") as batch_norm2d
 source("nn/layers/conv2d.dml") as conv2d
 source("nn/layers/conv2d_builtin.dml") as conv2d_builtin
+source("nn/layers/conv2d_depthwise.dml") as conv2d_depthwise
 source("nn/layers/conv2d_transpose.dml") as conv2d_transpose
 source("nn/layers/cross_entropy_loss.dml") as cross_entropy_loss
 source("nn/layers/max_pool2d.dml") as max_pool2d
@@ -200,6 +201,74 @@ conv2d = function() {
   }
 }
 
+conv2d_depthwise = function() {
+  /*
+   * Test for the 2D depthwise convolution function.
+   */
+  print("Testing the 2D depthwise convolution function.")
+
+  # Generate data
+  N = 2  # num examples
+  C = 2  # num channels
+  Hin = 3  # input height
+  Win = 3  # input width
+  M = 2  # num filters per input channel (i.e. depth multiplier)
+  Hf = 3  # filter height
+  Wf = 3  # filter width
+  stride = 1
+  pad = 1
+  X = matrix(seq(1,N*C*Hin*Win), rows=N, cols=C*Hin*Win) / (N*C*Hin*Win) * 2 - 1  # normalized
+
+  # Create layer
+  W = matrix(seq(1,C*M*Hf*Wf), rows=C, cols=M*Hf*Wf) / (C*M*Hf*Wf) * 2 - 1  # normalized
+  b = matrix(seq(1,C*M), rows=C*M, cols=1) / (C*M)^2  # non-zero & non-one
+
+  # Forward
+  [out, Hout, Wout] = conv2d_depthwise::forward(X, W, b, Hin, Win, M, Hf, Wf, stride, stride,
+                                                pad, pad)
+
+  # Equivalency check
+  target = matrix("2.13040113  3.20447516  2.16743827
+                   3.30324078  4.94212961  3.30324078
+                   2.16743827  3.20447516  2.13040113
+
+                   0.52623457  0.85030866  0.67438275
+                   1.11574078  1.75462961  1.2824074
+                   0.89660496  1.35030866  0.97067899
+
+                  -0.30015433 -0.42052469 -0.15200615
+                  -0.15509261 -0.1828704   0.01157404
+                   0.07021603  0.07947529  0.1442901
+
+                  -0.90432101 -1.27469134 -0.64506173
+                  -0.8425926  -1.12037039 -0.50925928
+                  -0.20061731 -0.2746914  -0.01543214
+
+
+                  -0.31404325 -0.62885809 -0.49922845
+                  -0.86342597 -1.55787039 -1.19675934
+                  -0.94367278 -1.62885797 -1.20293212
+
+                   0.0817901   0.01697529  0.00771603
+                  -0.05092596 -0.2453704  -0.21759261
+                  -0.21450615 -0.48302469 -0.36265433
+
+                   1.25540125  1.74614203  1.1813271
+                   1.67824078  2.31712961  1.51157403
+                   0.95910496  1.24614203  0.81095684
+
+                   2.65123463  3.8919754   2.68827152
+                   3.99074078  5.87962961  3.99074078
+                   2.68827152  3.8919754   2.65123463", rows=N, cols=C*M*Hout*Wout)
+
+  for (i in 1:nrow(out)) {
+    for(j in 1:ncol(out)) {
+      rel_error = test_util::check_rel_error(as.scalar(out[i,j]),
+                                             as.scalar(target[i,j]), 1e-3, 1e-4)
+    }
+  }
+}
+
 conv2d_transpose = function() {
   /*
    * Test for the 2D transpose convolution function.