You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mxnet.apache.org by GitBox <gi...@apache.org> on 2018/06/13 00:42:16 UTC

[GitHub] lanking520 closed pull request #11198: [MXNET-531][Work In Progress] MNIST Examples for Scala new API

lanking520 closed pull request #11198: [MXNET-531][Work In Progress] MNIST Examples for Scala new API
URL: https://github.com/apache/incubator-mxnet/pull/11198
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/3rdparty/ps-lite b/3rdparty/ps-lite
index 8a763892a97..a6dda54604a 160000
--- a/3rdparty/ps-lite
+++ b/3rdparty/ps-lite
@@ -1 +1 @@
-Subproject commit 8a763892a973afc1acd3d4b469d05bb338a83a6e
+Subproject commit a6dda54604a07d1fb21b016ed1e3f4246b08222a
diff --git a/scala-package/core/src/main/scala/org/apache/mxnet/NDArray.scala b/scala-package/core/src/main/scala/org/apache/mxnet/NDArray.scala
index 49f4d35136f..f55ae3f0d08 100644
--- a/scala-package/core/src/main/scala/org/apache/mxnet/NDArray.scala
+++ b/scala-package/core/src/main/scala/org/apache/mxnet/NDArray.scala
@@ -72,7 +72,6 @@ object NDArray {
         case arg =>
           posArgs.append(arg.toString)
     }
-
     require(posArgs.length <= function.arguments.length,
       s"len(posArgs) = ${posArgs.length}, should be less or equal to len(arguments) " +
       s"= ${function.arguments.length}")
