-
Notifications
You must be signed in to change notification settings - Fork 381
perf: fuse Comet cache vector reads into Spark codegen #5859
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
ec92ee5
17dcdc6
8dc61ad
091eb00
eafdba5
49b7ec0
03981e5
ee0e24f
14b5d7b
cea2caa
eadfdff
64a25bc
dbfb182
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| /* | ||
| * 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.comet.rules | ||
|
|
||
| import org.apache.spark.sql.catalyst.expressions.LeafExpression | ||
| import org.apache.spark.sql.catalyst.expressions.codegen.CodegenFallback | ||
| import org.apache.spark.sql.catalyst.rules.Rule | ||
| import org.apache.spark.sql.comet.execution.arrow.ArrowCachedBatchSerializer | ||
| import org.apache.spark.sql.execution.{CodegenSupport, ColumnarToRowExec, ColumnarToRowTransition, SparkPlan, WholeStageCodegenExec} | ||
| import org.apache.spark.sql.execution.adaptive.QueryStageExec | ||
| import org.apache.spark.sql.execution.columnar.InMemoryTableScanExec | ||
| import org.apache.spark.sql.internal.SQLConf | ||
|
|
||
| import org.apache.comet.CometConf.COMET_EXEC_IN_MEMORY_CACHE_ENABLED | ||
| import org.apache.comet.CometSparkSessionExtensions.isCometLoaded | ||
|
|
||
| /** | ||
| * Lets Spark's generated consumers read cached Arrow vectors without an intermediate UnsafeRow. | ||
| * | ||
| * Data flows upward. Spark's InputAdapter/whole-stage wrappers and an optional AQE cache stage | ||
| * are omitted: | ||
| * {{{ | ||
| * Before After | ||
| * +------------------------+ +------------------------+ | ||
| * | Spark codegen consumer | | Spark codegen consumer | | ||
| * +------------------------+ +------------------------+ | ||
| * ^ ^ | ||
| * | UnsafeRow | column values | ||
| * +------------------------+ +------------------------+ | ||
| * | InMemoryTableScanExec | | ColumnarToRowExec | | ||
| * | row iterator | | fused with consumer | | ||
| * +------------------------+ +------------------------+ | ||
| * ^ | ||
| * | ColumnarBatch | ||
| * +------------------------+ | ||
| * | InMemoryTableScanExec | | ||
| * | Arrow vectors | | ||
| * +------------------------+ | ||
| * }}} | ||
| */ | ||
| object CometCacheColumnarRule extends Rule[SparkPlan] { | ||
| override def apply(plan: SparkPlan): SparkPlan = { | ||
| if (!isCometLoaded(conf) || !COMET_EXEC_IN_MEMORY_CACHE_ENABLED.get(conf)) return plan | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since #5394, |
||
| if (!conf.wholeStageEnabled) return plan | ||
|
peterxcli marked this conversation as resolved.
|
||
| if (conf.getConf(SQLConf.CODEGEN_FACTORY_MODE).toString == "NO_CODEGEN") return plan | ||
|
|
||
| plan.transformUp { | ||
| case parent: CodegenSupport | ||
| if parent.supportCodegen && !parent.supportsColumnar && | ||
| !parent.isInstanceOf[ColumnarToRowTransition] && | ||
| !WholeStageCodegenExec.isTooManyFields(conf, parent.schema) && | ||
| !parent.children.exists(p => WholeStageCodegenExec.isTooManyFields(conf, p.schema)) && | ||
| !parent.expressions.exists(_.exists { | ||
| case _: LeafExpression => false | ||
| case _: CodegenFallback => true | ||
| case _ => false | ||
| }) => | ||
| // Match the consuming edge rather than every scan: an existing columnar consumer (or a | ||
| // cache stage being materialized by AQE) must keep receiving batches. Spark inserts an | ||
| // InputAdapter around the scan later, while this transition fuses with the row consumer. | ||
| parent.withNewChildren(parent.children.map { | ||
| case child if isColumnarCometCache(child) => ColumnarToRowExec(child) | ||
| case child => child | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| private def isColumnarCometCache(plan: SparkPlan): Boolean = { | ||
| plan.supportsColumnar && (plan match { | ||
| case scan: InMemoryTableScanExec => | ||
| // The serializer delegates unsupported schemas to Spark, whose cache keeps its own reader. | ||
| scan.relation.cacheBuilder.serializer.isInstanceOf[ArrowCachedBatchSerializer] && | ||
| ArrowCachedBatchSerializer.supportsSchema(scan.relation.output) | ||
| case stage: QueryStageExec => isColumnarCometCache(stage.plan) | ||
| case _ => false | ||
| }) | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| /* | ||
| * 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.comet.execution.arrow | ||
|
|
||
| import org.apache.spark.sql.catalyst.InternalRow | ||
| import org.apache.spark.sql.catalyst.expressions.{Attribute, BoundReference, CodeGeneratorWithInterpretedFallback, InterpretedUnsafeProjection} | ||
| import org.apache.spark.sql.catalyst.expressions.codegen._ | ||
| import org.apache.spark.sql.catalyst.expressions.codegen.Block._ | ||
| import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector} | ||
|
|
||
| /** | ||
| * Reads vectors directly into Spark's reusable UnsafeRow buffer. The input iterator owns the | ||
| * batches and releases them on advancement or task completion. As with Spark's cache reader, | ||
| * callers must copy rows they retain across next(), but the returned row owns its variable-width | ||
| * values and remains valid when hasNext() releases the batch that supplied them. | ||
| */ | ||
| private[arrow] class CachedBatchRowIterator(attributes: Seq[Attribute]) | ||
| extends CodeGeneratorWithInterpretedFallback[Iterator[ColumnarBatch], Iterator[InternalRow]] { | ||
|
|
||
| private def fields: Seq[BoundReference] = attributes.zipWithIndex.map { case (attr, i) => | ||
| BoundReference(i, attr.dataType, attr.nullable) | ||
| } | ||
|
|
||
| override protected def createCodeGeneratedObject( | ||
| batches: Iterator[ColumnarBatch]): Iterator[InternalRow] = { | ||
| val ctx = new CodegenContext | ||
| val columns = attributes.indices.map { i => | ||
| ctx.addMutableState(classOf[ColumnVector].getName, s"column$i") | ||
| } | ||
| ctx.currentVars = attributes.zip(columns).map { case (attr, column) => | ||
| val value = JavaCode.variable(ctx.freshName("value"), attr.dataType) | ||
| val getter = CodeGenerator.getValueFromVector(column, attr.dataType, "rowId") | ||
| val javaType = CodeGenerator.javaType(attr.dataType) | ||
| if (attr.nullable) { | ||
| val isNull = JavaCode.isNullVariable(ctx.freshName("isNull")) | ||
| ExprCode( | ||
| code""" | ||
| boolean $isNull = $column.isNullAt(rowId); | ||
| $javaType $value = $isNull ? ${CodeGenerator.defaultValue(attr.dataType)} : ($getter); | ||
| """, | ||
| isNull, | ||
| value) | ||
| } else { | ||
| ExprCode(code"$javaType $value = $getter;", FalseLiteral, value) | ||
| } | ||
| } | ||
| val projection = GenerateUnsafeProjection.createCode(ctx, fields) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Preserve code splitting for wide cache projections. Reading 1,500 selected INT columns with alternating nullable/non-nullable attributes makes the generated Evidence: Compiled the unchanged exact-head
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This starts well below the 64 KB limit. Under it the method still compiles, but once So falling back only when compilation fails would not be enough. |
||
| val batchesRef = ctx.addReferenceObj("batches", batches, "scala.collection.Iterator") | ||
| val bindColumns = columns.zipWithIndex | ||
| .map { case (column, i) => | ||
| s"$column = batch.column($i);" | ||
| } | ||
| .mkString("\n") | ||
| val code = s""" | ||
| public Object generate(Object[] references) { | ||
| return new SpecificCachedBatchRowIterator(references); | ||
| } | ||
|
|
||
| class SpecificCachedBatchRowIterator extends scala.collection.AbstractIterator { | ||
| private final Object[] references; | ||
| private final scala.collection.Iterator batches; | ||
| private int rowId = 0; | ||
| private int numRows = 0; | ||
| ${ctx.declareMutableStates()} | ||
|
|
||
| public SpecificCachedBatchRowIterator(Object[] references) { | ||
| this.references = references; | ||
| this.batches = $batchesRef; | ||
| ${ctx.initMutableStates()} | ||
| } | ||
|
|
||
| public boolean hasNext() { | ||
| while (rowId >= numRows && batches.hasNext()) { | ||
| ${classOf[ColumnarBatch].getName} batch = | ||
| (${classOf[ColumnarBatch].getName}) batches.next(); | ||
| numRows = batch.numRows(); | ||
| rowId = 0; | ||
| $bindColumns | ||
| } | ||
| return rowId < numRows; | ||
| } | ||
|
|
||
| public InternalRow next() { | ||
| if (!hasNext()) throw new java.util.NoSuchElementException(); | ||
| ${projection.code} | ||
| rowId++; | ||
| return ${projection.value}; | ||
| } | ||
|
|
||
| ${ctx.declareAddedFunctions()} | ||
| } | ||
| """ | ||
| val (compiled, _) = | ||
| CodeGenerator.compile(new CodeAndComment(code, ctx.getPlaceHolderToComments())) | ||
| compiled.generate(ctx.references.toArray).asInstanceOf[Iterator[InternalRow]] | ||
| } | ||
|
|
||
| override protected def createInterpretedObject( | ||
| batches: Iterator[ColumnarBatch]): Iterator[InternalRow] = { | ||
| val toUnsafe = InterpretedUnsafeProjection.createProjection(fields) | ||
| batches.flatMap { batch => | ||
| new Iterator[InternalRow] { | ||
| private var rowId = 0 | ||
| override def hasNext: Boolean = rowId < batch.numRows() | ||
| override def next(): InternalRow = { | ||
| if (!hasNext) throw new NoSuchElementException | ||
| val row = toUnsafe(batch.getRow(rowId)) | ||
| rowId += 1 | ||
| row | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This describes the new split, but the Limitations section of
docs/source/user-guide/latest/in-memory-cache.mdstill says Spark-operator reads are slower than Spark's own format and that the cause is not yet established. Its table was measured with Comet off, and those reads now go throughCachedBatchRowIterator. With Comet on and exec off, eligible consumers take the fused path instead. Could you update that section in this PR, including when the fused path applies? With exec on, a Spark operator above the cache already reads throughCometColumnarToRowover the native scan, so that case does not change.