jinchengchenghh commented on code in PR #8931:
URL: https://github.com/apache/incubator-gluten/pull/8931#discussion_r2895044304
##########
cpp/velox/jni/VeloxJniWrapper.cc:
##########
@@ -84,12 +89,13 @@ jint JNI_OnLoad(JavaVM* vm, void*) {
createGlobalClassReferenceOrError(env,
"Lorg/apache/spark/sql/execution/datasources/BlockStripes;");
blockStripesConstructor = getMethodIdOrError(env, blockStripesClass,
"<init>", "(J[J[II[[B)V");
- batchWriteMetricsClass =
- createGlobalClassReferenceOrError(env,
"Lorg/apache/gluten/metrics/BatchWriteMetrics;");
+ batchWriteMetricsClass = createGlobalClassReferenceOrError(env,
"Lorg/apache/gluten/metrics/BatchWriteMetrics;");
batchWriteMetricsConstructor = getMethodIdOrError(env,
batchWriteMetricsClass, "<init>", "(JIJJ)V");
DLOG(INFO) << "Loaded Velox backend.";
+ gluten::vm = vm;
Review Comment:
I'm not sure if we can do that CC @zhztheplayer
##########
cpp/velox/jni/VeloxJniWrapper.cc:
##########
@@ -439,8 +444,8 @@ JNIEXPORT jlong JNICALL
Java_org_apache_gluten_utils_VeloxBatchResizerJniWrapper
auto ctx = getRuntime(env, wrapper);
auto pool =
dynamic_cast<VeloxMemoryManager*>(ctx->memoryManager())->getLeafMemoryPool();
auto iter = makeJniColumnarBatchIterator(env, jIter, ctx);
- auto appender = std::make_shared<ResultIterator>(
- std::make_unique<VeloxBatchResizer>(pool.get(), minOutputBatchSize,
maxOutputBatchSize, preferredBatchBytes, std::move(iter)));
+ auto appender =
std::make_shared<ResultIterator>(std::make_unique<VeloxBatchResizer>(
Review Comment:
I don't see the change
##########
gluten-substrait/src/main/scala/org/apache/gluten/config/GlutenConfig.scala:
##########
@@ -998,6 +1001,13 @@ object GlutenConfig extends ConfigRegistry {
.intConf
.createWithDefault(12)
+ val COLUMNAR_PHYSICAL_JOIN_OPTIMIZATION_OUTPUT_SIZE =
+ buildConf("spark.gluten.sql.columnar.physicalJoinOptimizationOutputSize")
Review Comment:
Could you describe more about the configuration?
##########
cpp/velox/jni/VeloxJniWrapper.cc:
##########
@@ -914,18 +922,181 @@ JNIEXPORT jobject JNICALL
Java_org_apache_gluten_execution_IcebergWriteJniWrappe
auto writer = ObjectStore::retrieve<IcebergWriter>(writerHandle);
auto writeStats = writer->writeStats();
jobject writeMetrics = env->NewObject(
- batchWriteMetricsClass,
- batchWriteMetricsConstructor,
- writeStats.numWrittenBytes,
- writeStats.numWrittenFiles,
- writeStats.writeIOTimeNs,
- writeStats.writeWallNs);
+ batchWriteMetricsClass,
+ batchWriteMetricsConstructor,
+ writeStats.numWrittenBytes,
+ writeStats.numWrittenFiles,
+ writeStats.writeIOTimeNs,
+ writeStats.writeWallNs);
return writeMetrics;
JNI_METHOD_END(nullptr)
}
#endif
+JNIEXPORT jlong JNICALL
Java_org_apache_gluten_vectorized_HashJoinBuilder_nativeBuild( // NOLINT
+ JNIEnv* env,
+ jclass,
+ jstring tableId,
+ jlongArray batchHandles,
+ jstring joinKey,
+ jint joinType,
+ jboolean hasMixedJoinCondition,
+ jboolean isExistenceJoin,
+ jbyteArray namedStruct,
+ jboolean isNullAwareAntiJoin,
+ jlong bloomFilterPushdownSize,
+ jint broadcastHashTableBuildThreads) {
+ JNI_METHOD_START
+ const auto hashTableId = jStringToCString(env, tableId);
+ const auto hashJoinKey = jStringToCString(env, joinKey);
+ const auto inputType = gluten::getByteArrayElementsSafe(env, namedStruct);
+ std::string structString{
+ reinterpret_cast<const char*>(inputType.elems()),
static_cast<std::string::size_type>(inputType.length())};
+
+ substrait::NamedStruct substraitStruct;
+ substraitStruct.ParseFromString(structString);
+
+ std::vector<facebook::velox::TypePtr> veloxTypeList;
+ veloxTypeList = SubstraitParser::parseNamedStruct(substraitStruct);
+
+ const auto& substraitNames = substraitStruct.names();
+
+ std::vector<std::string> names;
+ names.reserve(substraitNames.size());
+ for (const auto& name : substraitNames) {
+ names.emplace_back(name);
+ }
+
+ std::vector<std::shared_ptr<ColumnarBatch>> cb;
+ int handleCount = env->GetArrayLength(batchHandles);
+ auto safeArray = getLongArrayElementsSafe(env, batchHandles);
+ for (int i = 0; i < handleCount; ++i) {
+ int64_t handle = safeArray.elems()[i];
+ cb.push_back(ObjectStore::retrieve<ColumnarBatch>(handle));
+ }
+
+ size_t maxThreads = broadcastHashTableBuildThreads > 0
+ ? std::min((size_t)broadcastHashTableBuildThreads, (size_t)32)
+ : std::min((size_t)std::thread::hardware_concurrency(), (size_t)32);
+
+ // Heuristic: Each thread should process at least a certain number of
batches to justify parallelism overhead.
+ // 32 batches is roughly 128k rows, which is a reasonable granularity for a
single thread.
+ constexpr size_t kMinBatchesPerThread = 32;
+ size_t numThreads = std::min(maxThreads, (handleCount + kMinBatchesPerThread
- 1) / kMinBatchesPerThread);
+ numThreads = std::max((size_t)1, numThreads);
+
+ if (numThreads <= 1) {
+ auto builder = nativeHashTableBuild(
+ hashJoinKey,
+ names,
+ veloxTypeList,
+ joinType,
+ hasMixedJoinCondition,
+ isExistenceJoin,
+ isNullAwareAntiJoin,
+ bloomFilterPushdownSize,
+ cb,
+ defaultLeafVeloxMemoryPool());
+
+ auto mainTable = builder->uniqueTable();
+ mainTable->prepareJoinTable(
+ {},
+ facebook::velox::exec::BaseHashTable::kNoSpillInputStartPartitionBit,
+ 1'000'000,
+ builder->dropDuplicates(),
+ nullptr);
+ builder->setHashTable(std::move(mainTable));
+
+ return gluten::hashTableObjStore->save(builder);
+ }
+
+ std::vector<std::thread> threads;
+
+ std::vector<std::shared_ptr<gluten::HashTableBuilder>>
hashTableBuilders(numThreads);
+ std::vector<std::unique_ptr<facebook::velox::exec::BaseHashTable>>
otherTables(numThreads);
+
+ for (size_t t = 0; t < numThreads; ++t) {
+ size_t start = (handleCount * t) / numThreads;
+ size_t end = (handleCount * (t + 1)) / numThreads;
+
+ threads.emplace_back([&, t, start, end]() {
+ std::vector<std::shared_ptr<gluten::ColumnarBatch>> threadBatches;
+ for (size_t i = start; i < end; ++i) {
+ threadBatches.push_back(cb[i]);
+ }
+
+ auto builder = nativeHashTableBuild(
+ hashJoinKey,
+ names,
+ veloxTypeList,
+ joinType,
+ hasMixedJoinCondition,
+ isExistenceJoin,
+ isNullAwareAntiJoin,
+ bloomFilterPushdownSize,
+ threadBatches,
+ defaultLeafVeloxMemoryPool());
Review Comment:
Do we track this memory?
##########
cpp/velox/jni/JniHashTable.cc:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.
+ */
+
+#include <arrow/c/abi.h>
+
+#include <jni/JniCommon.h>
+#include "JniHashTable.h"
+#include "folly/String.h"
+#include "memory/ColumnarBatch.h"
+#include "memory/VeloxColumnarBatch.h"
+#include "substrait/algebra.pb.h"
+#include "substrait/type.pb.h"
+#include "velox/core/PlanNode.h"
+#include "velox/type/Type.h"
+
+namespace gluten {
+
+static jclass jniVeloxBroadcastBuildSideCache = nullptr;
+static jmethodID jniGet = nullptr;
+
+jlong callJavaGet(const std::string& id) {
+ JNIEnv* env;
+ if (vm->GetEnv(reinterpret_cast<void**>(&env), jniVersion) != JNI_OK) {
+ throw gluten::GlutenException("JNIEnv was not attached to current thread");
+ }
+
+ const jstring s = env->NewStringUTF(id.c_str());
+
+ auto result = env->CallStaticLongMethod(jniVeloxBroadcastBuildSideCache,
jniGet, s);
+ return result;
+}
+
+// Return the velox's hash table.
+std::shared_ptr<HashTableBuilder> nativeHashTableBuild(
+ const std::string& joinKeys,
+ std::vector<std::string> names,
+ std::vector<facebook::velox::TypePtr> veloxTypeList,
+ int joinType,
+ bool hasMixedJoinCondition,
+ bool isExistenceJoin,
+ bool isNullAwareAntiJoin,
+ int64_t bloomFilterPushdownSize,
+ std::vector<std::shared_ptr<ColumnarBatch>>& batches,
+ std::shared_ptr<facebook::velox::memory::MemoryPool> memoryPool) {
+ auto rowType = std::make_shared<facebook::velox::RowType>(std::move(names),
std::move(veloxTypeList));
+
+ auto sJoin = static_cast<substrait::JoinRel_JoinType>(joinType);
+ facebook::velox::core::JoinType vJoin;
+ switch (sJoin) {
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_INNER:
+ vJoin = facebook::velox::core::JoinType::kInner;
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_OUTER:
+ vJoin = facebook::velox::core::JoinType::kFull;
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_LEFT:
+ vJoin = facebook::velox::core::JoinType::kLeft;
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_RIGHT:
+ vJoin = facebook::velox::core::JoinType::kRight;
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_LEFT_SEMI:
+ // Determine the semi join type based on extracted information.
+ if (isExistenceJoin) {
+ vJoin = facebook::velox::core::JoinType::kLeftSemiProject;
+ } else {
+ vJoin = facebook::velox::core::JoinType::kLeftSemiFilter;
+ }
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_RIGHT_SEMI:
+ // Determine the semi join type based on extracted information.
+ if (isExistenceJoin) {
+ vJoin = facebook::velox::core::JoinType::kRightSemiProject;
+ } else {
+ vJoin = facebook::velox::core::JoinType::kRightSemiFilter;
+ }
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_LEFT_ANTI: {
+ // Determine the anti join type based on extracted information.
+ vJoin = facebook::velox::core::JoinType::kAnti;
+ break;
+ }
+ default:
+ VELOX_NYI("Unsupported Join type: {}", std::to_string(sJoin));
+ }
+
+ std::vector<std::string> joinKeyNames;
+ folly::split(',', joinKeys, joinKeyNames);
Review Comment:
The join key should be an array, what if the join key name contains `,`
##########
cpp/velox/jni/JniHashTable.cc:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.
+ */
+
+#include <arrow/c/abi.h>
+
+#include <jni/JniCommon.h>
+#include "JniHashTable.h"
+#include "folly/String.h"
+#include "memory/ColumnarBatch.h"
+#include "memory/VeloxColumnarBatch.h"
+#include "substrait/algebra.pb.h"
+#include "substrait/type.pb.h"
+#include "velox/core/PlanNode.h"
+#include "velox/type/Type.h"
+
+namespace gluten {
+
+static jclass jniVeloxBroadcastBuildSideCache = nullptr;
+static jmethodID jniGet = nullptr;
+
+jlong callJavaGet(const std::string& id) {
+ JNIEnv* env;
+ if (vm->GetEnv(reinterpret_cast<void**>(&env), jniVersion) != JNI_OK) {
+ throw gluten::GlutenException("JNIEnv was not attached to current thread");
+ }
+
+ const jstring s = env->NewStringUTF(id.c_str());
+
+ auto result = env->CallStaticLongMethod(jniVeloxBroadcastBuildSideCache,
jniGet, s);
+ return result;
+}
+
+// Return the velox's hash table.
+std::shared_ptr<HashTableBuilder> nativeHashTableBuild(
+ const std::string& joinKeys,
+ std::vector<std::string> names,
+ std::vector<facebook::velox::TypePtr> veloxTypeList,
+ int joinType,
+ bool hasMixedJoinCondition,
+ bool isExistenceJoin,
+ bool isNullAwareAntiJoin,
+ int64_t bloomFilterPushdownSize,
+ std::vector<std::shared_ptr<ColumnarBatch>>& batches,
+ std::shared_ptr<facebook::velox::memory::MemoryPool> memoryPool) {
+ auto rowType = std::make_shared<facebook::velox::RowType>(std::move(names),
std::move(veloxTypeList));
+
+ auto sJoin = static_cast<substrait::JoinRel_JoinType>(joinType);
+ facebook::velox::core::JoinType vJoin;
+ switch (sJoin) {
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_INNER:
+ vJoin = facebook::velox::core::JoinType::kInner;
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_OUTER:
+ vJoin = facebook::velox::core::JoinType::kFull;
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_LEFT:
+ vJoin = facebook::velox::core::JoinType::kLeft;
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_RIGHT:
+ vJoin = facebook::velox::core::JoinType::kRight;
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_LEFT_SEMI:
+ // Determine the semi join type based on extracted information.
+ if (isExistenceJoin) {
+ vJoin = facebook::velox::core::JoinType::kLeftSemiProject;
+ } else {
+ vJoin = facebook::velox::core::JoinType::kLeftSemiFilter;
+ }
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_RIGHT_SEMI:
+ // Determine the semi join type based on extracted information.
+ if (isExistenceJoin) {
+ vJoin = facebook::velox::core::JoinType::kRightSemiProject;
+ } else {
+ vJoin = facebook::velox::core::JoinType::kRightSemiFilter;
+ }
+ break;
+ case ::substrait::JoinRel_JoinType::JoinRel_JoinType_JOIN_TYPE_LEFT_ANTI: {
+ // Determine the anti join type based on extracted information.
+ vJoin = facebook::velox::core::JoinType::kAnti;
+ break;
+ }
+ default:
+ VELOX_NYI("Unsupported Join type: {}", std::to_string(sJoin));
+ }
+
+ std::vector<std::string> joinKeyNames;
+ folly::split(',', joinKeys, joinKeyNames);
+
+ std::vector<std::shared_ptr<const
facebook::velox::core::FieldAccessTypedExpr>> joinKeyTypes;
+ joinKeyTypes.reserve(joinKeyNames.size());
+ for (const auto& name : joinKeyNames) {
+ joinKeyTypes.emplace_back(
+
std::make_shared<facebook::velox::core::FieldAccessTypedExpr>(rowType->findChild(name),
name));
+ }
+
+ auto hashTableBuilder = std::make_shared<HashTableBuilder>(
+ vJoin,
+ isNullAwareAntiJoin,
+ hasMixedJoinCondition,
+ bloomFilterPushdownSize,
+ joinKeyTypes,
+ rowType,
+ memoryPool.get());
+
+ for (auto i = 0; i < batches.size(); i++) {
+ auto rowVector = VeloxColumnarBatch::from(memoryPool.get(),
batches[i])->getRowVector();
+ hashTableBuilder->addInput(rowVector);
+ }
+
+ return hashTableBuilder;
+}
+
+long getJoin(std::string hashTableId) {
Review Comment:
std::string_view or const std::string&
##########
gluten-substrait/src/main/scala/org/apache/gluten/execution/JoinUtils.scala:
##########
@@ -184,6 +184,7 @@ object JoinUtils {
inputBuildOutput: Seq[Attribute],
substraitContext: SubstraitContext,
operatorId: java.lang.Long,
+ hashTableId: String = "",
Review Comment:
When is the hashTableId ""?
##########
cpp/velox/jni/VeloxJniWrapper.cc:
##########
@@ -914,18 +922,181 @@ JNIEXPORT jobject JNICALL
Java_org_apache_gluten_execution_IcebergWriteJniWrappe
auto writer = ObjectStore::retrieve<IcebergWriter>(writerHandle);
auto writeStats = writer->writeStats();
jobject writeMetrics = env->NewObject(
- batchWriteMetricsClass,
- batchWriteMetricsConstructor,
- writeStats.numWrittenBytes,
- writeStats.numWrittenFiles,
- writeStats.writeIOTimeNs,
- writeStats.writeWallNs);
+ batchWriteMetricsClass,
Review Comment:
Looks like introduced many irrelevant change.
##########
gluten-substrait/src/main/scala/org/apache/gluten/extension/columnar/FallbackRules.scala:
##########
@@ -38,17 +38,32 @@ case class FallbackMultiCodegens(session: SparkSession)
extends Rule[SparkPlan]
lazy val glutenConf: GlutenConfig = GlutenConfig.get
lazy val physicalJoinOptimize = glutenConf.enablePhysicalJoinOptimize
lazy val optimizeLevel: Integer = glutenConf.physicalJoinOptimizationThrottle
+ lazy val outputSize: Integer = glutenConf.physicalJoinOptimizationOutputSize
def existsMultiCodegens(plan: SparkPlan, count: Int = 0): Boolean =
plan match {
case plan: CodegenSupport if plan.supportCodegen =>
- if ((count + 1) >= optimizeLevel) return true
+ if (
+ (count + 1) >= optimizeLevel &&
plan.output.map(_.dataType.defaultSize).sum == outputSize
Review Comment:
plan.output.map(_.dataType.defaultSize).sum >= outputSize?
--
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]