diff --git a/scala-package/examples/src/main/scala/org/apache/mxnet/examples/imclassification/ModelTrain.scala b/scala-package/examples/src/main/scala/org/apache/mxnet/examples/imclassification/ModelTrain.scala
new file mode 100644
index 00000000000..1fa3ecaefaf
--- /dev/null
+++ b/scala-package/examples/src/main/scala/org/apache/mxnet/examples/imclassification/ModelTrain.scala
@@ -0,0 +1,114 @@
+/*
+ * 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.
+ */
+
+package org.apache.mxnet.examples.imclassification
+
+import org.apache.mxnet.Callback.Speedometer
+import org.apache.mxnet._
+import org.apache.mxnet.optimizer.SGD
+import org.slf4j.LoggerFactory
+
+object ModelTrain {
+  private val logger = LoggerFactory.getLogger(classOf[ModelTrain])
+
+  // scalastyle:off parameterNum
+  def fit(dataDir: String, batchSize: Int, numExamples: Int, devs: Array[Context],
+          network: Symbol, dataLoader: (String, Int, KVStore) => (DataIter, DataIter),
+          kvStore: String, numEpochs: Int, modelPrefix: String = null, loadEpoch: Int = -1,
+          lr: Float = 0.1f, lrFactor: Float = 1f, lrFactorEpoch: Float = 1f,
+          clipGradient: Float = 0f, monitorSize: Int = -1): Accuracy = {
+    // kvstore
+    var kv = KVStore.create(kvStore)
+
+    // load model
+    val modelPrefixWithRank =
+      if (modelPrefix == null) null
+      else modelPrefix + s"-${kv.rank}"
+
+    val (argParams, auxParams, beginEpoch) =
+      if (loadEpoch >= 0) {
+        require(modelPrefixWithRank != null)
+        val tmp = FeedForward.load(modelPrefix, loadEpoch)
+        (tmp.getArgParams, tmp.getAuxParams, loadEpoch)
+      } else {
+        (null, null, 0)
+      }
+
+    // save model
+    val checkpoint: EpochEndCallback =
+      if (modelPrefix == null) null
+      else new EpochEndCallback {
+        override def invoke(epoch: Int, symbol: Symbol,
+                            argParams: Map[String, NDArray],
+                            auxStates: Map[String, NDArray]): Unit = {
+          Model.saveCheckpoint(modelPrefix, epoch + 1, symbol, argParams, auxParams)
+        }
+      }
+
+    // data
+    val (train, validation) = dataLoader(dataDir, batchSize, kv)
+
+    // train
+    val epochSize =
+      if (kvStore == "dist_sync") numExamples / batchSize / kv.numWorkers
+      else numExamples / batchSize
+
+    val lrScheduler =
+      if (lrFactor < 1f) {
+        new FactorScheduler(step = Math.max((epochSize * lrFactorEpoch).toInt, 1),
+                            factor = lrFactor)
+      } else {
+        null
+      }
+    val optimizer: Optimizer = new SGD(learningRate = lr,
+        lrScheduler = lrScheduler, clipGradient = clipGradient,
+        momentum = 0.9f, wd = 0.00001f)
+
+    // disable kvstore for single device
+    if (kv.`type`.contains("local") && (devs.length == 1 || devs(0).deviceType != "gpu")) {
+      kv.dispose()
+      kv = null
+    }
+
+    val model = new FeedForward(ctx = devs,
+                                symbol = network,
+                                numEpoch = numEpochs,
+                                optimizer = optimizer,
+                                initializer = new Xavier(factorType = "in", magnitude = 2.34f),
+                                argParams = argParams,
+                                auxParams = auxParams,
+                                beginEpoch = beginEpoch,
+                                epochSize = epochSize)
+    if (monitorSize > 0) {
+      model.setMonitor(new Monitor(monitorSize))
+    }
+    val acc = new Accuracy()
+    model.fit(trainData = train,
+              evalData = validation,
+              evalMetric = acc,
+              kvStore = kv,
+              batchEndCallback = new Speedometer(batchSize, 50),
+              epochEndCallback = checkpoint)
+    if (kv != null) {
+      kv.dispose()
+    }
+    acc
+  }
+  // scalastyle:on parameterNum
+}
+
+class ModelTrain
diff --git a/scala-package/examples/src/main/scala/org/apache/mxnet/examples/imclassification/README.md b/scala-package/examples/src/main/scala/org/apache/mxnet/examples/imclassification/README.md
new file mode 100644
index 00000000000..d286a050dd6
--- /dev/null
+++ b/scala-package/examples/src/main/scala/org/apache/mxnet/examples/imclassification/README.md
@@ -0,0 +1,5 @@
+# MNIST Training Example for Scala
+
+## Introduction
+
+## Steps to run the Example
\ No newline at end of file
diff --git a/scala-package/examples/src/main/scala/org/apache/mxnet/examples/imclassification/TrainMnist.scala b/scala-package/examples/src/main/scala/org/apache/mxnet/examples/imclassification/TrainMnist.scala
new file mode 100644
index 00000000000..c984b857e31
--- /dev/null
+++ b/scala-package/examples/src/main/scala/org/apache/mxnet/examples/imclassification/TrainMnist.scala
@@ -0,0 +1,209 @@
+/*
+ * 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.
+ */
+
+package org.apache.mxnet.examples.imclassification
+
+import org.apache.mxnet._
+import org.kohsuke.args4j.{CmdLineParser, Option}
+import org.slf4j.LoggerFactory
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+object TrainMnist {
+  private val logger = LoggerFactory.getLogger(classOf[TrainMnist])
+
+  // multi-layer perceptron
+  def getMlp: Symbol = {
+    val data = Symbol.Variable("data")
+
+    // val fc1 = Symbol.FullyConnected(name = "relu")()(Map("data" -> data, "act_type" -> "relu"))
+    val fc1 = Symbol.api.FullyConnected(data = Some(data), num_hidden = 128, name = "fc1")
+    val act1 = Symbol.api.Activation (data = Some(fc1), "relu", name = "relu")
+    val fc2 = Symbol.api.FullyConnected(Some(act1), None, None, 64, name = "fc2")
+    val act2 = Symbol.api.Activation(data = Some(fc2), "relu", name = "relu2")
+    val fc3 = Symbol.api.FullyConnected(Some(act2), None, None, 10, name = "fc3")
+    val mlp = Symbol.api.SoftmaxOutput(name = "softmax", data = Some(fc3))
+    mlp
+  }
+
+  // LeCun, Yann, Leon Bottou, Yoshua Bengio, and Patrick
+  // Haffner. "Gradient-based learning applied to document recognition."
+  // Proceedings of the IEEE (1998)
+
+  def getLenet: Symbol = {
+    val data = Symbol.Variable("data")
+    // first conv
+    val conv1 = Symbol.api.Convolution(data = Some(data), kernel = Shape(5, 5), num_filter = 20)
+    val tanh1 = Symbol.api.tanh(data = Some(conv1))
+    val pool1 = Symbol.api.Pooling(data = Some(tanh1), pool_type = Some("max"),
+      kernel = Some(Shape(2, 2)), stride = Some(Shape(2, 2)))
+    // second conv
+    val conv2 = Symbol.api.Convolution(data = Some(pool1), kernel = Shape(5, 5), num_filter = 50)
+    val tanh2 = Symbol.api.tanh(data = Some(conv2))
+    val pool2 = Symbol.api.Pooling(data = Some(tanh2), pool_type = Some("max"),
+      kernel = Some(Shape(2, 2)), stride = Some(Shape(2, 2)))
+    // first fullc
+    val flatten = Symbol.api.Flatten(data = Some(pool2))
+    val fc1 = Symbol.api.FullyConnected(data = Some(flatten), num_hidden = 500)
+    val tanh3 = Symbol.api.tanh(data = Some(fc1))
+    // second fullc
+    val fc2 = Symbol.api.FullyConnected(data = Some(tanh3), num_hidden = 10)
+    // loss
+    val lenet = Symbol.api.SoftmaxOutput(name = "softmax", data = Some(fc2))
+    lenet
+  }
+
+  def getIterator(dataShape: Shape)
+    (dataDir: String, batchSize: Int, kv: KVStore): (DataIter, DataIter) = {
+    val flat = if (dataShape.size == 3) "False" else "True"
+
+    val train = IO.MNISTIter(Map(
+      "image" -> (dataDir + "train-images-idx3-ubyte"),
+      "label" -> (dataDir + "train-labels-idx1-ubyte"),
+      "label_name" -> "softmax_label",
+      "input_shape" -> dataShape.toString,
+      "batch_size" -> batchSize.toString,
+      "shuffle" -> "True",
+      "flat" -> flat,
+      "num_parts" -> kv.numWorkers.toString,
+      "part_index" -> kv.`rank`.toString))
+
+    val eval = IO.MNISTIter(Map(
+      "image" -> (dataDir + "t10k-images-idx3-ubyte"),
+      "label" -> (dataDir + "t10k-labels-idx1-ubyte"),
+      "label_name" -> "softmax_label",
+      "input_shape" -> dataShape.toString,
+      "batch_size" -> batchSize.toString,
+      "flat" -> flat,
+      "num_parts" -> kv.numWorkers.toString,
+      "part_index" -> kv.`rank`.toString))
+
+    (train, eval)
+  }
+
+  def test(dataPath : String) : Float = {
+    val (dataShape, net) = (Shape(784), getMlp)
+    val devs = Array(Context.cpu(0))
+    val envs: mutable.Map[String, String] = mutable.HashMap.empty[String, String]
+    val Acc = ModelTrain.fit(dataDir = dataPath,
+      batchSize = 128, numExamples = 60000, devs = devs,
+      network = net, dataLoader = getIterator(dataShape),
+      kvStore = "local", numEpochs = 10)
+    logger.info("Finish test fit ...")
+    val (_, num) = Acc.get
+    num(0)
+  }
+
+
+  def main(args: Array[String]): Unit = {
+    val inst = new TrainMnist
+    val parser: CmdLineParser = new CmdLineParser(inst)
+    try {
+      parser.parseArgument(args.toList.asJava)
+
+      val dataPath = if (inst.dataDir == null) System.getenv("MXNET_DATA_DIR")
+        else inst.dataDir
+
+      val (dataShape, net) =
+        if (inst.network == "mlp") (Shape(784), getMlp)
+        else (Shape(1, 28, 28), getLenet)
+
+      val devs =
+        if (inst.gpus != null) inst.gpus.split(',').map(id => Context.gpu(id.trim.toInt))
+        else if (inst.cpus != null) inst.cpus.split(',').map(id => Context.cpu(id.trim.toInt))
+        else Array(Context.cpu(0))
+
+      val envs: mutable.Map[String, String] = mutable.HashMap.empty[String, String]
+      envs.put("DMLC_ROLE", inst.role)
+      if (inst.schedulerHost != null) {
+        require(inst.schedulerPort > 0, "scheduler port not specified")
+        envs.put("DMLC_PS_ROOT_URI", inst.schedulerHost)
+        envs.put("DMLC_PS_ROOT_PORT", inst.schedulerPort.toString)
+        require(inst.numWorker > 0, "Num of workers must > 0")
+        envs.put("DMLC_NUM_WORKER", inst.numWorker.toString)
+        require(inst.numServer > 0, "Num of servers must > 0")
+        envs.put("DMLC_NUM_SERVER", inst.numServer.toString)
+        logger.info("Init PS environments")
+        KVStoreServer.init(envs.toMap)
+      }
+
+      if (inst.role != "worker") {
+        logger.info("Start KVStoreServer for scheduler & servers")
+        KVStoreServer.start()
+      } else {
+        ModelTrain.fit(dataDir = inst.dataDir,
+          batchSize = inst.batchSize, numExamples = inst.numExamples, devs = devs,
+          network = net, dataLoader = getIterator(dataShape),
+          kvStore = inst.kvStore, numEpochs = inst.numEpochs,
+          modelPrefix = inst.modelPrefix, loadEpoch = inst.loadEpoch,
+          lr = inst.lr, lrFactor = inst.lrFactor, lrFactorEpoch = inst.lrFactorEpoch,
+          monitorSize = inst.monitor)
+        logger.info("Finish fit ...")
+      }
+    } catch {
+      case ex: Exception => {
+        logger.error(ex.getMessage, ex)
+        parser.printUsage(System.err)
+        sys.exit(1)
+      }
+    }
+  }
+}
+
+class TrainMnist {
+  @Option(name = "--network", usage = "the cnn to use: ['mlp', 'lenet']")
+  private val network: String = "mlp"
+  @Option(name = "--data-dir", usage = "the input data directory")
+  private val dataDir: String = "mnist/"
+  @Option(name = "--gpus", usage = "the gpus will be used, e.g. '0,1,2,3'")
+  private val gpus: String = null
+  @Option(name = "--cpus", usage = "the cpus will be used, e.g. '0,1,2,3'")
+  private val cpus: String = null
+  @Option(name = "--num-examples", usage = "the number of training examples")
+  private val numExamples: Int = 60000
+  @Option(name = "--batch-size", usage = "the batch size")
+  private val batchSize: Int = 128
+  @Option(name = "--lr", usage = "the initial learning rate")
+  private val lr: Float = 0.1f
+  @Option(name = "--model-prefix", usage = "the prefix of the model to load/save")
+  private val modelPrefix: String = null
+  @Option(name = "--num-epochs", usage = "the number of training epochs")
+  private val numEpochs = 10
+  @Option(name = "--load-epoch", usage = "load the model on an epoch using the model-prefix")
+  private val loadEpoch: Int = -1
+  @Option(name = "--kv-store", usage = "the kvstore type")
+  private val kvStore = "local"
+  @Option(name = "--lr-factor",
+          usage = "times the lr with a factor for every lr-factor-epoch epoch")
+  private val lrFactor: Float = 1f
+  @Option(name = "--lr-factor-epoch", usage = "the number of epoch to factor the lr, could be .5")
+  private val lrFactorEpoch: Float = 1f
+  @Option(name = "--monitor", usage = "monitor the training process every N batch")
+  private val monitor: Int = -1
+
+  @Option(name = "--role", usage = "scheduler/server/worker")
+  private val role: String = "worker"
+  @Option(name = "--scheduler-host", usage = "Scheduler hostname / ip address")
+  private val schedulerHost: String = null
+  @Option(name = "--scheduler-port", usage = "Scheduler port")
+  private val schedulerPort: Int = 0
+  @Option(name = "--num-worker", usage = "# of workers")
+  private val numWorker: Int = 1
+  @Option(name = "--num-server", usage = "# of servers")
+  private val numServer: Int = 1
+}
diff --git a/scala-package/examples/src/test/scala/org/apache/mxnet/examples/imclassification/MNISTExampleSuite.scala b/scala-package/examples/src/test/scala/org/apache/mxnet/examples/imclassification/MNISTExampleSuite.scala
new file mode 100644
index 00000000000..8303b9e9a19
--- /dev/null
+++ b/scala-package/examples/src/test/scala/org/apache/mxnet/examples/imclassification/MNISTExampleSuite.scala
@@ -0,0 +1,60 @@
+/*
+ * 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.
+ */
+
+package org.apache.mxnet.examples.imclassification
+
+import java.io.File
+
+import org.apache.mxnet.Context
+import org.scalatest.{BeforeAndAfterAll, FunSuite}
+import org.slf4j.LoggerFactory
+
+import scala.sys.process.Process
+
+/**
+  * Integration test for imageClassifier example.
+  * This will run as a part of "make scalatest"
+  */
+class MNISTExampleSuite extends FunSuite with BeforeAndAfterAll {
+  private val logger = LoggerFactory.getLogger(classOf[MNISTExampleSuite])
+
+  test("Example CI: Test MNIST Training") {
+    // This test is CPU only
+    if (System.getenv().containsKey("SCALA_TEST_ON_GPU") &&
+      System.getenv("SCALA_TEST_ON_GPU").toInt == 1) {
+      logger.info("CPU test only, skipped...")
+    } else {
+      logger.info("Downloading mnist model")
+      val tempDirPath = System.getProperty("java.io.tmpdir")
+      val modelDirPath = tempDirPath + File.separator + "mnist/"
+      logger.info("tempDirPath: %s".format(tempDirPath))
+      Process("wget https://s3.us-east-2.amazonaws.com/mxnet-scala/scala-example-ci" +
+        "/mnist/mnist.zip " + "-P " + tempDirPath + "/mnist/ -q") !
+
+      Process("unzip " + tempDirPath + "/mnist/mnist.zip -d "
+        + tempDirPath + "/mnist/") !
+
+      var context = Context.cpu()
+
+      val output = TrainMnist.test(modelDirPath)
+      Process("rm -rf " + modelDirPath) !
+
+      assert(output >= 0.95f)
+    }
+
+  }
+}


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on 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