hvanhovell commented on code in PR #48791:
URL: https://github.com/apache/spark/pull/48791#discussion_r1877028075


##########
sql/connect/server/src/main/scala/org/apache/spark/sql/connect/ml/MLHandler.scala:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.spark.sql.connect.ml
+
+import scala.jdk.CollectionConverters.CollectionHasAsScala
+
+import org.apache.spark.connect.proto
+import org.apache.spark.internal.Logging
+import org.apache.spark.ml.{Estimator, Model}
+import org.apache.spark.ml.param.ParamMap
+import org.apache.spark.ml.util.{MLWritable, Summary}
+import org.apache.spark.sql.DataFrame
+import org.apache.spark.sql.connect.common.LiteralValueProtoConverter
+import org.apache.spark.sql.connect.ml.Serializer.deserializeMethodArguments
+import org.apache.spark.sql.connect.service.SessionHolder
+
+/**
+ * Helper function to get the attribute from an object by reflection
+ */
+private class AttributeHelper(
+    val sessionHolder: SessionHolder,
+    val objIdentifier: String,
+    val method: Option[String],
+    val argValues: Array[Object] = Array.empty,
+    val argClasses: Array[Class[_]] = Array.empty) {
+
+  private val methodChain = method.map(n => 
s"$objIdentifier.$n").getOrElse(objIdentifier)
+  private val methodChains = methodChain.split("\\.")
+  private val modelId = methodChains.head
+
+  protected lazy val instance = sessionHolder.mlCache.get(modelId)
+  private lazy val methods = methodChains.slice(1, methodChains.length)
+
+  def getAttribute: Any = {
+    assert(methods.length >= 1)
+    if (argValues.length == 0) {
+      methods.foldLeft(instance) { (obj, attribute) =>
+        MLUtils.invokeMethodAllowed(obj, attribute)
+      }
+    } else {
+      val lastMethod = methods.last
+      if (methods.length == 1) {
+        MLUtils.invokeMethodAllowed(instance, lastMethod, argValues, 
argClasses)
+      } else {
+        val prevMethods = methods.slice(0, methods.length - 1)
+        val finalObj = prevMethods.foldLeft(instance) { (obj, attribute) =>
+          MLUtils.invokeMethodAllowed(obj, attribute)
+        }
+        MLUtils.invokeMethodAllowed(finalObj, lastMethod, argValues, 
argClasses)
+      }
+    }
+  }
+}
+
+private class ModelAttributeHelper(
+    sessionHolder: SessionHolder,
+    objIdentifier: String,
+    method: Option[String],
+    argValues: Array[Object] = Array.empty,
+    argClasses: Array[Class[_]] = Array.empty)
+    extends AttributeHelper(sessionHolder, objIdentifier, method, argValues, 
argClasses) {
+
+  def transform(relation: proto.MlRelation.Transform): DataFrame = {
+    // Create a copied model to avoid concurrently modify model params.
+    val model = instance.asInstanceOf[Model[_]]
+    val copiedModel = model.copy(ParamMap.empty).asInstanceOf[Model[_]]
+    MLUtils.setInstanceParams(copiedModel, relation.getParams)
+    val inputDF = MLUtils.parseRelationProto(relation.getInput, sessionHolder)
+    copiedModel.transform(inputDF)
+  }
+}
+
+private object AttributeHelper {
+  def apply(
+      sessionHolder: SessionHolder,
+      modelId: String,
+      method: Option[String] = None,
+      args: Array[proto.FetchAttr.Args] = Array.empty): AttributeHelper = {
+    val tmp = deserializeMethodArguments(args, sessionHolder)
+    val argValues = tmp.map(_._1)
+    val argClasses = tmp.map(_._2)
+    new AttributeHelper(sessionHolder, modelId, method, argValues, argClasses)
+  }
+}
+
+private object ModelAttributeHelper {
+  def apply(
+      sessionHolder: SessionHolder,
+      modelId: String,
+      method: Option[String] = None,
+      args: Array[proto.FetchAttr.Args] = Array.empty): ModelAttributeHelper = 
{
+    val tmp = deserializeMethodArguments(args, sessionHolder)
+    val argValues = tmp.map(_._1)
+    val argClasses = tmp.map(_._2)
+    new ModelAttributeHelper(sessionHolder, modelId, method, argValues, 
argClasses)
+  }
+}
+
+// MLHandler is a utility to group all ML operations
+object MLHandler extends Logging {
+  def handleMlCommand(
+      sessionHolder: SessionHolder,
+      mlCommand: proto.MlCommand): proto.MlCommandResult = {
+
+    val mlCache = sessionHolder.mlCache
+
+    mlCommand.getCommandCase match {
+      case proto.MlCommand.CommandCase.FIT =>
+        val fitCmd = mlCommand.getFit
+        val estimatorProto = fitCmd.getEstimator
+        assert(estimatorProto.getType == 
proto.MlOperator.OperatorType.ESTIMATOR)
+
+        val dataset = MLUtils.parseRelationProto(fitCmd.getDataset, 
sessionHolder)
+        val estimator = MLUtils.getEstimator(estimatorProto, 
Some(fitCmd.getParams))
+        val model = estimator.fit(dataset).asInstanceOf[Model[_]]
+        val id = mlCache.register(model)
+        proto.MlCommandResult
+          .newBuilder()
+          .setOperatorInfo(
+            proto.MlCommandResult.MlOperatorInfo
+              .newBuilder()
+              .setObjRef(proto.ObjectRef.newBuilder().setId(id)))
+          .build()
+
+      case proto.MlCommand.CommandCase.FETCH_ATTR =>
+        val args = mlCommand.getFetchAttr.getArgsList.asScala.toArray
+        val helper = AttributeHelper(
+          sessionHolder,
+          mlCommand.getFetchAttr.getObjRef.getId,
+          Option(mlCommand.getFetchAttr.getMethod),
+          args)
+        val attrResult = helper.getAttribute
+        attrResult match {
+          case s: Summary =>
+            val id = mlCache.register(s)
+            proto.MlCommandResult.newBuilder().setSummary(id).build()
+          case _ =>
+            val param = Serializer.serializeParam(attrResult)
+            proto.MlCommandResult.newBuilder().setParam(param).build()
+        }
+
+      case proto.MlCommand.CommandCase.DELETE =>
+        val modelId = mlCommand.getDelete.getObjRef.getId
+        var result = false
+        if (!modelId.contains(".")) {

Review Comment:
   Why is "." excluded?



-- 
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.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to