This is an automated email from the ASF dual-hosted git repository.
zhengruifeng pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/branch-4.x by this push:
new 9e2449019bb3 [SPARK-61228][SQL][ML] Add a SparseVectorToArray Catalyst
expression
9e2449019bb3 is described below
commit 9e2449019bb3ad0c4947789b4c8e64a881c6ce98
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Thu Nov 12 15:10:09 2026 +0800
[SPARK-61228][SQL][ML] Add a SparseVectorToArray Catalyst expression
### What changes were proposed in this pull request?
Add SparseVectorToArray, an internal Catalyst ML expression that accepts
the SQL struct representation of a sparse MLlib vector and expands it into a
dense array of doubles or floats. It reads size, indices, and values from the
standard four-field vector schema, so it can be composed with UnwrapUDT.
The input schema must match the vector SQL type, including field
nullability and containsNull=false for both indices and values arrays. Missing
vector positions are filled with zero. A null struct or null size, indices, or
values field produces a null result. Interpreted and generated evaluation
allocate the requested output type directly.
### Why are the changes needed?
Provide a sparse vector expansion primitive that consumes Catalyst vector
structs without deserializing MLlib vector objects and can be used with
UnwrapUDT.
### Does this PR introduce _any_ user-facing change?
No. This adds an internal expression and its tests. The existing
vector_to_array registration and behavior are unchanged.
### How was this patch tested?
Compiled the two added Scala sources and ran SparseVectorToArraySuite with
the ScalaTest runner against locally cached Spark dependencies: all 6 tests
passed. Coverage includes interpreted and generated execution, UnwrapUDT
composition, sparse and empty inputs, both output types, zero filling, null
structs and fields, vector-schema nullability, NaN/infinities, signed zero, and
unsupported output types.
Scalastyle on both added files and git diff --check passed. A full SBT
build was not run.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: OpenAI Codex (GPT-6)
Closes #60224 from zhengruifeng/ml-vector-to-array-expression.
Authored-by: Ruifeng Zheng <[email protected]>
Signed-off-by: Ruifeng Zheng <[email protected]>
(cherry picked from commit 719842e78e13137a5c866c40c56a3fee02884419)
Signed-off-by: Ruifeng Zheng <[email protected]>
skip-checks: true
---
.../expressions/ml/SparseVectorToArray.scala | 118 +++++++++++++++++
.../expressions/ml/SparseVectorToArraySuite.scala | 144 +++++++++++++++++++++
2 files changed, 262 insertions(+)
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ml/SparseVectorToArray.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ml/SparseVectorToArray.scala
new file mode 100644
index 000000000000..c727bc54ac0c
--- /dev/null
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ml/SparseVectorToArray.scala
@@ -0,0 +1,118 @@
+/*
+ * 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.catalyst.expressions.ml
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.analysis.TypeCheckResult
+import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.DataTypeMismatch
+import org.apache.spark.sql.catalyst.expressions.{Expression, UnaryExpression,
UnsafeArrayData}
+import org.apache.spark.sql.catalyst.expressions.Cast._
+import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext,
CodeGenerator, ExprCode}
+import org.apache.spark.sql.types._
+
+/**
+ * Expands the SQL struct representation of a sparse MLlib vector into a dense
array of doubles
+ * or floats. This expression is dedicated only for Spark ML and can be used
with `unwrap_udt`.
+ * The input must match the vector SQL schema, including field and array
element nullability.
+ * A null vector, size, indices, or values field produces a null result.
+ */
+case class SparseVectorToArray(child: Expression, elementType: DataType)
+ extends UnaryExpression {
+
+ require(elementType == DoubleType || elementType == FloatType,
+ "SparseVectorToArray requires a double or float element type.")
+
+ override def nullIntolerant: Boolean = true
+
+ override def prettyName: String = "sparse_vector_to_array"
+
+ override def dataType: DataType = ArrayType(elementType, containsNull =
false)
+
+ // The sparse vector fields are nullable in the vector SQL schema.
+ override def nullable: Boolean = true
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ if (child.dataType == VectorScaleShift.vectorSqlType) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ DataTypeMismatch(
+ errorSubClass = "UNEXPECTED_INPUT_TYPE",
+ messageParameters = Map(
+ "paramIndex" -> ordinalNumber(0),
+ "requiredType" -> toSQLType(VectorScaleShift.vectorSqlType),
+ "inputSql" -> toSQLExpr(child),
+ "inputType" -> toSQLType(child.dataType)))
+ }
+ }
+
+ override protected def nullSafeEval(input: Any): Any = {
+ val vector = input.asInstanceOf[InternalRow]
+ if (vector.isNullAt(1) || vector.isNullAt(2) || vector.isNullAt(3)) {
+ return null
+ }
+ val vectorSize = vector.getInt(1)
+ val vectorIndices = vector.getArray(2)
+ val vectorValues = vector.getArray(3)
+ if (elementType == FloatType) {
+ val result = new Array[Float](vectorSize)
+ var i = 0
+ while (i < vectorIndices.numElements()) {
+ result(vectorIndices.getInt(i)) = vectorValues.getDouble(i).toFloat
+ i += 1
+ }
+ UnsafeArrayData.fromPrimitiveArray(result)
+ } else {
+ val result = new Array[Double](vectorSize)
+ var i = 0
+ while (i < vectorIndices.numElements()) {
+ result(vectorIndices.getInt(i)) = vectorValues.getDouble(i)
+ i += 1
+ }
+ UnsafeArrayData.fromPrimitiveArray(result)
+ }
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode):
ExprCode = {
+ val javaType = CodeGenerator.javaType(elementType)
+ val vectorSize = ctx.freshName("vectorSize")
+ val vectorIndices = ctx.freshName("vectorIndices")
+ val vectorValues = ctx.freshName("vectorValues")
+ val result = ctx.freshName("result")
+ val index = ctx.freshName("index")
+ val unsafeArrayData = classOf[UnsafeArrayData].getName
+ nullSafeCodeGen(ctx, ev, vector => {
+ s"""
+ |${ev.isNull} = $vector.isNullAt(1) || $vector.isNullAt(2) ||
$vector.isNullAt(3);
+ |if (!${ev.isNull}) {
+ | int $vectorSize = $vector.getInt(1);
+ | ArrayData $vectorIndices = $vector.getArray(2);
+ | ArrayData $vectorValues = $vector.getArray(3);
+ | $javaType[] $result = new $javaType[$vectorSize];
+ | for (int $index = 0; $index < $vectorIndices.numElements();
$index++) {
+ | $result[$vectorIndices.getInt($index)] = ($javaType)
$vectorValues.getDouble($index);
+ | }
+ | ${ev.value} = $unsafeArrayData.fromPrimitiveArray($result);
+ |}
+ """.stripMargin
+ })
+ }
+
+ override protected def withNewChildInternal(newChild: Expression):
SparseVectorToArray = {
+ copy(child = newChild)
+ }
+}
diff --git
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ml/SparseVectorToArraySuite.scala
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ml/SparseVectorToArraySuite.scala
new file mode 100644
index 000000000000..3662e5f1bfeb
--- /dev/null
+++
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ml/SparseVectorToArraySuite.scala
@@ -0,0 +1,144 @@
+/*
+ * 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.catalyst.expressions.ml
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{BoundReference,
ExpressionEvalHelper, GenericInternalRow, Literal, UnsafeArrayData, UnwrapUDT}
+import org.apache.spark.sql.catalyst.util.ArrayData
+import org.apache.spark.sql.types._
+
+class SparseVectorToArraySuite extends SparkFunSuite with ExpressionEvalHelper
{
+ private val vectorSqlType = VectorScaleShift.vectorSqlType
+
+ private def sparseRow(size: Int, indices: Array[Int], values:
Array[Double]): InternalRow = {
+ new GenericInternalRow(Array[Any](
+ 0.toByte,
+ size,
+ UnsafeArrayData.fromPrimitiveArray(indices),
+ UnsafeArrayData.fromPrimitiveArray(values)))
+ }
+
+ private def sparseToArray(
+ size: Int,
+ indices: Array[Int],
+ values: Array[Double],
+ elementType: DataType): SparseVectorToArray = {
+ SparseVectorToArray(Literal(sparseRow(size, indices, values),
vectorSqlType), elementType)
+ }
+
+ test("sparse vector to array interpreted and code-generated evaluation") {
+ val vectors = Seq(
+ (0, Array.emptyIntArray, Array.emptyDoubleArray, Seq.empty[Double]),
+ (4, Array.emptyIntArray, Array.emptyDoubleArray, Seq(0.0, 0.0, 0.0,
0.0)),
+ (5, Array(1, 4), Array(1.1, -2.5), Seq(0.0, 1.1, 0.0, 0.0, -2.5)),
+ (3, Array(0, 1, 2), Array(Double.NaN, Double.PositiveInfinity,
Double.NegativeInfinity),
+ Seq(Double.NaN, Double.PositiveInfinity, Double.NegativeInfinity)))
+
+ for ((size, indices, values, expected) <- vectors;
+ elementType <- Seq(DoubleType, FloatType)) {
+ val expression = sparseToArray(size, indices, values, elementType)
+ assert(expression.checkInputDataTypes().isSuccess)
+ assert(expression.prettyName === "sparse_vector_to_array")
+ assert(expression.dataType === ArrayType(elementType, containsNull =
false))
+ val result = if (elementType == FloatType) expected.map(_.toFloat) else
expected
+ checkEvaluation(expression, result)
+ checkEvaluation(
+ SparseVectorToArray(BoundReference(0, vectorSqlType, nullable = true),
elementType),
+ result,
+ InternalRow(sparseRow(size, indices, values)))
+ }
+ }
+
+ test("sparse vector to array accepts unwrapped vector UDT inputs") {
+ val input = BoundReference(0, new SparseVectorToArrayTestUDT, nullable =
true)
+ val vector = sparseRow(4, Array(1, 3), Array(1.1, -2.5))
+ for (elementType <- Seq(DoubleType, FloatType)) {
+ assert(SparseVectorToArray(input,
elementType).checkInputDataTypes().isFailure)
+ val expression = SparseVectorToArray(UnwrapUDT(input), elementType)
+ assert(expression.checkInputDataTypes().isSuccess)
+ val expected = if (elementType == FloatType) {
+ Seq(0.0f, 1.1f, 0.0f, -2.5f)
+ } else {
+ Seq(0.0, 1.1, 0.0, -2.5)
+ }
+ checkEvaluation(expression, expected, InternalRow(vector))
+ }
+ }
+
+ test("sparse vector to array propagates null structs and sparse fields") {
+ val nullFields = Seq(1, 2, 3).map { field =>
+ val row = sparseRow(3, Array(1), Array(2.5))
+ row.setNullAt(field)
+ Literal(row, vectorSqlType)
+ }
+ for (input <- Literal(null, vectorSqlType) +: nullFields;
+ elementType <- Seq(DoubleType, FloatType)) {
+ val expression = SparseVectorToArray(input, elementType)
+ assert(expression.checkInputDataTypes().isSuccess)
+ assert(expression.nullable)
+ checkEvaluation(expression, null)
+ }
+ }
+
+ test("sparse vector to array requires the vector SQL schema including
nullability") {
+ val fieldNullabilityMismatches = vectorSqlType.fields.indices.map { index
=>
+ val field = vectorSqlType.fields(index)
+ StructType(vectorSqlType.fields.updated(index, field.copy(nullable =
!field.nullable)))
+ }
+ val elementNullabilityMismatches = Seq(2, 3).map { index =>
+ val field = vectorSqlType.fields(index)
+ val elementType = field.dataType.asInstanceOf[ArrayType].elementType
+ StructType(vectorSqlType.fields.updated(
+ index, field.copy(dataType = ArrayType(elementType, containsNull =
true))))
+ }
+ val invalidTypes = Seq(IntegerType, ArrayType(DoubleType),
+ vectorSqlType.add("extra", DoubleType),
+ StructType(vectorSqlType.fields.updated(1, StructField("size",
LongType)))) ++
+ fieldNullabilityMismatches ++ elementNullabilityMismatches
+ for (inputType <- invalidTypes; elementType <- Seq(DoubleType, FloatType))
{
+ val expression = SparseVectorToArray(
+ BoundReference(0, inputType, nullable = true), elementType)
+ assert(expression.checkInputDataTypes().isFailure)
+ }
+ }
+
+ test("sparse vector to array preserves signed zero") {
+ checkEvaluation(sparseToArray(3, Array(1), Array(-0.0), DoubleType),
Seq(0.0, -0.0, 0.0))
+ checkEvaluation(sparseToArray(3, Array(1), Array(-0.0), FloatType),
Seq(0.0f, -0.0f, 0.0f))
+ val doubles = sparseToArray(3, Array(1), Array(-0.0), DoubleType)
+ .eval().asInstanceOf[ArrayData]
+ val floats = sparseToArray(3, Array(1), Array(-0.0), FloatType)
+ .eval().asInstanceOf[ArrayData]
+ assert(java.lang.Double.doubleToRawLongBits(doubles.getDouble(1)) ===
Long.MinValue)
+ assert(java.lang.Float.floatToRawIntBits(floats.getFloat(1)) ===
Int.MinValue)
+ }
+
+ test("sparse vector to array rejects unsupported output types") {
+ intercept[IllegalArgumentException] {
+ sparseToArray(1, Array(0), Array(1.0), IntegerType)
+ }
+ }
+}
+
+class SparseVectorToArrayTestUDT extends UserDefinedType[InternalRow] {
+ override def sqlType: DataType = VectorScaleShift.vectorSqlType
+ override def serialize(value: InternalRow): Any = value
+ override def deserialize(value: Any): InternalRow =
value.asInstanceOf[InternalRow]
+ override def userClass: Class[InternalRow] = classOf[InternalRow]
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]