You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@predictionio.apache.org by takezoe <gi...@git.apache.org> on 2017/07/18 00:20:03 UTC

[GitHub] incubator-predictionio pull request #412: [PIO-105] Batch Predictions

Github user takezoe commented on a diff in the pull request:

    https://github.com/apache/incubator-predictionio/pull/412#discussion_r127852943
  
    --- Diff: core/src/main/scala/org/apache/predictionio/workflow/BatchPredict.scala ---
    @@ -0,0 +1,228 @@
    +/*
    + * 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.predictionio.workflow
    +
    +import java.io.Serializable
    +
    +import com.twitter.bijection.Injection
    +import com.twitter.chill.{KryoBase, KryoInjection, ScalaKryoInstantiator}
    +import de.javakaffee.kryoserializers.SynchronizedCollectionsSerializer
    +import grizzled.slf4j.Logging
    +import org.apache.predictionio.controller.{Engine, Utils}
    +import org.apache.predictionio.core.{BaseAlgorithm, BaseServing, Doer}
    +import org.apache.predictionio.data.storage.{EngineInstance, Storage}
    +import org.apache.predictionio.workflow.JsonExtractorOption.JsonExtractorOption
    +import org.apache.spark.rdd.RDD
    +import org.json4s._
    +import org.json4s.native.JsonMethods._
    +import scala.language.existentials
    +
    +case class BatchPredictConfig(
    +  inputFilePath: String = "batchpredict-input.json",
    +  outputFilePath: String = "batchpredict-output.json",
    +  queryPartitions: Option[Int] = None,
    +  engineInstanceId: String = "",
    +  engineId: Option[String] = None,
    +  engineVersion: Option[String] = None,
    +  engineVariant: String = "",
    +  env: Option[String] = None,
    +  verbose: Boolean = false,
    +  debug: Boolean = false,
    +  jsonExtractor: JsonExtractorOption = JsonExtractorOption.Both)
    +
    +object BatchPredict extends Logging {
    +
    +  class KryoInstantiator(classLoader: ClassLoader) extends ScalaKryoInstantiator {
    +    override def newKryo(): KryoBase = {
    +      val kryo = super.newKryo()
    +      kryo.setClassLoader(classLoader)
    +      SynchronizedCollectionsSerializer.registerSerializers(kryo)
    +      kryo
    +    }
    +  }
    +
    +  object KryoInstantiator extends Serializable {
    +    def newKryoInjection : Injection[Any, Array[Byte]] = {
    +      val kryoInstantiator = new KryoInstantiator(getClass.getClassLoader)
    +      KryoInjection.instance(kryoInstantiator)
    +    }
    +  }
    +
    +  val engineInstances = Storage.getMetaDataEngineInstances
    +  val modeldata = Storage.getModelDataModels
    +
    +  def main(args: Array[String]): Unit = {
    +    val parser = new scopt.OptionParser[BatchPredictConfig]("BatchPredict") {
    +      opt[String]("input") action { (x, c) =>
    +        c.copy(inputFilePath = x)
    +      } text("Path to file containing input queries; a " +
    +        "multi-object JSON file with one object per line.")
    +      opt[String]("output") action { (x, c) =>
    +        c.copy(outputFilePath = x)
    +      } text("Path to file containing output predictions; a " +
    +        "multi-object JSON file with one object per line.")
    +      opt[Int]("query-partitions") action { (x, c) =>
    +        c.copy(queryPartitions = Some(x))
    +      } text("Limit concurrency of predictions by setting the number " +
    +        "of partitions used internally for the RDD of queries.")
    +      opt[String]("engineId") action { (x, c) =>
    +        c.copy(engineId = Some(x))
    +      } text("Engine ID.")
    +      opt[String]("engineId") action { (x, c) =>
    +        c.copy(engineId = Some(x))
    +      } text("Engine ID.")
    +      opt[String]("engineVersion") action { (x, c) =>
    +        c.copy(engineVersion = Some(x))
    +      } text("Engine version.")
    +      opt[String]("engine-variant") required() action { (x, c) =>
    +        c.copy(engineVariant = x)
    +      } text("Engine variant JSON.")
    +      opt[String]("env") action { (x, c) =>
    +        c.copy(env = Some(x))
    +      } text("Comma-separated list of environmental variables (in 'FOO=BAR' " +
    +        "format) to pass to the Spark execution environment.")
    +      opt[String]("engineInstanceId") required() action { (x, c) =>
    +        c.copy(engineInstanceId = x)
    +      } text("Engine instance ID.")
    +      opt[Unit]("verbose") action { (x, c) =>
    +        c.copy(verbose = true)
    +      } text("Enable verbose output.")
    +      opt[Unit]("debug") action { (x, c) =>
    +        c.copy(debug = true)
    +      } text("Enable debug output.")
    +      opt[String]("json-extractor") action { (x, c) =>
    +        c.copy(jsonExtractor = JsonExtractorOption.withName(x))
    +      }
    +    }
    +
    +    parser.parse(args, BatchPredictConfig()) map { config =>
    +      WorkflowUtils.modifyLogging(config.verbose)
    +      engineInstances.get(config.engineInstanceId) map { engineInstance =>
    +
    +        val engine = getEngine(engineInstance)
    +
    +        run(config, engineInstance, engine)
    +
    +      } getOrElse {
    +        error(s"Invalid engine instance ID. Aborting batch predict.")
    +      }
    +    }
    +  }
    +
    +  def getEngine(engineInstance: EngineInstance): Engine[_, _, _, _, _, _] = {
    +
    +    val engineFactoryName = engineInstance.engineFactory
    +
    +    val (engineLanguage, engineFactory) =
    +      WorkflowUtils.getEngine(engineFactoryName, getClass.getClassLoader)
    +    val maybeEngine = engineFactory()
    +
    +    // EngineFactory return a base engine, which may not be deployable.
    --- End diff --
    
    You can check type and cast at once by using pattern match:
    
    ```scala
    maybeEngine match {
      case e: Engine[_, _, _, _, _, _] => e
      case _ => throw new NoSuchMethodException(
        s"Engine $maybeEngine cannot be used for batch predict")
    }
    ```


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---